@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.11

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 (293) hide show
  1. package/CHANGELOG.md +275 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-3FIKGFKI.js +54 -0
  19. package/dist/chunk-4FMALWYB.js +669 -0
  20. package/dist/chunk-4GPCWBBA.js +143 -0
  21. package/dist/chunk-4UE5TCMQ.js +104 -0
  22. package/dist/chunk-65VPWMPV.js +1134 -0
  23. package/dist/chunk-6HFAEZ52.js +29 -0
  24. package/dist/chunk-6SVOHNIC.js +17 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BRNEKPWX.js +37 -0
  27. package/dist/chunk-BXJ2J27B.js +219 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-CXBZTONY.js +65 -0
  30. package/dist/chunk-EE4M2UOF.js +818 -0
  31. package/dist/chunk-GFRAYYRD.js +817 -0
  32. package/dist/chunk-IVQHLI56.js +1890 -0
  33. package/dist/chunk-IZ6Q4SE3.js +178 -0
  34. package/dist/chunk-JKMQSAJP.js +174 -0
  35. package/dist/chunk-K7E34Q3A.js +1445 -0
  36. package/dist/chunk-KVG7YCTS.js +115 -0
  37. package/dist/chunk-L23O2FFE.js +51 -0
  38. package/dist/chunk-MFVUENZR.js +1549 -0
  39. package/dist/chunk-ML7D5DWY.js +263 -0
  40. package/dist/chunk-MQXYDYRD.js +968 -0
  41. package/dist/chunk-POR5L2DG.js +247 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QQQYCWSC.js +240 -0
  44. package/dist/chunk-R5U7XKVJ.js +16 -0
  45. package/dist/chunk-RYKLVOVK.js +309 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T6OZMPPV.js +68 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-VGOA5Y7S.js +251 -0
  50. package/dist/chunk-VWGP4NVJ.js +513 -0
  51. package/dist/chunk-WBVO43HU.js +355 -0
  52. package/dist/chunk-WUOAQVOA.js +86 -0
  53. package/dist/chunk-XJTRY453.js +868 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-RSRk1M36.d.ts +707 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +125 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-CGE5yLBj.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +185 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +135 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-C3RWGwRi.d.ts +125 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.root.conformance.test.ts +166 -0
  150. package/src/cli.test.ts +95 -1
  151. package/src/cli.ts +234 -25
  152. package/src/completion-scripts.ts +16 -0
  153. package/src/completion-values.test.ts +76 -16
  154. package/src/completion-values.ts +170 -66
  155. package/src/completion.conformance.test.ts +298 -0
  156. package/src/completion.test.ts +268 -145
  157. package/src/completion.ts +772 -121
  158. package/src/compliance.test.ts +196 -2
  159. package/src/compliance.ts +440 -20
  160. package/src/config-merge.test.ts +425 -0
  161. package/src/config.test.ts +228 -1
  162. package/src/config.ts +429 -16
  163. package/src/delegation.test.ts +299 -0
  164. package/src/delegation.ts +807 -0
  165. package/src/gen/crud_pb.ts +7 -7
  166. package/src/id/README.md +38 -0
  167. package/src/id/contract.test.ts +1 -1
  168. package/src/id/index.test.ts +1 -1
  169. package/src/id/index.ts +3 -2
  170. package/src/index.test.ts +71 -0
  171. package/src/index.ts +46 -0
  172. package/src/llm-anthropic.conformance.test.ts +1135 -0
  173. package/src/llm-anthropic.test.ts +152 -0
  174. package/src/llm-anthropic.ts +940 -0
  175. package/src/llm-choice-hermetic.test.ts +335 -0
  176. package/src/llm-config.test.ts +232 -0
  177. package/src/llm-config.ts +106 -0
  178. package/src/llm-endpoint.ts +254 -0
  179. package/src/llm-error.ts +17 -0
  180. package/src/llm-errors.ts +152 -0
  181. package/src/llm-file.ts +126 -0
  182. package/src/llm-http.ts +317 -0
  183. package/src/llm-keys.ts +167 -0
  184. package/src/llm-media.conformance.test.ts +87 -0
  185. package/src/llm-media.test.ts +279 -0
  186. package/src/llm-media.ts +322 -0
  187. package/src/llm-openai.conformance.test.ts +407 -0
  188. package/src/llm-openai.test.ts +510 -0
  189. package/src/llm-openai.ts +708 -0
  190. package/src/llm-payload.ts +155 -0
  191. package/src/llm-quote.ts +46 -0
  192. package/src/llm-routellm.conformance.test.ts +44 -0
  193. package/src/llm-toolnames.conformance.test.ts +112 -0
  194. package/src/llm-toolnames.test.ts +132 -0
  195. package/src/llm-toolnames.ts +298 -0
  196. package/src/llm-uri.ts +99 -0
  197. package/src/llm.test.ts +43 -15
  198. package/src/llm.toolcall.test.ts +175 -0
  199. package/src/llm.ts +602 -190
  200. package/src/log.parity.test.ts +105 -0
  201. package/src/log.test.ts +270 -1
  202. package/src/log.ts +228 -49
  203. package/src/mcp/README.md +63 -0
  204. package/src/mcp/args-separator.test.ts +164 -0
  205. package/src/mcp/args.test.ts +223 -0
  206. package/src/mcp/args.ts +160 -0
  207. package/src/mcp/audit.test.ts +520 -0
  208. package/src/mcp/audit.ts +70 -0
  209. package/src/mcp/bridge.test.ts +250 -0
  210. package/src/mcp/bridge.ts +286 -0
  211. package/src/mcp/conformance.test.ts +357 -0
  212. package/src/mcp/dispatch.ts +359 -0
  213. package/src/mcp/identity.test.ts +166 -0
  214. package/src/mcp/identity.ts +72 -0
  215. package/src/mcp/index.ts +176 -0
  216. package/src/mcp/legacy-notify.test.ts +59 -0
  217. package/src/mcp/legacy.ts +367 -0
  218. package/src/mcp/mcp.test.ts +707 -0
  219. package/src/mcp/modern-confirm.test.ts +520 -0
  220. package/src/mcp/modern-confirm.ts +484 -0
  221. package/src/mcp/modern.ts +788 -0
  222. package/src/mcp/stdio.test.ts +313 -0
  223. package/src/mcp/stdio.ts +254 -0
  224. package/src/mcp/tasks.ts +82 -0
  225. package/src/mcp/testtree.ts +250 -0
  226. package/src/mcp/toolname.test.ts +147 -0
  227. package/src/mcp/types.ts +689 -0
  228. package/src/netpolicy.test.ts +280 -0
  229. package/src/netpolicy.ts +256 -0
  230. package/src/output/README.md +46 -0
  231. package/src/output/builtins.ts +5 -5
  232. package/src/output/dispatch.ts +10 -2
  233. package/src/output/error.ts +459 -0
  234. package/src/output/formatter.ts +29 -5
  235. package/src/output/formatters/README.md +50 -0
  236. package/src/output/formatters/csv.ts +48 -12
  237. package/src/output/formatters/json.ts +4 -25
  238. package/src/output/formatters/project.ts +34 -0
  239. package/src/output/formatters/table.ts +8 -6
  240. package/src/output/formatters/text.ts +7 -3
  241. package/src/output/formatters/yaml.ts +5 -22
  242. package/src/output/projection.test.ts +298 -0
  243. package/src/output/projection.ts +33 -59
  244. package/src/output/template.ts +11 -21
  245. package/src/output.surface.test.ts +41 -0
  246. package/src/output.ts +64 -3
  247. package/src/plan.ts +89 -0
  248. package/src/policy.ts +472 -0
  249. package/src/published-types.test.ts +133 -0
  250. package/src/routellm.test.ts +209 -28
  251. package/src/routellm.toolcall.test.ts +521 -0
  252. package/src/routellm.ts +213 -177
  253. package/src/router/README.md +44 -0
  254. package/src/router/server.test.ts +41 -0
  255. package/src/router/server.ts +11 -0
  256. package/src/safety.test.ts +19 -9
  257. package/src/scope-defaults.json +29 -29
  258. package/src/serve.test.ts +1257 -0
  259. package/src/serve.ts +1665 -0
  260. package/src/sideeffect.ts +105 -0
  261. package/src/telemetry/README.md +48 -0
  262. package/src/telemetry/client.test.ts +31 -0
  263. package/src/telemetry/client.ts +12 -6
  264. package/src/telemetry/offline.test.ts +64 -0
  265. package/src/toolspec-internal.ts +279 -0
  266. package/src/toolspec-manifest.test.ts +167 -0
  267. package/src/toolspec-manifest.ts +415 -0
  268. package/src/toolspec-spec-schemas.ts +12 -0
  269. package/src/toolspec-spec.test.ts +273 -0
  270. package/src/toolspec-spec.ts +458 -0
  271. package/src/toolspec.from-command.test.ts +350 -0
  272. package/src/toolspec.test.ts +2 -2
  273. package/src/toolspec.ts +222 -0
  274. package/src/triton/README.md +34 -0
  275. package/src/tui/README.md +42 -0
  276. package/src/tui/parity.test.ts +120 -31
  277. package/src/tui/parity.ts +58 -7
  278. package/src/upgrade.test.ts +291 -0
  279. package/src/upgrade.ts +116 -7
  280. package/src/wizard.test.ts +7 -7
  281. package/test/llm/conformance-helpers.ts +100 -0
  282. package/test/output/csv.test.ts +164 -0
  283. package/test/output/dispatch.test.ts +1 -2
  284. package/test/output/error.test.ts +277 -0
  285. package/test/output/smoke-capture.ts +2 -2
  286. package/test/output/smoke.test.ts +2 -2
  287. package/test/output/taxonomy-contract.test.ts +148 -0
  288. package/test/setup-env.ts +16 -0
  289. package/test/toolspec/fixture.ts +79 -0
  290. package/tsconfig.json +3 -1
  291. package/tsconfig.test.json +10 -0
  292. package/vitest.config.ts +9 -0
  293. package/src/tui/parity.json +0 -74
@@ -2,10 +2,28 @@
2
2
  * @module completion-values
3
3
  * @package @hop-top/kit
4
4
  *
5
- * Dynamic value completion system for Commander-based CLIs.
6
- * Provides a Completer interface and built-in completers for
7
- * flags and positional arguments. Shell scripts (from completion.ts)
8
- * call back via __complete; the registry resolves the right completer.
5
+ * Dynamic value completion for Commander-based CLIs. Ports Go
6
+ * `console/cli/completion`; behaviour is pinned by
7
+ * `contracts/completion-v1/completers.json`.
8
+ *
9
+ * A {@link Completer} turns the word being completed into
10
+ * {@link CompletionItem}s. `bindFlag` / `bindArgs` (in `completion`)
11
+ * attach one to a flag or to a command's positional arguments; the
12
+ * scripts `completion <shell>` writes call back into the program's
13
+ * hidden `__complete` entry point, which runs the bound completer and
14
+ * prints the result through {@link resolveCompletions} in cobra's wire
15
+ * format.
16
+ *
17
+ * Contract:
18
+ * - Prefix matching in static, config-key and the dimension half of
19
+ * prefixed completers is case-insensitive; an empty prefix returns
20
+ * every item. {@link funcCompleter} sees the raw prefix, unfiltered.
21
+ * - A completer fails by throwing (or rejecting); the bridge turns that
22
+ * into {@link ShellCompDirective.Error}.
23
+ * - {@link fileCompleter} and {@link dirCompleter} yield a directive,
24
+ * not suggestions: filter by extension (the extensions travel as the
25
+ * completions), directories only, or plain file completion when no
26
+ * extension is given.
9
27
  */
10
28
 
11
29
  export interface CompletionItem {
@@ -13,10 +31,102 @@ export interface CompletionItem {
13
31
  description?: string;
14
32
  }
15
33
 
34
+ /** What a completer knows about the command line it completes. */
35
+ export interface CompletionContext {
36
+ /** Space-separated path of the command below the root; empty for the root. */
37
+ commandPath: string;
38
+ /** Positional arguments already given, flags removed. */
39
+ args: string[];
40
+ }
41
+
42
+ /** What a file completer asks the shell for. */
43
+ export type FileFilter =
44
+ | { kind: 'extensions'; extensions: string[] }
45
+ | { kind: 'dirs' };
46
+
16
47
  export interface Completer {
17
- complete(prefix: string): CompletionItem[] | Promise<CompletionItem[]>;
48
+ complete(
49
+ prefix: string,
50
+ ctx?: CompletionContext,
51
+ ): CompletionItem[] | Promise<CompletionItem[]>;
52
+ /** Set by {@link fileCompleter} and {@link dirCompleter}. */
53
+ readonly fileFilter?: FileFilter;
54
+ }
55
+
56
+ /** cobra's shell directive bits, read by the scripts from the `:<n>` line. */
57
+ export const ShellCompDirective = {
58
+ Default: 0,
59
+ Error: 1,
60
+ NoSpace: 2,
61
+ NoFileComp: 4,
62
+ FilterFileExt: 8,
63
+ FilterDirs: 16,
64
+ KeepOrder: 32,
65
+ } as const;
66
+
67
+ /** cobra's name for a directive, as printed on stderr after a request. */
68
+ export function directiveName(d: number): string {
69
+ if (d >= 64) return `ERROR: unexpected ShellCompDirective value: ${d}`;
70
+ const names: [number, string][] = [
71
+ [ShellCompDirective.Error, 'ShellCompDirectiveError'],
72
+ [ShellCompDirective.NoSpace, 'ShellCompDirectiveNoSpace'],
73
+ [ShellCompDirective.NoFileComp, 'ShellCompDirectiveNoFileComp'],
74
+ [ShellCompDirective.FilterFileExt, 'ShellCompDirectiveFilterFileExt'],
75
+ [ShellCompDirective.FilterDirs, 'ShellCompDirectiveFilterDirs'],
76
+ [ShellCompDirective.KeepOrder, 'ShellCompDirectiveKeepOrder'],
77
+ ];
78
+ const set = names.filter(([bit]) => (d & bit) === bit).map(([, n]) => n);
79
+ return set.length ? set.join(', ') : 'ShellCompDirectiveDefault';
80
+ }
81
+
82
+ /** Completions in wire form plus the directive. */
83
+ export interface ResolvedCompletions {
84
+ /** `value`, or `value\tdescription` when there is one. */
85
+ completions: string[];
86
+ directive: number;
87
+ }
88
+
89
+ /**
90
+ * Runs `c` for `toComplete` and converts the result to the shell wire
91
+ * format: values with any description joined by a tab, plus the
92
+ * directive (no file completion on success, error when `c` fails).
93
+ */
94
+ export async function resolveCompletions(
95
+ c: Completer,
96
+ toComplete: string,
97
+ ctx: CompletionContext = { commandPath: '', args: [] },
98
+ ): Promise<ResolvedCompletions> {
99
+ const f = c.fileFilter;
100
+ if (f?.kind === 'dirs') {
101
+ return { completions: [], directive: ShellCompDirective.FilterDirs };
102
+ }
103
+ if (f?.kind === 'extensions') {
104
+ // An empty filter list would filter every candidate out.
105
+ return f.extensions.length === 0
106
+ ? { completions: [], directive: ShellCompDirective.Default }
107
+ : { completions: [...f.extensions], directive: ShellCompDirective.FilterFileExt };
108
+ }
109
+ try {
110
+ const items = await c.complete(toComplete, ctx);
111
+ return {
112
+ completions: items.map(withDescription),
113
+ directive: ShellCompDirective.NoFileComp,
114
+ };
115
+ } catch {
116
+ return { completions: [], directive: ShellCompDirective.Error };
117
+ }
118
+ }
119
+
120
+ /** `value`, or `value\tdescription` when there is one. */
121
+ export function withDescription(i: CompletionItem): string {
122
+ return i.description ? `${i.value}\t${i.description}` : i.value;
18
123
  }
19
124
 
125
+ /**
126
+ * Maps flag names and argument positions to completers, for sharing
127
+ * completers across a command tree (Go `Registry`). A lookup table
128
+ * only: `bindFlag` / `bindArgs` wire a completer into completion.
129
+ */
20
130
  export class CompletionRegistry {
21
131
  private flags = new Map<string, Completer>();
22
132
  private args = new Map<string, Completer>();
@@ -38,12 +148,12 @@ export class CompletionRegistry {
38
148
  }
39
149
  }
40
150
 
41
- /** Filter items by case-insensitive prefix match. */
151
+ /** Filter items by case-insensitive prefix match; keeps duplicates. */
42
152
  function filterByPrefix(
43
153
  items: CompletionItem[],
44
154
  prefix: string,
45
155
  ): CompletionItem[] {
46
- if (!prefix) return items;
156
+ if (!prefix) return [...items];
47
157
  const lp = prefix.toLowerCase();
48
158
  return items.filter(i => i.value.toLowerCase().startsWith(lp));
49
159
  }
@@ -65,109 +175,103 @@ export function staticValues(...values: string[]): Completer {
65
175
  return staticCompleter(...items);
66
176
  }
67
177
 
68
- /** Completer backed by a callback function. */
178
+ /**
179
+ * Completer backed by a callback. The callback sees the raw prefix;
180
+ * nothing is filtered for it. Throw (or reject) to fail.
181
+ */
69
182
  export function funcCompleter(
70
- fn: (prefix: string) => CompletionItem[],
183
+ fn: (
184
+ prefix: string,
185
+ ctx: CompletionContext,
186
+ ) => CompletionItem[] | Promise<CompletionItem[]>,
71
187
  ): Completer {
72
- return { complete: fn };
188
+ return {
189
+ complete(prefix, ctx = { commandPath: '', args: [] }) {
190
+ return fn(prefix, ctx);
191
+ },
192
+ };
73
193
  }
74
194
 
75
195
  /**
76
- * Completer for dimensioned values like `env:prod`.
77
- * Before the colon, suggests the dimension prefix.
78
- * After the colon, delegates to the inner completer.
196
+ * Completer for dimensioned values like `env:prod`. While no colon is
197
+ * typed it suggests `dimension:` (matched case-insensitively); after
198
+ * the first colon it delegates the rest to `values` and re-prepends
199
+ * the declared `dimension:`.
79
200
  */
80
201
  export function prefixedCompleter(
81
202
  dimension: string,
82
203
  values: Completer,
83
204
  ): Completer {
205
+ const lower = dimension.toLowerCase();
206
+ const prepend = (items: CompletionItem[]) =>
207
+ items.map(i => {
208
+ const v = `${dimension}:${i.value}`;
209
+ return i.description ? { value: v, description: i.description } : { value: v };
210
+ });
84
211
  return {
85
- complete(prefix: string) {
212
+ complete(prefix, ctx) {
86
213
  const colonIdx = prefix.indexOf(':');
87
214
  if (colonIdx < 0) {
88
- // no colon yet — suggest dimension prefix
89
- return [{ value: `${dimension}:`, description: `${dimension}:...` }];
90
- }
91
-
92
- const dim = prefix.slice(0, colonIdx);
93
- if (dim !== dimension) return [];
94
-
95
- const valPrefix = prefix.slice(colonIdx + 1);
96
- const inner = values.complete(valPrefix);
97
- if (Array.isArray(inner)) {
98
- return inner.map(i => ({
99
- value: `${dimension}:${i.value}`,
100
- description: i.description,
101
- }));
215
+ const dim = `${dimension}:`;
216
+ return dim.toLowerCase().startsWith(prefix.toLowerCase())
217
+ ? [{ value: dim, description: `${dimension} values` }]
218
+ : [];
102
219
  }
103
- // async path
104
- return (inner as Promise<CompletionItem[]>).then(items =>
105
- items.map(i => ({
106
- value: `${dimension}:${i.value}`,
107
- description: i.description,
108
- })),
109
- );
220
+ if (prefix.slice(0, colonIdx).toLowerCase() !== lower) return [];
221
+ const inner = values.complete(prefix.slice(colonIdx + 1), ctx);
222
+ return Array.isArray(inner) ? prepend(inner) : inner.then(prepend);
110
223
  },
111
224
  };
112
225
  }
113
226
 
114
- /** Flatten object keys into dot-notation paths. */
115
- function flattenKeys(
116
- obj: Record<string, any>,
117
- prefix = '',
118
- ): string[] {
119
- const keys: string[] = [];
227
+ /** The dotted leaf keys of a config tree, lowercased like viper's AllKeys. */
228
+ function leafKeys(obj: Record<string, unknown>, prefix: string, out: Set<string>): void {
120
229
  for (const [k, v] of Object.entries(obj)) {
121
- const full = prefix ? `${prefix}.${k}` : k;
122
- keys.push(full);
230
+ const full = prefix ? `${prefix}.${k.toLowerCase()}` : k.toLowerCase();
123
231
  if (v != null && typeof v === 'object' && !Array.isArray(v)) {
124
- keys.push(...flattenKeys(v, full));
232
+ leafKeys(v as Record<string, unknown>, full, out);
233
+ } else {
234
+ out.add(full);
125
235
  }
126
236
  }
127
- return keys;
128
237
  }
129
238
 
130
- /** Completer that suggests config keys in dot-notation. */
239
+ /**
240
+ * Completer that suggests config keys: the dotted leaf keys of
241
+ * `config`, lowercased, matched case-insensitively.
242
+ */
131
243
  export function configKeysCompleter(
132
- config: Record<string, any>,
244
+ config: Record<string, unknown>,
133
245
  ): Completer {
134
246
  return {
135
247
  complete(prefix: string) {
136
- const all = flattenKeys(config);
137
- return filterByPrefix(
138
- all.map(k => ({ value: k })),
139
- prefix,
140
- );
248
+ const keys = new Set<string>();
249
+ leafKeys(config, '', keys);
250
+ return filterByPrefix([...keys].map(k => ({ value: k })), prefix);
141
251
  },
142
252
  };
143
253
  }
144
254
 
145
255
  /**
146
- * Completer that signals shell-level file completion.
147
- * Returns a marker item; the __complete handler translates
148
- * this to shell-native file glob directives.
256
+ * Completer that asks the shell for files with these extensions (e.g.
257
+ * `.yaml`); none means any file. Its items are the extensions, which
258
+ * travel as the completions of a filter-by-extension directive.
149
259
  */
150
260
  export function fileCompleter(...extensions: string[]): Completer {
151
- const desc = extensions.length
152
- ? `Files: ${extensions.join(', ')}`
153
- : 'Files';
154
261
  return {
262
+ fileFilter: { kind: 'extensions', extensions: [...extensions] },
155
263
  complete() {
156
- return [
157
- {
158
- value: '__file__',
159
- description: desc,
160
- },
161
- ];
264
+ return extensions.map(e => ({ value: e }));
162
265
  },
163
266
  };
164
267
  }
165
268
 
166
- /** Completer that signals shell-level directory completion. */
269
+ /** Completer that asks the shell for directories only. */
167
270
  export function dirCompleter(): Completer {
168
271
  return {
272
+ fileFilter: { kind: 'dirs' },
169
273
  complete() {
170
- return [{ value: '__dir__', description: 'Directories' }];
274
+ return [];
171
275
  },
172
276
  };
173
277
  }
@@ -0,0 +1,298 @@
1
+ // Runs the shared completion corpus in contracts/completion-v1. The
2
+ // vectors are the source of truth: a failure means this port drifted
3
+ // from the contract (Go is canonical), not that a vector should be
4
+ // edited to fit.
5
+ //
6
+ // Strict: unknown fields fail, `version` must be `v1` and every JSON
7
+ // file in the corpus must have a runner here.
8
+
9
+ import { readdirSync, readFileSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { Command } from 'commander';
12
+ import { afterEach, describe, expect, it, vi } from 'vitest';
13
+
14
+ import { AliasStore, bridgeAliases, findCommand } from './alias';
15
+ import { createCLI } from './cli';
16
+ import { bindArgs, bindFlag, completeRequest, completionCommand } from './completion';
17
+
18
+ import {
19
+ type Completer,
20
+ type CompletionItem,
21
+ configKeysCompleter,
22
+ dirCompleter,
23
+ fileCompleter,
24
+ funcCompleter,
25
+ prefixedCompleter,
26
+ resolveCompletions,
27
+ staticCompleter,
28
+ staticValues,
29
+ } from './completion-values';
30
+
31
+ const CORPUS = join(__dirname, '..', '..', '..', 'contracts', 'completion-v1');
32
+ const FILES = ['completers.json', 'requests.json', 'scripts.json'];
33
+
34
+ function strictKeys(o: object, allowed: string[], where: string): void {
35
+ for (const k of Object.keys(o)) {
36
+ if (!allowed.includes(k)) throw new Error(`${where}: unknown field ${k}`);
37
+ }
38
+ }
39
+
40
+ function load<T>(name: string): T {
41
+ for (const n of readdirSync(CORPUS)) {
42
+ if (n.endsWith('.json') && !FILES.includes(n)) {
43
+ throw new Error(`${n} has no runner`);
44
+ }
45
+ }
46
+ const f = JSON.parse(readFileSync(join(CORPUS, name), 'utf8'));
47
+ strictKeys(f, ['$schema', '$id', 'version', 'description', 'cases', 'trees'], name);
48
+ if (f.version !== 'v1') throw new Error(`${name}: version ${f.version}`);
49
+ if (!Array.isArray(f.cases) || f.cases.length === 0) {
50
+ throw new Error(`${name}: cases section is empty`);
51
+ }
52
+ return f as T;
53
+ }
54
+
55
+ interface ConfItem { value: string; description?: string }
56
+
57
+ function item(i: ConfItem): CompletionItem {
58
+ strictKeys(i, ['value', 'description'], 'item');
59
+ return i.description ? { value: i.value, description: i.description } : { value: i.value };
60
+ }
61
+
62
+ /** A one-key completer spec. */
63
+ type Spec = Record<string, any>;
64
+
65
+ function buildCompleter(s: Spec): Completer {
66
+ strictKeys(s, ['static', 'static_values', 'func', 'prefixed', 'config_keys', 'file', 'dir'], 'spec');
67
+ const keys = Object.keys(s);
68
+ if (keys.length !== 1) throw new Error('completer spec needs exactly one key');
69
+ const v = s[keys[0]!];
70
+ switch (keys[0]) {
71
+ case 'static': return staticCompleter(...(v as ConfItem[]).map(item));
72
+ case 'static_values': return staticValues(...(v as string[]));
73
+ case 'func': {
74
+ strictKeys(v, ['items', 'error'], 'func');
75
+ if ((v.items === undefined) === (v.error === undefined)) {
76
+ throw new Error('func spec needs exactly one of items, error');
77
+ }
78
+ return funcCompleter(() => {
79
+ if (v.error !== undefined) throw new Error(v.error);
80
+ return (v.items as ConfItem[]).map(item);
81
+ });
82
+ }
83
+ case 'prefixed':
84
+ strictKeys(v, ['dimension', 'values'], 'prefixed');
85
+ return prefixedCompleter(v.dimension, buildCompleter(v.values));
86
+ case 'config_keys': return configKeysCompleter(v);
87
+ case 'file': return fileCompleter(...(v as string[]));
88
+ default:
89
+ strictKeys(v, [], 'dir');
90
+ return dirCompleter();
91
+ }
92
+ }
93
+
94
+ function same(got: string[], want: string[], unordered: boolean): void {
95
+ if (unordered) {
96
+ expect([...got].sort()).toEqual([...want].sort());
97
+ } else {
98
+ expect(got).toEqual(want);
99
+ }
100
+ }
101
+
102
+ interface CompleterCase {
103
+ name: string;
104
+ completer: Spec;
105
+ prefix: string;
106
+ items?: ConfItem[];
107
+ error?: boolean;
108
+ unordered?: boolean;
109
+ resolved: { completions: string[]; directive: number };
110
+ }
111
+
112
+ describe('completion-v1 conformance: completers.json', () => {
113
+ const f = load<{ cases: CompleterCase[] }>('completers.json');
114
+
115
+ it.each(f.cases.map(c => [c.name, c] as const))('%s', async (_n, c) => {
116
+ strictKeys(c, ['name', 'completer', 'prefix', 'items', 'error', 'unordered', 'resolved'], c.name);
117
+ strictKeys(c.resolved, ['completions', 'directive'], c.name);
118
+ const comp = buildCompleter(c.completer);
119
+ const flat = (is: CompletionItem[]) => is.map(i => `${i.value}|${i.description ?? ''}`);
120
+ let items: CompletionItem[] | undefined;
121
+ let failed = false;
122
+ try {
123
+ items = await comp.complete(c.prefix, { commandPath: '', args: [] });
124
+ } catch {
125
+ failed = true;
126
+ }
127
+ expect(failed).toBe(c.error === true);
128
+ if (!failed) {
129
+ same(flat(items!), flat((c.items ?? []).map(item)), c.unordered === true);
130
+ } else {
131
+ expect(c.items).toBeUndefined();
132
+ }
133
+ const r = await resolveCompletions(comp, c.prefix);
134
+ same(r.completions, c.resolved.completions, c.unordered === true);
135
+ expect(r.directive).toBe(c.resolved.directive);
136
+ });
137
+ });
138
+
139
+ // --- requests.json ---
140
+
141
+ interface ConfFlag { long: string; short?: string; help: string; value: boolean }
142
+ interface ConfCommand { name: string; about: string; flags?: ConfFlag[]; commands?: ConfCommand[] }
143
+ interface Tree {
144
+ program: string;
145
+ about: string;
146
+ commands: ConfCommand[];
147
+ aliases: Record<string, string>;
148
+ flag_enums: { path: string; flag: string; values: string[] }[];
149
+ flag_completers: { path: string; flag: string; completer: Spec }[];
150
+ arg_completers: { path: string; completer: Spec }[];
151
+ }
152
+ interface RequestCase {
153
+ name: string;
154
+ tree: string;
155
+ args: string[];
156
+ no_desc?: boolean;
157
+ unordered?: boolean;
158
+ stdout: string[];
159
+ stderr_contains?: string;
160
+ }
161
+
162
+ /**
163
+ * Cases this port cannot pass yet, with the reason. The TS SDK has no
164
+ * completion-spec exporter, so `completion fig|usage` do not exist.
165
+ */
166
+ const KNOWN_GAPS: Record<string, string> = {
167
+ 'completion command lists its shells':
168
+ 'no TS completion-spec exporter: `completion fig|usage` missing',
169
+ };
170
+
171
+ function buildCommand(c: ConfCommand): Command {
172
+ strictKeys(c, ['name', 'about', 'flags', 'commands'], c.name);
173
+ const cmd = new Command(c.name).description(c.about);
174
+ for (const f of c.flags ?? []) {
175
+ strictKeys(f, ['long', 'short', 'help', 'value'], `${c.name} --${f.long}`);
176
+ const names = f.short ? `-${f.short}, --${f.long}` : `--${f.long}`;
177
+ cmd.option(f.value ? `${names} <value>` : names, f.help);
178
+ }
179
+ for (const child of c.commands ?? []) cmd.addCommand(buildCommand(child));
180
+ return cmd;
181
+ }
182
+
183
+ function walk(cmd: Command, fn: (c: Command) => void): void {
184
+ fn(cmd);
185
+ for (const c of cmd.commands) walk(c, fn);
186
+ }
187
+
188
+ /** A kit root as the Go runner builds it (createCLI: persistent root flags included). */
189
+ function buildRoot(t: Tree): Command {
190
+ strictKeys(t, ['program', 'about', 'commands', 'aliases', 'flag_enums',
191
+ 'flag_completers', 'arg_completers'], t.program);
192
+ const { program } = createCLI({ name: t.program, version: '1.0.0', description: t.about });
193
+ for (const c of t.commands) program.addCommand(buildCommand(c));
194
+ const store = new AliasStore('');
195
+ for (const [name, target] of Object.entries(t.aliases)) store.set(name, target);
196
+ bridgeAliases(program, store);
197
+ // A flag enum is commander's choices: tree-wide first, then the
198
+ // command-scoped declarations, which win.
199
+ const ordered = [...t.flag_enums].sort((a, b) => Number(a.path !== '') - Number(b.path !== ''));
200
+ for (const e of ordered) {
201
+ strictKeys(e, ['path', 'flag', 'values'], 'flag_enums');
202
+ const scope = e.path ? findCommand(program, e.path)! : program;
203
+ walk(scope, c => {
204
+ if (e.path && c !== scope) return;
205
+ c.options.find(o => o.long === `--${e.flag}`)?.choices(e.values);
206
+ });
207
+ }
208
+ // As in cobra, the built-in completion command yields to a command
209
+ // or alias of that name.
210
+ const taken = program.commands.some(c =>
211
+ c.name() === 'completion' || c.aliases().includes('completion'));
212
+ if (!taken) program.addCommand(completionCommand(program));
213
+ for (const fc of t.flag_completers) {
214
+ strictKeys(fc, ['path', 'flag', 'completer'], 'flag_completers');
215
+ bindFlag(findCommand(program, fc.path)!, fc.flag, buildCompleter(fc.completer));
216
+ }
217
+ for (const ac of t.arg_completers) {
218
+ strictKeys(ac, ['path', 'completer'], 'arg_completers');
219
+ bindArgs(findCommand(program, ac.path)!, buildCompleter(ac.completer));
220
+ }
221
+ return program;
222
+ }
223
+
224
+ describe('completion-v1 conformance: requests.json', () => {
225
+ const f = load<{ trees: Record<string, Tree>; cases: RequestCase[] }>('requests.json');
226
+ const roots = new Map(Object.entries(f.trees).map(([n, t]) => [n, buildRoot(t)]));
227
+
228
+ it('every tree has a case', () => {
229
+ const used = new Set(f.cases.map(c => c.tree));
230
+ expect(Object.keys(f.trees).filter(n => !used.has(n))).toEqual([]);
231
+ });
232
+
233
+ for (const [name, reason] of Object.entries(KNOWN_GAPS)) {
234
+ it.skip(`${name} (known gap: ${reason})`, () => {});
235
+ }
236
+
237
+ const cases = f.cases.filter(c => !(c.name in KNOWN_GAPS));
238
+ it.each(cases.map(c => [c.name, c] as const))('%s', async (_n, c) => {
239
+ strictKeys(c, ['name', 'tree', 'args', 'no_desc', 'unordered', 'stdout', 'stderr_contains'], c.name);
240
+ const root = roots.get(c.tree);
241
+ expect(root, `no tree ${c.tree}`).toBeDefined();
242
+ let out = '';
243
+ let err = '';
244
+ await completeRequest(root!, c.args, c.no_desc === true, {
245
+ out: s => { out += s; },
246
+ err: s => { err += s; },
247
+ });
248
+ const got = out.replace(/\n$/, '').split('\n');
249
+ const want = [...c.stdout];
250
+ expect(got.pop()).toBe(want.pop());
251
+ same(got, want, c.unordered === true);
252
+ if (c.stderr_contains) expect(err).toContain(c.stderr_contains);
253
+ });
254
+
255
+ it('known gaps name real cases', () => {
256
+ const names = new Set(f.cases.map(c => c.name));
257
+ expect(Object.keys(KNOWN_GAPS).filter(n => !names.has(n))).toEqual([]);
258
+ });
259
+ });
260
+
261
+ // --- scripts.json ---
262
+
263
+ interface ScriptCase {
264
+ name: string;
265
+ program: string;
266
+ shell: string;
267
+ no_descriptions: boolean;
268
+ golden: string;
269
+ }
270
+
271
+ describe('completion-v1 conformance: scripts.json', () => {
272
+ const f = load<{ cases: ScriptCase[] }>('scripts.json');
273
+ afterEach(() => { vi.restoreAllMocks(); });
274
+
275
+ it('every golden is claimed by a case', () => {
276
+ const goldens = readdirSync(join(CORPUS, 'scripts'))
277
+ .filter(n => n !== 'README.md').map(n => `scripts/${n}`);
278
+ const claimed = new Set(f.cases.map(c => c.golden));
279
+ expect(goldens.filter(g => !claimed.has(g))).toEqual([]);
280
+ });
281
+
282
+ it.each(f.cases.map(c => [c.name, c] as const))('%s', async (_n, c) => {
283
+ strictKeys(c, ['name', 'program', 'shell', 'no_descriptions', 'golden'], c.name);
284
+ const want = readFileSync(join(CORPUS, c.golden), 'utf8');
285
+ const program = new Command(c.program).description('Kit app');
286
+ program.command('sub').description('A subcommand');
287
+ program.addCommand(completionCommand(program));
288
+ let got = '';
289
+ vi.spyOn(process.stdout, 'write').mockImplementation((s: string | Uint8Array) => {
290
+ got += String(s);
291
+ return true;
292
+ });
293
+ const argv = ['completion', c.shell, ...(c.no_descriptions ? ['--no-descriptions'] : [])];
294
+ await program.parseAsync(argv, { from: 'user' });
295
+ vi.restoreAllMocks();
296
+ expect(got).toBe(want);
297
+ });
298
+ });