@hop-top/kit 0.5.0-alpha.2 → 0.5.0-alpha.4

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 +60 -0
  2. package/LICENSE +1 -1
  3. package/README.md +48 -480
  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-JTMPNXVQ.js +1491 -0
  26. package/dist/chunk-KVG7YCTS.js +115 -0
  27. package/dist/chunk-L23O2FFE.js +51 -0
  28. package/dist/chunk-MQXYDYRD.js +968 -0
  29. package/dist/chunk-MUIQVU6E.js +251 -0
  30. package/dist/chunk-POR5L2DG.js +247 -0
  31. package/dist/chunk-PSFYJGDG.js +1445 -0
  32. package/dist/chunk-QJVSKKRQ.js +369 -0
  33. package/dist/chunk-QPUCXQXT.js +67 -0
  34. package/dist/chunk-R5U7XKVJ.js +16 -0
  35. package/dist/chunk-S45UHXQF.js +182 -0
  36. package/dist/chunk-T46YPHKN.js +669 -0
  37. package/dist/chunk-UIOOOK6M.js +334 -0
  38. package/dist/chunk-UKZIAQA7.js +26 -0
  39. package/dist/chunk-WBVO43HU.js +355 -0
  40. package/dist/chunk-WTYDHXPW.js +574 -0
  41. package/dist/chunk-WUOAQVOA.js +86 -0
  42. package/dist/chunk-WWUKGJB5.js +90 -0
  43. package/dist/chunk-YGYQUFGY.js +219 -0
  44. package/dist/chunk-YOBAUCVN.js +583 -0
  45. package/dist/{cli-DgOEOsPB.d.ts → cli-8rfITnv4.d.ts} +13 -4
  46. package/dist/cli.d.ts +4 -3
  47. package/dist/cli.js +50 -1056
  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-Do8Qji43.d.ts +231 -0
  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--C7Mtsmm.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 -13
  59. package/dist/index.js +40 -5792
  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-VFFLqor9.d.ts → output-CjZWmL8s.d.ts} +29 -130
  75. package/dist/output.d.ts +2 -1
  76. package/dist/output.js +137 -958
  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-D8yWMrTc.d.ts +646 -0
  88. package/dist/serve.d.ts +3 -0
  89. package/dist/serve.js +75 -0
  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 -4
  94. package/dist/tui/index.js +17 -373
  95. package/dist/upgrade.js +6 -114
  96. package/dist/xdg.js +14 -128
  97. package/package.json +135 -25
  98. package/src/README.md +15 -0
  99. package/src/cli.test.ts +56 -1
  100. package/src/cli.ts +24 -4
  101. package/src/completion-values.test.ts +10 -10
  102. package/src/compliance.test.ts +196 -2
  103. package/src/compliance.ts +440 -20
  104. package/src/config.test.ts +187 -1
  105. package/src/config.ts +173 -7
  106. package/src/gen/crud_pb.ts +7 -7
  107. package/src/id/README.md +38 -0
  108. package/src/id/contract.test.ts +1 -1
  109. package/src/id/index.test.ts +1 -1
  110. package/src/id/index.ts +3 -2
  111. package/src/index.test.ts +12 -0
  112. package/src/index.ts +3 -0
  113. package/src/llm-anthropic.conformance.test.ts +1135 -0
  114. package/src/llm-anthropic.test.ts +152 -0
  115. package/src/llm-anthropic.ts +940 -0
  116. package/src/llm-choice-hermetic.test.ts +335 -0
  117. package/src/llm-config.test.ts +232 -0
  118. package/src/llm-config.ts +106 -0
  119. package/src/llm-endpoint.ts +254 -0
  120. package/src/llm-error.ts +17 -0
  121. package/src/llm-errors.ts +152 -0
  122. package/src/llm-file.ts +126 -0
  123. package/src/llm-http.ts +317 -0
  124. package/src/llm-keys.ts +167 -0
  125. package/src/llm-media.conformance.test.ts +87 -0
  126. package/src/llm-media.test.ts +279 -0
  127. package/src/llm-media.ts +322 -0
  128. package/src/llm-openai.conformance.test.ts +407 -0
  129. package/src/llm-openai.test.ts +510 -0
  130. package/src/llm-openai.ts +708 -0
  131. package/src/llm-payload.ts +155 -0
  132. package/src/llm-quote.ts +46 -0
  133. package/src/llm-routellm.conformance.test.ts +44 -0
  134. package/src/llm-toolnames.conformance.test.ts +112 -0
  135. package/src/llm-toolnames.test.ts +132 -0
  136. package/src/llm-toolnames.ts +298 -0
  137. package/src/llm-uri.ts +99 -0
  138. package/src/llm.test.ts +43 -15
  139. package/src/llm.toolcall.test.ts +175 -0
  140. package/src/llm.ts +602 -190
  141. package/src/mcp/README.md +57 -0
  142. package/src/mcp/conformance.test.ts +24 -3
  143. package/src/mcp/dispatch.ts +4 -4
  144. package/src/mcp/identity.test.ts +166 -0
  145. package/src/mcp/identity.ts +72 -0
  146. package/src/mcp/index.ts +6 -0
  147. package/src/mcp/legacy.ts +21 -8
  148. package/src/mcp/mcp.test.ts +14 -4
  149. package/src/mcp/modern-confirm.ts +1 -1
  150. package/src/mcp/modern.ts +12 -11
  151. package/src/mcp/tasks.ts +1 -1
  152. package/src/mcp/types.ts +80 -8
  153. package/src/netpolicy.test.ts +78 -0
  154. package/src/netpolicy.ts +28 -3
  155. package/src/output/README.md +46 -0
  156. package/src/output/builtins.ts +5 -5
  157. package/src/output/error.ts +167 -1
  158. package/src/output/formatters/README.md +50 -0
  159. package/src/output.ts +26 -1
  160. package/src/published-types.test.ts +115 -0
  161. package/src/routellm.test.ts +209 -28
  162. package/src/routellm.toolcall.test.ts +521 -0
  163. package/src/routellm.ts +213 -177
  164. package/src/router/README.md +44 -0
  165. package/src/router/server.test.ts +41 -0
  166. package/src/router/server.ts +11 -0
  167. package/src/safety.test.ts +19 -9
  168. package/src/scope-defaults.json +29 -29
  169. package/src/serve.test.ts +1257 -0
  170. package/src/serve.ts +1665 -0
  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 +38 -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/src/mcp/types.ts CHANGED
@@ -22,6 +22,8 @@ import {
22
22
  SERVER_INFO_META_KEY,
23
23
  } from '@modelcontextprotocol/server';
24
24
 
25
+ import type { McpHttpRequest } from './dispatch.js';
26
+
25
27
  // --- protocol constants -------------------------------------------------
26
28
 
27
29
  /** Reserved `params._meta` / result `_meta` keys (from the v2 SDK). */
@@ -40,16 +42,21 @@ export const HEADER_MCP_NAME = 'Mcp-Name';
40
42
  * 2026-07-28 additions come from the SDK's ProtocolErrorCode;
41
43
  * HeaderMismatch (-32020) is spec-reserved but absent from the SDK
42
44
  * enum, so it is pinned here.
45
+ *
46
+ * The explicit enum-member annotations keep the declaration output a
47
+ * type reference. Inferred, it is `declare const X = ProtocolErrorCode.Y`,
48
+ * and the declaration bundler drops the `ProtocolErrorCode` import an
49
+ * initializer needs, leaving consumers an unresolved name (TS2304).
43
50
  */
44
- export const MCP_ERR_PARSE = ProtocolErrorCode.ParseError;
45
- export const MCP_ERR_INVALID_REQUEST = ProtocolErrorCode.InvalidRequest;
46
- export const MCP_ERR_METHOD_NOT_FOUND = ProtocolErrorCode.MethodNotFound;
47
- export const MCP_ERR_INVALID_PARAMS = ProtocolErrorCode.InvalidParams;
48
- export const MCP_ERR_INTERNAL = ProtocolErrorCode.InternalError;
51
+ export const MCP_ERR_PARSE: ProtocolErrorCode.ParseError = ProtocolErrorCode.ParseError;
52
+ export const MCP_ERR_INVALID_REQUEST: ProtocolErrorCode.InvalidRequest = ProtocolErrorCode.InvalidRequest;
53
+ export const MCP_ERR_METHOD_NOT_FOUND: ProtocolErrorCode.MethodNotFound = ProtocolErrorCode.MethodNotFound;
54
+ export const MCP_ERR_INVALID_PARAMS: ProtocolErrorCode.InvalidParams = ProtocolErrorCode.InvalidParams;
55
+ export const MCP_ERR_INTERNAL: ProtocolErrorCode.InternalError = ProtocolErrorCode.InternalError;
49
56
  export const MCP_ERR_HEADER_MISMATCH = -32020;
50
- export const MCP_ERR_MISSING_CLIENT_CAPABILITY =
57
+ export const MCP_ERR_MISSING_CLIENT_CAPABILITY: ProtocolErrorCode.MissingRequiredClientCapability =
51
58
  ProtocolErrorCode.MissingRequiredClientCapability;
52
- export const MCP_ERR_UNSUPPORTED_VERSION =
59
+ export const MCP_ERR_UNSUPPORTED_VERSION: ProtocolErrorCode.UnsupportedProtocolVersion =
53
60
  ProtocolErrorCode.UnsupportedProtocolVersion;
54
61
 
55
62
  /** The two protocol revisions this surface serves. */
@@ -205,11 +212,32 @@ export interface Leaf {
205
212
  enabled?: Partial<Record<Surface, boolean>>;
206
213
  }
207
214
 
215
+ /**
216
+ * How the surface established a caller, as recorded in
217
+ * `InvocationMeta.established`. Mirrors Go's `cmdsurface.Establishment`:
218
+ * `verified` means the mount's verifier accepted a credential the
219
+ * request presented. Absent means nothing was established; any caller
220
+ * the request claims is a claim, not an identity.
221
+ */
222
+ export type McpEstablishment = 'verified';
223
+
208
224
  /** Metadata attached to one invocation, forwarded to audit sinks. */
209
225
  export interface InvocationMeta {
210
226
  surface: Surface;
211
227
  requestedAt: Date;
212
- /** Free-form audit bag; the modern path records spec + client info. */
228
+ /**
229
+ * The principal the mount's verifier established. Never taken from
230
+ * the request body or headers.
231
+ */
232
+ caller?: string;
233
+ /** The tenant the verifier established, when it named one. */
234
+ tenant?: string;
235
+ /** Set only when the verifier established the caller. */
236
+ established?: McpEstablishment;
237
+ /**
238
+ * Free-form audit bag; the modern path records spec + client info.
239
+ * `scopes` (comma-joined) comes only from the verifier.
240
+ */
213
241
  extra?: Record<string, string>;
214
242
  }
215
243
 
@@ -246,6 +274,43 @@ export interface McpBridge {
246
274
  invoke(inv: Invocation): Promise<InvokeResult> | InvokeResult;
247
275
  }
248
276
 
277
+ // --- caller verification ------------------------------------------------
278
+
279
+ /**
280
+ * The caller a verifier established for one request. Mirrors the Go
281
+ * surfaces' `Meta` identity: `caller` is the stable principal (a user
282
+ * id, a service account, a client id), `tenant` the account it acts
283
+ * in, `scopes` what it was granted. All optional: a verifier may
284
+ * accept a credential that names no principal.
285
+ */
286
+ export interface McpIdentity {
287
+ caller?: string;
288
+ tenant?: string;
289
+ scopes?: string[];
290
+ }
291
+
292
+ /**
293
+ * Establishes who is calling. The mount calls it once per `tools/call`
294
+ * with the request as received; it checks a credential the request
295
+ * presents (a bearer token, a signed header) and returns the caller,
296
+ * or `null`/`undefined` to refuse. Throwing refuses too.
297
+ *
298
+ * Only an identity a verifier returns authenticates a call: a
299
+ * `kit/auth-required` leaf is refused with 401 unless it does. An
300
+ * `Authorization` header is presence, not verification, and a caller
301
+ * or scopes the request claims in its body never become identity.
302
+ */
303
+ export type McpVerifier = (
304
+ req: McpHttpRequest,
305
+ ) =>
306
+ | McpIdentity
307
+ | null
308
+ | undefined
309
+ | Promise<McpIdentity | null | undefined>;
310
+
311
+ /** The challenge a 401 carries in WWW-Authenticate, as Go's api.DefaultAuthChallenge. */
312
+ export const MCP_AUTH_CHALLENGE = 'Bearer';
313
+
249
314
  // --- mount options ------------------------------------------------------
250
315
 
251
316
  /**
@@ -271,6 +336,11 @@ export interface McpMountOptions {
271
336
  confirmationKey?: Uint8Array | string;
272
337
  /** Policy gate. Default: defaultPolicy(). */
273
338
  policy?: Policy;
339
+ /**
340
+ * Establishes the caller of each `tools/call`. Without one no call
341
+ * is established, so every `kit/auth-required` leaf is refused.
342
+ */
343
+ verifier?: McpVerifier;
274
344
  }
275
345
 
276
346
  /** Resolved, validated mount configuration. */
@@ -285,6 +355,7 @@ export interface ResolvedMcpConfig {
285
355
  originAllowlist: string[];
286
356
  confirmationKey?: Uint8Array;
287
357
  policy: Policy;
358
+ verifier?: McpVerifier;
288
359
  }
289
360
 
290
361
  /**
@@ -359,6 +430,7 @@ export function resolveMcpConfig(
359
430
  originAllowlist: opts.originAllowlist ?? [],
360
431
  confirmationKey,
361
432
  policy: opts.policy ?? defaultPolicy(),
433
+ verifier: opts.verifier,
362
434
  };
363
435
  }
364
436
 
@@ -15,6 +15,7 @@ import {
15
15
  install,
16
16
  isOffline,
17
17
  isOfflineError,
18
+ OfflineError,
18
19
  withOffline,
19
20
  } from './netpolicy';
20
21
 
@@ -136,6 +137,83 @@ describe('guardFetch', () => {
136
137
  expect((err as Error).message).toContain('--offline');
137
138
  });
138
139
 
140
+ // The refusal names where the request was going, never what it carried:
141
+ // scheme, host and path only. Query, fragment and userinfo may hold
142
+ // credentials (an API key param, basic-auth userinfo) and are dropped.
143
+ // Mirrors Go's TestGuard_RefusalOmitsQueryFragmentUserinfo.
144
+ describe('refusal omits query, fragment and userinfo', () => {
145
+ const raw =
146
+ 'https://alice:pw-secret@example.invalid/v1/models/m:generate' +
147
+ '?alt=sse&key=q-secret#frag-secret';
148
+ const leaks = ['alice', 'pw-secret', 'q-secret', 'key=', 'alt=sse', 'frag-secret', '?', '#', '@'];
149
+
150
+ // The fetch spec forbids credentials in a Request URL, so the Request
151
+ // case carries query and fragment only.
152
+ const noUserinfo = raw.replace('alice:pw-secret@', '');
153
+
154
+ for (const [label, call] of [
155
+ ['string input', (f: typeof globalThis.fetch) => f(raw, { method: 'POST' })],
156
+ ['URL input', (f: typeof globalThis.fetch) => f(new URL(raw), { method: 'POST' })],
157
+ [
158
+ 'Request input',
159
+ (f: typeof globalThis.fetch) => f(new Request(noUserinfo, { method: 'POST' })),
160
+ ],
161
+ ] as const) {
162
+ it(label, async () => {
163
+ const guarded = guardFetch(recorder().fn);
164
+
165
+ const err = await withOffline(true, async () => {
166
+ try {
167
+ await call(guarded);
168
+ return null;
169
+ } catch (e) {
170
+ return e;
171
+ }
172
+ });
173
+
174
+ expect(isOfflineError(err), `expected ErrOffline, got ${err}`).toBe(true);
175
+ const msg = (err as Error).message;
176
+ expect(msg).toBe(
177
+ 'POST https://example.invalid/v1/models/m:generate: network disabled by --offline',
178
+ );
179
+ for (const leak of leaks) {
180
+ expect(msg, `refusal carries ${leak}`).not.toContain(leak);
181
+ }
182
+ });
183
+ }
184
+
185
+ // An unparseable target is refused (fail closed) and cannot be
186
+ // stripped reliably, so none of it is echoed.
187
+ it('unparseable target', async () => {
188
+ const guarded = guardFetch(recorder().fn);
189
+
190
+ const err = await withOffline(true, async () => {
191
+ try {
192
+ await guarded('not a url?key=q-secret#frag-secret');
193
+ return null;
194
+ } catch (e) {
195
+ return e;
196
+ }
197
+ });
198
+
199
+ expect(isOfflineError(err), `expected ErrOffline, got ${err}`).toBe(true);
200
+ const msg = (err as Error).message;
201
+ expect(msg).toMatch(/^GET .*: network disabled by --offline$/);
202
+ for (const leak of leaks) {
203
+ expect(msg, `refusal carries ${leak}`).not.toContain(leak);
204
+ }
205
+ });
206
+
207
+ // An adopter constructing the error by hand gets the same stripping.
208
+ it('OfflineError constructed directly', () => {
209
+ const err = new OfflineError('GET', raw);
210
+ expect(isOfflineError(err)).toBe(true);
211
+ expect(err.message).toBe(
212
+ 'GET https://example.invalid/v1/models/m:generate: network disabled by --offline',
213
+ );
214
+ });
215
+ });
216
+
139
217
  // Wrapping must be idempotent, mirroring Go's Guard.
140
218
  it('does not double-wrap', () => {
141
219
  const once = guardFetch(recorder().fn);
package/src/netpolicy.ts CHANGED
@@ -52,13 +52,38 @@ import { AsyncLocalStorage } from 'node:async_hooks';
52
52
  */
53
53
  export const ErrOffline = 'OfflineError';
54
54
 
55
- /** Error rejected by {@link guardFetch}. Matchable via {@link isOfflineError}. */
55
+ /**
56
+ * Error rejected by {@link guardFetch}. Matchable via {@link isOfflineError}.
57
+ *
58
+ * The message names the method and the destination as scheme, host and
59
+ * path only; `url` is reduced by {@link destination} whoever constructs
60
+ * the error.
61
+ */
56
62
  export class OfflineError extends Error {
57
63
  override readonly name = ErrOffline;
58
64
 
59
65
  constructor(method: string, url: string) {
60
- super(`${method} ${url}: network disabled by --offline`);
66
+ super(`${method} ${destination(url)}: network disabled by --offline`);
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Render url as scheme, host and path only: enough to say where a refused
72
+ * request was going, nothing it carried. Query, fragment and userinfo are
73
+ * dropped because they may hold credentials (an API key param, basic-auth
74
+ * userinfo). An opaque URL (`data:`, `mailto:`) keeps its scheme alone,
75
+ * and a target that does not parse cannot be stripped reliably, so none
76
+ * of it is echoed. Mirrors Go's `netpolicy` refusal.
77
+ */
78
+ function destination(url: string): string {
79
+ let u: URL;
80
+ try {
81
+ u = new URL(url);
82
+ } catch {
83
+ return '<unparseable URL>';
61
84
  }
85
+ if (u.host === '' && !u.pathname.startsWith('/')) return u.protocol;
86
+ return `${u.protocol}//${u.host}${u.pathname}`;
62
87
  }
63
88
 
64
89
  /**
@@ -124,7 +149,7 @@ export function isOffline(): boolean {
124
149
  * IPs (DNS names) are treated as remote: resolving them would itself be
125
150
  * network access.
126
151
  */
127
- function isLoopback(hostname: string): boolean {
152
+ export function isLoopback(hostname: string): boolean {
128
153
  // URL.hostname keeps IPv6 literals bracketed and lower-cases the rest.
129
154
  const h = hostname.replace(/^\[|\]$/g, '');
130
155
  if (h === 'localhost') return true;
@@ -0,0 +1,46 @@
1
+ # output
2
+
3
+ ## What it answers
4
+
5
+ How a command turns a structured value into bytes on a stream in the format the caller picked: table, json, yaml, csv, text, or a `--template`. It also owns the structured error envelope and the exit-code table. Wrong module for terminal widgets (`@hop-top/kit/tui`), progress events (`@hop-top/kit/progress`), or any flag outside the output suite (`@hop-top/kit/cli`).
6
+
7
+ ## Use it when
8
+
9
+ - one-off render, no flags involved: `render(w, format, data)`
10
+ - Commander program that must honour `--format`, `--format-opt`, `--cols`, `--template`, `--output|-o`, `--format-help`: `registerOutputFlags(program)` then `dispatch(program, data)`
11
+ - fail with a machine-readable error under `--format json|yaml`: `notFoundError`, `usageError`, `wrapError` and friends, rendered by `renderError`
12
+ - add a format: implement `Formatter`, `defaultRegistry.register(f)`; built-ins live in [`formatters/`](formatters/README.md)
13
+
14
+ ## Quick start
15
+
16
+ ```ts
17
+ import { render, TABLE_FORMAT, JSON_FORMAT } from '@hop-top/kit/output';
18
+
19
+ render(process.stdout, TABLE_FORMAT, [{ id: '1', name: 'Alice' }]);
20
+ render(process.stdout, JSON_FORMAT, { ok: true });
21
+ ```
22
+
23
+ ## Contract
24
+
25
+ - `render(w, format, v)` renders every column in payload key order. `ColumnSpec[]` and `--cols` are reachable only through `dispatch`.
26
+ - `--cols` selects and reorders; the user's order wins over the `ColumnSpec` list.
27
+ - `--template` and `--cols` are mutually exclusive; `dispatch` throws.
28
+ - Format resolution: explicit `--format`, else the `--output` extension, else `table`.
29
+ - Error envelope keys are wire snake_case; empty optionals stay off the wire (Go `omitempty`).
30
+ - Exit codes are exported constants (`EXIT_*`); import them, never hardcode, and read the constants rather than a list in prose — the line that used to sit here named four and stopped at 65, so it read as a ceiling once `EXIT_PREREQUISITE` 70 existed.
31
+ - Parity: [`sdk/tests/cross-lang/fixtures/ordering.json`](../../../tests/cross-lang/fixtures/ordering.json), replayed by `sdk/tests/cross-lang/run-order.sh`.
32
+
33
+ ## Neighbours
34
+
35
+ - `@hop-top/kit/cli`: program factory, help layout, `Theme`
36
+ - `@hop-top/kit/tui`: styled TTY widgets (status, badge, spinner)
37
+ - `@hop-top/kit/progress`: Factor 9 progress events
38
+ - `@hop-top/kit/provenance`: `_meta` provenance wrapper around payloads
39
+ - `@hop-top/kit/stream`: stdout/stderr discipline
40
+ - Go reference: [`go/console/output`](../../../../go/console/output/README.md); Python port: [`hop_top_kit/output`](../../../py/hop_top_kit/output/README.md)
41
+
42
+ ## See also
43
+
44
+ - [`sdk/ts/README.md`](../../README.md), section "Output formatting": flag surface, column-ordering rules, conformance status
45
+ - [`docs/adopters/reference/ts-api-reference.md`](../../../../docs/adopters/reference/ts-api-reference.md)
46
+ - [`sdk/tests/cross-lang/README.md`](../../../tests/cross-lang/README.md): column-ordering harness
@@ -7,25 +7,25 @@
7
7
  */
8
8
 
9
9
  import { defaultRegistry } from './registry';
10
+ import { csvFormatter } from './formatters/csv';
10
11
  import { jsonFormatter } from './formatters/json';
11
- import { yamlFormatter } from './formatters/yaml';
12
12
  import { tableFormatter } from './formatters/table';
13
- import { csvFormatter } from './formatters/csv';
14
13
  import { textFormatter } from './formatters/text';
14
+ import { yamlFormatter } from './formatters/yaml';
15
15
 
16
16
  let registered = false;
17
17
 
18
18
  /**
19
- * Register the built-in formatters (json, yaml, table, csv, text) against
19
+ * Register the built-in formatters (csv, json, table, text, yaml) against
20
20
  * defaultRegistry. Idempotent — safe to call from multiple entry points.
21
21
  */
22
22
  export function registerBuiltins(): void {
23
23
  if (registered) return;
24
+ defaultRegistry.register(csvFormatter);
24
25
  defaultRegistry.register(jsonFormatter);
25
- defaultRegistry.register(yamlFormatter);
26
26
  defaultRegistry.register(tableFormatter);
27
- defaultRegistry.register(csvFormatter);
28
27
  defaultRegistry.register(textFormatter);
28
+ defaultRegistry.register(yamlFormatter);
29
29
  registered = true;
30
30
  }
31
31
 
@@ -32,7 +32,7 @@ export const TRANSIENCE_PERMANENT = 'permanent';
32
32
  export const TRANSIENCE_UNKNOWN = 'unknown';
33
33
 
34
34
  // ---------------------------------------------------------------------------
35
- // Standard codes mapping the cross-tool exit codes (conventions §8.1)
35
+ // Standard codes mapping the cross-tool exit codes
36
36
  // ---------------------------------------------------------------------------
37
37
 
38
38
  export const CODE_OK = 'OK'; // exit 0
@@ -42,15 +42,58 @@ export const CODE_NOT_FOUND = 'NOT_FOUND'; // exit 3
42
42
  export const CODE_CONFLICT = 'CONFLICT'; // exit 4
43
43
  export const CODE_UNAUTHORIZED = 'UNAUTHORIZED'; // exit 5
44
44
  export const CODE_TRANSIENT = 'TRANSIENT'; // exit 6 — Factor-11 transient/retryable failure
45
+ export const CODE_CONSENT_REFUSED = 'CONSENT_REFUSED'; // exit 7 — confirmation gate declined
45
46
  export const CODE_PROVENANCE_MISSING = 'PROVENANCE_MISSING'; // exit 65 — Factor-12 strict-mode refusal
46
47
  export const CODE_RATE_LIMITED = 'RATE_LIMITED'; // exit 64 — Factor-10 max-ops budget exceeded
48
+ export const CODE_PREREQUISITE = 'PREREQUISITE'; // exit 70 — declared dependency unreachable
47
49
 
50
+ /**
51
+ * Success. Present for completeness so a table of the full taxonomy can
52
+ * be written without a bare 0.
53
+ */
54
+ export const EXIT_OK = 0;
55
+ /**
56
+ * Spec-assigned exit code for the generic failure class: the command
57
+ * failed and no narrower code applies. Pair it with {@link genericError}
58
+ * rather than hand-rolling exit 1, so the envelope carries a transience
59
+ * class.
60
+ */
61
+ export const EXIT_GENERIC = 1;
62
+ /**
63
+ * The caller's invocation being wrong: an unknown flag, a missing
64
+ * argument, a value the command cannot parse. Permanent by
65
+ * construction — the same argv fails identically.
66
+ */
67
+ export const EXIT_USAGE = 2;
68
+ /** A named resource the command could not locate. */
69
+ export const EXIT_NOT_FOUND = 3;
70
+ /**
71
+ * A request that cannot be satisfied against the current state: a
72
+ * precondition failed, a write raced, an identifier is already taken.
73
+ */
74
+ export const EXIT_CONFLICT = 4;
75
+ /**
76
+ * An authentication or authorization refusal. Permanent: the caller
77
+ * needs new credentials or a different policy, not a retry. Distinct
78
+ * from {@link EXIT_CONSENT_REFUSED}, which a re-invocation with
79
+ * `--confirm=yes` clears.
80
+ */
81
+ export const EXIT_UNAUTHORIZED = 5;
48
82
  /**
49
83
  * Spec-assigned exit code for transient/retryable failures (Factor 11).
50
84
  * Agents branch on it before parsing stderr: exit 6 means a retry may
51
85
  * clear the failure.
52
86
  */
53
87
  export const EXIT_TRANSIENT = 6;
88
+ /**
89
+ * Exit code for a confirmation gate that declined to run a destructive
90
+ * operation (`--confirm=no`, the non-TTY default, a missing or
91
+ * mismatched `--confirm-token`, or `N` at the prompt). Classified
92
+ * transient: re-invoking with `--confirm=yes` clears it. Distinct from
93
+ * {@link CODE_UNAUTHORIZED} at exit 5, which is permanent because no
94
+ * confirmation can clear a policy denial.
95
+ */
96
+ export const EXIT_CONSENT_REFUSED = 7;
54
97
  /** Conventional exit code for Factor-10 rate-limit refusals. */
55
98
  export const EXIT_RATE_LIMITED = 64;
56
99
  /**
@@ -60,6 +103,16 @@ export const EXIT_RATE_LIMITED = 64;
60
103
  * codes, and kit as a library stays out of the low per-tool range.
61
104
  */
62
105
  export const EXIT_PROVENANCE_MISSING = 65;
106
+ /**
107
+ * Exit code for a declared external dependency kit could not contact:
108
+ * nothing listening on the configured endpoint, connection refused,
109
+ * dial timeout. Separates a correct invocation whose logic never ran
110
+ * from the uncharacterized failures on exit 1. Classified transient,
111
+ * but deliberately not {@link CODE_TRANSIENT}: a dependency that is not
112
+ * running never comes up on its own, so the caller repairs the
113
+ * environment instead of backing off.
114
+ */
115
+ export const EXIT_PREREQUISITE = 70;
63
116
 
64
117
  /**
65
118
  * Structured-error envelope rendered to stderr when `--format json|yaml`
@@ -103,12 +156,70 @@ export function transienceForCode(code: string): string {
103
156
  return TRANSIENCE_PERMANENT;
104
157
  case CODE_RATE_LIMITED:
105
158
  case CODE_TRANSIENT:
159
+ case CODE_CONSENT_REFUSED:
160
+ case CODE_PREREQUISITE:
106
161
  return TRANSIENCE_TRANSIENT;
107
162
  default:
108
163
  return TRANSIENCE_UNKNOWN;
109
164
  }
110
165
  }
111
166
 
167
+ /**
168
+ * The class-symbol-to-exit-code relation, as data. Mirrors Go's
169
+ * `exitCodeForClass` in `go/console/output/envelope/exitcodes.go`.
170
+ *
171
+ * Expressed as a table rather than as constants plus trailing comments
172
+ * because the string-to-number relationship is the thing consumers
173
+ * actually need, and a comment cannot be consumed — nor can it be
174
+ * checked against the cross-language contract. Pinned against
175
+ * `contracts/exit-taxonomy-v1/taxonomy.json` by
176
+ * `test/output/taxonomy-contract.test.ts`.
177
+ *
178
+ * Scope is the classes kit itself owns. The conformance band's
179
+ * tool-specific slots (66 LEAK_DETECTED, 67 CONFIG, 68 GRADE_FAIL,
180
+ * 69 GRADE_UNGRADABLE) are deliberately absent: they are declared by the
181
+ * packages that own them.
182
+ */
183
+ const EXIT_CODE_FOR_CLASS: ReadonlyMap<string, number> = new Map([
184
+ [CODE_OK, EXIT_OK],
185
+ [CODE_GENERIC, EXIT_GENERIC],
186
+ [CODE_USAGE, EXIT_USAGE],
187
+ [CODE_NOT_FOUND, EXIT_NOT_FOUND],
188
+ [CODE_CONFLICT, EXIT_CONFLICT],
189
+ [CODE_UNAUTHORIZED, EXIT_UNAUTHORIZED],
190
+ [CODE_TRANSIENT, EXIT_TRANSIENT],
191
+ [CODE_CONSENT_REFUSED, EXIT_CONSENT_REFUSED],
192
+ [CODE_RATE_LIMITED, EXIT_RATE_LIMITED],
193
+ [CODE_PROVENANCE_MISSING, EXIT_PROVENANCE_MISSING],
194
+ [CODE_PREREQUISITE, EXIT_PREREQUISITE],
195
+ ]);
196
+
197
+ /**
198
+ * Resolves a standard class symbol to its numeric exit code, or
199
+ * `undefined` for adopter-defined and tool-specific codes.
200
+ *
201
+ * Callers that must produce a number for an unknown class decide their
202
+ * own fallback. This function does not pick one: a built-in fallback
203
+ * turns "this class was added to kit and never copied here" into an
204
+ * assertion against exit 1 that looks like a real failure rather than a
205
+ * stale table.
206
+ */
207
+ export function exitCodeForClass(code: string): number | undefined {
208
+ return EXIT_CODE_FOR_CLASS.get(code);
209
+ }
210
+
211
+ /**
212
+ * The class symbols kit defines, in ascending exit-code order (ties
213
+ * broken by symbol). Callers rendering the taxonomy iterate this rather
214
+ * than hard-coding rows, so a class added above appears without a
215
+ * second edit.
216
+ */
217
+ export function exitClasses(): string[] {
218
+ return [...EXIT_CODE_FOR_CLASS.entries()]
219
+ .sort((a, b) => (a[1] !== b[1] ? a[1] - b[1] : a[0].localeCompare(b[0])))
220
+ .map(([code]) => code);
221
+ }
222
+
112
223
  /**
113
224
  * Builds an envelope from `err`, retaining it for {@link unwrapError}
114
225
  * while rendering as `code` and message. Transience defaults from the
@@ -152,6 +263,22 @@ export function withTransience(e: CliError, transience: string): CliError {
152
263
  return clone;
153
264
  }
154
265
 
266
+ /**
267
+ * CODE_GENERIC envelope with exit code 1. The catch-all for failures no
268
+ * narrower code describes; permanent because retrying the same input
269
+ * in the same environment is not expected to help. Wrapping an
270
+ * arbitrary error as CODE_GENERIC via {@link wrapError} still defaults
271
+ * to unknown.
272
+ */
273
+ export function genericError(message: string): CliError {
274
+ return {
275
+ code: CODE_GENERIC,
276
+ message,
277
+ exit_code: EXIT_GENERIC,
278
+ transience: TRANSIENCE_PERMANENT,
279
+ };
280
+ }
281
+
155
282
  /** CODE_NOT_FOUND envelope with exit code 3. */
156
283
  export function notFoundError(message: string): CliError {
157
284
  return {
@@ -206,6 +333,45 @@ export function transientError(message: string): CliError {
206
333
  };
207
334
  }
208
335
 
336
+ /**
337
+ * CODE_CONSENT_REFUSED envelope with exit code 7. Use it when a
338
+ * confirmation gate declines to run a destructive operation:
339
+ * `--confirm=no`, the non-TTY default, a missing or mismatched
340
+ * `--confirm-token`, or `N` at the prompt.
341
+ *
342
+ * Classified transient: the caller clears it by re-invoking with
343
+ * `--confirm=yes` (or the matching token). Do not use it for policy
344
+ * denials, which no confirmation can clear — those stay
345
+ * {@link unauthorizedError} and permanent.
346
+ */
347
+ export function consentRefusedError(message: string): CliError {
348
+ return {
349
+ code: CODE_CONSENT_REFUSED,
350
+ message,
351
+ exit_code: EXIT_CONSENT_REFUSED,
352
+ transience: TRANSIENCE_TRANSIENT,
353
+ };
354
+ }
355
+
356
+ /**
357
+ * CODE_PREREQUISITE envelope with exit code 70. Use it when a declared
358
+ * external dependency could not be contacted: nothing listening on the
359
+ * configured endpoint, connection refused, dial timeout.
360
+ *
361
+ * Classified transient: the operator starts the dependency and the same
362
+ * command succeeds. Do not use it for a dependency that answered and
363
+ * then misbehaved — that is {@link genericError} — nor for one that was
364
+ * never configured, which is {@link usageError}.
365
+ */
366
+ export function prerequisiteError(message: string): CliError {
367
+ return {
368
+ code: CODE_PREREQUISITE,
369
+ message,
370
+ exit_code: EXIT_PREREQUISITE,
371
+ transience: TRANSIENCE_TRANSIENT,
372
+ };
373
+ }
374
+
209
375
  /** CODE_RATE_LIMITED envelope with exit code 64 (Factor 10). */
210
376
  export function rateLimitedError(message: string): CliError {
211
377
  return {
@@ -0,0 +1,50 @@
1
+ # output/formatters
2
+
3
+ ## What it answers
4
+
5
+ Which bytes each built-in format emits and which `--format-opt` keys it accepts. Every file here is one `Formatter` registered against `defaultRegistry` when [`../builtins.ts`](../builtins.ts) loads. Wrong place for flag wiring or format resolution: that is [`../dispatch.ts`](../dispatch.ts) and [`../flags.ts`](../flags.ts).
6
+
7
+ ## Use it when
8
+
9
+ - you need a formatter without the flag suite: `defaultRegistry.lookup(key)` then `render(out, data, opts, cols)`
10
+ - you are adding a built-in: copy the closest file, export a `Formatter`, register it in `../builtins.ts`
11
+ - you are checking what an option does: read the file's header comment
12
+
13
+ | Key | Extensions | Options |
14
+ |-----|------------|---------|
15
+ | `json` | `.json` | `indent` (int, default 2) |
16
+ | `yaml` | `.yaml`, `.yml` | `flow-level` (int, default -1) |
17
+ | `table` | none | none |
18
+ | `csv` | `.csv` | `delimiter`, `no-header`, `quote-all`, `crlf` |
19
+ | `text` | `.txt` | `style` (kv, lines, paragraph), `separator` (kv only) |
20
+
21
+ ## Quick start
22
+
23
+ ```ts
24
+ import { defaultRegistry } from '@hop-top/kit/output';
25
+
26
+ console.log(defaultRegistry.keys());
27
+ const csv = defaultRegistry.lookup('csv')!;
28
+ csv.render(process.stdout, [{ id: '1', name: 'Alice' }], { delimiter: ';' }, []);
29
+ ```
30
+
31
+ ## Contract
32
+
33
+ - `render` trusts `opts`: callers run `parseOptions` against `options()` first.
34
+ - `json` and `yaml` preserve the payload's outer shape (object stays object, array stays array) and pass non-object payloads through untouched; [`project.ts`](project.ts) is the shared shim.
35
+ - `table`, `csv` and `text` take column order from the `ColumnSpec` list, else the first row's key order; `cols` narrows and reorders.
36
+ - `csv` encoding is hand-rolled: a quoted field's bytes are preserved verbatim in both line-ending modes.
37
+ - `text` mirrors `go/console/output/text.go` byte for byte.
38
+ - Parity: [`sdk/tests/cross-lang/fixtures/ordering.json`](../../../../tests/cross-lang/fixtures/ordering.json).
39
+
40
+ ## Neighbours
41
+
42
+ - [`../registry.ts`](../registry.ts): `Registry`, `defaultRegistry`, duplicate-key fail-loud
43
+ - [`../template.ts`](../template.ts): `--template` (eta), not a formatter
44
+ - [`../format_help.ts`](../format_help.ts): `--format-help` catalog
45
+ - Python port: [`hop_top_kit/output/formatters`](../../../../py/hop_top_kit/output/formatters/README.md)
46
+
47
+ ## See also
48
+
49
+ - [`../README.md`](../README.md)
50
+ - [`sdk/ts/README.md`](../../../README.md), section "Built-in formatters"