@hop-top/kit 0.5.0-alpha.3 → 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 (187) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +1 -1
  3. package/README.md +47 -575
  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-DLygZLi9.d.ts → cli-8rfITnv4.d.ts} +13 -4
  46. package/dist/cli.d.ts +4 -4
  47. package/dist/cli.js +50 -1057
  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-DISJKeDu.d.ts → error-Do8Qji43.d.ts} +88 -1
  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-Bc5c7Ty5.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 -15
  59. package/dist/index.js +39 -6722
  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-4aXs91GY.d.ts → output-CjZWmL8s.d.ts} +28 -4
  75. package/dist/output.d.ts +2 -2
  76. package/dist/output.js +137 -971
  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-DE-jscpb.d.ts → serve-D8yWMrTc.d.ts} +2 -2
  88. package/dist/serve.d.ts +2 -2
  89. package/dist/serve.js +75 -1019
  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 -5
  94. package/dist/tui/index.js +17 -374
  95. package/dist/upgrade.js +6 -114
  96. package/dist/xdg.js +14 -128
  97. package/package.json +130 -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 +2 -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 +144 -1
  158. package/src/output/formatters/README.md +50 -0
  159. package/src/output.ts +24 -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.ts +1 -1
  170. package/src/telemetry/README.md +48 -0
  171. package/src/telemetry/client.ts +5 -5
  172. package/src/toolspec.test.ts +2 -2
  173. package/src/triton/README.md +34 -0
  174. package/src/tui/README.md +42 -0
  175. package/src/wizard.test.ts +7 -7
  176. package/test/llm/conformance-helpers.ts +100 -0
  177. package/test/output/dispatch.test.ts +1 -2
  178. package/test/output/error.test.ts +33 -2
  179. package/test/output/smoke-capture.ts +2 -2
  180. package/test/output/smoke.test.ts +2 -2
  181. package/test/output/taxonomy-contract.test.ts +148 -0
  182. package/test/setup-env.ts +16 -0
  183. package/tsconfig.json +3 -1
  184. package/tsconfig.test.json +10 -0
  185. package/vitest.config.ts +9 -0
  186. package/dist/llm-B5XUWH8T.d.ts +0 -231
  187. package/dist/routellm-PGSt2D1y.d.ts +0 -75
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * Tests for layered config loader (config.ts).
3
- * Covers: merge order, missing-file skip, bad YAML error, envOverride, empty opts.
3
+ * Covers: merge order, missing-file skip, bad YAML error, envOverride, empty opts,
4
+ * and the per-layer merge rules (objects recursive, arrays/scalars replace,
5
+ * null, type conflicts, non-plain objects).
4
6
  */
5
7
 
6
8
  import * as fs from "fs";
@@ -108,3 +110,187 @@ describe("load", () => {
108
110
  expect(result).toBe(dst);
109
111
  });
110
112
  });
113
+
114
+ // ---------------------------------------------------------------------------
115
+ // Merge rules
116
+ // ---------------------------------------------------------------------------
117
+
118
+ /** Writes each YAML body to a temp file, loads them in order, cleans up. */
119
+ function loadLayers<T extends object>(dst: T, ...bodies: string[]): T {
120
+ const files = bodies.map(tmpYaml);
121
+ try {
122
+ const [systemConfigPath, userConfigPath, projectConfigPath] = files;
123
+ return load(dst, { systemConfigPath, userConfigPath, projectConfigPath });
124
+ } finally {
125
+ cleanup(...files);
126
+ }
127
+ }
128
+
129
+ describe("load merge rules", () => {
130
+ it("merges nested maps across layers instead of replacing them", () => {
131
+ const got = loadLayers<Record<string, unknown>>(
132
+ {},
133
+ "",
134
+ "db:\n host: x\n port: 1\n",
135
+ "db:\n port: 2\n",
136
+ );
137
+ expect(got).toEqual({ db: { host: "x", port: 2 } });
138
+ });
139
+
140
+ it("merges at every depth and keeps dst defaults", () => {
141
+ const dst = { a: { b: { c: 1, d: 2 }, keep: true } };
142
+ loadLayers(dst, "a:\n b:\n d: 3\n e: 4\n");
143
+ expect(dst).toEqual({ a: { b: { c: 1, d: 3, e: 4 }, keep: true } });
144
+ });
145
+
146
+ it("an empty mapping leaves the object as is", () => {
147
+ const dst = { m: { a: 1 } };
148
+ loadLayers(dst, "m: {}\n");
149
+ expect(dst).toEqual({ m: { a: 1 } });
150
+ });
151
+
152
+ it("replaces arrays wholesale, including with an empty one", () => {
153
+ const dst = { tags: ["d"] };
154
+ loadLayers(dst, "tags: [a, b]\n", "tags: [c]\n");
155
+ expect(dst.tags).toEqual(["c"]);
156
+ loadLayers(dst, "tags: []\n");
157
+ expect(dst.tags).toEqual([]);
158
+ });
159
+
160
+ it("replaces scalars", () => {
161
+ const dst = { name: "d", port: 1, debug: false };
162
+ loadLayers(dst, "name: a\nport: 2\n", "name: b\ndebug: true\n");
163
+ expect(dst).toEqual({ name: "b", port: 2, debug: true });
164
+ });
165
+
166
+ it("null leaves a scalar untouched", () => {
167
+ const dst = { name: "d", port: 1 };
168
+ loadLayers(dst, "name: a\n", "name: ~\nport: null\n");
169
+ expect(dst).toEqual({ name: "a", port: 1 });
170
+ });
171
+
172
+ it("null clears objects and arrays", () => {
173
+ const dst = { m: { a: 1 }, tags: ["x"], deep: { inner: { k: "v" } } };
174
+ loadLayers(dst, "m: ~\ntags: ~\ndeep:\n inner: ~\n");
175
+ expect(dst).toEqual({ m: null, tags: null, deep: { inner: null } });
176
+ });
177
+
178
+ it("null sets a key that is absent or already null", () => {
179
+ const dst: Record<string, unknown> = { n: null };
180
+ loadLayers(dst, "n: ~\nfresh: ~\n");
181
+ expect(dst).toEqual({ n: null, fresh: null });
182
+ });
183
+
184
+ it("type conflicts: the later value replaces the earlier one", () => {
185
+ const dst: Record<string, unknown> = {
186
+ objToScalar: { a: 1 },
187
+ scalarToObj: 5,
188
+ objToArray: { a: 1 },
189
+ arrayToObj: [1],
190
+ };
191
+ loadLayers(
192
+ dst,
193
+ "objToScalar: 7\nscalarToObj: {b: 2}\nobjToArray: [x]\narrayToObj: {c: 3}\n",
194
+ );
195
+ expect(dst).toEqual({
196
+ objToScalar: 7,
197
+ scalarToObj: { b: 2 },
198
+ objToArray: ["x"],
199
+ arrayToObj: { c: 3 },
200
+ });
201
+ });
202
+
203
+ it("does not merge into non-plain objects; replaces them", () => {
204
+ class Endpoint {
205
+ host = "h";
206
+ port = 1;
207
+ }
208
+ const dst: Record<string, unknown> = {
209
+ when: new Date(0),
210
+ ep: new Endpoint(),
211
+ map: new Map([["k", "v"]]),
212
+ };
213
+ loadLayers(dst, "when: {y: 1}\nep: {port: 2}\nmap: {k: w}\n");
214
+ expect(dst).toEqual({ when: { y: 1 }, ep: { port: 2 }, map: { k: "w" } });
215
+ expect(Object.getPrototypeOf(dst.ep)).toBe(Object.prototype);
216
+ });
217
+
218
+ it("a YAML timestamp (Date) replaces a plain object", () => {
219
+ const dst: Record<string, unknown> = { when: { y: 1 } };
220
+ loadLayers(dst, "when: 2026-01-02\n");
221
+ expect(dst.when).toBeInstanceOf(Date);
222
+ });
223
+
224
+ it("aliased mappings are copied, so later merges do not leak across keys", () => {
225
+ const dst: Record<string, unknown> = {};
226
+ loadLayers(dst, "a: &x {k: v}\nb: *x\n", "a:\n k: changed\n");
227
+ expect(dst).toEqual({ a: { k: "changed" }, b: { k: "v" } });
228
+ });
229
+
230
+ it("does not let __proto__ keys reach Object.prototype", () => {
231
+ const dst: Record<string, unknown> = {};
232
+ loadLayers(dst, "__proto__:\n polluted: yes\n", "__proto__:\n polluted2: yes\n");
233
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
234
+ expect(({} as Record<string, unknown>).polluted2).toBeUndefined();
235
+ expect(Object.getPrototypeOf(dst)).toBe(Object.prototype);
236
+ });
237
+
238
+ it("ignores a document whose root is not a mapping", () => {
239
+ const dst = { a: 1 };
240
+ loadLayers(dst, "- x\n- y\n", "just a string\n");
241
+ expect(dst).toEqual({ a: 1 });
242
+ });
243
+ });
244
+
245
+ // ---------------------------------------------------------------------------
246
+ // Resource bounds
247
+ // ---------------------------------------------------------------------------
248
+
249
+ /** `levels` anchors, each a list of `width` aliases of the previous one. */
250
+ function aliasBomb(levels: number, width = 9): string {
251
+ const row = (ref: string): string => `[${Array(width).fill(ref).join(", ")}]`;
252
+ let out = `a0: &a0 ${row("lol")}\n`;
253
+ for (let i = 1; i < levels; i++) out += `a${i}: &a${i} ${row(`*a${i - 1}`)}\n`;
254
+ return out;
255
+ }
256
+
257
+ describe("load resource bounds", () => {
258
+ it("fails fast on an exponential alias bomb", () => {
259
+ const started = Date.now();
260
+ expect(() => loadLayers({}, aliasBomb(10))).toThrow(
261
+ /failed to parse .*: document contains excessive aliasing/,
262
+ );
263
+ expect(Date.now() - started).toBeLessThan(2000);
264
+ });
265
+
266
+ it("fails on the shared config-v1 excessive aliasing vector", () => {
267
+ const corpus = JSON.parse(
268
+ fs.readFileSync(path.join(__dirname, "../../../contracts/config-v1/load.json"), "utf8"),
269
+ ) as { cases: { name: string; files: string[] }[] };
270
+ const c = corpus.cases.find((x) => x.name === "excessive aliasing");
271
+ expect(c).toBeDefined();
272
+ expect(() => loadLayers({}, ...(c?.files ?? []))).toThrow(/excessive aliasing/);
273
+ });
274
+
275
+ it("allows ordinary alias use", () => {
276
+ const got = loadLayers<Record<string, unknown>>({}, aliasBomb(2) + "x: *a1\n");
277
+ expect((got.x as unknown[]).length).toBe(9);
278
+ });
279
+
280
+ it("fails on nesting deeper than the limit", () => {
281
+ const deep = "x: " + "[".repeat(150) + "]".repeat(150) + "\n";
282
+ expect(() => loadLayers({}, deep)).toThrow(/failed to parse .*: nesting exceeded maxDepth \(100\)/);
283
+ });
284
+
285
+ it("fails on alias chains that nest deeper than the limit", () => {
286
+ let doc = "a0: &a0 [x]\n";
287
+ for (let i = 1; i < 150; i++) doc += `a${i}: &a${i} [*a${i - 1}]\n`;
288
+ expect(() => loadLayers({}, doc)).toThrow(/failed to parse .*: nesting exceeded maxDepth \(100\)/);
289
+ });
290
+
291
+ it("accepts nesting at the limit", () => {
292
+ const ok = "x: " + "[".repeat(98) + "]".repeat(98) + "\n";
293
+ expect(() => loadLayers({}, ok)).not.toThrow();
294
+ });
295
+ });
296
+
package/src/config.ts CHANGED
@@ -6,9 +6,38 @@
6
6
  * Merges configuration from up to three file layers in priority order:
7
7
  * system → user → project → envOverride
8
8
  *
9
- * Each later layer's values overwrite earlier ones via {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign | Object.assign}.
9
+ * Each layer merges into `dst` with these rules:
10
+ *
11
+ * - Plain objects merge recursively, key by key, so a later layer only
12
+ * overrides the keys it sets (`db: {port: 2}` keeps an earlier `db.host`).
13
+ * - Arrays and scalars are replaced wholesale.
14
+ * - `null` clears an object or array; it leaves a scalar untouched.
15
+ * - On a type conflict (object vs non-object) the later value replaces the
16
+ * earlier one.
17
+ * - Non-plain objects (`Date`, `Map`, class instances) are never merged
18
+ * into; a later value replaces them.
19
+ *
20
+ * This matches Go's `kit/core/config` for struct fields. Go differs where its
21
+ * target type differs: a `map[...]` value or an `any` field is replaced
22
+ * whole rather than merged, and a type conflict on a typed field is a decode
23
+ * error rather than a replacement.
24
+ *
10
25
  * Missing files are silently skipped. A file that exists but contains invalid
11
- * YAML causes {@link load} to throw.
26
+ * YAML causes {@link load} to throw. A document whose root is not a mapping
27
+ * is ignored.
28
+ *
29
+ * Each file is checked before it merges, with aliases expanded, and
30
+ * {@link load} throws `config: failed to parse <path>: <reason>` when:
31
+ *
32
+ * - its aliases expand past Go yaml.v3's budget: more than 100 nodes inside
33
+ * alias expansions and more than 1000 in total, with the share inside
34
+ * aliases above 0.99 (up to 400k nodes), falling linearly to 0.10 at 4M
35
+ * (`document contains excessive aliasing`). Go counts only the keys its
36
+ * target struct reads; TS has no target, so it counts every key, and a
37
+ * file Go accepts because the aliases sit under ignored keys fails here.
38
+ * - collections nest deeper than 100, counted through aliases
39
+ * (`nesting exceeded maxDepth (100)`). Go allows 10000 levels of text
40
+ * nesting and caps alias chains only through the budget above.
12
41
  *
13
42
  * @example
14
43
  * ```ts
@@ -59,13 +88,13 @@ export interface Options<T extends object = object> {
59
88
 
60
89
  /**
61
90
  * Path to the per-user config file, e.g. `~/.config/mytool/config.yaml`.
62
- * Applied second; overwrites system values for shared keys.
91
+ * Applied second; merges over system values (see the module merge rules).
63
92
  */
64
93
  userConfigPath?: string;
65
94
 
66
95
  /**
67
96
  * Path to the project-level config file, e.g. `.mytool.yaml`.
68
- * Applied third; overwrites system and user values for shared keys.
97
+ * Applied third; merges over system and user values.
69
98
  */
70
99
  projectConfigPath?: string;
71
100
 
@@ -85,6 +114,8 @@ export interface Options<T extends object = object> {
85
114
  * Merge order: `systemConfigPath` → `userConfigPath` → `projectConfigPath` →
86
115
  * `envOverride`.
87
116
  *
117
+ * - Objects merge recursively; arrays and scalars replace; `null` clears
118
+ * objects and arrays but not scalars (see the module docs for details).
88
119
  * - Missing files (ENOENT) are silently skipped.
89
120
  * - A file that exists but is not valid YAML causes this function to throw
90
121
  * a descriptive error wrapping the parse failure.
@@ -128,7 +159,7 @@ export function load<T extends object>(dst: T, opts: Options<T> = {}): T {
128
159
  // ---------------------------------------------------------------------------
129
160
 
130
161
  /**
131
- * Read `path`, parse as YAML, and shallow-merge into `dst`.
162
+ * Read `path`, parse as YAML, and merge into `dst` with {@link mergeInto}.
132
163
  * ENOENT is silently ignored; other errors propagate.
133
164
  */
134
165
  function mergeFile<T extends object>(dst: T, filePath: string): void {
@@ -143,17 +174,152 @@ function mergeFile<T extends object>(dst: T, filePath: string): void {
143
174
  let parsed: unknown;
144
175
  try {
145
176
  parsed = yaml.load(raw);
177
+ checkBounds(parsed);
146
178
  } catch (err: unknown) {
147
179
  throw new Error(
148
180
  `config: failed to parse ${filePath}: ${err instanceof Error ? err.message : String(err)}`,
149
181
  );
150
182
  }
151
183
 
152
- if (parsed !== null && parsed !== undefined && typeof parsed === "object") {
153
- Object.assign(dst, parsed);
184
+ if (isPlainObject(parsed)) {
185
+ mergeInto(dst as Record<string, unknown>, parsed);
154
186
  }
155
187
  }
156
188
 
189
+ /**
190
+ * Collection nesting limit, counted through aliases. js-yaml already rejects
191
+ * text nested deeper than its `maxDepth` (default 100, not in its typings),
192
+ * but an alias chain can nest deeper than the text does, and merge/copy
193
+ * recurse once per level.
194
+ */
195
+ const MAX_DEPTH = 100;
196
+
197
+ /** yaml.v3's alias budget (decode.go): see {@link checkBounds}. */
198
+ const ALIAS_MIN_ALIASES = 100;
199
+ const ALIAS_MIN_DECODED = 1000;
200
+ const ALIAS_RATIO_LOW = 400_000;
201
+ const ALIAS_RATIO_HIGH = 4_000_000;
202
+
203
+ function allowedAliasRatio(decoded: number): number {
204
+ if (decoded <= ALIAS_RATIO_LOW) return 0.99;
205
+ if (decoded >= ALIAS_RATIO_HIGH) return 0.1;
206
+ return 0.99 - 0.89 * ((decoded - ALIAS_RATIO_LOW) / (ALIAS_RATIO_HIGH - ALIAS_RATIO_LOW));
207
+ }
208
+
209
+ /**
210
+ * Walks the parsed document the way merge and copy will, aliases expanded,
211
+ * and throws before that work can blow up.
212
+ *
213
+ * js-yaml returns an alias as a second reference to the anchored object, so
214
+ * copying it expands every reference: a "billion laughs" file of a few
215
+ * hundred bytes turns into ~10^9 nodes. js-yaml has no option to cap aliases,
216
+ * so this applies Go yaml.v3's budget: once more than 100 nodes were decoded
217
+ * inside alias expansions and more than 1000 in total, the share decoded
218
+ * inside aliases must stay at or below 0.99 (up to 400k nodes), falling
219
+ * linearly to 0.10 at 4M; otherwise `document contains excessive aliasing`.
220
+ * The first reference to an object is its anchor; later ones count as alias
221
+ * expansions. Scalars are counted but cannot be told apart from aliased
222
+ * scalars. Unlike Go, which skips keys its target struct ignores, every key
223
+ * counts. Iterative, so depth never touches the call stack.
224
+ */
225
+ function checkBounds(root: unknown): void {
226
+ const seen = new WeakSet<object>();
227
+ // [node, depth, inside an alias expansion]
228
+ const stack: [unknown, number, boolean][] = [[root, 1, false]];
229
+ let decoded = 0;
230
+ let aliased = 0;
231
+ while (stack.length > 0) {
232
+ const [node, depth, inAlias] = stack.pop() as [unknown, number, boolean];
233
+ let alias = inAlias;
234
+ const container = Array.isArray(node) || isPlainObject(node);
235
+ if (container) {
236
+ if (seen.has(node)) {
237
+ decoded++; // the alias node itself, as yaml.v3 counts it
238
+ alias = true;
239
+ } else {
240
+ seen.add(node);
241
+ }
242
+ }
243
+ decoded++;
244
+ if (alias) aliased++;
245
+ if (
246
+ aliased > ALIAS_MIN_ALIASES &&
247
+ decoded > ALIAS_MIN_DECODED &&
248
+ aliased / decoded > allowedAliasRatio(decoded)
249
+ ) {
250
+ throw new Error("document contains excessive aliasing");
251
+ }
252
+ if (!container) continue;
253
+ if (depth > MAX_DEPTH) {
254
+ throw new Error(`nesting exceeded maxDepth (${MAX_DEPTH})`);
255
+ }
256
+ if (Array.isArray(node)) {
257
+ for (let i = node.length - 1; i >= 0; i--) stack.push([node[i], depth + 1, alias]);
258
+ } else {
259
+ const keys = Object.keys(node);
260
+ for (let i = keys.length - 1; i >= 0; i--) {
261
+ decoded++; // the key node
262
+ if (alias) aliased++;
263
+ stack.push([(node as Record<string, unknown>)[keys[i]], depth + 1, alias]);
264
+ }
265
+ }
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Merges `src` into `dst` in place: plain objects recurse, everything else
271
+ * replaces, and `null` clears only objects and arrays.
272
+ */
273
+ function mergeInto(dst: Record<string, unknown>, src: Record<string, unknown>): void {
274
+ for (const key of Object.keys(src)) {
275
+ const next = src[key];
276
+ const has = Object.prototype.hasOwnProperty.call(dst, key);
277
+ const cur = has ? dst[key] : undefined;
278
+ if (next === null) {
279
+ if (has && cur !== null && cur !== undefined && typeof cur !== "object") {
280
+ continue; // null leaves a scalar untouched
281
+ }
282
+ setOwn(dst, key, null);
283
+ } else if (isPlainObject(next) && isPlainObject(cur)) {
284
+ mergeInto(cur, next);
285
+ } else {
286
+ setOwn(dst, key, copy(next));
287
+ }
288
+ }
289
+ }
290
+
291
+ /** Own data property even for keys like `__proto__`, never a setter call. */
292
+ function setOwn(dst: Record<string, unknown>, key: string, value: unknown): void {
293
+ Object.defineProperty(dst, key, {
294
+ value,
295
+ writable: true,
296
+ enumerable: true,
297
+ configurable: true,
298
+ });
299
+ }
300
+
301
+ /**
302
+ * Copies plain objects and arrays so YAML aliases do not share one instance
303
+ * in `dst` (a later merge into one key would otherwise leak into another).
304
+ * Memoizing per source object would bring that sharing back, so each
305
+ * reference is copied; {@link checkBounds} has already capped the total.
306
+ */
307
+ function copy(v: unknown): unknown {
308
+ if (Array.isArray(v)) return v.map(copy);
309
+ if (isPlainObject(v)) {
310
+ const out: Record<string, unknown> = {};
311
+ for (const k of Object.keys(v)) setOwn(out, k, copy(v[k]));
312
+ return out;
313
+ }
314
+ return v;
315
+ }
316
+
317
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
318
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return false;
319
+ const proto: unknown = Object.getPrototypeOf(v);
320
+ return proto === Object.prototype || proto === null;
321
+ }
322
+
157
323
  function isEnoent(err: unknown): boolean {
158
324
  return (
159
325
  typeof err === "object" &&
@@ -1,4 +1,4 @@
1
- // @generated by protoc-gen-es v2.11.0 with parameter "target=ts"
1
+ // @generated by protoc-gen-es v2.15.0 with parameter "target=ts"
2
2
  // @generated from file crud.proto (package crud.v1, syntax proto3)
3
3
  /* eslint-disable */
4
4
 
@@ -11,7 +11,7 @@ import type { JsonObject, Message } from "@bufbuild/protobuf";
11
11
  * Describes the file crud.proto.
12
12
  */
13
13
  export const file_crud: GenFile = /*@__PURE__*/
14
- fileDesc("CgpjcnVkLnByb3RvEgdjcnVkLnYxIjgKDUNyZWF0ZVJlcXVlc3QSJwoGZW50aXR5GAEgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCI5Cg5DcmVhdGVSZXNwb25zZRInCgZlbnRpdHkYASABKAsyFy5nb29nbGUucHJvdG9idWYuU3RydWN0IhgKCkdldFJlcXVlc3QSCgoCaWQYASABKAkiNgoLR2V0UmVzcG9uc2USJwoGZW50aXR5GAEgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCJKCgtMaXN0UmVxdWVzdBINCgVsaW1pdBgBIAEoBRIOCgZvZmZzZXQYAiABKAUSDAoEc29ydBgDIAEoCRIOCgZzZWFyY2gYBCABKAkiOQoMTGlzdFJlc3BvbnNlEikKCGVudGl0aWVzGAEgAygLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCI4Cg1VcGRhdGVSZXF1ZXN0EicKBmVudGl0eRgBIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QiOQoOVXBkYXRlUmVzcG9uc2USJwoGZW50aXR5GAEgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCIbCg1EZWxldGVSZXF1ZXN0EgoKAmlkGAEgASgJIhAKDkRlbGV0ZVJlc3BvbnNlMqcCCg1FbnRpdHlTZXJ2aWNlEjkKBkNyZWF0ZRIWLmNydWQudjEuQ3JlYXRlUmVxdWVzdBoXLmNydWQudjEuQ3JlYXRlUmVzcG9uc2USMAoDR2V0EhMuY3J1ZC52MS5HZXRSZXF1ZXN0GhQuY3J1ZC52MS5HZXRSZXNwb25zZRIzCgRMaXN0EhQuY3J1ZC52MS5MaXN0UmVxdWVzdBoVLmNydWQudjEuTGlzdFJlc3BvbnNlEjkKBlVwZGF0ZRIWLmNydWQudjEuVXBkYXRlUmVxdWVzdBoXLmNydWQudjEuVXBkYXRlUmVzcG9uc2USOQoGRGVsZXRlEhYuY3J1ZC52MS5EZWxldGVSZXF1ZXN0GhcuY3J1ZC52MS5EZWxldGVSZXNwb25zZUJ3Cgtjb20uY3J1ZC52MUIJQ3J1ZFByb3RvUAFaIGhvcC50b3Ava2l0L3Byb3RvL2NydWQvdjE7Y3J1ZHYxogIDQ1hYqgIHQ3J1ZC5WMcoCB0NydWRcVjHiAhNDcnVkXFYxXEdQQk1ldGFkYXRh6gIIQ3J1ZDo6VjFiBnByb3RvMw", [file_google_protobuf_struct]);
14
+ fileDesc("CgpjcnVkLnByb3RvEgdjcnVkLnYxIjgKDUNyZWF0ZVJlcXVlc3QSJwoGZW50aXR5GAEgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCI5Cg5DcmVhdGVSZXNwb25zZRInCgZlbnRpdHkYASABKAsyFy5nb29nbGUucHJvdG9idWYuU3RydWN0IhgKCkdldFJlcXVlc3QSCgoCaWQYASABKAkiNgoLR2V0UmVzcG9uc2USJwoGZW50aXR5GAEgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCJKCgtMaXN0UmVxdWVzdBINCgVsaW1pdBgBIAEoBRIOCgZvZmZzZXQYAiABKAUSDAoEc29ydBgDIAEoCRIOCgZzZWFyY2gYBCABKAkiOQoMTGlzdFJlc3BvbnNlEikKCGVudGl0aWVzGAEgAygLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCI4Cg1VcGRhdGVSZXF1ZXN0EicKBmVudGl0eRgBIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QiOQoOVXBkYXRlUmVzcG9uc2USJwoGZW50aXR5GAEgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCIbCg1EZWxldGVSZXF1ZXN0EgoKAmlkGAEgASgJIhAKDkRlbGV0ZVJlc3BvbnNlMqcCCg1FbnRpdHlTZXJ2aWNlEjkKBkNyZWF0ZRIWLmNydWQudjEuQ3JlYXRlUmVxdWVzdBoXLmNydWQudjEuQ3JlYXRlUmVzcG9uc2USMAoDR2V0EhMuY3J1ZC52MS5HZXRSZXF1ZXN0GhQuY3J1ZC52MS5HZXRSZXNwb25zZRIzCgRMaXN0EhQuY3J1ZC52MS5MaXN0UmVxdWVzdBoVLmNydWQudjEuTGlzdFJlc3BvbnNlEjkKBlVwZGF0ZRIWLmNydWQudjEuVXBkYXRlUmVxdWVzdBoXLmNydWQudjEuVXBkYXRlUmVzcG9uc2USOQoGRGVsZXRlEhYuY3J1ZC52MS5EZWxldGVSZXF1ZXN0GhcuY3J1ZC52MS5EZWxldGVSZXNwb25zZUKBAQoLY29tLmNydWQudjFCCUNydWRQcm90b1ABWipob3AudG9wL2tpdC9jb250cmFjdHMvcHJvdG8vY3J1ZC92MTtjcnVkdjGiAgNDWFiqAgdDcnVkLlYxygIHQ3J1ZFxWMeICE0NydWRcVjFcR1BCTWV0YWRhdGHqAghDcnVkOjpWMWIGcHJvdG8z", [file_google_protobuf_struct]);
15
15
 
16
16
  /**
17
17
  * @generated from message crud.v1.CreateRequest
@@ -22,7 +22,7 @@ export type CreateRequest = Message<"crud.v1.CreateRequest"> & {
22
22
  *
23
23
  * @generated from field: google.protobuf.Struct entity = 1;
24
24
  */
25
- entity?: JsonObject;
25
+ entity?: JsonObject | undefined;
26
26
  };
27
27
 
28
28
  /**
@@ -41,7 +41,7 @@ export type CreateResponse = Message<"crud.v1.CreateResponse"> & {
41
41
  *
42
42
  * @generated from field: google.protobuf.Struct entity = 1;
43
43
  */
44
- entity?: JsonObject;
44
+ entity?: JsonObject | undefined;
45
45
  };
46
46
 
47
47
  /**
@@ -75,7 +75,7 @@ export type GetResponse = Message<"crud.v1.GetResponse"> & {
75
75
  /**
76
76
  * @generated from field: google.protobuf.Struct entity = 1;
77
77
  */
78
- entity?: JsonObject;
78
+ entity?: JsonObject | undefined;
79
79
  };
80
80
 
81
81
  /**
@@ -149,7 +149,7 @@ export type UpdateRequest = Message<"crud.v1.UpdateRequest"> & {
149
149
  /**
150
150
  * @generated from field: google.protobuf.Struct entity = 1;
151
151
  */
152
- entity?: JsonObject;
152
+ entity?: JsonObject | undefined;
153
153
  };
154
154
 
155
155
  /**
@@ -166,7 +166,7 @@ export type UpdateResponse = Message<"crud.v1.UpdateResponse"> & {
166
166
  /**
167
167
  * @generated from field: google.protobuf.Struct entity = 1;
168
168
  */
169
- entity?: JsonObject;
169
+ entity?: JsonObject | undefined;
170
170
  };
171
171
 
172
172
  /**
@@ -0,0 +1,38 @@
1
+ # id
2
+
3
+ ## What it answers
4
+
5
+ How to mint and parse kit entity IDs so that Go, Python, Rust and PHP produce the same string for the same `(prefix, uuid)`. Canonical wire form: `<prefix>_<26-char-base32>`, a Crockford-base32 UUIDv7 behind a lowercase prefix. Wrong module for URI composition such as `tlc://task/task_...`: use `@hop-top/cite`.
6
+
7
+ ## Use it when
8
+
9
+ - new entity: `newId('task')`
10
+ - validate or split an incoming id: `parse(s)` returns `{ prefix, uuid }` and throws on malformed input
11
+ - compile-time prefix safety: `Typed<'task'>` with `newTyped` / `parseTyped`
12
+
13
+ ## Quick start
14
+
15
+ ```ts
16
+ import { newId, parse } from '@hop-top/kit/id';
17
+
18
+ const id = newId('task');
19
+ console.log(id, parse(id).uuid);
20
+ ```
21
+
22
+ ## Contract
23
+
24
+ - Thin wrapper over `typeid-js`; the string returned by `newId` is the JSON wire form and round-trips losslessly through `parse`.
25
+ - Prefix grammar and length limit follow the typeid spec pinned in the fixture; a divergence is a wire-format break.
26
+ - No transitive dependency on the URI registry, by design.
27
+ - Parity: [`contracts/typeid-v1/fixtures.json`](../../../../contracts/typeid-v1/fixtures.json), replayed by [`contract.test.ts`](contract.test.ts).
28
+
29
+ ## Neighbours
30
+
31
+ - `@hop-top/cite`: URI composition on top of the canonical string
32
+ - `@hop-top/kit/sqlstore`: persistence keyed by these ids
33
+ - Go reference: `go/core/id`; Python port: [`hop_top_kit/id`](../../../py/hop_top_kit/id/README.md)
34
+
35
+ ## See also
36
+
37
+ - [`docs/announcements/2026-05-typeid-primitive.md`](../../../../docs/announcements/2026-05-typeid-primitive.md)
38
+ - [`docs/adopters/reference/go-primitives.md`](../../../../docs/adopters/reference/go-primitives.md)
@@ -1,4 +1,4 @@
1
- // Cross-language parity contract test (tlc T-0753).
1
+ // Cross-language parity contract test.
2
2
  //
3
3
  // Loads contracts/typeid-v1/fixtures.json from the repo root and
4
4
  // asserts that this TS SDK's encode (via typeid-js's TypeID.fromUUID)
@@ -10,7 +10,7 @@ import {
10
10
  } from './index';
11
11
 
12
12
  // Canonical fixture set — these EXACT uuid inputs are shared with the
13
- // other language SDKs so future cross-language parity work (T-0753)
13
+ // other language SDKs so future cross-language parity work
14
14
  // finds matching outputs. Do not mutate without coordinating across
15
15
  // sdk/{go,rs,py,php}.
16
16
  const FIXTURES: ReadonlyArray<{ prefix: string; uuid: string }> = [
package/src/id/index.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  * @package @hop-top/kit
4
4
  *
5
5
  * TypeID primitive — thin wrapper around `typeid-js` (jetify-com)
6
- * implementing the cross-language kit API SHAPE per ADR 0001.
6
+ * implementing the cross-language kit API SHAPE per
7
+ * docs/announcements/2026-05-typeid-primitive.md.
7
8
  *
8
9
  * Canonical wire form: `<prefix>_<26-char-base32>` where the suffix is
9
10
  * a Crockford-base32-encoded UUIDv7. The TS surface adds a
@@ -13,7 +14,7 @@
13
14
  * URI composition (e.g. `tlc://task/task_…`) is NOT in this module —
14
15
  * callers should use the `@hop-top/cite` package directly. This
15
16
  * keeps `kit/id` free of any transitive dependency on the URI
16
- * registry, per the ADR's scope boundary.
17
+ * registry.
17
18
  */
18
19
 
19
20
  import { typeid, TypeID } from 'typeid-js';
package/src/index.test.ts CHANGED
@@ -7,6 +7,7 @@ import * as kit from './index.js';
7
7
  const pkgDir = join(__dirname, '..');
8
8
  const pkg = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8')) as {
9
9
  exports: Record<string, Record<string, string>>;
10
+ typesVersions?: Record<string, Record<string, string[]>>;
10
11
  scripts: Record<string, string>;
11
12
  };
12
13
 
@@ -39,6 +40,17 @@ describe('exports map contract', () => {
39
40
  it('root "." exposes the same condition set as the other entries', () => {
40
41
  expect(Object.keys(pkg.exports['.']).sort()).toEqual(['default', 'require', 'types']);
41
42
  });
43
+
44
+ // moduleResolution node10 ignores `exports`; `typesVersions` is its only
45
+ // route to subpath types, so every subpath needs a matching entry.
46
+ it('typesVersions maps every subpath to its exports types target', () => {
47
+ const expected = Object.fromEntries(
48
+ subpaths
49
+ .filter(([subpath]) => subpath !== '.')
50
+ .map(([subpath, conditions]) => [subpath.replace(/^\.\//, ''), [conditions.types]]),
51
+ );
52
+ expect(pkg.typesVersions).toEqual({ '*': expected });
53
+ });
42
54
  });
43
55
 
44
56
  describe('root barrel', () => {
package/src/index.ts CHANGED
@@ -13,6 +13,7 @@
13
13
 
14
14
  export * as aim from './aim.js';
15
15
  export * as alias from './alias.js';
16
+ export * as anthropic from './llm-anthropic.js';
16
17
  export * as api from './api.js';
17
18
  export * as auth from './auth.js';
18
19
  export * as cli from './cli.js';
@@ -22,6 +23,7 @@ export * as id from './id/index.js';
22
23
  export * as llm from './llm.js';
23
24
  export * as mcp from './mcp/index.js';
24
25
  export * as netpolicy from './netpolicy.js';
26
+ export * as openai from './llm-openai.js';
25
27
  export * as output from './output.js';
26
28
  export * as progress from './progress.js';
27
29
  export * as provenance from './provenance.js';