@hop-top/kit 0.4.0-alpha.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 (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
package/src/cli.ts ADDED
@@ -0,0 +1,741 @@
1
+ /**
2
+ * @module cli
3
+ * @package @hop-top/kit
4
+ *
5
+ * Commander-based CLI factory that enforces the hop-top CLI contract.
6
+ *
7
+ * The hop-top CLI contract:
8
+ * - No `help` subcommand; help is exposed only as -h/--help flag.
9
+ * - `completion` is a management-group command (hidden from default help).
10
+ * - Version is a root-level option (-v/--version), NOT a subcommand.
11
+ * - All hop-top CLIs expose three global options on the root command:
12
+ * --format <fmt> table | json | yaml (default: "table")
13
+ * --quiet suppress non-essential output
14
+ * --no-color disable ANSI colour
15
+ * - Errors are printed to stderr in error color (unless --no-color is set).
16
+ *
17
+ * Requirements: Node >= 20, commander ^14.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { createCLI } from '@hop-top/kit/cli';
22
+ * const { program, theme } = createCLI({ name: 'mytool', version: '1.0.0', description: 'My tool' });
23
+ * program.command('run').action(() => { ... });
24
+ * program.parse();
25
+ * ```
26
+ */
27
+
28
+ import { Command, Help } from 'commander';
29
+ import { parity } from './tui/parity.js';
30
+ import { registerOutputFlags } from './output/flags.js';
31
+ import './output/builtins.js';
32
+ export { HintSet, hintsEnabled, renderHints, active,
33
+ registerUpgradeHints, registerVersionHints } from './hint.js';
34
+ export type { Hint, HintOptions } from './hint.js';
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // Verbose count — stacking -V flags
38
+ // ---------------------------------------------------------------------------
39
+
40
+ const verboseCountMap = new WeakMap<Command, number>();
41
+
42
+ /** Read the accumulated -V count for a parsed command tree. */
43
+ export function verboseCount(cmd: Command): number {
44
+ // Walk up to root to find the stored count.
45
+ let c: Command | null = cmd;
46
+ while (c) {
47
+ const v = verboseCountMap.get(c);
48
+ if (v !== undefined) return v;
49
+ c = c.parent ?? null;
50
+ }
51
+ return 0;
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Named streams — registerStream / channel
56
+ // ---------------------------------------------------------------------------
57
+
58
+ interface StreamDef {
59
+ name: string;
60
+ description: string;
61
+ }
62
+
63
+ const streamDefsMap = new WeakMap<Command, StreamDef[]>();
64
+
65
+ /**
66
+ * Register a named diagnostic stream on a command.
67
+ * Adds a `--stream <names>` option (comma-separated) on first call.
68
+ *
69
+ * Parity note: Go uses StringSlice (repeatable --stream); TS and Python
70
+ * use a single comma-separated string value.
71
+ */
72
+ export function registerStream(
73
+ cmd: Command, name: string, description: string,
74
+ ): void {
75
+ let defs = streamDefsMap.get(cmd);
76
+ if (!defs) {
77
+ defs = [];
78
+ streamDefsMap.set(cmd, defs);
79
+ // Add --stream option on first registration.
80
+ cmd.option(
81
+ '--stream <names>',
82
+ 'Enable diagnostic streams (comma-separated)',
83
+ );
84
+ }
85
+ defs.push({ name, description });
86
+ }
87
+
88
+ /** Return registered stream definitions for a command. */
89
+ export function getStreamDefs(cmd: Command): StreamDef[] {
90
+ return streamDefsMap.get(cmd) ?? [];
91
+ }
92
+
93
+ const noopWriter = { write(_s: string): boolean { return true; } };
94
+
95
+ /**
96
+ * Return a writer for a named stream. When the stream is enabled via
97
+ * `--stream`, writes go to stderr with a `[name] ` prefix. Otherwise
98
+ * writes are discarded.
99
+ */
100
+ export function channel(
101
+ cmd: Command, name: string,
102
+ ): { write(s: string): boolean } {
103
+ const opts = cmd.opts();
104
+ const enabled = typeof opts.stream === 'string'
105
+ ? opts.stream.split(',').map((s: string) => s.trim()).includes(name)
106
+ : false;
107
+ if (!enabled) return noopWriter;
108
+ return {
109
+ write(s: string): boolean {
110
+ // Split on newlines and prefix each line (parity with Go/Python).
111
+ const lines = s.split('\n');
112
+ for (const line of lines) {
113
+ if (line) process.stderr.write(`[${name}] ${line}\n`);
114
+ }
115
+ return true;
116
+ },
117
+ };
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // Palette
122
+ // ---------------------------------------------------------------------------
123
+
124
+ /**
125
+ * Brand color pair used across a theme.
126
+ * Hex strings (e.g. `"#7ED957"`).
127
+ */
128
+ export interface Palette {
129
+ /** Commands / primary accent. */
130
+ command: string;
131
+ /** Flags / secondary accent. */
132
+ flag: string;
133
+ }
134
+
135
+ /**
136
+ * Built-in Neon palette — vivid grass green + neon pink.
137
+ * Mirrors Go's `Neon` palette in `kit/cli/theme.go`.
138
+ */
139
+ export const Neon: Palette = {
140
+ command: '#7ED957', // grass green
141
+ flag: '#FF00FF', // vivid neon pink
142
+ };
143
+
144
+ /**
145
+ * Built-in Dark palette — softer lime + pink.
146
+ * Mirrors Go's `Dark` palette in `kit/cli/theme.go`.
147
+ */
148
+ export const Dark: Palette = {
149
+ command: '#C1FF72', // lime
150
+ flag: '#FF66C4', // pink
151
+ };
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // Theme
155
+ // ---------------------------------------------------------------------------
156
+
157
+ /**
158
+ * Semantic color theme for CLI output.
159
+ * Mirrors Go's `Theme` struct in `kit/cli/theme.go`.
160
+ */
161
+ export interface Theme {
162
+ palette: Palette;
163
+ /** Primary accent — same as `palette.command`. */
164
+ accent: string;
165
+ /** Secondary accent — same as `palette.flag`. */
166
+ secondary: string;
167
+ /** Muted/dim color (CharmTone Squid). */
168
+ muted: string;
169
+ /** Error color (CharmTone Cherry). */
170
+ error: string;
171
+ /** Success color (CharmTone Guac). */
172
+ success: string;
173
+ /** Title/header color — mirrors fang's ColorScheme.Title (#FFFFFF). */
174
+ title: string;
175
+ /** Argument placeholder color — mirrors fang's ColorScheme.Argument (#B5E89B). */
176
+ argument: string;
177
+ /** Dimmed argument color — mirrors fang's ColorScheme.DimmedArgument (#8ABF6E). */
178
+ dimmedArgument: string;
179
+ }
180
+
181
+ /**
182
+ * Build a Theme from an optional accent override.
183
+ * When `accent` is provided it replaces `palette.command`; otherwise
184
+ * the Neon palette is used. Mirrors Go's `buildTheme` function.
185
+ */
186
+ export function buildTheme(accent?: string): Theme {
187
+ const palette: Palette = { ...Neon };
188
+ if (accent) {
189
+ palette.command = accent;
190
+ }
191
+ return {
192
+ palette,
193
+ accent: palette.command,
194
+ secondary: palette.flag,
195
+ muted: '#858183', // CharmTone Squid
196
+ error: '#ED4A5E', // CharmTone Cherry
197
+ success: '#52CF84', // CharmTone Guac
198
+ title: '#FFFFFF', // fang ColorScheme.Title
199
+ argument: '#B5E89B', // fang ColorScheme.Argument
200
+ dimmedArgument: '#8ABF6E', // fang ColorScheme.DimmedArgument
201
+ };
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // CLIConfig
206
+ // ---------------------------------------------------------------------------
207
+
208
+ /**
209
+ * Configuration passed to {@link createCLI} to identify the program.
210
+ */
211
+ export interface CLIConfig {
212
+ /**
213
+ * Binary name as invoked by the user (e.g. `"mytool"`).
214
+ * Used as the Commander program name and in the version string output.
215
+ */
216
+ name: string;
217
+
218
+ /**
219
+ * Semver version string (e.g. `"1.2.3"`).
220
+ * Exposed via `-v / --version`; do NOT include a leading `v`.
221
+ */
222
+ version: string;
223
+
224
+ /**
225
+ * One-line description shown in help output.
226
+ */
227
+ description: string;
228
+
229
+ /**
230
+ * Optional hex color string (e.g. `"#FF0000"`) used as the theme accent.
231
+ * Omit to use the Neon palette default.
232
+ */
233
+ accent?: string;
234
+
235
+ /** Opt-out built-in global flags. Zero value = all enabled. */
236
+ disable?: {
237
+ format?: boolean;
238
+ quiet?: boolean;
239
+ noColor?: boolean;
240
+ hints?: boolean;
241
+ };
242
+
243
+ /** Command groups for partitioned help (e.g. COMMANDS vs MANAGEMENT). */
244
+ groups?: Array<{
245
+ id: string; // e.g. "management"
246
+ title: string; // e.g. "MANAGEMENT"
247
+ hidden?: boolean; // hidden from default --help
248
+ }>;
249
+
250
+ /** Extra tool-specific persistent flags on root command. */
251
+ globals?: Array<{
252
+ name: string; // long name without -- (e.g. "verbose")
253
+ short?: string; // single char optional (e.g. "v")
254
+ usage: string; // description shown in --help
255
+ default?: string; // string default; empty = no default
256
+ }>;
257
+
258
+ /**
259
+ * Root --help layout overrides.
260
+ * Defaults are loaded from contracts/parity/parity.json.
261
+ */
262
+ help?: {
263
+ /**
264
+ * Appended to `description` as a separate paragraph when non-empty.
265
+ * Empty = no extra block.
266
+ */
267
+ disclaimer?: string;
268
+ /**
269
+ * Section rendering order using fang vocabulary
270
+ * (e.g. `["commands", "flags"]`). Omit to use parity.json default.
271
+ */
272
+ sectionOrder?: string[];
273
+ showAliases?: boolean;
274
+ };
275
+ }
276
+
277
+ // ---------------------------------------------------------------------------
278
+ // createCLI result
279
+ // ---------------------------------------------------------------------------
280
+
281
+ /**
282
+ * Result of {@link createCLI}.
283
+ */
284
+ export interface CLIResult {
285
+ /** Configured Commander root program. */
286
+ program: Command;
287
+ /** Theme derived from the config accent (or Neon default). */
288
+ theme: Theme;
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // Command groups
293
+ // ---------------------------------------------------------------------------
294
+
295
+ /** Map Command → group ID for partitioned help rendering. */
296
+ const commandGroupMap = new WeakMap<Command, string>();
297
+
298
+ /** Assign a command to a named group (used in formatHelp partitioning). */
299
+ export function setCommandGroup(cmd: Command, groupId: string): void {
300
+ commandGroupMap.set(cmd, groupId);
301
+ }
302
+
303
+ /** Retrieve the group ID for a command (undefined = default group). */
304
+ export function getCommandGroup(cmd: Command): string | undefined {
305
+ return commandGroupMap.get(cmd);
306
+ }
307
+
308
+ // ---------------------------------------------------------------------------
309
+ // Help theming
310
+ // ---------------------------------------------------------------------------
311
+
312
+ /** Parse a hex color string like "#7ED957" into [r, g, b]. */
313
+ function hexToRgb(hex: string): [number, number, number] {
314
+ const h = hex.replace('#', '');
315
+ return [
316
+ parseInt(h.slice(0, 2), 16),
317
+ parseInt(h.slice(2, 4), 16),
318
+ parseInt(h.slice(4, 6), 16),
319
+ ];
320
+ }
321
+
322
+ /** Wrap text in an ANSI 24-bit foreground color SGR sequence. */
323
+ function ansi(hex: string, text: string): string {
324
+ const [r, g, b] = hexToRgb(hex);
325
+ return `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
326
+ }
327
+
328
+ /** Bold + color wrapper. */
329
+ function ansiBold(hex: string, text: string): string {
330
+ const [r, g, b] = hexToRgb(hex);
331
+ return `\x1b[1;38;2;${r};${g};${b}m${text}\x1b[0m`;
332
+ }
333
+
334
+ /**
335
+ * Apply hop-top brand colors to Commander's help output.
336
+ *
337
+ * Uses Commander's structured Help API (optionTerm, subcommandTerm, etc.)
338
+ * to color each element independently — no regex post-processing on
339
+ * description text.
340
+ *
341
+ * Color mapping (mirrors Go's brandColorScheme):
342
+ * - Section headers: #FFFFFF bold
343
+ * - Flag names: theme.secondary (#FF00FF)
344
+ * - Command names: theme.accent (#7ED957)
345
+ * - Arguments (<angle>): theme.argument (#B5E89B)
346
+ * - Dimmed args ([optional]): theme.dimmedArgument (#8ABF6E)
347
+ * - Descriptions: theme.muted (#858183)
348
+ * - Usage program name: theme.accent
349
+ */
350
+ export function applyHelpTheme(
351
+ program: Command,
352
+ theme: Theme,
353
+ noColor: boolean,
354
+ sectionOrder?: string[],
355
+ showAliases?: boolean,
356
+ groups?: CLIConfig['groups'],
357
+ ): void {
358
+ // Determine no-color state lazily at render time.
359
+ const isNoColor = (): boolean =>
360
+ noColor ||
361
+ process.argv.includes('--no-color') ||
362
+ process.env['NO_COLOR'] !== undefined;
363
+
364
+ // Tell Commander our output supports color so it won't strip ANSI.
365
+ // Our style hooks already handle no-color suppression.
366
+ program.configureOutput({
367
+ ...((program as any)._outputConfiguration ?? {}),
368
+ getOutHasColors: () => !isNoColor(),
369
+ getErrHasColors: () => !isNoColor(),
370
+ });
371
+
372
+ program.configureHelp({
373
+ // --- V14 style hooks: delegate coloring here ---
374
+ styleTitle(str: string): string {
375
+ return isNoColor() ? str : ansiBold(theme.title, str);
376
+ },
377
+ styleUsage(str: string): string {
378
+ if (isNoColor()) return str;
379
+ // Color each word: command names as accent, args/options dimmed.
380
+ return str.split(' ').map(word => {
381
+ if (word === '[options]' || word === '[--flags]')
382
+ return ansi(theme.dimmedArgument, word);
383
+ if (word[0] === '[' || word[0] === '<')
384
+ return ansi(theme.argument, word);
385
+ return ansi(theme.accent, word);
386
+ }).join(' ');
387
+ },
388
+ styleCommandText(str: string): string {
389
+ return isNoColor() ? str : ansi(theme.accent, str);
390
+ },
391
+ styleSubcommandText(str: string): string {
392
+ return isNoColor() ? str : ansi(theme.accent, str);
393
+ },
394
+ styleOptionText(str: string): string {
395
+ return isNoColor() ? str : ansi(theme.secondary, str);
396
+ },
397
+ styleArgumentText(str: string): string {
398
+ return isNoColor() ? str : ansi(theme.argument, str);
399
+ },
400
+ styleDescriptionText(str: string): string {
401
+ return isNoColor() ? str : ansi(theme.muted, str);
402
+ },
403
+
404
+ // Color each part of option term separately (short, long, arg).
405
+ styleOptionTerm(str: string): string {
406
+ if (isNoColor()) return str;
407
+ return str.split(' ').map(word => {
408
+ if (word === ',') return word;
409
+ if (word.startsWith('<') || word.startsWith('['))
410
+ return ansi(theme.argument, word);
411
+ if (word.endsWith(','))
412
+ return ansi(theme.secondary, word.slice(0, -1)) + ',';
413
+ return ansi(theme.secondary, word);
414
+ }).join(' ');
415
+ },
416
+
417
+ // Color subcommand term parts: name in accent, args dimmed.
418
+ styleSubcommandTerm(str: string): string {
419
+ if (isNoColor()) return str;
420
+ const words = str.split(' ');
421
+ return words.map((word, i) => {
422
+ if (i === 0) return ansi(theme.accent, word);
423
+ if (word.startsWith('<') || word.startsWith('['))
424
+ return ansi(theme.dimmedArgument, word);
425
+ return ansi(theme.accent, word);
426
+ }).join(' ');
427
+ },
428
+
429
+ // --- Term overrides ---
430
+ subcommandTerm(cmd: Command): string {
431
+ // Match Go/fang: name <args> [--flags] or name [command]
432
+ const args = cmd.registeredArguments
433
+ .map((a: any) => a.required ? `<${a.name()}>` : `[${a.name()}]`)
434
+ .join(' ');
435
+ const hasSubcmds = cmd.commands.length > 0;
436
+ let term = cmd.name();
437
+ if (args) term += ' ' + args;
438
+ if (hasSubcmds) term += ' [command]';
439
+ else if (cmd.options.length) term += ' [--flags]';
440
+ return term;
441
+ },
442
+
443
+ // --- Custom formatHelp for group partitioning + section ordering ---
444
+ formatHelp(cmd: Command, helper: Help): string {
445
+ const termWidth = helper.padWidth(cmd, helper);
446
+
447
+ function callFormatItem(term: string, description: string): string {
448
+ return helper.formatItem(term, termWidth, description, helper);
449
+ }
450
+
451
+ const output: string[] = [];
452
+
453
+ // Usage line.
454
+ output.push(
455
+ `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,
456
+ );
457
+ output.push('');
458
+
459
+ // Description.
460
+ const desc = helper.commandDescription(cmd);
461
+ if (desc) {
462
+ output.push(helper.styleCommandDescription(desc));
463
+ output.push('');
464
+ }
465
+
466
+ // Collect sections in parity order.
467
+ const helpSections: { name: string; items: string[] }[] = [];
468
+
469
+ // Check --help-all and --help-<id> from argv.
470
+ const helpAll = process.argv.includes('--help-all');
471
+ let helpGroupFilter: string | undefined;
472
+ for (const arg of process.argv) {
473
+ const m = arg.match(/^--help-(.+)$/);
474
+ if (m && m[1] !== 'all') {
475
+ helpGroupFilter = m[1];
476
+ break;
477
+ }
478
+ }
479
+
480
+ // Build group lookup: id -> { title, hidden }.
481
+ const groupDefs = new Map<string, { title: string; hidden: boolean }>();
482
+ for (const g of groups ?? []) {
483
+ groupDefs.set(g.id, { title: g.title, hidden: g.hidden ?? false });
484
+ }
485
+
486
+ // Commands — partition by group.
487
+ const allCmds = helper.visibleCommands(cmd)
488
+ .filter((sc: Command) => sc.name() !== 'help');
489
+ const defaultCmds: Command[] = [];
490
+ const groupedCmds = new Map<string, Command[]>();
491
+
492
+ for (const sc of allCmds) {
493
+ const gid = getCommandGroup(sc);
494
+ if (gid && groupDefs.has(gid)) {
495
+ let arr = groupedCmds.get(gid);
496
+ if (!arr) { arr = []; groupedCmds.set(gid, arr); }
497
+ arr.push(sc);
498
+ } else {
499
+ defaultCmds.push(sc);
500
+ }
501
+ }
502
+
503
+ // Build formatted items for a list of commands.
504
+ const buildCmdItems = (cmds: Command[]): string[] => {
505
+ return cmds.map((sc: Command) => {
506
+ let descr = helper.subcommandDescription(sc);
507
+ if (showAliases && sc.aliases().length > 0) {
508
+ descr += ` (aliases: ${sc.aliases().join(', ')})`;
509
+ }
510
+ return callFormatItem(
511
+ helper.styleSubcommandTerm(helper.subcommandTerm(sc)),
512
+ helper.styleSubcommandDescription(descr),
513
+ );
514
+ });
515
+ };
516
+
517
+ if (defaultCmds.length > 0 && !helpGroupFilter) {
518
+ helpSections.push({
519
+ name: 'commands', items: buildCmdItems(defaultCmds),
520
+ });
521
+ }
522
+
523
+ // Group sections (respecting hidden/helpAll/helpGroupFilter).
524
+ for (const [gid, cmds] of groupedCmds) {
525
+ if (helpGroupFilter && gid !== helpGroupFilter) continue;
526
+ const def = groupDefs.get(gid)!;
527
+ if (!helpGroupFilter && def.hidden && !helpAll) continue;
528
+ if (cmds.length > 0) {
529
+ helpSections.push({ name: gid, items: buildCmdItems(cmds) });
530
+ }
531
+ }
532
+
533
+ // Flags section — use v14's formatItem for consistent padding.
534
+ const opts = helper.visibleOptions(cmd);
535
+ if (opts.length > 0) {
536
+ const flagItems = opts.map((o: any) =>
537
+ callFormatItem(
538
+ helper.styleOptionTerm(helper.optionTerm(o)),
539
+ helper.styleOptionDescription(helper.optionDescription(o)),
540
+ ),
541
+ );
542
+ helpSections.push({ name: 'flags', items: flagItems });
543
+ }
544
+
545
+ // Render sections in parity order.
546
+ const sectionMap = new Map(helpSections.map(s => [s.name, s]));
547
+ const effectiveOrder = (sectionOrder && sectionOrder.length > 0)
548
+ ? sectionOrder : parity.help.section_order;
549
+ const sectionTitles = parity.help.sections ?? {};
550
+
551
+ const resolveTitle = (name: string): string => {
552
+ const gdef = groupDefs.get(name);
553
+ if (gdef) return gdef.title;
554
+ return sectionTitles[name]?.title
555
+ ?? name.charAt(0).toUpperCase() + name.slice(1);
556
+ };
557
+
558
+ // Render sections: flags always last, after all command groups.
559
+ for (const name of effectiveOrder) {
560
+ if (name === 'flags') continue;
561
+ const sec = sectionMap.get(name);
562
+ if (!sec) continue;
563
+ output.push(helper.styleTitle(`${resolveTitle(name)}:`));
564
+ output.push(...sec.items);
565
+ output.push('');
566
+ }
567
+ for (const sec of helpSections) {
568
+ if (sec.name === 'flags') continue;
569
+ if (effectiveOrder.includes(sec.name)) continue;
570
+ output.push(helper.styleTitle(`${resolveTitle(sec.name)}:`));
571
+ output.push(...sec.items);
572
+ output.push('');
573
+ }
574
+ // FLAGS last.
575
+ const flagsSec = sectionMap.get('flags');
576
+ if (flagsSec) {
577
+ output.push(helper.styleTitle(`${resolveTitle('flags')}:`));
578
+ output.push(...flagsSec.items);
579
+ output.push('');
580
+ }
581
+
582
+ // STREAMS section — show registered streams for this command.
583
+ const defs = getStreamDefs(cmd);
584
+ if (defs.length > 0) {
585
+ const styleTerm = (helper as any).styleOptionTerm?.bind(helper)
586
+ ?? ((s: string) => s);
587
+ const styleDesc = (helper as any).styleDescriptionText?.bind(helper)
588
+ ?? ((s: string) => s);
589
+ output.push(helper.styleTitle('STREAMS:'));
590
+ for (const d of defs) {
591
+ output.push(callFormatItem(styleTerm(d.name), styleDesc(d.description)));
592
+ }
593
+ output.push('');
594
+ }
595
+
596
+ return output.join('\n') + '\n';
597
+ },
598
+ });
599
+ }
600
+
601
+ // ---------------------------------------------------------------------------
602
+ // Factory
603
+ // ---------------------------------------------------------------------------
604
+
605
+ /**
606
+ * Creates a Commander `Command` (root program) pre-configured to the hop-top CLI contract.
607
+ *
608
+ * Contract enforced by this factory (callers must NOT override these):
609
+ * - No `help` subcommand; -h/--help flag only.
610
+ * - `completion` available as management-group command (hidden by default).
611
+ * - `-v, --version` is a root option (not a subcommand); prints `<name> v<version>` and exits.
612
+ * - Global options added to the returned program:
613
+ * `--format <fmt>` Output format — `"table"` | `"json"` | `"yaml"` (default `"table"`)
614
+ * `--quiet` Suppress non-essential output (boolean, default `false`)
615
+ * `--no-color` Disable ANSI colour (boolean, default `false`)
616
+ * - `showHelpAfterError` is enabled; unknown commands print help to stderr.
617
+ * - Errors are written to stderr in `theme.error` color unless `--no-color` is active.
618
+ *
619
+ * Requires commander ^14. Do not add `-v/--version`, `--format`, `--quiet`, or
620
+ * `--no-color` again on the returned program — they are already registered.
621
+ *
622
+ * @param cfg - Program identity (name, version, description, optional accent). See {@link CLIConfig}.
623
+ * @returns `{ program, theme }` — program ready for sub-commands; theme for TUI components.
624
+ *
625
+ * @example
626
+ * ```ts
627
+ * const { program, theme } = createCLI({ name: 'hop', version: '2.0.0', description: 'hop CLI' });
628
+ * program.command('deploy').action(() => { ... });
629
+ * program.parse();
630
+ * ```
631
+ */
632
+ export function createCLI(cfg: CLIConfig): CLIResult {
633
+ const theme = buildTheme(cfg.accent);
634
+
635
+ const desc = cfg.help?.disclaimer
636
+ ? `${cfg.description}\n\n${cfg.help.disclaimer}`
637
+ : cfg.description;
638
+
639
+ // Format version as "<name> v<version>" per hop-top contract.
640
+ const normalizedVersion = cfg.version.startsWith('v') ? cfg.version : `v${cfg.version}`;
641
+ const versionOutput = `${cfg.name} ${normalizedVersion}`;
642
+
643
+ const program = new Command(cfg.name)
644
+ .description(desc)
645
+ .version(versionOutput, '-v, --version', `Print ${cfg.name} version and exit`)
646
+ .helpOption('-h, --help', 'Display help')
647
+ .addHelpCommand(false)
648
+ .showHelpAfterError(true);
649
+
650
+ // Output flag suite: --format + --format-opt + --format-help +
651
+ // --cols/--columns + --template + --output|-o. disable.format toggles
652
+ // the whole suite for callers that pipe stdout as part of a contract.
653
+ if (!cfg.disable?.format) {
654
+ registerOutputFlags(program);
655
+ }
656
+ if (!cfg.disable?.quiet) {
657
+ program.option('--quiet', 'Suppress non-essential output', false);
658
+ }
659
+ if (!cfg.disable?.noColor) {
660
+ program.option('--no-color', 'Disable ANSI colour', false);
661
+ }
662
+ if (!cfg.disable?.hints) {
663
+ program.option('--no-hints', 'Suppress next-step hints after command output', false);
664
+ }
665
+
666
+ // -V / --verbose: accumulator pattern for stacking (-VV = 2).
667
+ program.option(
668
+ '-V, --verbose', 'Increase verbosity',
669
+ (_: string, prev: number) => prev + 1, 0,
670
+ );
671
+ // Store count after parse; quiet overrides verbose.
672
+ program.hook('preAction', (thisCmd) => {
673
+ const opts = thisCmd.opts();
674
+ const count = opts.quiet ? 0 : (opts.verbose ?? 0);
675
+ verboseCountMap.set(thisCmd, count);
676
+ });
677
+
678
+ if (cfg.groups?.some(g => g.hidden)) {
679
+ program.option('--help-all', 'Show all commands including hidden groups');
680
+ program.on('option:help-all', () => {
681
+ program.help();
682
+ });
683
+ }
684
+
685
+ // Per-group help flags: --help-<id> for each registered group.
686
+ for (const g of cfg.groups ?? []) {
687
+ program.option(`--help-${g.id}`, `Show ${g.title} commands`);
688
+ program.on(`option:help-${g.id}`, () => {
689
+ program.help();
690
+ });
691
+ }
692
+
693
+ // help <group> subcommand (hidden from default help).
694
+ if (cfg.groups && cfg.groups.length > 0) {
695
+ const groupIds = cfg.groups.map(g => g.id);
696
+ const helpCmd = program.command('help [group]')
697
+ .description('Show help for a command group')
698
+ .action((group?: string) => {
699
+ if (group === 'all') {
700
+ process.argv.push('--help-all');
701
+ program.help();
702
+ } else if (group && groupIds.includes(group)) {
703
+ process.argv.push(`--help-${group}`);
704
+ program.help();
705
+ } else {
706
+ program.help();
707
+ }
708
+ });
709
+ // Hide from default help output.
710
+ (helpCmd as any).hideHelp = true;
711
+ (helpCmd as any)._hidden = true;
712
+ }
713
+
714
+ for (const g of cfg.globals ?? []) {
715
+ const flag = g.short ? `-${g.short}, --${g.name} <value>` : `--${g.name} <value>`;
716
+ program.option(flag, g.usage, g.default ?? '');
717
+ }
718
+
719
+ // Apply brand color scheme + section order to --help output.
720
+ // noColor is read lazily at render time inside applyHelpTheme.
721
+ applyHelpTheme(program, theme, false, cfg.help?.sectionOrder,
722
+ cfg.help?.showAliases, cfg.groups);
723
+
724
+ // Styled error output: merge with existing outputConfiguration to
725
+ // preserve getOutHasColors/getErrHasColors set by applyHelpTheme.
726
+ const existing = (program as any)._outputConfiguration ?? {};
727
+ program.configureOutput({
728
+ ...existing,
729
+ outputError(str: string, write: (s: string) => void) {
730
+ const nc = process.argv.includes('--no-color') ||
731
+ process.env['NO_COLOR'] !== undefined;
732
+ if (nc) {
733
+ write(str);
734
+ } else {
735
+ write(ansi(theme.error, str));
736
+ }
737
+ },
738
+ });
739
+
740
+ return { program, theme };
741
+ }