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

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 (107) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +333 -9
  3. package/dist/aim-CTp-kJW2.d.ts +139 -0
  4. package/dist/aim.d.ts +1 -116
  5. package/dist/alias-dhhr08Ei.d.ts +88 -0
  6. package/dist/alias.d.ts +2 -73
  7. package/dist/api-miiso81x.d.ts +77 -0
  8. package/dist/api.d.ts +1 -62
  9. package/dist/auth-2-jfgiHn.d.ts +34 -0
  10. package/dist/auth.d.ts +1 -26
  11. package/dist/cli-DLygZLi9.d.ts +450 -0
  12. package/dist/cli.d.ts +6 -309
  13. package/dist/cli.js +192 -63
  14. package/dist/config-BUY7_W2n.d.ts +103 -0
  15. package/dist/config.d.ts +1 -97
  16. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  17. package/dist/errcorrect.d.ts +1 -37
  18. package/dist/error-DISJKeDu.d.ts +144 -0
  19. package/dist/id/index.d.ts +2 -83
  20. package/dist/index-Bc5c7Ty5.d.ts +328 -0
  21. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  22. package/dist/index-MLrRDvEG.d.ts +1073 -0
  23. package/dist/index-QSffbLnj.d.ts +94 -0
  24. package/dist/index.d.ts +28 -0
  25. package/dist/index.js +6794 -0
  26. package/dist/llm-B5XUWH8T.d.ts +231 -0
  27. package/dist/llm.d.ts +1 -188
  28. package/dist/mcp/index.d.ts +2 -0
  29. package/dist/mcp/index.js +1453 -0
  30. package/dist/netpolicy-asvCfwi8.d.ts +138 -0
  31. package/dist/netpolicy.d.ts +1 -0
  32. package/dist/netpolicy.js +118 -0
  33. package/dist/output-4aXs91GY.d.ts +396 -0
  34. package/dist/output.d.ts +3 -213
  35. package/dist/output.js +567 -43
  36. package/dist/progress-CAzyxeWl.d.ts +38 -0
  37. package/dist/progress.d.ts +1 -30
  38. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  39. package/dist/provenance.d.ts +1 -24
  40. package/dist/routellm-PGSt2D1y.d.ts +75 -0
  41. package/dist/routellm.d.ts +2 -64
  42. package/dist/rpc-D5xLEf8V.d.ts +32 -0
  43. package/dist/rpc.d.ts +2 -25
  44. package/dist/safety-CUaYEjZc.d.ts +30 -0
  45. package/dist/safety.d.ts +1 -24
  46. package/dist/scope-BrhYB4ij.d.ts +141 -0
  47. package/dist/scope.d.ts +1 -121
  48. package/dist/serve-DE-jscpb.d.ts +646 -0
  49. package/dist/serve.d.ts +3 -0
  50. package/dist/serve.js +1019 -0
  51. package/dist/stream-CrjeCp0M.d.ts +44 -0
  52. package/dist/stream.d.ts +1 -35
  53. package/dist/telemetry/index.d.ts +1 -315
  54. package/dist/telemetry/index.js +12 -1
  55. package/dist/tui/index.d.ts +5 -298
  56. package/dist/tui/index.js +3 -10
  57. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  58. package/dist/upgrade.d.ts +1 -95
  59. package/dist/xdg-DB7Shoib.d.ts +179 -0
  60. package/dist/xdg.d.ts +1 -169
  61. package/package.json +26 -3
  62. package/src/cli.offline.test.ts +93 -0
  63. package/src/cli.parity.test.ts +192 -0
  64. package/src/cli.ts +112 -12
  65. package/src/index.test.ts +58 -0
  66. package/src/index.ts +37 -0
  67. package/src/log.parity.test.ts +105 -0
  68. package/src/log.ts +64 -13
  69. package/src/mcp/bridge.test.ts +150 -0
  70. package/src/mcp/bridge.ts +246 -0
  71. package/src/mcp/conformance.test.ts +336 -0
  72. package/src/mcp/dispatch.ts +313 -0
  73. package/src/mcp/index.ts +138 -0
  74. package/src/mcp/legacy.ts +314 -0
  75. package/src/mcp/mcp.test.ts +697 -0
  76. package/src/mcp/modern-confirm.test.ts +520 -0
  77. package/src/mcp/modern-confirm.ts +452 -0
  78. package/src/mcp/modern.ts +723 -0
  79. package/src/mcp/tasks.ts +82 -0
  80. package/src/mcp/testtree.ts +250 -0
  81. package/src/mcp/types.ts +504 -0
  82. package/src/netpolicy.test.ts +202 -0
  83. package/src/netpolicy.ts +231 -0
  84. package/src/output/dispatch.ts +10 -2
  85. package/src/output/error.ts +316 -0
  86. package/src/output/formatter.ts +29 -5
  87. package/src/output/formatters/csv.ts +48 -12
  88. package/src/output/formatters/json.ts +4 -25
  89. package/src/output/formatters/project.ts +34 -0
  90. package/src/output/formatters/table.ts +8 -6
  91. package/src/output/formatters/text.ts +7 -3
  92. package/src/output/formatters/yaml.ts +5 -22
  93. package/src/output/projection.test.ts +298 -0
  94. package/src/output/projection.ts +33 -59
  95. package/src/output/template.ts +11 -21
  96. package/src/output.surface.test.ts +41 -0
  97. package/src/output.ts +41 -3
  98. package/src/serve.test.ts +1257 -0
  99. package/src/serve.ts +1665 -0
  100. package/src/telemetry/client.test.ts +31 -0
  101. package/src/telemetry/client.ts +7 -1
  102. package/src/telemetry/offline.test.ts +64 -0
  103. package/src/tui/parity.test.ts +120 -31
  104. package/src/tui/parity.ts +58 -7
  105. package/test/output/csv.test.ts +164 -0
  106. package/test/output/error.test.ts +246 -0
  107. package/src/tui/parity.json +0 -74
package/CHANGELOG.md CHANGED
@@ -4,6 +4,113 @@ All notable changes to `@hop-top/kit` are documented in this file.
4
4
  Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
5
5
  versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.5.0-alpha.3](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.5.0-alpha.2...kit-ts/v0.5.0-alpha.3) (2026-09-05)
8
+
9
+ The hop-top team is happy to announce Kit's TS SDK 0.5.0-alpha.3. This release includes new features and bug fixes.
10
+
11
+
12
+ ### Features
13
+
14
+ * **sdk:** EXIT_GENERIC and generic error constructor in all SDKs
15
+ * **ts:** EXIT_GENERIC and genericError for the exit-1 class
16
+ * **ts:** serve --enable/--disable and timeout flags
17
+ * **ts:** serve cross-language contract and TypeScript implementation
18
+ * **ts:** serve hierarchy and service lifecycle
19
+
20
+
21
+ ### Bug Fixes
22
+
23
+ * **parity:** record and implement serve --enable/--disable and timeout flags
24
+
25
+ Full diff: [kit-ts/v0.5.0-alpha.2...kit-ts/v0.5.0-alpha.3](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.5.0-alpha.2...kit-ts/v0.5.0-alpha.3)
26
+
27
+ ## [0.5.0-alpha.2](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.5.0-alpha.1...kit-ts/v0.5.0-alpha.2) (2026-09-04)
28
+
29
+ The hop-top team is happy to announce Kit's TS SDK 0.5.0-alpha.2. This release includes new features and bug fixes.
30
+
31
+
32
+ ### ⚠ BREAKING CHANGES
33
+
34
+ * **ai/llm:** `Request.Temperature` type changes from `float64` to `*float64`. Callers setting a literal must pass a pointer; zero-value construction (unset) keeps behaving as before via nil.
35
+
36
+ ### Features
37
+
38
+ * merge offline-transport
39
+ * merge offline-transport
40
+ * **sdk/ts:** add structured error envelope with transience class
41
+ * **ts/mcp:** implement MRTR confirmation loop on the modern surface
42
+ * **ts:** enforce --offline at the fetch layer
43
+ * **ts:** serve dual-spec MCP surface
44
+
45
+
46
+ ### Bug Fixes
47
+
48
+ * **ai/llm:** send explicit zero temperature on the wire
49
+ * **output:** collapse header/key split, let --cols reorder
50
+ * **output:** emit valid csv from ts in crlf mode
51
+ * **output:** reach projection helpers from every render
52
+ * **parity:** load verbosity/streams blocks, drop decorative table block
53
+ * **ts:** exempt telemetry from `--offline`
54
+ * **ts:** re-export registerOutputFlags + dispatch from output subpath
55
+ * **ts:** ship root index entry so bare package import resolves
56
+
57
+ Full diff: [kit-ts/v0.5.0-alpha.1...kit-ts/v0.5.0-alpha.2](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.5.0-alpha.1...kit-ts/v0.5.0-alpha.2)
58
+
59
+ ## [Unreleased]
60
+
61
+ ### Changed
62
+
63
+ - **Output column ordering is now driven by the `ColumnSpec[]` list.** The
64
+ projection helpers already implemented the rule but were unreachable from a
65
+ render: `options.columns` was consumed by `--cols` validation and then
66
+ dropped, while the built-in formatters derived headers from
67
+ `Object.keys(rows[0])`. The list now supplies the default column order, the
68
+ header labels, and the column selection. **User-visible:** callers passing a
69
+ `columns` list whose order differs from their payload's key order will see
70
+ columns reorder, and payload keys absent from the schema stop being emitted.
71
+ Anyone parsing column positions or diffing `--format json` output sees
72
+ different bytes. Precedence is `--cols` (user order always wins; it reorders
73
+ as well as selects), else `ColumnSpec` order, else payload key order.
74
+ - `Formatter.render` is **unchanged**. `resolveEffectiveCols` collapses
75
+ `--cols` and the `ColumnSpec` list into one ordered list once, at the
76
+ dispatch layer, and passes it through the existing `cols` argument — so
77
+ third-party formatters keep working and pick up correct ordering with no
78
+ code change. The collapse is sound only because `header === key`.
79
+ - **`header` must equal `key`.** The two name the same column: the label, the
80
+ value matched against `--cols`, and the property read off the row. Go cannot
81
+ express a header/key split through its `table:""` struct tags, so no SDK
82
+ may. `key` is retained for source compatibility and must equal `header`.
83
+ `priority` is still accepted and stored but remains ignored outside Go.
84
+
85
+ ### Removed
86
+
87
+ - `filterColumns` and `buildHeaderToKey`. Under `header === key` the latter
88
+ was an identity map and `projectRows`' `out[c.header] = r[c.key]` an
89
+ identity mapping; `filterColumns` became unreachable once dispatch passes
90
+ the resolved column list verbatim. Unknown-`--cols` rejection was never
91
+ lost — it lives in `validateCols`.
92
+
93
+ ### Known limitations
94
+
95
+ - `csv` and `text` formatters are not implemented in the Rust and PHP SDKs.
96
+ Only `table`, `json` and `yaml` are portable across all five kit runtimes.
97
+
98
+ ### Fixed
99
+
100
+ - **CSV no longer emits structurally invalid output in `crlf` mode.** A field
101
+ containing an embedded LF was written UNQUOTED, so a single record decoded
102
+ as two records (three under some readers). This was data corruption, not a
103
+ quoting preference. Encoding is now hand-rolled instead of delegated to
104
+ csv-stringify, which produced that output in its `windows`
105
+ record-delimiter mode.
106
+ - **A field beginning with whitespace is now quoted**, matching the other
107
+ SDKs; it was previously emitted bare. A field equal to `\.` is quoted too,
108
+ since that sequence alone on a line terminates a PostgreSQL `COPY` stream.
109
+ - A quoted field's bytes are preserved verbatim in both line-ending modes and
110
+ both quoting paths; `crlf` changes the record terminator and nothing else.
111
+ RFC 4180 lists `CR` and `LF` as separate alternatives inside the `escaped`
112
+ production, so a bare CR between quotes is legal.
113
+
7
114
  ## [0.5.0-alpha.1](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.5.0-alpha.0...kit-ts/v0.5.0-alpha.1) (2026-07-14)
8
115
 
9
116
  The hop-top team is happy to announce Kit's TS SDK 0.5.0-alpha.1. This release includes maintenance release with bug fixes.
package/README.md CHANGED
@@ -89,6 +89,8 @@ const htmlFormatter: Formatter = {
89
89
  extensions: ['.html'],
90
90
  options: [],
91
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".
92
94
  // ... render HTML to `out`
93
95
  },
94
96
  };
@@ -103,17 +105,18 @@ r.register(htmlFormatter);
103
105
 
104
106
  ### Column metadata
105
107
 
106
- TS lacks struct tags; pass an explicit `ColumnSpec[]` list to `dispatch`
107
- when you want headers/keys to differ or want priority ordering for
108
- table layout:
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:
109
112
 
110
113
  ```ts
111
114
  import type { ColumnSpec } from '@hop-top/kit/output';
112
115
 
113
116
  const userCols: ColumnSpec[] = [
114
- { header: 'ID', key: 'id', priority: 9 },
115
- { header: 'Name', key: 'name', priority: 8 },
116
- { header: 'Notes', key: 'notes', priority: 2 },
117
+ { header: 'id', key: 'id', priority: 9 },
118
+ { header: 'name', key: 'name', priority: 8 },
119
+ { header: 'notes', key: 'notes', priority: 2 },
117
120
  ];
118
121
 
119
122
  await dispatch(cmd, users, { columns: userCols });
@@ -122,6 +125,119 @@ await dispatch(cmd, users, { columns: userCols });
122
125
  When no `columns` is passed, headers are derived from the first row's
123
126
  own enumerable keys.
124
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
+
125
241
  ### Backward compatibility
126
242
 
127
243
  The legacy `render(w, format, v)` signature stays. It is now a thin
@@ -137,7 +253,14 @@ render(process.stdout, JSON_FORMAT, { ok: true });
137
253
 
138
254
  - `@hop-top/kit/cli` — `createCLI(cfg)` builds a Commander root program
139
255
  with the hop-top contract: `--format`, `--quiet`, `--no-color`,
140
- `--no-hints`, themed help, version, hidden completion command.
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)`.
141
264
  - `@hop-top/kit/id` — TypeID primitive (cross-language; see
142
265
  [ADR 0001](../../docs/adr/0001-typeid-primitive.md)). Source:
143
266
  [`src/id/`](src/id/).
@@ -150,13 +273,214 @@ render(process.stdout, JSON_FORMAT, { ok: true });
150
273
  - `@hop-top/kit/uri` — thin facade over `@hop-top/cite` for URI parsing,
151
274
  action resolution, completions, registries, and OS handler metadata.
152
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)).
153
279
 
154
280
  See package.json `exports` for the full list.
155
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
+ program.parse();
317
+ ```
318
+
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.
327
+
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.
333
+
334
+ ### Configuration
335
+
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
+
156
479
  ## URI facade
157
480
 
158
- The URI module delegates to `@hop-top/cite`; it does not reimplement the URI
159
- contract. It mirrors the kit Go URI command intent for SDK consumers:
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:
160
484
 
161
485
  ```ts
162
486
  import { parse, resolve, complete, handler, newRegistry } from '@hop-top/kit/uri';
@@ -0,0 +1,139 @@
1
+ interface Modalities {
2
+ input?: string[];
3
+ output?: string[];
4
+ }
5
+ interface Limit {
6
+ context?: number;
7
+ output?: number;
8
+ }
9
+ interface Cost {
10
+ input?: number;
11
+ output?: number;
12
+ }
13
+ interface Model {
14
+ id: string;
15
+ name: string;
16
+ provider?: string;
17
+ family?: string;
18
+ input: string[];
19
+ output: string[];
20
+ tool_call: boolean;
21
+ reasoning: boolean;
22
+ open_weights: boolean;
23
+ context: number;
24
+ maxOutput: number;
25
+ costInput: number;
26
+ costOutput: number;
27
+ modalities?: Modalities;
28
+ limit?: Limit;
29
+ cost?: Cost;
30
+ }
31
+ interface Provider {
32
+ id: string;
33
+ name: string;
34
+ models: Record<string, Model>;
35
+ }
36
+ interface Filter {
37
+ input?: string;
38
+ output?: string;
39
+ provider?: string;
40
+ family?: string;
41
+ toolCall?: boolean;
42
+ reasoning?: boolean;
43
+ openWeights?: boolean;
44
+ query?: string;
45
+ }
46
+ /** Flatten nested wire fields into top-level Model fields. */
47
+ declare function normalize(m: Model): Model;
48
+ interface Source {
49
+ fetch(signal?: AbortSignal): Promise<Record<string, Provider>>;
50
+ }
51
+ interface ETagSource extends Source {
52
+ fetchWithETag(etag: string, signal?: AbortSignal): Promise<{
53
+ providers: Record<string, Provider> | null;
54
+ etag: string;
55
+ notModified: boolean;
56
+ }>;
57
+ }
58
+ interface ModelsDevSourceOptions {
59
+ url?: string;
60
+ timeout?: number;
61
+ maxSize?: number;
62
+ }
63
+ declare class ModelsDevSource implements ETagSource {
64
+ private url;
65
+ private timeout;
66
+ private maxSize;
67
+ constructor(opts?: ModelsDevSourceOptions);
68
+ private doFetch;
69
+ private readBody;
70
+ fetch(signal?: AbortSignal): Promise<Record<string, Provider>>;
71
+ fetchWithETag(etag: string, signal?: AbortSignal): Promise<{
72
+ providers: null;
73
+ etag: string;
74
+ notModified: true;
75
+ } | {
76
+ providers: Record<string, Provider>;
77
+ notModified: false;
78
+ etag: string;
79
+ }>;
80
+ }
81
+ interface CacheOptions {
82
+ ttl?: number;
83
+ dir?: string;
84
+ }
85
+ declare class Cache implements Source {
86
+ private src;
87
+ private ttl;
88
+ private dir;
89
+ constructor(src: Source, opts?: CacheOptions);
90
+ fetch(signal?: AbortSignal): Promise<Record<string, Provider>>;
91
+ forceRefresh(signal?: AbortSignal): Promise<Record<string, Provider>>;
92
+ private refresh;
93
+ private load;
94
+ private store;
95
+ private readFile;
96
+ private writeFile;
97
+ }
98
+ declare function parseQuery(q: string): Filter;
99
+ interface RegistryOptions {
100
+ sources?: Source[];
101
+ cacheDir?: string;
102
+ cacheTTL?: number;
103
+ }
104
+ declare class Registry {
105
+ private cache;
106
+ private providers;
107
+ constructor(opts?: RegistryOptions);
108
+ ensure(): Promise<void>;
109
+ refresh(): Promise<void>;
110
+ getProviders(): Promise<Provider[]>;
111
+ models(f: Filter): Promise<Model[]>;
112
+ get(provider: string, model: string): Promise<Model | undefined>;
113
+ query(q: string): Promise<Model[]>;
114
+ }
115
+
116
+ type aim_Cache = Cache;
117
+ declare const aim_Cache: typeof Cache;
118
+ type aim_CacheOptions = CacheOptions;
119
+ type aim_Cost = Cost;
120
+ type aim_ETagSource = ETagSource;
121
+ type aim_Filter = Filter;
122
+ type aim_Limit = Limit;
123
+ type aim_Modalities = Modalities;
124
+ type aim_Model = Model;
125
+ type aim_ModelsDevSource = ModelsDevSource;
126
+ declare const aim_ModelsDevSource: typeof ModelsDevSource;
127
+ type aim_ModelsDevSourceOptions = ModelsDevSourceOptions;
128
+ type aim_Provider = Provider;
129
+ type aim_Registry = Registry;
130
+ declare const aim_Registry: typeof Registry;
131
+ type aim_RegistryOptions = RegistryOptions;
132
+ type aim_Source = Source;
133
+ declare const aim_normalize: typeof normalize;
134
+ declare const aim_parseQuery: typeof parseQuery;
135
+ declare namespace aim {
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
+ }
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 };