@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
@@ -0,0 +1,48 @@
1
+ # telemetry
2
+
3
+ ## What it answers
4
+
5
+ What a TS adopter needs before emitting usage telemetry: the mode gate (`off`, `anon`, `full`), the anonymous rotatable install id, the consent reader, the redactor, and a non-blocking `Client` with jsonl and https sinks. Default-denied: a fresh install never emits. Wrong module for Factor 11 provenance metadata on payloads (`@hop-top/kit/provenance`) and for the compliance checker (`@hop-top/kit/compliance`).
6
+
7
+ ## Use it when
8
+
9
+ - record an event: `new Client(opts)`, `client.record(event, attrs)`, `await client.shutdown(ms)`
10
+ - know which tier applies: `resolveMode(process.env)`
11
+ - read or rotate the install id: `getInstallId()`, `rotate()`
12
+ - check the operator's decision: `loadConsent()`
13
+ - scrub before your own sink: `redact(value)`, `redactString(s)`
14
+
15
+ ## Quick start
16
+
17
+ ```ts
18
+ import { Client } from '@hop-top/kit/telemetry';
19
+
20
+ const client = new Client({ sink: 'jsonl', sinkFile: '/tmp/kit-events.jsonl', sdkVersion: '0.0.0' });
21
+ client.record('cmd.invoked', { command: 'launch', exit_code: 0 });
22
+ await client.shutdown(5_000);
23
+ ```
24
+
25
+ `record` is a no-op until consent is granted and `KIT_TELEMETRY_MODE` is `anon` or `full`.
26
+
27
+ ## Contract
28
+
29
+ - Envelope shape is [`sdk/docs/telemetry-event-schema.md`](../../../docs/telemetry-event-schema.md); keys are wire snake_case.
30
+ - `record` returns synchronously and never throws; the queue is bounded and drops count.
31
+ - Consent and mode are consulted on each `record`, so a live consent flip takes effect without restart.
32
+ - Redactor placeholders are `<redacted:email>`, `<redacted:ipv4>`, `<redacted:ipv6>`, `<redacted:token>`, and `$HOME` for home-path prefixes.
33
+ - The envelope carries a free-form `event` plus `attrs` where Go carries `CommandPath`; this is a documented divergence.
34
+ - Parity: [`sdk/tests/cross-lang/expected/envelope.json`](../../../tests/cross-lang/expected/envelope.json), driven by `sdk/tests/cross-lang/run.sh` from [`fixtures/consent.yaml`](../../../tests/cross-lang/fixtures/consent.yaml) and [`fixtures/install_id.bytes`](../../../tests/cross-lang/fixtures/install_id.bytes).
35
+
36
+ ## Neighbours
37
+
38
+ - `@hop-top/kit/provenance`: `_meta` on output payloads
39
+ - `@hop-top/kit/compliance`: 12-factor checks, including the telemetry consent factor
40
+ - `@hop-top/kit/xdg`: state and config paths the install id and consent file live under
41
+ - Go reference: [`go/runtime/telemetry`](../../../../go/runtime/telemetry/README.md); Python port: [`hop_top_kit/telemetry`](../../../py/hop_top_kit/telemetry/README.md)
42
+
43
+ ## See also
44
+
45
+ - [`sdk/ts/README.md`](../../README.md), section "Telemetry": env vars, redactor, envelope
46
+ - [`docs/adopters/guides/telemetry.md`](../../../../docs/adopters/guides/telemetry.md)
47
+ - [`docs/adopters/reference/telemetry-compliance.md`](../../../../docs/adopters/reference/telemetry-compliance.md)
48
+ - [`sdk/tests/cross-lang/README.md`](../../../tests/cross-lang/README.md)
@@ -18,10 +18,10 @@
18
18
  * a fail-closed posture.
19
19
  * - **Default Mode is Off**: `resolveMode()` is consulted at the same
20
20
  * gating step. Anything other than `anon` / `full` no-ops.
21
- * - **Envelope shape**: matches the cross-language event-schema doc
22
- * for the common fields. NOTE: per the task spec, the TS+Py SDKs
23
- * diverge from Go by carrying free-form `event` (string) + `attrs`
24
- * (object) at the envelope root. See event-schema §3.
21
+ * - **Envelope shape**: matches the cross-language event schema
22
+ * for the common fields. NOTE: the TS+Py SDKs diverge from Go by
23
+ * carrying free-form `event` (string) + `attrs` (object) at the
24
+ * envelope root.
25
25
  * - **install_id caching**: `getInstallId()` does file I/O; we resolve
26
26
  * it lazily and cache the resolved promise.
27
27
  *
@@ -69,7 +69,7 @@ const DEFAULT_QUEUE_SIZE = 1024;
69
69
  const FLUSH_INTERVAL_MS = 5_000;
70
70
  /** Threshold that triggers an early flush before the interval fires. */
71
71
  const FLUSH_BATCH_TRIGGER = 64;
72
- /** HTTPS connect timeout (per the ADR's "non-blocking" stance). */
72
+ /** HTTPS connect timeout (telemetry must never block the caller). */
73
73
  const HTTPS_CONNECT_TIMEOUT_MS = 5_000;
74
74
  /** HTTPS overall timeout. */
75
75
  const HTTPS_TOTAL_TIMEOUT_MS = 10_000;
@@ -27,8 +27,8 @@ describe("loadToolSpec", () => {
27
27
  ]);
28
28
  expect(spec.stateIntrospection!.envVars).toEqual([
29
29
  "SPACED_FORMAT",
30
- "SPACED_LOG_LEVEL",
31
30
  "SPACED_LOG_FORMAT",
31
+ "SPACED_LOG_LEVEL",
32
32
  ]);
33
33
  });
34
34
 
@@ -40,7 +40,7 @@ describe("loadToolSpec", () => {
40
40
  expect(launch).toBeDefined();
41
41
  expect(launch!.intent?.domain).toBe("space");
42
42
  expect(launch!.intent?.category).toBe("operations");
43
- expect(launch!.intent?.tags).toEqual(["mission", "launch"]);
43
+ expect(launch!.intent?.tags).toEqual(["launch", "mission"]);
44
44
  });
45
45
 
46
46
  it("loads contract fields", () => {
@@ -0,0 +1,34 @@
1
+ # triton
2
+
3
+ ## What it answers
4
+
5
+ How to call a model hosted on Triton Inference Server over HTTP with the KServe v2 protocol, including `triton://host:port/model[/version]` URI parsing. Wrong module for chat-style LLM calls (`@hop-top/kit/llm`) and for routing decisions ([`../router`](../router/README.md)).
6
+
7
+ ## Use it when
8
+
9
+ - parse a configured endpoint: `parseTritonURI(uri)` returns `{ host, port, modelName, modelVersion }`
10
+ - run inference: `new TritonClient(...)` implementing `TritonScorer`
11
+ - liveness: `ServerHealth`
12
+
13
+ ## Quick start
14
+
15
+ ```ts
16
+ import { parseTritonURI } from './client';
17
+
18
+ console.log(parseTritonURI('triton://localhost:8000/bert_router'));
19
+ ```
20
+
21
+ ## Contract
22
+
23
+ - Request and response bodies are the KServe v2 `InferRequest` / `InferResponse` shapes; tensor `datatype` is one of `TritonDataType`.
24
+ - Failures raise `TritonError`.
25
+ - Not on the package exports map and not in the `tsup` build: reachable only by relative import inside `src/`.
26
+
27
+ ## Neighbours
28
+
29
+ - [`../router/bert.ts`](../router/bert.ts): the consumer, through the `TritonInfer` interface
30
+ - `@hop-top/kit/llm`: provider clients for chat completions
31
+
32
+ ## See also
33
+
34
+ - [KServe v2 inference protocol](https://kserve.github.io/website/modelserving/inference_api/)
@@ -0,0 +1,42 @@
1
+ # tui
2
+
3
+ ## What it answers
4
+
5
+ How a TS CLI paints the same terminal widgets as a Go kit CLI: status lines, badges, pills, spinner, progress bar, gradient animation, confirm and list prompts, all themed from `@hop-top/kit/cli`'s `Theme`. Wrong module for structured output (`@hop-top/kit/output`) and for machine-readable progress events (`@hop-top/kit/progress`).
6
+
7
+ ## Use it when
8
+
9
+ - prefixed status line: `status(theme, text, 'info' | 'success' | 'error' | 'warn')`
10
+ - inline label: `badge(theme, text)`, `pills(theme, items)`
11
+ - long-running step in a TTY: `spinner(theme)`, `progress(theme)`
12
+ - yes/no or pick-one prompt: `confirm(theme, ...)`, `list(theme, ...)`
13
+
14
+ ## Quick start
15
+
16
+ ```ts
17
+ import { buildTheme } from '@hop-top/kit/cli';
18
+ import { status, badge } from '@hop-top/kit/tui';
19
+
20
+ const theme = buildTheme();
21
+ console.log(status(theme, 'Deployed', 'success'));
22
+ console.log(badge(theme, 'beta'));
23
+ ```
24
+
25
+ ## Contract
26
+
27
+ - Status symbols, spinner frames and interval, and animation runes come from [`contracts/parity/parity.json`](../../../../contracts/parity/parity.json) through [`parity.ts`](parity.ts); never inline them.
28
+ - [`parity.test.ts`](parity.test.ts) is the block-registry guard: a block declared in the contract without a loader here fails.
29
+ - Every renderer takes `Theme` as its first argument; there is no module-level default theme.
30
+ - Parity: [`contracts/parity/README.md`](../../../../contracts/parity/README.md), table "Declared blocks", rows `status`, `spinner`, `anim`.
31
+
32
+ ## Neighbours
33
+
34
+ - `@hop-top/kit/cli`: `Theme`, `buildTheme`, help layout
35
+ - `@hop-top/kit/output`: tables and structured formats
36
+ - `@hop-top/kit/progress`: JSON progress events for non-TTY consumers
37
+ - Go reference: [`go/console/tui`](../../../../go/console/tui/README.md); Python port: [`hop_top_kit/tui`](../../../py/hop_top_kit/tui/README.md)
38
+
39
+ ## See also
40
+
41
+ - [`docs/adopters/guides/tui-component-gallery.md`](../../../../docs/adopters/guides/tui-component-gallery.md)
42
+ - [`docs/adopters/guides/cli-parity-guide.md`](../../../../docs/adopters/guides/cli-parity-guide.md)
@@ -16,7 +16,7 @@ import {
16
16
  resultBool,
17
17
  resultStrings,
18
18
  resultChoice,
19
- type Step,
19
+ Step,
20
20
  } from "./wizard";
21
21
 
22
22
  // --- construction ---
@@ -39,11 +39,11 @@ describe("Wizard construction", () => {
39
39
  it("rejects empty key", () => {
40
40
  expect(
41
41
  () =>
42
- new Wizard({
42
+ new Wizard(new Step({
43
43
  key: "",
44
44
  kind: StepKind.TextInput,
45
45
  label: "Name",
46
- } as Step),
46
+ })),
47
47
  ).toThrow(/key must not be empty/i);
48
48
  });
49
49
 
@@ -56,23 +56,23 @@ describe("Wizard construction", () => {
56
56
  it("rejects action without fn", () => {
57
57
  expect(
58
58
  () =>
59
- new Wizard({
59
+ new Wizard(new Step({
60
60
  key: "act",
61
61
  kind: StepKind.Action,
62
62
  label: "do",
63
- } as Step),
63
+ })),
64
64
  ).toThrow(/actionFn/i);
65
65
  });
66
66
 
67
67
  it("rejects select without options", () => {
68
68
  expect(
69
69
  () =>
70
- new Wizard({
70
+ new Wizard(new Step({
71
71
  key: "sel",
72
72
  kind: StepKind.Select,
73
73
  label: "pick",
74
74
  options: [],
75
- } as Step),
75
+ })),
76
76
  ).toThrow(/options/i);
77
77
  });
78
78
 
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Shared helpers for the llm-v1 conformance runners: the vector file,
3
+ * a loopback HTTP server and env isolation. Test-only.
4
+ *
5
+ * @internal
6
+ */
7
+
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
10
+ import type { AddressInfo } from "node:net";
11
+ import { dirname, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ /** Loads contracts/llm-v1/vectors.json from the repo. */
15
+ export function loadVectors<T>(): T {
16
+ let dir = dirname(fileURLToPath(import.meta.url));
17
+ for (let i = 0; i < 10; i++) {
18
+ const p = resolve(dir, "contracts/llm-v1/vectors.json");
19
+ if (existsSync(p)) return JSON.parse(readFileSync(p, "utf8")) as T;
20
+ dir = dirname(dir);
21
+ }
22
+ throw new Error("contracts/llm-v1/vectors.json not found");
23
+ }
24
+
25
+ export interface Hit {
26
+ method: string;
27
+ url: string;
28
+ headers: IncomingMessage["headers"];
29
+ body: string;
30
+ }
31
+
32
+ export interface FakeServer {
33
+ url: string;
34
+ hits: Hit[];
35
+ close(): Promise<void>;
36
+ }
37
+
38
+ /** A loopback server answering every request with `handler`. */
39
+ export async function fakeServer(
40
+ handler: (hit: Hit, res: ServerResponse, n: number) => void
41
+ ): Promise<FakeServer> {
42
+ const hits: Hit[] = [];
43
+ const srv = createServer((req, res) => {
44
+ const chunks: Buffer[] = [];
45
+ req.on("data", (c: Buffer) => chunks.push(c));
46
+ req.on("end", () => {
47
+ const hit: Hit = {
48
+ method: req.method ?? "",
49
+ url: req.url ?? "",
50
+ headers: req.headers,
51
+ body: Buffer.concat(chunks).toString("utf8"),
52
+ };
53
+ hits.push(hit);
54
+ handler(hit, res, hits.length - 1);
55
+ });
56
+ });
57
+ await new Promise<void>((r) => srv.listen(0, "127.0.0.1", r));
58
+ const { port } = srv.address() as AddressInfo;
59
+ return {
60
+ url: `http://127.0.0.1:${port}`,
61
+ hits,
62
+ close: () =>
63
+ new Promise<void>((r) => {
64
+ srv.closeAllConnections();
65
+ srv.close(() => r());
66
+ }),
67
+ };
68
+ }
69
+
70
+ /** Writes `body` with `contentType` and status 200. */
71
+ export function reply(res: ServerResponse, contentType: string, body: string, status = 200): void {
72
+ res.writeHead(status, { "content-type": contentType });
73
+ res.end(body);
74
+ }
75
+
76
+ /** Env vars a runner clears before each vector and restores after. */
77
+ export const LLM_ENV = [
78
+ "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL",
79
+ "ANTHROPIC_WORKSPACE_ID", "LLM_BASE_URL", "LLM_API_KEY", "LLM_PROVIDER",
80
+ "LLM_FALLBACK", "OPENAI_API_KEY", "ROUTELLM_BASE_URL",
81
+ ];
82
+
83
+ /** Snapshots `keys`, clears them, and returns a restore function. */
84
+ export function isolateEnv(keys: string[] = LLM_ENV): () => void {
85
+ const saved = new Map(keys.map((k) => [k, process.env[k]]));
86
+ for (const k of keys) delete process.env[k];
87
+ return () => {
88
+ for (const [k, v] of saved) {
89
+ if (v === undefined) delete process.env[k];
90
+ else process.env[k] = v;
91
+ }
92
+ };
93
+ }
94
+
95
+ /** Fails on any key of `obj` outside `allowed`: vectors are strict. */
96
+ export function strictKeys(obj: object, allowed: string[], where: string): void {
97
+ for (const k of Object.keys(obj)) {
98
+ if (!allowed.includes(k)) throw new Error(`${where}: unknown field ${JSON.stringify(k)}`);
99
+ }
100
+ }
@@ -23,7 +23,6 @@ function makeProgram(argv: readonly string[]) {
23
23
 
24
24
  function captureStdout(): { restore: () => void; out: () => string } {
25
25
  const chunks: Buffer[] = [];
26
- const original = process.stdout.write.bind(process.stdout);
27
26
  const spy = vi.spyOn(process.stdout, 'write').mockImplementation(
28
27
  ((c: string | Buffer) => {
29
28
  chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c));
@@ -31,7 +30,7 @@ function captureStdout(): { restore: () => void; out: () => string } {
31
30
  }) as typeof process.stdout.write,
32
31
  );
33
32
  return {
34
- restore: () => spy.mockRestore() && original.toString,
33
+ restore: () => spy.mockRestore(),
35
34
  out: () => Buffer.concat(chunks).toString(),
36
35
  };
37
36
  }
@@ -2,13 +2,18 @@ import { describe, it, expect } from 'vitest';
2
2
  import * as yaml from 'js-yaml';
3
3
  import {
4
4
  CODE_CONFLICT,
5
+ CODE_CONSENT_REFUSED,
5
6
  CODE_GENERIC,
6
7
  CODE_NOT_FOUND,
8
+ CODE_PREREQUISITE,
7
9
  CODE_PROVENANCE_MISSING,
8
10
  CODE_RATE_LIMITED,
9
11
  CODE_TRANSIENT,
10
12
  CODE_UNAUTHORIZED,
11
13
  CODE_USAGE,
14
+ EXIT_CONSENT_REFUSED,
15
+ EXIT_GENERIC,
16
+ EXIT_PREREQUISITE,
12
17
  EXIT_PROVENANCE_MISSING,
13
18
  EXIT_RATE_LIMITED,
14
19
  EXIT_TRANSIENT,
@@ -16,7 +21,10 @@ import {
16
21
  TRANSIENCE_TRANSIENT,
17
22
  TRANSIENCE_UNKNOWN,
18
23
  conflictError,
24
+ consentRefusedError,
25
+ genericError,
19
26
  notFoundError,
27
+ prerequisiteError,
20
28
  provenanceMissingError,
21
29
  rateLimitedError,
22
30
  renderError,
@@ -43,6 +51,7 @@ function capture(): { write(chunk: string): void; text(): string } {
43
51
 
44
52
  describe('constructors — code/exit/transience', () => {
45
53
  const cases: Array<[string, CliError, string, number, string]> = [
54
+ ['Generic', genericError('boom'), CODE_GENERIC, 1, TRANSIENCE_PERMANENT],
46
55
  ['NotFound', notFoundError('nope'), CODE_NOT_FOUND, 3, TRANSIENCE_PERMANENT],
47
56
  ['Conflict', conflictError('dup'), CODE_CONFLICT, 4, TRANSIENCE_PERMANENT],
48
57
  [
@@ -74,6 +83,20 @@ describe('constructors — code/exit/transience', () => {
74
83
  65,
75
84
  TRANSIENCE_PERMANENT,
76
85
  ],
86
+ [
87
+ 'ConsentRefused',
88
+ consentRefusedError('declined'),
89
+ CODE_CONSENT_REFUSED,
90
+ 7,
91
+ TRANSIENCE_TRANSIENT,
92
+ ],
93
+ [
94
+ 'Prerequisite',
95
+ prerequisiteError('no listener'),
96
+ CODE_PREREQUISITE,
97
+ 70,
98
+ TRANSIENCE_TRANSIENT,
99
+ ],
77
100
  ];
78
101
  it.each(cases)('%s', (_name, got, wantCode, wantExit, wantTransience) => {
79
102
  expect(got.code).toBe(wantCode);
@@ -81,14 +104,25 @@ describe('constructors — code/exit/transience', () => {
81
104
  expect(got.transience).toBe(wantTransience);
82
105
  });
83
106
 
84
- it('exit-code table is unique, 6 transient / 65 provenance', () => {
107
+ // Mirrors Go's envelope exit-code table: the 0-6 core taxonomy plus
108
+ // CONSENT_REFUSED 7 and the kit extension band 64/65/70. Uniqueness
109
+ // pins the taxonomy; the per-number assertions pin which class owns
110
+ // which slot, so a port that adds a class at a number Go already
111
+ // spent fails here rather than on a user's machine.
112
+ it('exit-code table is unique and every slot is owned by its Go class', () => {
85
113
  const exits = new Map(cases.map(([, e]) => [e.exit_code, e.code]));
86
- expect(exits.size).toBe(7);
114
+ expect(exits.size).toBe(10);
115
+ expect(EXIT_GENERIC).toBe(1);
87
116
  expect(EXIT_TRANSIENT).toBe(6);
117
+ expect(EXIT_CONSENT_REFUSED).toBe(7);
88
118
  expect(EXIT_RATE_LIMITED).toBe(64);
89
119
  expect(EXIT_PROVENANCE_MISSING).toBe(65);
120
+ expect(EXIT_PREREQUISITE).toBe(70);
121
+ expect(exits.get(1)).toBe(CODE_GENERIC);
90
122
  expect(exits.get(6)).toBe(CODE_TRANSIENT);
123
+ expect(exits.get(7)).toBe(CODE_CONSENT_REFUSED);
91
124
  expect(exits.get(65)).toBe(CODE_PROVENANCE_MISSING);
125
+ expect(exits.get(70)).toBe(CODE_PREREQUISITE);
92
126
  });
93
127
  });
94
128
 
@@ -101,6 +135,8 @@ describe('transienceForCode', () => {
101
135
  [CODE_PROVENANCE_MISSING, TRANSIENCE_PERMANENT],
102
136
  [CODE_RATE_LIMITED, TRANSIENCE_TRANSIENT],
103
137
  [CODE_TRANSIENT, TRANSIENCE_TRANSIENT],
138
+ [CODE_CONSENT_REFUSED, TRANSIENCE_TRANSIENT],
139
+ [CODE_PREREQUISITE, TRANSIENCE_TRANSIENT],
104
140
  [CODE_GENERIC, TRANSIENCE_UNKNOWN],
105
141
  ['ADOPTER_SPECIFIC', TRANSIENCE_UNKNOWN],
106
142
  ['', TRANSIENCE_UNKNOWN],
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Captures verbatim output for each smoke command listed in T-1011 so the
3
- * track report can include real-world output samples. Run with:
2
+ * Captures verbatim output for each smoke command so a report can
3
+ * include real-world output samples. Run with:
4
4
  *
5
5
  * pnpm exec tsx test/output/smoke-capture.ts
6
6
  */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Smoke tests mirroring T-1011's manual checklist. Each test exercises a
2
+ * Smoke tests mirroring the manual checklist. Each test exercises a
3
3
  * dispatch path end-to-end against an in-memory writer or temp file so the
4
4
  * suite is hermetic but covers the same surface a real `cli list` invocation
5
5
  * would.
@@ -44,7 +44,7 @@ const rows = [
44
44
  { id: '2', name: 'Bob', status: 'idle' },
45
45
  ];
46
46
 
47
- describe('smoke — T-1011 checklist', () => {
47
+ describe('smoke — checklist', () => {
48
48
  it('cli list (default table)', async () => {
49
49
  const program = makeProgram([]);
50
50
  const cap = captureStdout();
@@ -0,0 +1,148 @@
1
+ // Cross-language exit-taxonomy contract loader.
2
+ //
3
+ // Loads contracts/exit-taxonomy-v1/taxonomy.json — generated from
4
+ // go/console/output/envelope, the single source of truth — and asserts
5
+ // this TS SDK's table agrees with it on every class, every exit number
6
+ // and every transience.
7
+ //
8
+ // A failure here means Go's taxonomy moved and this port did not follow.
9
+ // That is the exact drift this contract exists to catch: when Go gained
10
+ // CONSENT_REFUSED 7 and PREREQUISITE 70, all four SDK ports silently
11
+ // kept the old nine-class table for two releases, and
12
+ // transienceForCode returned 'unknown' where Go returned 'transient' —
13
+ // so four runtimes handed agents wrong retry guidance.
14
+ //
15
+ // Fix by adding the missing class here, not by editing the contract:
16
+ // the contract is regenerated from Go, never hand-edited.
17
+
18
+ import { existsSync, readFileSync } from 'node:fs';
19
+ import { dirname, resolve } from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+
22
+ import { describe, it, expect } from 'vitest';
23
+
24
+ import {
25
+ exitClasses,
26
+ exitCodeForClass,
27
+ transienceForCode,
28
+ } from '../../src/output/error';
29
+
30
+ interface TaxonomyClass {
31
+ readonly class: string;
32
+ readonly exit: number;
33
+ readonly transience: string;
34
+ }
35
+
36
+ interface BandSlot {
37
+ readonly exit: number;
38
+ readonly class: string;
39
+ readonly owner: string;
40
+ }
41
+
42
+ interface TaxonomyContract {
43
+ readonly version: string;
44
+ readonly source: string;
45
+ readonly transiences: ReadonlyArray<string>;
46
+ readonly classes: ReadonlyArray<TaxonomyClass>;
47
+ readonly extension_band: ReadonlyArray<BandSlot>;
48
+ }
49
+
50
+ // Walk up from this test file's directory until we hit a directory
51
+ // holding contracts/exit-taxonomy-v1/taxonomy.json. Robust against both
52
+ // `vitest run` (CWD = sdk/ts) and IDE-driven invocations whose CWD may
53
+ // vary.
54
+ function locateContract(): string {
55
+ const here = dirname(fileURLToPath(import.meta.url));
56
+ let dir = here;
57
+ for (let i = 0; i < 10; i++) {
58
+ const candidate = resolve(
59
+ dir,
60
+ 'contracts',
61
+ 'exit-taxonomy-v1',
62
+ 'taxonomy.json',
63
+ );
64
+ if (existsSync(candidate)) return candidate;
65
+ const parent = dirname(dir);
66
+ if (parent === dir) break;
67
+ dir = parent;
68
+ }
69
+ throw new Error(
70
+ `contracts/exit-taxonomy-v1/taxonomy.json: not found walking up from ${here}`,
71
+ );
72
+ }
73
+
74
+ const CONTRACT: TaxonomyContract = JSON.parse(
75
+ readFileSync(locateContract(), 'utf8'),
76
+ ) as TaxonomyContract;
77
+
78
+ // The slots envelope itself owns. The conformance-tree slots (66-69)
79
+ // are recorded in the contract so a new allocation cannot double-book a
80
+ // number, but no SDK port is expected to export them.
81
+ const ENVELOPE_OWNER = 'hop.top/kit/go/console/output/envelope';
82
+
83
+ describe('exit-taxonomy-v1 contract metadata', () => {
84
+ it('pins version and source', () => {
85
+ expect(CONTRACT.version).toBe('v1');
86
+ expect(CONTRACT.source).toBe(ENVELOPE_OWNER);
87
+ expect(CONTRACT.classes.length).toBeGreaterThan(0);
88
+ });
89
+ });
90
+
91
+ describe('exit-taxonomy-v1: this port matches the contract', () => {
92
+ // Membership in both directions. A port carrying an extra class Go
93
+ // does not define is as much a divergence as a port missing one: an
94
+ // adopter branching on it gets a number no other runtime produces.
95
+ it('declares exactly the contract classes, in contract order', () => {
96
+ expect(exitClasses()).toEqual(CONTRACT.classes.map((c) => c.class));
97
+ });
98
+
99
+ it.each(CONTRACT.classes.map((c) => [c.class, c] as const))(
100
+ '%s resolves to the contract exit and transience',
101
+ (_name, row) => {
102
+ expect(exitCodeForClass(row.class)).toBe(row.exit);
103
+ expect(transienceForCode(row.class)).toBe(row.transience);
104
+ },
105
+ );
106
+
107
+ // The transience vocabulary is itself a contract: an agent branching
108
+ // on a fourth string has no defined behavior.
109
+ it('answers only with the contract transience vocabulary', () => {
110
+ for (const row of CONTRACT.classes) {
111
+ expect(CONTRACT.transiences).toContain(transienceForCode(row.class));
112
+ }
113
+ });
114
+
115
+ // An unknown class must resolve to nothing rather than to a fallback
116
+ // number. A built-in fallback is what turns "kit added a class and
117
+ // this port never copied it" into an assertion against exit 1 that
118
+ // reads as a real failure rather than a stale table.
119
+ it('does not invent a code for an adopter-defined class', () => {
120
+ expect(exitCodeForClass('ADOPTER_SPECIFIC')).toBeUndefined();
121
+ expect(transienceForCode('ADOPTER_SPECIFIC')).toBe('unknown');
122
+ });
123
+ });
124
+
125
+ describe('exit-taxonomy-v1 extension band', () => {
126
+ it('exports every band slot envelope owns', () => {
127
+ const owned = CONTRACT.extension_band.filter(
128
+ (s) => s.owner === ENVELOPE_OWNER,
129
+ );
130
+ expect(owned.length).toBeGreaterThan(0);
131
+ for (const slot of owned) {
132
+ expect(exitCodeForClass(slot.class)).toBe(slot.exit);
133
+ }
134
+ });
135
+
136
+ // Slots owned elsewhere must NOT be claimed here. A port that
137
+ // exported LEAK_DETECTED would be minting a number the conformance
138
+ // tree owns, which is the collision the band record exists to stop.
139
+ it('leaves slots owned by other packages unclaimed', () => {
140
+ const foreign = CONTRACT.extension_band.filter(
141
+ (s) => s.owner !== ENVELOPE_OWNER,
142
+ );
143
+ expect(foreign.length).toBeGreaterThan(0);
144
+ for (const slot of foreign) {
145
+ expect(exitCodeForClass(slot.class)).toBeUndefined();
146
+ }
147
+ });
148
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Vitest setup: points XDG_CONFIG_HOME at an empty temp dir per test
3
+ * file, so a developer's own config (llm.yaml included) never reaches
4
+ * a test. A test that needs a config writes it there or sets its own.
5
+ *
6
+ * @internal
7
+ */
8
+
9
+ import { mkdtempSync, rmSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { afterAll } from "vitest";
13
+
14
+ const dir = mkdtempSync(join(tmpdir(), "kit-ts-xdg-"));
15
+ process.env["XDG_CONFIG_HOME"] = dir;
16
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
package/tsconfig.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "compilerOptions": {
3
3
  "target": "ES2020",
4
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
4
5
  "module": "CommonJS",
5
6
  "declaration": true,
6
7
  "outDir": "./dist",
@@ -8,5 +9,6 @@
8
9
  "esModuleInterop": true,
9
10
  "resolveJsonModule": true
10
11
  },
11
- "include": ["src"]
12
+ "include": ["src"],
13
+ "exclude": ["src/**/*.test.ts"]
12
14
  }
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": true,
5
+ "module": "ESNext",
6
+ "moduleResolution": "Bundler"
7
+ },
8
+ "include": ["src", "test"],
9
+ "exclude": []
10
+ }
@@ -0,0 +1,9 @@
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ // Every test file starts with an empty XDG config home, so no
6
+ // developer's llm.yaml (or other config) reaches a test.
7
+ setupFiles: ["test/setup-env.ts"],
8
+ },
9
+ });