@hop-top/kit 0.5.0-alpha.3 → 0.5.0-alpha.5

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 (188) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +1 -1
  3. package/README.md +47 -575
  4. package/dist/{aim-CTp-kJW2.d.ts → aim-DZHwwiIc.d.ts} +1 -1
  5. package/dist/aim.d.ts +1 -1
  6. package/dist/aim.js +13 -414
  7. package/dist/{alias-dhhr08Ei.d.ts → alias-BOj0-VAr.d.ts} +1 -1
  8. package/dist/alias.d.ts +1 -1
  9. package/dist/alias.js +18 -206
  10. package/dist/{api-miiso81x.d.ts → api-DAexsu2H.d.ts} +1 -1
  11. package/dist/api.d.ts +1 -1
  12. package/dist/api.js +10 -164
  13. package/dist/auth.js +6 -40
  14. package/dist/chunk-3FIKGFKI.js +54 -0
  15. package/dist/chunk-4UE5TCMQ.js +104 -0
  16. package/dist/chunk-6HFAEZ52.js +29 -0
  17. package/dist/chunk-6SVOHNIC.js +17 -0
  18. package/dist/chunk-72XZWQX7.js +504 -0
  19. package/dist/chunk-ABQSE7AI.js +513 -0
  20. package/dist/chunk-BDNNPRX6.js +41 -0
  21. package/dist/chunk-BRNEKPWX.js +37 -0
  22. package/dist/chunk-CSJWB6D3.js +151 -0
  23. package/dist/chunk-GGWJRWWA.js +309 -0
  24. package/dist/chunk-IQXEISMC.js +142 -0
  25. package/dist/chunk-IXVQ62NZ.js +334 -0
  26. package/dist/chunk-JTMPNXVQ.js +1491 -0
  27. package/dist/chunk-KVG7YCTS.js +115 -0
  28. package/dist/chunk-L23O2FFE.js +51 -0
  29. package/dist/chunk-MQXYDYRD.js +968 -0
  30. package/dist/chunk-MUIQVU6E.js +251 -0
  31. package/dist/chunk-POR5L2DG.js +247 -0
  32. package/dist/chunk-PSFYJGDG.js +1445 -0
  33. package/dist/chunk-QJVSKKRQ.js +369 -0
  34. package/dist/chunk-QPUCXQXT.js +67 -0
  35. package/dist/chunk-R5U7XKVJ.js +16 -0
  36. package/dist/chunk-S45UHXQF.js +182 -0
  37. package/dist/chunk-T46YPHKN.js +669 -0
  38. package/dist/chunk-UKZIAQA7.js +26 -0
  39. package/dist/chunk-WBVO43HU.js +355 -0
  40. package/dist/chunk-WUOAQVOA.js +86 -0
  41. package/dist/chunk-WWUKGJB5.js +90 -0
  42. package/dist/chunk-YGYQUFGY.js +219 -0
  43. package/dist/chunk-YOBAUCVN.js +583 -0
  44. package/dist/chunk-ZC5TZYZJ.js +609 -0
  45. package/dist/{cli-DLygZLi9.d.ts → cli-8rfITnv4.d.ts} +13 -4
  46. package/dist/cli.d.ts +4 -4
  47. package/dist/cli.js +51 -1057
  48. package/dist/{config-BUY7_W2n.d.ts → config-Bm9fBXch.d.ts} +35 -4
  49. package/dist/config.d.ts +1 -1
  50. package/dist/config.js +6 -78
  51. package/dist/errcorrect.js +8 -68
  52. package/dist/{error-DISJKeDu.d.ts → error-Do8Qji43.d.ts} +88 -1
  53. package/dist/id/index.d.ts +1 -1
  54. package/dist/id/index.js +14 -65
  55. package/dist/{index-MLrRDvEG.d.ts → index-B-pqGHhU.d.ts} +113 -19
  56. package/dist/{index-Bc5c7Ty5.d.ts → index-DEyjGoo2.d.ts} +1 -1
  57. package/dist/{index-QSffbLnj.d.ts → index-VLDcI5NF.d.ts} +3 -2
  58. package/dist/index.d.ts +18 -15
  59. package/dist/index.js +39 -6722
  60. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  61. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  62. package/dist/llm-anthropic.d.ts +2 -0
  63. package/dist/llm-anthropic.js +13 -0
  64. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  65. package/dist/llm-openai.d.ts +2 -0
  66. package/dist/llm-openai.js +19 -0
  67. package/dist/llm.d.ts +1 -1
  68. package/dist/llm.js +101 -356
  69. package/dist/mcp/index.d.ts +2 -1
  70. package/dist/mcp/index.js +155 -1453
  71. package/dist/{netpolicy-asvCfwi8.d.ts → netpolicy-Brx5XZUB.d.ts} +16 -3
  72. package/dist/netpolicy.d.ts +1 -1
  73. package/dist/netpolicy.js +25 -118
  74. package/dist/{output-4aXs91GY.d.ts → output-CjZWmL8s.d.ts} +28 -4
  75. package/dist/output.d.ts +2 -2
  76. package/dist/output.js +137 -971
  77. package/dist/progress.js +6 -55
  78. package/dist/provenance.js +6 -31
  79. package/dist/routellm-B0nv59mH.d.ts +111 -0
  80. package/dist/routellm.d.ts +2 -2
  81. package/dist/routellm.js +13 -255
  82. package/dist/{rpc-D5xLEf8V.d.ts → rpc-D31Lg0Kc.d.ts} +1 -1
  83. package/dist/rpc.d.ts +2 -2
  84. package/dist/rpc.js +4 -98
  85. package/dist/safety.js +6 -43
  86. package/dist/scope.js +20 -377
  87. package/dist/{serve-DE-jscpb.d.ts → serve-D8yWMrTc.d.ts} +2 -2
  88. package/dist/serve.d.ts +2 -2
  89. package/dist/serve.js +75 -1019
  90. package/dist/sqlstore.js +6 -39
  91. package/dist/stream.js +8 -51
  92. package/dist/telemetry/index.js +24 -608
  93. package/dist/tui/index.d.ts +5 -5
  94. package/dist/tui/index.js +17 -374
  95. package/dist/upgrade.js +6 -114
  96. package/dist/xdg.js +14 -128
  97. package/package.json +130 -25
  98. package/src/README.md +15 -0
  99. package/src/cli.help-command.test.ts +105 -0
  100. package/src/cli.test.ts +95 -1
  101. package/src/cli.ts +78 -13
  102. package/src/completion-values.test.ts +10 -10
  103. package/src/compliance.test.ts +196 -2
  104. package/src/compliance.ts +440 -20
  105. package/src/config.test.ts +187 -1
  106. package/src/config.ts +173 -7
  107. package/src/gen/crud_pb.ts +7 -7
  108. package/src/id/README.md +38 -0
  109. package/src/id/contract.test.ts +1 -1
  110. package/src/id/index.test.ts +1 -1
  111. package/src/id/index.ts +3 -2
  112. package/src/index.test.ts +12 -0
  113. package/src/index.ts +2 -0
  114. package/src/llm-anthropic.conformance.test.ts +1135 -0
  115. package/src/llm-anthropic.test.ts +152 -0
  116. package/src/llm-anthropic.ts +940 -0
  117. package/src/llm-choice-hermetic.test.ts +335 -0
  118. package/src/llm-config.test.ts +232 -0
  119. package/src/llm-config.ts +106 -0
  120. package/src/llm-endpoint.ts +254 -0
  121. package/src/llm-error.ts +17 -0
  122. package/src/llm-errors.ts +152 -0
  123. package/src/llm-file.ts +126 -0
  124. package/src/llm-http.ts +317 -0
  125. package/src/llm-keys.ts +167 -0
  126. package/src/llm-media.conformance.test.ts +87 -0
  127. package/src/llm-media.test.ts +279 -0
  128. package/src/llm-media.ts +322 -0
  129. package/src/llm-openai.conformance.test.ts +407 -0
  130. package/src/llm-openai.test.ts +510 -0
  131. package/src/llm-openai.ts +708 -0
  132. package/src/llm-payload.ts +155 -0
  133. package/src/llm-quote.ts +46 -0
  134. package/src/llm-routellm.conformance.test.ts +44 -0
  135. package/src/llm-toolnames.conformance.test.ts +112 -0
  136. package/src/llm-toolnames.test.ts +132 -0
  137. package/src/llm-toolnames.ts +298 -0
  138. package/src/llm-uri.ts +99 -0
  139. package/src/llm.test.ts +43 -15
  140. package/src/llm.toolcall.test.ts +175 -0
  141. package/src/llm.ts +602 -190
  142. package/src/mcp/README.md +57 -0
  143. package/src/mcp/conformance.test.ts +24 -3
  144. package/src/mcp/dispatch.ts +4 -4
  145. package/src/mcp/identity.test.ts +166 -0
  146. package/src/mcp/identity.ts +72 -0
  147. package/src/mcp/index.ts +6 -0
  148. package/src/mcp/legacy.ts +21 -8
  149. package/src/mcp/mcp.test.ts +14 -4
  150. package/src/mcp/modern-confirm.ts +1 -1
  151. package/src/mcp/modern.ts +12 -11
  152. package/src/mcp/tasks.ts +1 -1
  153. package/src/mcp/types.ts +80 -8
  154. package/src/netpolicy.test.ts +78 -0
  155. package/src/netpolicy.ts +28 -3
  156. package/src/output/README.md +46 -0
  157. package/src/output/builtins.ts +5 -5
  158. package/src/output/error.ts +144 -1
  159. package/src/output/formatters/README.md +50 -0
  160. package/src/output.ts +24 -1
  161. package/src/published-types.test.ts +115 -0
  162. package/src/routellm.test.ts +209 -28
  163. package/src/routellm.toolcall.test.ts +521 -0
  164. package/src/routellm.ts +213 -177
  165. package/src/router/README.md +44 -0
  166. package/src/router/server.test.ts +41 -0
  167. package/src/router/server.ts +11 -0
  168. package/src/safety.test.ts +19 -9
  169. package/src/scope-defaults.json +29 -29
  170. package/src/serve.ts +1 -1
  171. package/src/telemetry/README.md +48 -0
  172. package/src/telemetry/client.ts +5 -5
  173. package/src/toolspec.test.ts +2 -2
  174. package/src/triton/README.md +34 -0
  175. package/src/tui/README.md +42 -0
  176. package/src/wizard.test.ts +7 -7
  177. package/test/llm/conformance-helpers.ts +100 -0
  178. package/test/output/dispatch.test.ts +1 -2
  179. package/test/output/error.test.ts +33 -2
  180. package/test/output/smoke-capture.ts +2 -2
  181. package/test/output/smoke.test.ts +2 -2
  182. package/test/output/taxonomy-contract.test.ts +148 -0
  183. package/test/setup-env.ts +16 -0
  184. package/tsconfig.json +3 -1
  185. package/tsconfig.test.json +10 -0
  186. package/vitest.config.ts +9 -0
  187. package/dist/llm-B5XUWH8T.d.ts +0 -231
  188. package/dist/routellm-PGSt2D1y.d.ts +0 -75
package/README.md CHANGED
@@ -1,11 +1,10 @@
1
1
  # @hop-top/kit (TypeScript)
2
2
 
3
- Shared CLI utilities for hop-top tools — CommonJS edition.
4
-
5
- Mirrors the Go `kit` package surface: a Commander-based CLI factory,
6
- output formatting with a registry/Formatter contract, theming, hint
7
- plumbing, XDG paths, config files, an embedded SQLite store, upgrade
8
- checks, LLM helpers, alias resolution, and a TUI toolkit.
3
+ Shared CLI utilities for hop-top tools, CommonJS edition. Mirrors the Go
4
+ `kit` package surface: a Commander-based CLI factory, output formatting
5
+ with a registry/Formatter contract, theming, hint plumbing, XDG paths,
6
+ config files, an embedded SQLite store, upgrade checks, LLM helpers,
7
+ alias resolution, and a TUI toolkit.
9
8
 
10
9
  ## Install
11
10
 
@@ -13,596 +12,69 @@ checks, LLM helpers, alias resolution, and a TUI toolkit.
13
12
  pnpm add @hop-top/kit
14
13
  ```
15
14
 
16
- Subpath imports follow the package's `exports` map (see
17
- `package.json`): `@hop-top/kit/cli`, `@hop-top/kit/output`,
18
- `@hop-top/kit/xdg`, `@hop-top/kit/uri`, …
19
-
20
- ## Output formatting
21
-
22
- The `output` module ships a Formatter + Registry contract identical to
23
- the Go `go/console/output` package, plus a Commander integration layer
24
- that wires the standard flag suite onto your program.
25
-
26
- ### Built-in formatters
27
-
28
- | Key | Extensions | Options |
29
- | ------- | -------------- | --------------------------------------------------------------------------------- |
30
- | `json` | `.json` | `indent` (int, default 2) |
31
- | `yaml` | `.yaml`, `.yml`| `flow-level` (int, default -1) |
32
- | `table` | (none) | (none) |
33
- | `csv` | `.csv` | `delimiter` (string), `no-header` (bool), `quote-all` (bool), `crlf` (bool) |
34
- | `text` | `.txt` | `style` (enum kv\|lines\|paragraph), `separator` (string, kv only) |
15
+ Subpath imports follow the package's `exports` map (see `package.json`),
16
+ mirrored in `typesVersions` for `moduleResolution: node10`: `@hop-top/kit/cli`,
17
+ `@hop-top/kit/output`, `@hop-top/kit/xdg`, `@hop-top/kit/uri`, and so on.
35
18
 
36
- ### Wiring into a Commander CLI
19
+ ## Quick start
37
20
 
38
21
  ```ts
39
- import { Command } from 'commander';
22
+ import { createCLI } from '@hop-top/kit/cli';
40
23
  import { registerOutputFlags, dispatch } from '@hop-top/kit/output';
41
24
 
42
- const program = new Command('mytool');
25
+ const { program } = createCLI({
26
+ name: 'mytool', version: '1.0.0', description: 'does things',
27
+ });
43
28
  registerOutputFlags(program);
44
29
 
45
30
  program.command('list').action(async () => {
46
31
  await dispatch(program, [{ id: '1', name: 'Alice' }]);
47
32
  });
48
33
 
49
- program.parseAsync();
50
- ```
51
-
52
- `registerOutputFlags` adds the full suite — opt-out per flag via
53
- `{ disable: { format?, formatOpt?, formatHelp?, cols?, template?, output? } }`.
54
-
55
- ### Flag surface
56
-
57
- - `--format <fmt>` — pick a registered formatter (default `table`).
58
- - `--format-opt <kv...>` — repeatable key=value pairs validated against
59
- the active formatter's option specs (e.g. `--format-opt delimiter=';'`).
60
- Bool keys may omit `=value`.
61
- - `--format-help [fmt]` — without an argument, list every registered
62
- formatter; with an argument, print that formatter's options table.
63
- Short-circuits before render.
64
- - `--cols`, `--columns <cols...>` — restrict output to the named
65
- columns. Accepts comma-separated or repeated flags. Honored by all
66
- five built-ins.
67
- - `--template <tpl>` — eta template applied to results. Mutually
68
- exclusive with `--cols`. Template input shape: `{ items, cols, data }`.
69
- See [eta syntax](https://eta.js.org/docs/intro/syntax) — note the
70
- EJS-style `<%= %>` tags differ from Go's `{{ }}` text/template syntax.
71
- - `-o`, `--output <path>` — write to a file instead of stdout. Empty
72
- string or `-` means stdout. Extension inference: when `--format` is
73
- default and the path's extension matches a registered formatter, that
74
- formatter is selected (e.g. `-o report.csv` → csv). Mismatch is a
75
- hard error (e.g. `--format json -o report.csv`).
76
-
77
- ### Programmatic Formatter API
78
-
79
- ```ts
80
- import {
81
- defaultRegistry,
82
- Registry,
83
- type Formatter,
84
- } from '@hop-top/kit/output';
85
-
86
- // Custom formatter:
87
- const htmlFormatter: Formatter = {
88
- key: 'html',
89
- extensions: ['.html'],
90
- options: [],
91
- render(out, data, _opts, cols) {
92
- // `cols` is the resolved column list, already ordered — render it in
93
- // the order given. Empty means "fall back to payload key order".
94
- // ... render HTML to `out`
95
- },
96
- };
97
-
98
- // Replace a built-in or add a new one:
99
- defaultRegistry.override(htmlFormatter); // or .register() to fail-loud on dup
100
-
101
- // Isolated registry for tests/multi-CLI binaries:
102
- const r = new Registry();
103
- r.register(htmlFormatter);
104
- ```
105
-
106
- ### Column metadata
107
-
108
- Go reads column order off struct field declaration order via `table:""`
109
- tags. TS has no struct tags, so pass an explicit `ColumnSpec[]` list to
110
- `dispatch` to pin **which columns appear and in what order** — the list
111
- is what payload-shaped SDKs use in place of Go's field order:
112
-
113
- ```ts
114
- import type { ColumnSpec } from '@hop-top/kit/output';
115
-
116
- const userCols: ColumnSpec[] = [
117
- { header: 'id', key: 'id', priority: 9 },
118
- { header: 'name', key: 'name', priority: 8 },
119
- { header: 'notes', key: 'notes', priority: 2 },
120
- ];
121
-
122
- await dispatch(cmd, users, { columns: userCols });
123
- ```
124
-
125
- When no `columns` is passed, headers are derived from the first row's
126
- own enumerable keys.
127
-
128
- ### Column ordering
129
-
130
- 1. **Default order.** With a `ColumnSpec[]` and no `--cols`, column order
131
- and headers come from the list, in list order. Payload key order is the
132
- fallback only when no list was supplied.
133
- 2. **`--cols` precedence.** `--cols` reorders as well as selects:
134
- `--cols status,name` renders `status` then `name`, whatever the list
135
- says. Same rule on the no-schema fallback path.
136
- 3. **`header` == `key`.** The two are the same name: it is the label, the
137
- value matched against `--cols`, and the property read off the row. Go
138
- cannot express a split through `table:""` tags, so no SDK offers one.
139
- `key` is retained for source compatibility and must equal `header`.
140
- 4. **Empty payload.** Zero rows emits nothing — not even a bare header
141
- row. Emptiness is decided by row count, never by header count.
142
- 5. **`priority`.** Accepted and stored, currently ignored. Hide-on-overflow
143
- is implemented in Go only; the payload SDKs will port it separately.
144
-
145
- `dispatch` applies rules 1 and 2 before calling `render`, so the `cols`
146
- argument a formatter receives is already the final, ordered column list —
147
- empty only when it should fall back to payload key order. Custom
148
- formatters get correct ordering by rendering `cols` in the order given;
149
- they never see `ColumnSpec` and need no changes.
150
-
151
- Worked example — the same rows under each rule:
152
-
153
- ```ts
154
- const rows = [
155
- { count: 3, status: 'ready', name: 'alpha' },
156
- { count: 8, status: 'held', name: 'beta' },
157
- ];
158
- const cols: ColumnSpec[] = [
159
- { header: 'name', key: 'name', priority: 9 },
160
- { header: 'count', key: 'count', priority: 7 },
161
- { header: 'status', key: 'status', priority: 5 },
162
- ];
163
- ```
164
-
165
- With `columns: cols` and no `--cols`, the list drives order — note the
166
- payload's own key order is `count, status, name` and is not what appears
167
- (rule 1):
168
-
169
- ```
170
- name count status
171
- alpha 3 ready
172
- beta 8 held
173
- ```
174
-
175
- `--cols status,name` reorders as well as selects (rule 2), in `table`
176
- and `json` alike:
177
-
178
- ```
179
- status name
180
- ready alpha
181
- held beta
182
- ```
183
-
184
- ```json
185
- [
186
- {
187
- "status": "ready",
188
- "name": "alpha"
189
- },
190
- {
191
- "status": "held",
192
- "name": "beta"
193
- }
194
- ]
195
- ```
196
-
197
- With no `columns` at all, payload key order is the fallback:
198
-
199
- ```
200
- count status name
201
- 3 ready alpha
202
- 8 held beta
203
- ```
204
-
205
- Capability differences against the Go reference:
206
-
207
- | Capability | Go (reference) | ts / py | rs / php |
208
- |---|---|---|---|
209
- | Column order source | `table:""` tags, declaration order | `ColumnSpec[]` order | `ColumnSpec` list order |
210
- | `priority` hide-on-overflow | implemented | accepted, stored, ignored | accepted, stored, ignored |
211
- | `header != key` | inexpressible via `table:""` | rejected at construction | rejected at construction |
212
- | json/yaml key order | follows the resolved order | follows the resolved order | follows the resolved order |
213
- | `--cols` reorders | yes | yes | yes |
214
- | Built-in formats | `table`, `json`, `yaml`, `csv`, `text` (+ `human`) | same five | `table`, `json`, `yaml` only |
215
- | Ordered columns on the template path | `.Cols` | `cols` | `{*}` (php); none (rs) |
216
-
217
- Go's inability to express `header != key` is the *reason* rule 3 binds
218
- every runtime: no SDK may carry a capability the reference cannot mirror.
219
-
220
- ### Conformance status
221
-
222
- TS satisfies all five rules, as does Go across all five formats. The
223
- fixtures under `sdk/tests/cross-lang/` execute the contract against every
224
- runtime. Two gaps remain open and matter when writing portable code:
225
-
226
- - **`csv` and `text` do not exist in rs or php.** Only `table`, `json`
227
- and `yaml` are available in all five runtimes today. The fixtures
228
- record this as `rs-php-no-csv-text`.
229
- - **rs has no ordered-column affordance on the `--template` path.** Go
230
- exposes `.Cols` and py and ts expose `cols`; php has a `{*}`
231
- placeholder yielding pre-joined values. The spelling for rs is an open
232
- decision.
233
-
234
- The fixtures compare the **column order re-parsed from each runtime's own
235
- output**, never raw bytes — table padding and YAML block style differ
236
- legitimately between runtimes. Byte-level formatting parity is pinned by
237
- each SDK's own unit tests instead. `csv` output agrees byte-for-byte
238
- across go/py/ts in the default LF mode; the `crlf` option exposes known
239
- quoting divergences.
240
-
241
- ### Backward compatibility
242
-
243
- The legacy `render(w, format, v)` signature stays. It is now a thin
244
- shim over `defaultRegistry.lookup(format).render(...)`. Existing
245
- callers do not need to migrate.
246
-
247
- ```ts
248
- import { render, JSON_FORMAT } from '@hop-top/kit/output';
249
- render(process.stdout, JSON_FORMAT, { ok: true });
250
- ```
251
-
252
- ## Other modules
253
-
254
- - `@hop-top/kit/cli` — `createCLI(cfg)` builds a Commander root program
255
- with the hop-top contract: `--format`, `--quiet`, `--no-color`,
256
- `--no-hints`, `--offline`, themed help, version, hidden completion
257
- command.
258
- - `@hop-top/kit/netpolicy` — enforcement behind the `--offline` global.
259
- `createCLI` guards `globalThis.fetch`, so a leaf that never consults
260
- the marker is still refused; loopback stays reachable. Callers that
261
- inject their own transport wrap it with `guardFetch`, and socket-level
262
- clients (`node:net`, SQL drivers, gRPC) consult `isOffline()`
263
- themselves. Match the refusal with `isOfflineError(err)`.
264
- - `@hop-top/kit/id` — TypeID primitive (cross-language; see
265
- [ADR 0001](../../docs/adr/0001-typeid-primitive.md)). Source:
266
- [`src/id/`](src/id/).
267
- - `@hop-top/kit/xdg` — XDG Base Directory paths.
268
- - `@hop-top/kit/config` — config-file loading.
269
- - `@hop-top/kit/sqlstore` — embedded SQLite key/value store.
270
- - `@hop-top/kit/upgrade` — semver upgrade detection.
271
- - `@hop-top/kit/llm` / `routellm` — LLM client + routing helpers.
272
- - `@hop-top/kit/alias` — alias resolution + completion.
273
- - `@hop-top/kit/uri` — thin facade over `@hop-top/cite` for URI parsing,
274
- action resolution, completions, registries, and OS handler metadata.
275
- - `@hop-top/kit/tui` — TUI toolkit (parity, anim, prompts).
276
- - `@hop-top/kit/mcp` — dual-spec MCP surface (see [MCP surface](#mcp-surface)).
277
- - `@hop-top/kit/serve` — the serve hierarchy and service lifecycle (see
278
- [Serve](#serve)).
279
-
280
- See package.json `exports` for the full list.
281
-
282
- ## Serve
283
-
284
- `<tool> serve` supervises every configured and enabled service;
285
- `<tool> serve <service>` selects exactly one. Both forms share one
286
- lifecycle, so a service started by the selector observes the same
287
- readiness, shutdown, and exit semantics as the same service started by
288
- the supervisor.
289
-
290
- The normative contract is
291
- [`docs/contracts/serve-lifecycle.md`](../../docs/contracts/serve-lifecycle.md);
292
- this module implements the part of it §"Cross-language parity" makes
293
- binding on every SDK. Go is the reference implementation.
294
-
295
- ```ts
296
- import { createCLI } from '@hop-top/kit/cli';
297
- import { ServiceRegistry, registerServe } from '@hop-top/kit/serve';
298
-
299
- const registry = new ServiceRegistry();
300
- registry.register({
301
- name: 'api',
302
- async start(signal, ready) {
303
- // Report ready once every acquisition that can fail has succeeded.
304
- ready();
305
- await new Promise<void>((r) =>
306
- signal.addEventListener('abort', () => r(), { once: true }));
307
- },
308
- ready: () => true,
309
- async stop() { /* drain, then release */ },
310
- });
311
-
312
- const { program } = createCLI({
313
- name: 'mytool', version: '1.0.0', description: 'My tool',
314
- });
315
- registerServe(program, { registry, configs: { api: { enabled: true } } });
316
34
  program.parse();
317
35
  ```
318
36
 
319
- ### The override rule
320
-
321
- `serve <service>` starts the named service **even when
322
- `services.<name>.enabled` is false**, provided it is registered and its
323
- configuration and policy validate. Enablement answers "does the
324
- supervisor start this by default"; it is not an authorization decision,
325
- and an operator naming a service has already made the decision the flag
326
- exists to automate.
37
+ `createCLI` gives the root the hop-top contract: `--format`, `--quiet`,
38
+ `--no-color`, `--no-hints`, `--offline`, themed help, version, and a
39
+ hidden completion command.
327
40
 
328
- Under the supervisor form a disabled service is skipped silently and
329
- does not affect the exit code. A supervisor invocation that resolves to
330
- zero services exits 2 rather than 0: a process that exits 0 without
331
- listening is indistinguishable from a successful start to systemd or a
332
- container runtime.
41
+ ## Modules
333
42
 
334
- ### Configuration
43
+ | Path | What it is | Start here when |
44
+ |------|------------|-----------------|
45
+ | [`src/output/`](src/output/README.md) | formatter registry and the Commander flag suite | a command renders one payload as table, json, yaml, csv or text |
46
+ | [`src/mcp/`](src/mcp/README.md) | dual-spec MCP surface over a bridged command tree | MCP clients must call your commands as tools |
47
+ | [`src/telemetry/`](src/telemetry/README.md) | consent-gated usage events, redaction, sinks | you record usage under user consent |
48
+ | [`src/id/`](src/id/README.md) | TypeID primitive | you mint or parse prefixed identifiers |
49
+ | [`src/tui/`](src/tui/README.md) | TUI toolkit (parity, anim, prompts) | you build an interactive terminal surface |
50
+ | [`src/router/`](src/router/README.md) | RouteLLM strong/weak model routing and its Hono handler | a prompt must pick a model in-process |
51
+ | [`src/triton/`](src/triton/README.md) | Triton Inference Server client, KServe v2 over HTTP | you call a model hosted on Triton |
335
52
 
336
- | Key | Type | Default |
337
- |-----|------|---------|
338
- | `services.<name>.enabled` | bool | `false` |
339
- | `services.<name>.ready_timeout` | duration | `30s` |
340
- | `services.<name>.stop_timeout` | duration | `30s` |
341
- | `services.failure_policy` | `fail-fast` \| `isolate` | `fail-fast` |
342
- | `services.shutdown_timeout` | duration | `60s` |
343
-
344
- `registerServe` takes the resolved blocks as `configs`; this port does
345
- not resolve dotted keys itself, because `@hop-top/kit/config` merges
346
- whole documents rather than resolving per key. The contract requires the
347
- key *names*, not a particular resolution engine.
348
-
349
- ### Exit codes
350
-
351
- | Situation | Code | Exit |
352
- |-----------|------|------|
353
- | Clean stop after a signal | `OK` | 0 |
354
- | Invalid selection, invalid config, zero services | `USAGE` | 2 |
355
- | Unknown service name | `NOT_FOUND` | 3 |
356
- | Policy denied | `UNAUTHORIZED` | 5 |
357
- | Start failure, runtime crash, shutdown budget exceeded | `GENERIC` | 1 |
358
-
359
- ### Lifecycle events
360
-
361
- Six transitions are surfaced, on the bus when a `publisher` is wired and
362
- through the `logger` either way:
363
- `kit.serve.service.{started,ready_reported,failed,stopped}` and
364
- `kit.serve.supervisor.{ready_reported,stopped}`. The service identifier
365
- travels in the payload, never in the topic, so a subscriber is not
366
- forced to re-bind when a tool gains a service.
367
-
368
- ### What this port does not do
369
-
370
- The contract rules these out as Go-only; they are absent here by design,
371
- not unimplemented: the REST/OpenAPI projection of the command tree, the
372
- Unix socket service, `cmdreflect`-driven discovery, and the permission,
373
- provenance, and audit surface. This SDK ships no HTTP or socket server,
374
- so a service that listens is the adopter's to write.
375
-
376
- ## MCP surface
377
-
378
- Serves the Model Context Protocol over a bridged command tree, one MCP
379
- tool per runnable leaf. A single mount answers **both** revisions —
380
- `2024-11-05` (handshake) and `2026-07-28` (stateless per-request
381
- envelope) — choosing per request, because the newer revision has no
382
- handshake to negotiate with.
383
-
384
- Wire behaviour is pinned by the shared cross-language fixtures in
385
- `sdk/tests/cross-lang/fixtures/mcp-wire.json`, compared as raw bytes.
386
-
387
- ### Use the v2 scoped packages
388
-
389
- The protocol layer comes from `@modelcontextprotocol/core` and
390
- `@modelcontextprotocol/server`, both pinned at `2.0.0`. They are already
391
- dependencies of this package.
392
-
393
- **`@modelcontextprotocol/sdk` — the v1 package — is deliberately not a
394
- dependency.** It is legacy-era only: its `LATEST_PROTOCOL_VERSION` is
395
- `2025-11-25`, and `2026-07-28` appears nowhere in it. It cannot serve
396
- the modern era. It is also the name every search result reaches for, so
397
- it is the most likely mistake here — code that imports it passes the
398
- legacy fixtures and fails every modern one.
399
-
400
- ### Hosting: a framework-free handler
401
-
402
- `createMcpHandler` returns a plain async function, not a server. kit
403
- does not own your HTTP stack, and a pure request-to-response function is
404
- testable against the fixtures with no socket open.
405
-
406
- ```ts
407
- import { createMcpHandler, commanderBridge } from '@hop-top/kit/mcp';
408
-
409
- const bridge = commanderBridge(rootCommand, {
410
- run: async (inv, cmd) => ({ stdout: await execute(cmd, inv.flags), exitCode: 0 }),
411
- });
412
-
413
- const handler = createMcpHandler(bridge, {
414
- serverInfo: { name: 'my-cli', version: '1.4.0' },
415
- });
416
-
417
- const res = await handler({ method: 'POST', headers, body });
418
- // res: { status, headers, body }
419
- ```
420
-
421
- `commanderBridge` requires a `run` callback — kit does not dictate how a
422
- command's output is captured. Bind the handler to node:http, hono,
423
- express, fastify, or a Worker.
424
-
425
- ### Options
426
-
427
- `path` (`/mcp`), `serverInfo` (`cmdsurface` / `0.0.0`), `specVersions`
428
- (both eras), `cacheHints` (`ttlMs` 0, `cacheScope` `private`),
429
- `originAllowlist` (empty, no check), `confirmationKey`, and `policy`
430
- (`defaultPolicy()`). The option *set* is normative across every kit SDK;
431
- only the spelling is idiomatic.
432
-
433
- An explicitly empty `specVersions`, a negative ttl, an unrecognized
434
- cache scope, or an empty confirmation key all throw at mount time rather
435
- than starting a server that quietly serves nothing.
436
-
437
- ### Safety
438
-
439
- Exposure is gated by `policyAllowed(policy, cls, surface)`. The default
440
- is deliberately closed: **no remote surface may invoke a destructive
441
- leaf** — `defaultPolicy()` leaves `allowDestructiveOn` empty, and empty
442
- means block-all. A blocked call returns an `isError` result at HTTP 200,
443
- not a transport error: the call was understood and declined, not
444
- malformed.
445
-
446
- ```ts
447
- const policy = { allowDestructiveOn: ['mcp'], defaultEnabled: ['cli', 'lib', 'mcp'] };
448
- ```
449
-
450
- Leaves are classified from `kit/*` annotations: `kit/side-effect`
451
- (`destructive`, `destructive-local`, `destructive-shared`),
452
- `kit/auth-required`, `kit/requires-confirmation`.
453
-
454
- This gate is unrelated to the Factor 10 `safetyGuard` `--force` helper,
455
- which is a CLI-time TTY check for delegation safety.
456
-
457
- ### Confirmation is header-only in this port
458
-
459
- A `kit/requires-confirmation` leaf requires an `X-Confirm-Token` header.
460
- `confirmationKey` is accepted and validated at mount time but **the
461
- modern handler does not read it** — the MRTR elicitation round-trip that
462
- Go, Python, Rust and PHP offer is not implemented here yet. Do not plan
463
- an elicitation flow against this port today.
464
-
465
- ### Scope
466
-
467
- Deprecated upstream features (Roots, Sampling, Logging, HTTP+SSE) are
468
- unimplemented, matching the Go reference. `tasks/*` answers `-32601` and
469
- no `extensions` map is advertised in `server/discover`, which is the
470
- conformant way to not support it.
471
-
472
- ### Cross-references
473
-
474
- - [Serve MCP from any SDK](../../docs/adopters/guides/serve-mcp-from-any-sdk.md)
475
- — the polyglot adopter guide
476
- - [Expose your CLI over MCP](../../docs/adopters/guides/expose-cli-over-mcp.md)
477
- — the Go reference surface, in depth
478
-
479
- ## URI facade
480
-
481
- The URI module delegates to `@hop-top/cite` (`^0.1.0`); it does not
482
- reimplement the URI contract. It mirrors the kit Go URI command intent
483
- for SDK consumers:
484
-
485
- ```ts
486
- import { parse, resolve, complete, handler, newRegistry } from '@hop-top/kit/uri';
487
-
488
- const policy = {
489
- schemeNamespaceSegments: { tlc: 2 },
490
- actionRoutes: {
491
- 'task.claim': {
492
- command: 'tlc',
493
- args: ['-C', '{namespace}', 'task', 'claim', '{id}'],
494
- },
495
- },
496
- };
497
-
498
- const parsed = parse('tlc://hop-top/kit/T-0001?cmd=task&verb=claim', policy);
499
- const plan = resolve(parsed, policy); // command plan only; never executes
500
-
501
- const registry = newRegistry(policy);
502
- registry.register({ name: 'tlc', completer: async () => ['hop-top/kit/T-0001'] });
503
- const suggestions = await complete(registry, 'tlc', 'tlc://T-');
504
-
505
- const id = handler.id({
506
- vendor: 'hop-top',
507
- app: 'tlc',
508
- language: 'ts',
509
- scheme: 'tlc',
510
- appPath: '/usr/local/bin/tlc',
511
- });
512
- ```
513
-
514
- ## Telemetry
515
-
516
- `@hop-top/kit/telemetry` ships the SDK-side primitives for the kit
517
- telemetry contract: a non-blocking `Client`, a best-effort PII /
518
- secret redactor, and the consent + install-id readers needed to gate
519
- emission.
520
-
521
- **Default-denied**: a fresh install never emits. The `Client.record()`
522
- call is a no-op unless the operator has run `kit consent grant` AND a
523
- mode is selected via `KIT_TELEMETRY_MODE=anon|full` (or the prefixed
524
- `<APP>_TELEMETRY_MODE` equivalent). Inspect what would ship with `kit
525
- telemetry inspect`.
526
-
527
- ```ts
528
- import { Client } from '@hop-top/kit/telemetry';
529
-
530
- const client = new Client({
531
- sink: 'jsonl', // or 'https'
532
- sinkFile: '/tmp/kit-events.jsonl', // jsonl sink only
533
- endpoint: 'https://telemetry.example', // https sink only
534
- sdkVersion: '1.2.3',
535
- });
536
-
537
- // Fire-and-forget. Returns synchronously; never throws.
538
- client.record('cmd.invoked', { command: 'launch', exit_code: 0 });
539
-
540
- // Best-effort drain on process exit.
541
- await client.shutdown(5_000);
542
- ```
543
-
544
- ### Configuration
545
-
546
- All `ClientOptions` fields are mirrored by env vars (env wins when the
547
- option is omitted):
548
-
549
- | Field | Env var | Default |
550
- | ----------- | ----------------------------- | ---------------------------------------------------- |
551
- | `endpoint` | `KIT_TELEMETRY_ENDPOINT` | — |
552
- | `sink` | `KIT_TELEMETRY_SINK` | `jsonl` |
553
- | `sinkFile` | `KIT_TELEMETRY_SINK_FILE` | `$XDG_STATE_HOME/kit/telemetry/events.jsonl` |
554
- | `queueSize` | `KIT_TELEMETRY_QUEUE_SIZE` | `1024` |
555
-
556
- ### Redactor
557
-
558
- The default `redact()` pass scrubs emails, IPv4 / IPv6 addresses, `sk-`
559
- / `gh[pousr]_` / `xoxb-` token prefixes, and `$HOME` path prefixes
560
- before the envelope hits a sink. Placeholders (`<redacted:email>`,
561
- `<redacted:ipv4>`, `<redacted:ipv6>`, `<redacted:token>`) are
562
- byte-parity with the py / rs / php SDKs so the cross-language contract
563
- harness can diff outputs.
564
-
565
- ```ts
566
- import { redact, redactString } from '@hop-top/kit/telemetry';
567
-
568
- redactString('user@example.com from 10.0.0.1'); // → '<redacted:email> from <redacted:ipv4>'
569
- redact({ ip: '8.8.8.8', count: 3 }); // → { ip: '<redacted:ipv4>', count: 3 }
570
- ```
571
-
572
- A per-`Client` `redactor` callback runs BEFORE the default pass — use
573
- it for adopter-specific allowlists or stricter rules. Throwing
574
- callbacks are isolated (the event still goes through the default
575
- pass).
576
-
577
- ### Envelope
578
-
579
- Each emitted event is one NDJSON line with the shape:
580
-
581
- ```json
582
- {
583
- "schema_version": "1",
584
- "sdk_lang": "ts",
585
- "sdk_version": "0.4.0",
586
- "installation_id": "<64-char hex sha256>",
587
- "mode": "anon",
588
- "occurred_at": "2026-05-19T12:00:00.000Z",
589
- "event": "cmd.invoked",
590
- "attrs": { "command": "launch", "exit_code": 0 }
591
- }
592
- ```
53
+ Non-directory subpaths: `cli` (CLI factory), `serve` (serve hierarchy
54
+ and service lifecycle), `netpolicy` (`--offline` enforcement, guards
55
+ `globalThis.fetch`), `xdg` (base directory paths), `config`
56
+ (config-file loading), `sqlstore` (embedded SQLite key/value store),
57
+ `upgrade` (semver upgrade detection), `llm`, `anthropic`, `openai`,
58
+ `routellm`, `alias`, `uri` (facade over `@hop-top/cite`), `api`,
59
+ `rpc`, `aim`, `scope`, `safety`, `provenance`, `stream`, `progress`,
60
+ `auth`, `errcorrect`. See `package.json` `exports` for the full list.
593
61
 
594
- The `event` + `attrs` extension is the TS / Py divergence from Go's
595
- canonical envelope (Go pins a typed `Event` struct). See
596
- `sdk/docs/telemetry-event-schema.md` for the cross-language contract.
62
+ ## Contract
597
63
 
598
- ### Cross-SDK contract harness
64
+ - Five built-in formatters (`json`, `yaml`, `table`, `csv`, `text`), the same set every kit SDK ships.
65
+ - Column order comes from an explicit `ColumnSpec[]`; `--cols` reorders as well as selects; `header` must equal `key`.
66
+ - `serve <service>` starts a named service even when `services.<name>.enabled` is false; a supervisor run resolving to zero services exits 2.
67
+ - MCP exposure is default-closed: `defaultPolicy()` blocks every destructive leaf on every remote surface.
68
+ - Telemetry is default-denied: `Client.record()` is a no-op without both a granted consent decision and a non-`off` mode.
599
69
 
600
- The harness at `hops/main/sdk/tests/cross-lang/` (planned in T-0709)
601
- diffs envelopes across SDKs. As of this revision the harness is not
602
- landed; TS-side wiring is deferred until the directory exists.
70
+ ## See also
603
71
 
604
- ## License
72
+ - [TypeScript API reference](https://github.com/hop-top/poly-kit/blob/main/docs/adopters/reference/ts-api-reference.md):
73
+ every module in depth, output formatting rules and worked examples,
74
+ serve lifecycle, the MCP surface, the URI facade, telemetry envelope
75
+ and redactor, LLM adapters and tool calling (`toolCalls` / `toolCallId`)
76
+ - [Serve MCP from any SDK](https://github.com/hop-top/poly-kit/blob/main/docs/adopters/guides/serve-mcp-from-any-sdk.md), [serve lifecycle contract](https://github.com/hop-top/poly-kit/blob/main/docs/contracts/serve-lifecycle.md), [CLI parity guide](https://github.com/hop-top/poly-kit/blob/main/docs/adopters/guides/cli-parity-guide.md)
605
77
 
606
78
  MIT.
607
79
 
608
- <!-- release: track @hop-top/cite ^0.1.0 -->
80
+ <!-- release: track @hop-top/cite ^0.1.2 -->
@@ -136,4 +136,4 @@ declare namespace aim {
136
136
  export { aim_Cache as Cache, type aim_CacheOptions as CacheOptions, type aim_Cost as Cost, type aim_ETagSource as ETagSource, type aim_Filter as Filter, type aim_Limit as Limit, type aim_Modalities as Modalities, type aim_Model as Model, aim_ModelsDevSource as ModelsDevSource, type aim_ModelsDevSourceOptions as ModelsDevSourceOptions, type aim_Provider as Provider, aim_Registry as Registry, type aim_RegistryOptions as RegistryOptions, type aim_Source as Source, aim_normalize as normalize, aim_parseQuery as parseQuery };
137
137
  }
138
138
 
139
- export { Cache as C, type ETagSource as E, type Filter as F, type Limit as L, type Modalities as M, type Provider as P, Registry as R, type Source as S, type CacheOptions as a, type Cost as b, type Model as c, ModelsDevSource as d, type ModelsDevSourceOptions as e, type RegistryOptions as f, aim as g, normalize as n, parseQuery as p };
139
+ export { Cache as C, type ETagSource as E, type Filter as F, type Limit as L, type Modalities as M, type Provider as P, Registry as R, type Source as S, aim as a, type CacheOptions as b, type Cost as c, type Model as d, ModelsDevSource as e, type ModelsDevSourceOptions as f, type RegistryOptions as g, normalize as n, parseQuery as p };
package/dist/aim.d.ts CHANGED
@@ -1 +1 @@
1
- export { C as Cache, a as CacheOptions, b as Cost, E as ETagSource, F as Filter, L as Limit, M as Modalities, c as Model, d as ModelsDevSource, e as ModelsDevSourceOptions, P as Provider, R as Registry, f as RegistryOptions, S as Source, n as normalize, p as parseQuery } from './aim-CTp-kJW2.js';
1
+ export { C as Cache, b as CacheOptions, c as Cost, E as ETagSource, F as Filter, L as Limit, M as Modalities, d as Model, e as ModelsDevSource, f as ModelsDevSourceOptions, P as Provider, R as Registry, g as RegistryOptions, S as Source, n as normalize, p as parseQuery } from './aim-DZHwwiIc.js';