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

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 (101) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +237 -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-DgOEOsPB.d.ts +450 -0
  12. package/dist/cli.d.ts +5 -309
  13. package/dist/cli.js +190 -62
  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/id/index.d.ts +2 -83
  19. package/dist/index--C7Mtsmm.d.ts +328 -0
  20. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  21. package/dist/index-MLrRDvEG.d.ts +1073 -0
  22. package/dist/index-QSffbLnj.d.ts +94 -0
  23. package/dist/index.d.ts +26 -0
  24. package/dist/index.js +5863 -0
  25. package/dist/llm-B5XUWH8T.d.ts +231 -0
  26. package/dist/llm.d.ts +1 -188
  27. package/dist/mcp/index.d.ts +2 -0
  28. package/dist/mcp/index.js +1453 -0
  29. package/dist/netpolicy-asvCfwi8.d.ts +138 -0
  30. package/dist/netpolicy.d.ts +1 -0
  31. package/dist/netpolicy.js +118 -0
  32. package/dist/output-VFFLqor9.d.ts +521 -0
  33. package/dist/output.d.ts +2 -213
  34. package/dist/output.js +554 -43
  35. package/dist/progress-CAzyxeWl.d.ts +38 -0
  36. package/dist/progress.d.ts +1 -30
  37. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  38. package/dist/provenance.d.ts +1 -24
  39. package/dist/routellm-PGSt2D1y.d.ts +75 -0
  40. package/dist/routellm.d.ts +2 -64
  41. package/dist/rpc-D5xLEf8V.d.ts +32 -0
  42. package/dist/rpc.d.ts +2 -25
  43. package/dist/safety-CUaYEjZc.d.ts +30 -0
  44. package/dist/safety.d.ts +1 -24
  45. package/dist/scope-BrhYB4ij.d.ts +141 -0
  46. package/dist/scope.d.ts +1 -121
  47. package/dist/stream-CrjeCp0M.d.ts +44 -0
  48. package/dist/stream.d.ts +1 -35
  49. package/dist/telemetry/index.d.ts +1 -315
  50. package/dist/telemetry/index.js +12 -1
  51. package/dist/tui/index.d.ts +4 -298
  52. package/dist/tui/index.js +1 -9
  53. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  54. package/dist/upgrade.d.ts +1 -95
  55. package/dist/xdg-DB7Shoib.d.ts +179 -0
  56. package/dist/xdg.d.ts +1 -169
  57. package/package.json +21 -3
  58. package/src/cli.offline.test.ts +93 -0
  59. package/src/cli.parity.test.ts +192 -0
  60. package/src/cli.ts +112 -12
  61. package/src/index.test.ts +58 -0
  62. package/src/index.ts +36 -0
  63. package/src/log.parity.test.ts +105 -0
  64. package/src/log.ts +64 -13
  65. package/src/mcp/bridge.test.ts +150 -0
  66. package/src/mcp/bridge.ts +246 -0
  67. package/src/mcp/conformance.test.ts +336 -0
  68. package/src/mcp/dispatch.ts +313 -0
  69. package/src/mcp/index.ts +138 -0
  70. package/src/mcp/legacy.ts +314 -0
  71. package/src/mcp/mcp.test.ts +697 -0
  72. package/src/mcp/modern-confirm.test.ts +520 -0
  73. package/src/mcp/modern-confirm.ts +452 -0
  74. package/src/mcp/modern.ts +723 -0
  75. package/src/mcp/tasks.ts +82 -0
  76. package/src/mcp/testtree.ts +250 -0
  77. package/src/mcp/types.ts +504 -0
  78. package/src/netpolicy.test.ts +202 -0
  79. package/src/netpolicy.ts +231 -0
  80. package/src/output/dispatch.ts +10 -2
  81. package/src/output/error.ts +293 -0
  82. package/src/output/formatter.ts +29 -5
  83. package/src/output/formatters/csv.ts +48 -12
  84. package/src/output/formatters/json.ts +4 -25
  85. package/src/output/formatters/project.ts +34 -0
  86. package/src/output/formatters/table.ts +8 -6
  87. package/src/output/formatters/text.ts +7 -3
  88. package/src/output/formatters/yaml.ts +5 -22
  89. package/src/output/projection.test.ts +298 -0
  90. package/src/output/projection.ts +33 -59
  91. package/src/output/template.ts +11 -21
  92. package/src/output.surface.test.ts +41 -0
  93. package/src/output.ts +39 -3
  94. package/src/telemetry/client.test.ts +31 -0
  95. package/src/telemetry/client.ts +7 -1
  96. package/src/telemetry/offline.test.ts +64 -0
  97. package/src/tui/parity.test.ts +120 -31
  98. package/src/tui/parity.ts +58 -7
  99. package/test/output/csv.test.ts +164 -0
  100. package/test/output/error.test.ts +241 -0
  101. 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,293 @@
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 transient/retryable failures (Factor 11).
50
+ * Agents branch on it before parsing stderr: exit 6 means a retry may
51
+ * clear the failure.
52
+ */
53
+ export const EXIT_TRANSIENT = 6;
54
+ /** Conventional exit code for Factor-10 rate-limit refusals. */
55
+ export const EXIT_RATE_LIMITED = 64;
56
+ /**
57
+ * Conventional exit code for Factor-12 strict-mode provenance refusals.
58
+ * Lives at 65 in kit's extension band (alongside RATE_LIMITED at 64):
59
+ * the spec reserves 0-6 for its core taxonomy and leaves >6 to per-tool
60
+ * codes, and kit as a library stays out of the low per-tool range.
61
+ */
62
+ export const EXIT_PROVENANCE_MISSING = 65;
63
+
64
+ /**
65
+ * Structured-error envelope rendered to stderr when `--format json|yaml`
66
+ * is set. Keys are the on-wire snake_case names.
67
+ *
68
+ * `transience` classifies the failure for retry decisions (Factor 4):
69
+ * transient (retry-worthy), permanent (do not retry), or unknown.
70
+ * Constructors and {@link wrapError} populate it; {@link renderError}
71
+ * normalizes an unset value to unknown so every structured error carries
72
+ * a valid class on the wire.
73
+ */
74
+ export interface CliError {
75
+ code: string;
76
+ message: string;
77
+ cause?: string;
78
+ suggested_fix?: string;
79
+ alternatives?: string[];
80
+ exit_code: number;
81
+ transience?: string;
82
+ }
83
+
84
+ /**
85
+ * Retained source errors, keyed by envelope. Mirrors Go's unexported
86
+ * `err` field: off the wire by construction, readable via
87
+ * {@link unwrapError}.
88
+ */
89
+ const retained = new WeakMap<CliError, unknown>();
90
+
91
+ /**
92
+ * Default transience class for one of the standard codes. Unrecognized
93
+ * (adopter-defined) codes map to unknown; adopters set `transience`
94
+ * (or use {@link withTransience}) to classify their own codes.
95
+ */
96
+ export function transienceForCode(code: string): string {
97
+ switch (code) {
98
+ case CODE_USAGE:
99
+ case CODE_NOT_FOUND:
100
+ case CODE_CONFLICT:
101
+ case CODE_UNAUTHORIZED:
102
+ case CODE_PROVENANCE_MISSING:
103
+ return TRANSIENCE_PERMANENT;
104
+ case CODE_RATE_LIMITED:
105
+ case CODE_TRANSIENT:
106
+ return TRANSIENCE_TRANSIENT;
107
+ default:
108
+ return TRANSIENCE_UNKNOWN;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Builds an envelope from `err`, retaining it for {@link unwrapError}
114
+ * while rendering as `code` and message. Transience defaults from the
115
+ * code via {@link transienceForCode}; use {@link withTransience} to
116
+ * override.
117
+ */
118
+ export function wrapError(
119
+ err: unknown,
120
+ code: string,
121
+ exitCode: number,
122
+ ): CliError | null {
123
+ if (err === null || err === undefined) return null;
124
+ const e: CliError = {
125
+ code,
126
+ message: err instanceof Error ? err.message : String(err),
127
+ exit_code: exitCode,
128
+ transience: transienceForCode(code),
129
+ };
130
+ retained.set(e, err);
131
+ return e;
132
+ }
133
+
134
+ /**
135
+ * The error this envelope was built from via {@link wrapError}, so
136
+ * callers can classify failures by cause instead of string-matching
137
+ * `message`. Mirrors Go's `(*Error).Unwrap`.
138
+ */
139
+ export function unwrapError(e: CliError): unknown {
140
+ return retained.get(e);
141
+ }
142
+
143
+ /**
144
+ * Copy of `e` with `transience` set, every other field (and the retained
145
+ * source error) untouched. Copies rather than mutating: adopters
146
+ * commonly share module-level envelopes, and writing to one would leak
147
+ * across call sites.
148
+ */
149
+ export function withTransience(e: CliError, transience: string): CliError {
150
+ const clone: CliError = { ...e, transience };
151
+ if (retained.has(e)) retained.set(clone, retained.get(e));
152
+ return clone;
153
+ }
154
+
155
+ /** CODE_NOT_FOUND envelope with exit code 3. */
156
+ export function notFoundError(message: string): CliError {
157
+ return {
158
+ code: CODE_NOT_FOUND,
159
+ message,
160
+ exit_code: 3,
161
+ transience: TRANSIENCE_PERMANENT,
162
+ };
163
+ }
164
+
165
+ /** CODE_CONFLICT envelope with exit code 4. */
166
+ export function conflictError(message: string): CliError {
167
+ return {
168
+ code: CODE_CONFLICT,
169
+ message,
170
+ exit_code: 4,
171
+ transience: TRANSIENCE_PERMANENT,
172
+ };
173
+ }
174
+
175
+ /** CODE_UNAUTHORIZED envelope with exit code 5. */
176
+ export function unauthorizedError(message: string): CliError {
177
+ return {
178
+ code: CODE_UNAUTHORIZED,
179
+ message,
180
+ exit_code: 5,
181
+ transience: TRANSIENCE_PERMANENT,
182
+ };
183
+ }
184
+
185
+ /** CODE_USAGE envelope with exit code 2. */
186
+ export function usageError(message: string): CliError {
187
+ return {
188
+ code: CODE_USAGE,
189
+ message,
190
+ exit_code: 2,
191
+ transience: TRANSIENCE_PERMANENT,
192
+ };
193
+ }
194
+
195
+ /**
196
+ * CODE_TRANSIENT envelope with exit code 6 (Factor 11). Use it for
197
+ * failures a retry may clear: upstream timeouts, connection resets,
198
+ * service-unavailable responses.
199
+ */
200
+ export function transientError(message: string): CliError {
201
+ return {
202
+ code: CODE_TRANSIENT,
203
+ message,
204
+ exit_code: EXIT_TRANSIENT,
205
+ transience: TRANSIENCE_TRANSIENT,
206
+ };
207
+ }
208
+
209
+ /** CODE_RATE_LIMITED envelope with exit code 64 (Factor 10). */
210
+ export function rateLimitedError(message: string): CliError {
211
+ return {
212
+ code: CODE_RATE_LIMITED,
213
+ message,
214
+ exit_code: EXIT_RATE_LIMITED,
215
+ transience: TRANSIENCE_TRANSIENT,
216
+ };
217
+ }
218
+
219
+ /**
220
+ * CODE_PROVENANCE_MISSING envelope with exit code 65 (Factor 12).
221
+ * `detail` is a free-form string suitable for the `cause` slot
222
+ * (typically the JSON-pointer list of offending fields).
223
+ */
224
+ export function provenanceMissingError(detail: string): CliError {
225
+ return {
226
+ code: CODE_PROVENANCE_MISSING,
227
+ message: 'provenance not recorded for one or more output fields',
228
+ cause: detail,
229
+ suggested_fix:
230
+ 'record provenance for synthesized/cached fields before rendering ' +
231
+ '(see @hop-top/kit/provenance)',
232
+ exit_code: EXIT_PROVENANCE_MISSING,
233
+ transience: TRANSIENCE_PERMANENT,
234
+ };
235
+ }
236
+
237
+ /**
238
+ * Wire form of `e`: empty optional fields dropped (omitempty parity),
239
+ * key order mirroring the Go struct.
240
+ */
241
+ function toWire(e: CliError): CliError {
242
+ const wire: Record<string, unknown> = { code: e.code, message: e.message };
243
+ if (e.cause) wire.cause = e.cause;
244
+ if (e.suggested_fix) wire.suggested_fix = e.suggested_fix;
245
+ if (e.alternatives && e.alternatives.length > 0) {
246
+ wire.alternatives = [...e.alternatives];
247
+ }
248
+ wire.exit_code = e.exit_code;
249
+ if (e.transience) wire.transience = e.transience;
250
+ return wire as unknown as CliError;
251
+ }
252
+
253
+ /**
254
+ * Writes `err` to `w` in the requested format. `format === ''` or
255
+ * `'table'` renders human-readable plain text (`"Code: Message\nFix:
256
+ * ..."`); JSON/YAML render the envelope structurally. An unset
257
+ * transience is normalized to unknown on the wire (Factor 4) without
258
+ * mutating `err`. Always returns; the caller decides the exit code from
259
+ * `err.exit_code` after rendering.
260
+ */
261
+ export function renderError(
262
+ w: { write(chunk: string): unknown },
263
+ format: string,
264
+ err: CliError | null | undefined,
265
+ ): void {
266
+ if (!err) return;
267
+ const e = err.transience ? err : withTransience(err, TRANSIENCE_UNKNOWN);
268
+ if (format === 'json') {
269
+ w.write(`${JSON.stringify(toWire(e), null, 2)}\n`);
270
+ return;
271
+ }
272
+ if (format === 'yaml') {
273
+ w.write(yaml.dump(toWire(e)));
274
+ return;
275
+ }
276
+ renderErrorPlain(w, e);
277
+ }
278
+
279
+ /**
280
+ * Human-readable form used by `--format table` (and the default empty
281
+ * format). Each populated field appears on its own line so the output is
282
+ * grep-friendly.
283
+ */
284
+ function renderErrorPlain(
285
+ w: { write(chunk: string): unknown },
286
+ err: CliError,
287
+ ): void {
288
+ let out = err.code ? `${err.code}: ${err.message}\n` : `${err.message}\n`;
289
+ if (err.cause) out += `Cause: ${err.cause}\n`;
290
+ if (err.suggested_fix) out += `Fix: ${err.suggested_fix}\n`;
291
+ for (const alt of err.alternatives ?? []) out += `Alternative: ${alt}\n`;
292
+ w.write(out);
293
+ }
@@ -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,
@@ -1,12 +1,27 @@
1
1
  /**
2
2
  * @module output/formatters/csv
3
3
  *
4
- * Built-in CSV formatter. Uses csv-stringify (sync API) for RFC 4180 quoting.
5
- * Honors `delimiter`, `no-header`, `quote-all`, `crlf` options + `cols`
6
- * filtering.
4
+ * Built-in CSV formatter. Honors `delimiter`, `no-header`, `quote-all`,
5
+ * `crlf` options + `cols` filtering.
6
+ *
7
+ * Encoding is hand-rolled rather than delegated to csv-stringify. In its
8
+ * `windows` record-delimiter mode that library left a field containing an
9
+ * embedded LF UNQUOTED, so a single record decoded as two (or three)
10
+ * records — structurally invalid CSV, not merely a quoting difference. It
11
+ * also left a leading space bare where the other runtimes quote it.
12
+ *
13
+ * The rule: quote a field iff it contains the active delimiter, a double
14
+ * quote, LF, or CR, or begins with a unicode whitespace character. Trailing
15
+ * whitespace is not quoted. Internal quotes are doubled per RFC 4180.
16
+ *
17
+ * A quoted field's bytes are preserved verbatim in both line-ending modes and
18
+ * both quoting paths. RFC 4180's `escaped` production lists CR and LF as
19
+ * separate alternatives, so a bare CR between quotes is legal, and the W3C
20
+ * CSV on the Web note states that line endings within escaped cells are not
21
+ * normalised. The `crlf` option changes the record terminator and nothing
22
+ * else.
7
23
  */
8
24
 
9
- import { stringify } from 'csv-stringify/sync';
10
25
  import type { Formatter, Options } from '../formatter';
11
26
 
12
27
  export const csvFormatter: Formatter = {
@@ -47,20 +62,41 @@ export const csvFormatter: Formatter = {
47
62
  }
48
63
 
49
64
  const records = rows.map(r => headers.map(h => stringify_cell(r[h])));
65
+ // Headers are prepended here rather than via a library `header` option to
66
+ // keep row layout uniform and make `no-header` a single decision point.
50
67
  const csvRows = noHeader ? records : [headers, ...records];
51
68
 
52
- const text = stringify(csvRows, {
53
- delimiter,
54
- record_delimiter: crlf ? 'windows' : 'unix',
55
- quoted: quoteAll,
56
- // No `header: true` — we already prepend headers ourselves to keep
57
- // row layout uniform with csv format and to make `no-header` toggle
58
- // a single decision point.
59
- });
69
+ const eol = crlf ? '\r\n' : '\n';
70
+ let text = '';
71
+ for (const cells of csvRows) {
72
+ text += cells.map(c => encodeField(c, delimiter, quoteAll)).join(delimiter) + eol;
73
+ }
60
74
  out.write(text);
61
75
  },
62
76
  };
63
77
 
78
+ /**
79
+ * Quote a field iff it contains the delimiter, a quote, LF or CR, or begins
80
+ * with a unicode whitespace character. Note the asymmetry: a LEADING space
81
+ * forces quoting, a trailing one does not. `\.` alone on a line terminates a
82
+ * PostgreSQL COPY stream and is quoted defensively.
83
+ */
84
+ function needsQuotes(field: string, delim: string): boolean {
85
+ if (field === '') return false;
86
+ if (field === '\\.') return true;
87
+ if (field.includes(delim) || field.includes('"') || field.includes('\n') || field.includes('\r')) {
88
+ return true;
89
+ }
90
+ return /^\s/u.test(field);
91
+ }
92
+
93
+ function encodeField(field: string, delim: string, quoteAll: boolean): string {
94
+ if (!quoteAll && !needsQuotes(field, delim)) return field;
95
+ // RFC 4180: an embedded quote is doubled. Everything else, CR and LF
96
+ // included, is written through untouched.
97
+ return `"${field.replace(/"/g, '""')}"`;
98
+ }
99
+
64
100
  function normalise(v: unknown): Record<string, unknown>[] {
65
101
  if (Array.isArray(v)) return v as Record<string, unknown>[];
66
102
  return [v as Record<string, unknown>];