@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
@@ -0,0 +1,231 @@
1
+ /**
2
+ * @module netpolicy
3
+ * @package @hop-top/kit
4
+ *
5
+ * Owns the process-wide network policy marker and the `fetch` wrapper that
6
+ * enforces it.
7
+ *
8
+ * The `--offline` global (cli-parity-guide, "Global Flags") promises that
9
+ * network access is disabled. Marking a scope alone cannot keep that
10
+ * promise: it is advisory, so any caller that forgets to consult it still
11
+ * reaches the wire. {@link guardFetch} closes that gap by refusing the
12
+ * request inside the fetch implementation, beneath every caller, where no
13
+ * naive leaf can route around it.
14
+ *
15
+ * The marker lives in its own module rather than in `cli` so library code
16
+ * can enforce the policy without importing the CLI factory back.
17
+ *
18
+ * Loopback is deliberately exempt. `--offline` means "do not talk to the
19
+ * network", not "do not talk to myself": a local `kit serve` peer, a dev
20
+ * backend on 127.0.0.1 and unix sockets stay reachable so offline
21
+ * workflows remain usable.
22
+ *
23
+ * ## Scope
24
+ *
25
+ * {@link install} wraps `globalThis.fetch`, so it covers HTTP and HTTPS
26
+ * through the fetch API — which is every network client in kit today
27
+ * (`api`, `aim`, `upgrade`, `routellm`, `triton`, `telemetry`, and the
28
+ * ConnectRPC transport, which resolves `globalThis.fetch` lazily per
29
+ * call). undici's `setGlobalDispatcher` is not used: undici is not a
30
+ * dependency of this package, so the dispatcher hook is unavailable
31
+ * without adding one, and it would not cover callers that inject their
32
+ * own `fetch` anyway.
33
+ *
34
+ * It does NOT cover code that opens a socket directly: `node:net`,
35
+ * `node:http`/`node:https` (`http.request`), `node:dgram`, database
36
+ * drivers, or raw TLS. Nor does it cover a caller that captured a
37
+ * reference to the unguarded `fetch` before {@link install} ran, or one
38
+ * that injects its own transport (`APIClient({ fetch })`). For those,
39
+ * `--offline` remains advisory and the call site must consult
40
+ * {@link isOffline} itself, or wrap its own transport with
41
+ * {@link guardFetch}. Closing that gap needs a guarded dialer threaded
42
+ * through each such client; it is deliberately not attempted here.
43
+ */
44
+
45
+ import { AsyncLocalStorage } from 'node:async_hooks';
46
+
47
+ /**
48
+ * Name carried by the error {@link guardFetch} rejects with when a request
49
+ * is attempted in an offline-marked scope. JavaScript has no `errors.Is`,
50
+ * so the name is the matchable analogue of Go's sentinel `ErrOffline`;
51
+ * prefer {@link isOfflineError} over comparing it by hand.
52
+ */
53
+ export const ErrOffline = 'OfflineError';
54
+
55
+ /** Error rejected by {@link guardFetch}. Matchable via {@link isOfflineError}. */
56
+ export class OfflineError extends Error {
57
+ override readonly name = ErrOffline;
58
+
59
+ constructor(method: string, url: string) {
60
+ super(`${method} ${url}: network disabled by --offline`);
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Report whether err is the refusal raised by the offline guard. Matches on
66
+ * the error name rather than `instanceof` so a copy of this module loaded
67
+ * through a different resolution path (bundled adopter, dual dist/src
68
+ * graph) still matches — the JS analogue of `errors.Is`.
69
+ */
70
+ export function isOfflineError(err: unknown): boolean {
71
+ return err instanceof Error && err.name === ErrOffline;
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // Marker
76
+ // ---------------------------------------------------------------------------
77
+
78
+ /**
79
+ * Per-invocation marker. AsyncLocalStorage is the TypeScript analogue of
80
+ * Go's `context.Context` value: it propagates across `await` boundaries
81
+ * into the guarded fetch without threading a parameter through every
82
+ * library call.
83
+ */
84
+ const store = new AsyncLocalStorage<boolean>();
85
+
86
+ /** Set when the policy applies process-wide rather than to one async scope. */
87
+ let processOffline = false;
88
+
89
+ /**
90
+ * Run fn in a scope marked offline. Passing false runs fn unchanged so an
91
+ * unmarked scope stays clean, mirroring Go's `WithOffline(ctx, false)`.
92
+ */
93
+ export function withOffline<T>(offline: boolean, fn: () => T): T {
94
+ if (!offline) return fn();
95
+ return store.run(true, fn);
96
+ }
97
+
98
+ /**
99
+ * Mark the whole process offline. The CLI uses this rather than
100
+ * {@link withOffline} because commander dispatches an action handler
101
+ * without giving the framework a scope to wrap around it, and because a
102
+ * detached callback (a timer, an unawaited promise) must stay refused.
103
+ * Mirrors the process-global reach of Go's `netpolicy.Install`.
104
+ */
105
+ export function setProcessOffline(offline: boolean): void {
106
+ processOffline = offline;
107
+ }
108
+
109
+ /**
110
+ * Report whether the caller is running under the offline marker — either
111
+ * an enclosing {@link withOffline} scope or a process-wide
112
+ * {@link setProcessOffline}.
113
+ */
114
+ export function isOffline(): boolean {
115
+ return processOffline || store.getStore() === true;
116
+ }
117
+
118
+ // ---------------------------------------------------------------------------
119
+ // Enforcement
120
+ // ---------------------------------------------------------------------------
121
+
122
+ /**
123
+ * Report whether host names a loopback address. Hosts that are not literal
124
+ * IPs (DNS names) are treated as remote: resolving them would itself be
125
+ * network access.
126
+ */
127
+ function isLoopback(hostname: string): boolean {
128
+ // URL.hostname keeps IPv6 literals bracketed and lower-cases the rest.
129
+ const h = hostname.replace(/^\[|\]$/g, '');
130
+ if (h === 'localhost') return true;
131
+ if (h === '::1') return true;
132
+ // IPv4 loopback is the whole 127.0.0.0/8 block.
133
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
134
+ if (v4) {
135
+ return v4.slice(1).every((o) => Number(o) <= 255) && Number(v4[1]) === 127;
136
+ }
137
+ // IPv4-mapped IPv6 loopback, in either textual form.
138
+ const mapped = /^::ffff:(.+)$/i.exec(h);
139
+ if (mapped) {
140
+ const inner = mapped[1] ?? '';
141
+ if (/^7f00:1$/i.test(inner)) return true;
142
+ return isLoopback(inner);
143
+ }
144
+ return false;
145
+ }
146
+
147
+ /** Resolve the method and absolute URL a fetch call targets. */
148
+ function target(input: RequestInfo | URL, init?: RequestInit): { method: string; url: string } {
149
+ if (typeof Request !== 'undefined' && input instanceof Request) {
150
+ return { method: init?.method ?? input.method, url: input.url };
151
+ }
152
+ return { method: init?.method ?? 'GET', url: String(input) };
153
+ }
154
+
155
+ /** Marks a fetch implementation as already guarded, so wrapping is idempotent. */
156
+ const guarded = Symbol.for('hop.top/kit/netpolicy.guarded');
157
+ const unguardedBase = Symbol.for('hop.top/kit/netpolicy.unguardedBase');
158
+
159
+ /**
160
+ * Wrap base so requests made in an offline-marked scope reject with an
161
+ * {@link OfflineError} instead of reaching the network. Wrapping is
162
+ * idempotent: guarding an already guarded fetch returns it unchanged.
163
+ *
164
+ * A URL that does not parse is refused when offline: an unparseable target
165
+ * cannot be shown to be loopback, and the policy fails closed.
166
+ */
167
+ export function guardFetch(base: typeof globalThis.fetch): typeof globalThis.fetch {
168
+ if ((base as { [guarded]?: boolean })[guarded]) return base;
169
+
170
+ const wrapper: typeof globalThis.fetch = async (input, init) => {
171
+ if (isOffline()) {
172
+ const { method, url } = target(input, init);
173
+ let loopback = false;
174
+ try {
175
+ loopback = isLoopback(new URL(url).hostname);
176
+ } catch {
177
+ loopback = false; // fail closed on an unparseable target
178
+ }
179
+ if (!loopback) throw new OfflineError(method, url);
180
+ }
181
+ return base(input, init);
182
+ };
183
+
184
+ (wrapper as { [guarded]?: boolean })[guarded] = true;
185
+ // Remember the unwrapped transport so logging-class sinks can reach
186
+ // past the guard without capturing a reference at module load.
187
+ (wrapper as { [unguardedBase]?: typeof globalThis.fetch })[unguardedBase] = base;
188
+ return wrapper;
189
+ }
190
+
191
+ /**
192
+ * Wrap `globalThis.fetch` with {@link guardFetch}, so every caller that
193
+ * does not inject its own transport — the common case across kit and
194
+ * adopter code — enforces the policy without a per-site change.
195
+ *
196
+ * Idempotent and safe to call more than once. Call it once during process
197
+ * start-up (`createCLI` does this) and never concurrently with in-flight
198
+ * requests: it mutates a process-global.
199
+ *
200
+ * Callers that DO inject their own fetch must wrap it themselves with
201
+ * {@link guardFetch}; install cannot reach them.
202
+ */
203
+ export function install(): void {
204
+ globalThis.fetch = guardFetch(globalThis.fetch);
205
+ }
206
+
207
+ /**
208
+ * Fetch for logging-class egress — telemetry, and any future
209
+ * remote-logging or crash-reporting sink.
210
+ *
211
+ * `--offline` means "do not talk to the network on the user's behalf". It
212
+ * does not silence diagnostics, the same way a remote syslog target is
213
+ * not muted by an offline flag. Consent and the telemetry mode already
214
+ * govern whether those sinks emit at all; `--offline` is not a second
215
+ * consent gate.
216
+ *
217
+ * Resolved lazily, per call: it reads the *current* `globalThis.fetch`
218
+ * and unwraps the guard if {@link install} has wrapped it. Capturing a
219
+ * reference at module load instead would freeze out later stubbing —
220
+ * breaking both test fakes and adopters who swap the global transport.
221
+ *
222
+ * Never use this for anything the user asked for — that is exactly the
223
+ * traffic `--offline` exists to stop.
224
+ */
225
+ export function observabilityFetch(): typeof globalThis.fetch {
226
+ const current = globalThis.fetch as {
227
+ [guarded]?: boolean;
228
+ [unguardedBase]?: typeof globalThis.fetch;
229
+ };
230
+ return current?.[unguardedBase] ?? (globalThis.fetch as typeof globalThis.fetch);
231
+ }
@@ -15,7 +15,7 @@ import type { ColumnSpec, Formatter } from './formatter';
15
15
  import { parseOptions } from './formatter';
16
16
  import { registryFor, resolveCols } from './flags';
17
17
  import { renderFormatHelp } from './format_help';
18
- import { validateCols } from './projection';
18
+ import { resolveEffectiveCols, validateCols } from './projection';
19
19
  import { renderTemplate } from './template';
20
20
 
21
21
  /** Sentinel value of --output meaning "write to stdout". */
@@ -101,8 +101,16 @@ export async function dispatch<T>(
101
101
  const rows = Array.isArray(data) ? (data as readonly unknown[]) : [data];
102
102
  validateCols(rows, options.columns, cols);
103
103
  }
104
+ // Resolve column precedence once, here, rather than in each formatter:
105
+ // user --cols wins, else the ColumnSpec list's order, else payload keys.
106
+ const effectiveCols = resolveEffectiveCols(cols, options.columns);
104
107
  await Promise.resolve(
105
- (formatter as Formatter).render(writer, data as never, parsedOpts, cols),
108
+ (formatter as Formatter).render(
109
+ writer,
110
+ data as never,
111
+ parsedOpts,
112
+ effectiveCols,
113
+ ),
106
114
  );
107
115
  } finally {
108
116
  if (close) await close();
@@ -0,0 +1,316 @@
1
+ /**
2
+ * @module output/error
3
+ *
4
+ * Structured-error envelope. Mirrors Go's `go/console/output` error
5
+ * envelope: when a command fails under `--format json|yaml`, the error is
6
+ * materialized as a {@link CliError} and rendered to stderr by
7
+ * {@link renderError}. Plaintext mode (`--format table` or unset) prints
8
+ * `"Code: Message\nFix: ...\n"`.
9
+ *
10
+ * Fields use the on-wire snake_case keys directly (like the telemetry
11
+ * `Envelope`) so `JSON.stringify` is wire-exact; empty optional fields
12
+ * stay off the wire, mirroring Go's `omitempty`.
13
+ */
14
+
15
+ import * as yaml from 'js-yaml';
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Transience classes
19
+ // ---------------------------------------------------------------------------
20
+
21
+ /** Marks a failure a retry may clear (rate limit, timeout, upstream blip). */
22
+ export const TRANSIENCE_TRANSIENT = 'transient';
23
+ /**
24
+ * Marks a failure retrying cannot clear without changing the input or the
25
+ * environment.
26
+ */
27
+ export const TRANSIENCE_PERMANENT = 'permanent';
28
+ /**
29
+ * Marks a failure kit cannot classify. Agents should treat retries as
30
+ * best-effort and bounded.
31
+ */
32
+ export const TRANSIENCE_UNKNOWN = 'unknown';
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Standard codes mapping the cross-tool exit codes (conventions §8.1)
36
+ // ---------------------------------------------------------------------------
37
+
38
+ export const CODE_OK = 'OK'; // exit 0
39
+ export const CODE_GENERIC = 'GENERIC'; // exit 1
40
+ export const CODE_USAGE = 'USAGE'; // exit 2
41
+ export const CODE_NOT_FOUND = 'NOT_FOUND'; // exit 3
42
+ export const CODE_CONFLICT = 'CONFLICT'; // exit 4
43
+ export const CODE_UNAUTHORIZED = 'UNAUTHORIZED'; // exit 5
44
+ export const CODE_TRANSIENT = 'TRANSIENT'; // exit 6 — Factor-11 transient/retryable failure
45
+ export const CODE_PROVENANCE_MISSING = 'PROVENANCE_MISSING'; // exit 65 — Factor-12 strict-mode refusal
46
+ export const CODE_RATE_LIMITED = 'RATE_LIMITED'; // exit 64 — Factor-10 max-ops budget exceeded
47
+
48
+ /**
49
+ * Spec-assigned exit code for the generic failure class: the command
50
+ * failed and no narrower code applies. Pair it with {@link genericError}
51
+ * rather than hand-rolling exit 1, so the envelope carries a transience
52
+ * class.
53
+ */
54
+ export const EXIT_GENERIC = 1;
55
+ /**
56
+ * Spec-assigned exit code for transient/retryable failures (Factor 11).
57
+ * Agents branch on it before parsing stderr: exit 6 means a retry may
58
+ * clear the failure.
59
+ */
60
+ export const EXIT_TRANSIENT = 6;
61
+ /** Conventional exit code for Factor-10 rate-limit refusals. */
62
+ export const EXIT_RATE_LIMITED = 64;
63
+ /**
64
+ * Conventional exit code for Factor-12 strict-mode provenance refusals.
65
+ * Lives at 65 in kit's extension band (alongside RATE_LIMITED at 64):
66
+ * the spec reserves 0-6 for its core taxonomy and leaves >6 to per-tool
67
+ * codes, and kit as a library stays out of the low per-tool range.
68
+ */
69
+ export const EXIT_PROVENANCE_MISSING = 65;
70
+
71
+ /**
72
+ * Structured-error envelope rendered to stderr when `--format json|yaml`
73
+ * is set. Keys are the on-wire snake_case names.
74
+ *
75
+ * `transience` classifies the failure for retry decisions (Factor 4):
76
+ * transient (retry-worthy), permanent (do not retry), or unknown.
77
+ * Constructors and {@link wrapError} populate it; {@link renderError}
78
+ * normalizes an unset value to unknown so every structured error carries
79
+ * a valid class on the wire.
80
+ */
81
+ export interface CliError {
82
+ code: string;
83
+ message: string;
84
+ cause?: string;
85
+ suggested_fix?: string;
86
+ alternatives?: string[];
87
+ exit_code: number;
88
+ transience?: string;
89
+ }
90
+
91
+ /**
92
+ * Retained source errors, keyed by envelope. Mirrors Go's unexported
93
+ * `err` field: off the wire by construction, readable via
94
+ * {@link unwrapError}.
95
+ */
96
+ const retained = new WeakMap<CliError, unknown>();
97
+
98
+ /**
99
+ * Default transience class for one of the standard codes. Unrecognized
100
+ * (adopter-defined) codes map to unknown; adopters set `transience`
101
+ * (or use {@link withTransience}) to classify their own codes.
102
+ */
103
+ export function transienceForCode(code: string): string {
104
+ switch (code) {
105
+ case CODE_USAGE:
106
+ case CODE_NOT_FOUND:
107
+ case CODE_CONFLICT:
108
+ case CODE_UNAUTHORIZED:
109
+ case CODE_PROVENANCE_MISSING:
110
+ return TRANSIENCE_PERMANENT;
111
+ case CODE_RATE_LIMITED:
112
+ case CODE_TRANSIENT:
113
+ return TRANSIENCE_TRANSIENT;
114
+ default:
115
+ return TRANSIENCE_UNKNOWN;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Builds an envelope from `err`, retaining it for {@link unwrapError}
121
+ * while rendering as `code` and message. Transience defaults from the
122
+ * code via {@link transienceForCode}; use {@link withTransience} to
123
+ * override.
124
+ */
125
+ export function wrapError(
126
+ err: unknown,
127
+ code: string,
128
+ exitCode: number,
129
+ ): CliError | null {
130
+ if (err === null || err === undefined) return null;
131
+ const e: CliError = {
132
+ code,
133
+ message: err instanceof Error ? err.message : String(err),
134
+ exit_code: exitCode,
135
+ transience: transienceForCode(code),
136
+ };
137
+ retained.set(e, err);
138
+ return e;
139
+ }
140
+
141
+ /**
142
+ * The error this envelope was built from via {@link wrapError}, so
143
+ * callers can classify failures by cause instead of string-matching
144
+ * `message`. Mirrors Go's `(*Error).Unwrap`.
145
+ */
146
+ export function unwrapError(e: CliError): unknown {
147
+ return retained.get(e);
148
+ }
149
+
150
+ /**
151
+ * Copy of `e` with `transience` set, every other field (and the retained
152
+ * source error) untouched. Copies rather than mutating: adopters
153
+ * commonly share module-level envelopes, and writing to one would leak
154
+ * across call sites.
155
+ */
156
+ export function withTransience(e: CliError, transience: string): CliError {
157
+ const clone: CliError = { ...e, transience };
158
+ if (retained.has(e)) retained.set(clone, retained.get(e));
159
+ return clone;
160
+ }
161
+
162
+ /**
163
+ * CODE_GENERIC envelope with exit code 1. The catch-all for failures no
164
+ * narrower code describes; permanent because retrying the same input
165
+ * in the same environment is not expected to help. Wrapping an
166
+ * arbitrary error as CODE_GENERIC via {@link wrapError} still defaults
167
+ * to unknown.
168
+ */
169
+ export function genericError(message: string): CliError {
170
+ return {
171
+ code: CODE_GENERIC,
172
+ message,
173
+ exit_code: EXIT_GENERIC,
174
+ transience: TRANSIENCE_PERMANENT,
175
+ };
176
+ }
177
+
178
+ /** CODE_NOT_FOUND envelope with exit code 3. */
179
+ export function notFoundError(message: string): CliError {
180
+ return {
181
+ code: CODE_NOT_FOUND,
182
+ message,
183
+ exit_code: 3,
184
+ transience: TRANSIENCE_PERMANENT,
185
+ };
186
+ }
187
+
188
+ /** CODE_CONFLICT envelope with exit code 4. */
189
+ export function conflictError(message: string): CliError {
190
+ return {
191
+ code: CODE_CONFLICT,
192
+ message,
193
+ exit_code: 4,
194
+ transience: TRANSIENCE_PERMANENT,
195
+ };
196
+ }
197
+
198
+ /** CODE_UNAUTHORIZED envelope with exit code 5. */
199
+ export function unauthorizedError(message: string): CliError {
200
+ return {
201
+ code: CODE_UNAUTHORIZED,
202
+ message,
203
+ exit_code: 5,
204
+ transience: TRANSIENCE_PERMANENT,
205
+ };
206
+ }
207
+
208
+ /** CODE_USAGE envelope with exit code 2. */
209
+ export function usageError(message: string): CliError {
210
+ return {
211
+ code: CODE_USAGE,
212
+ message,
213
+ exit_code: 2,
214
+ transience: TRANSIENCE_PERMANENT,
215
+ };
216
+ }
217
+
218
+ /**
219
+ * CODE_TRANSIENT envelope with exit code 6 (Factor 11). Use it for
220
+ * failures a retry may clear: upstream timeouts, connection resets,
221
+ * service-unavailable responses.
222
+ */
223
+ export function transientError(message: string): CliError {
224
+ return {
225
+ code: CODE_TRANSIENT,
226
+ message,
227
+ exit_code: EXIT_TRANSIENT,
228
+ transience: TRANSIENCE_TRANSIENT,
229
+ };
230
+ }
231
+
232
+ /** CODE_RATE_LIMITED envelope with exit code 64 (Factor 10). */
233
+ export function rateLimitedError(message: string): CliError {
234
+ return {
235
+ code: CODE_RATE_LIMITED,
236
+ message,
237
+ exit_code: EXIT_RATE_LIMITED,
238
+ transience: TRANSIENCE_TRANSIENT,
239
+ };
240
+ }
241
+
242
+ /**
243
+ * CODE_PROVENANCE_MISSING envelope with exit code 65 (Factor 12).
244
+ * `detail` is a free-form string suitable for the `cause` slot
245
+ * (typically the JSON-pointer list of offending fields).
246
+ */
247
+ export function provenanceMissingError(detail: string): CliError {
248
+ return {
249
+ code: CODE_PROVENANCE_MISSING,
250
+ message: 'provenance not recorded for one or more output fields',
251
+ cause: detail,
252
+ suggested_fix:
253
+ 'record provenance for synthesized/cached fields before rendering ' +
254
+ '(see @hop-top/kit/provenance)',
255
+ exit_code: EXIT_PROVENANCE_MISSING,
256
+ transience: TRANSIENCE_PERMANENT,
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Wire form of `e`: empty optional fields dropped (omitempty parity),
262
+ * key order mirroring the Go struct.
263
+ */
264
+ function toWire(e: CliError): CliError {
265
+ const wire: Record<string, unknown> = { code: e.code, message: e.message };
266
+ if (e.cause) wire.cause = e.cause;
267
+ if (e.suggested_fix) wire.suggested_fix = e.suggested_fix;
268
+ if (e.alternatives && e.alternatives.length > 0) {
269
+ wire.alternatives = [...e.alternatives];
270
+ }
271
+ wire.exit_code = e.exit_code;
272
+ if (e.transience) wire.transience = e.transience;
273
+ return wire as unknown as CliError;
274
+ }
275
+
276
+ /**
277
+ * Writes `err` to `w` in the requested format. `format === ''` or
278
+ * `'table'` renders human-readable plain text (`"Code: Message\nFix:
279
+ * ..."`); JSON/YAML render the envelope structurally. An unset
280
+ * transience is normalized to unknown on the wire (Factor 4) without
281
+ * mutating `err`. Always returns; the caller decides the exit code from
282
+ * `err.exit_code` after rendering.
283
+ */
284
+ export function renderError(
285
+ w: { write(chunk: string): unknown },
286
+ format: string,
287
+ err: CliError | null | undefined,
288
+ ): void {
289
+ if (!err) return;
290
+ const e = err.transience ? err : withTransience(err, TRANSIENCE_UNKNOWN);
291
+ if (format === 'json') {
292
+ w.write(`${JSON.stringify(toWire(e), null, 2)}\n`);
293
+ return;
294
+ }
295
+ if (format === 'yaml') {
296
+ w.write(yaml.dump(toWire(e)));
297
+ return;
298
+ }
299
+ renderErrorPlain(w, e);
300
+ }
301
+
302
+ /**
303
+ * Human-readable form used by `--format table` (and the default empty
304
+ * format). Each populated field appears on its own line so the output is
305
+ * grep-friendly.
306
+ */
307
+ function renderErrorPlain(
308
+ w: { write(chunk: string): unknown },
309
+ err: CliError,
310
+ ): void {
311
+ let out = err.code ? `${err.code}: ${err.message}\n` : `${err.message}\n`;
312
+ if (err.cause) out += `Cause: ${err.cause}\n`;
313
+ if (err.suggested_fix) out += `Fix: ${err.suggested_fix}\n`;
314
+ for (const alt of err.alternatives ?? []) out += `Alternative: ${alt}\n`;
315
+ w.write(out);
316
+ }
@@ -24,11 +24,16 @@ export interface OptionSpec {
24
24
  export type Options = Readonly<Record<string, string | number | boolean>>;
25
25
 
26
26
  /**
27
- * Column metadata used by table/csv/text formatters and --cols validation.
27
+ * Column metadata used by every built-in formatter and by --cols validation.
28
28
  *
29
- * - `header` is the user-visible label and the value matched against --cols.
30
- * - `key` is the property name on the row object.
31
- * - `priority` (optional) controls hide-on-overflow for table; higher wins.
29
+ * - `header` is the user-visible label, the name matched against --cols, AND
30
+ * the property read off the row object: header == key, universally. Go
31
+ * cannot express a header/key split through `table:""` struct tags, so no
32
+ * SDK offers one.
33
+ * - `key` is retained for source compatibility and must equal `header`;
34
+ * `columnName` reports the single effective name.
35
+ * - `priority` is accepted and stored but ignored — hide-on-overflow is a
36
+ * Go-only feature today.
32
37
  */
33
38
  export interface ColumnSpec {
34
39
  readonly header: string;
@@ -36,6 +41,21 @@ export interface ColumnSpec {
36
41
  readonly priority?: number;
37
42
  }
38
43
 
44
+ /**
45
+ * Returns a ColumnSpec's effective column name, rejecting a header/key split.
46
+ *
47
+ * Validating at read time keeps drift impossible while `key` still exists as
48
+ * a field.
49
+ */
50
+ export function columnName(c: ColumnSpec): string {
51
+ if (c.key !== c.header) {
52
+ throw new Error(
53
+ `column "${c.header}": header and key must match (got key "${c.key}")`,
54
+ );
55
+ }
56
+ return c.header;
57
+ }
58
+
39
59
  /**
40
60
  * A Formatter encodes structured data to a writable stream.
41
61
  *
@@ -63,7 +83,11 @@ export interface Formatter<T = unknown> {
63
83
  * @param out Destination writable stream.
64
84
  * @param data Single row or readonly array of rows.
65
85
  * @param opts Validated options; only declared keys with coerced values.
66
- * @param cols User-requested column projection; empty means "all columns".
86
+ * @param cols Effective column list, already resolved by dispatch: the
87
+ * user's `--cols` when supplied, else the caller's ColumnSpec headers in
88
+ * list order, else empty meaning "fall back to payload key order".
89
+ * Render columns in exactly this order — it is both the labels and, since
90
+ * header == key, the lookup names on each row.
67
91
  */
68
92
  render(
69
93
  out: NodeJS.WritableStream,