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

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 (285) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +120 -31
  271. package/src/tui/parity.ts +58 -7
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
  285. package/src/tui/parity.json +0 -74
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Tool-name rules, the reversible sanitizer and the per-request name
3
+ * table, re-exported from `@hop-top/kit/llm`.
4
+ *
5
+ * Providers restrict tool names; callers use ids such as `pane.open`.
6
+ * A tool-calling adapter builds a {@link ToolNames} per request, sends
7
+ * wire names and returns the caller's names. Normative spec, shared by
8
+ * every kit SDK: `contracts/llm-v1/tool-names.md`.
9
+ */
10
+
11
+ import { createHash } from "node:crypto";
12
+
13
+ import { LLMError } from "./llm-error";
14
+
15
+ /** Provider param selecting the {@link ToolNameMode}: `?tool_names=strict`. */
16
+ export const TOOL_NAMES_PARAM = "tool_names";
17
+
18
+ /**
19
+ * How an adapter treats a name its provider does not accept.
20
+ * `sanitize` (default) rewrites it and maps it back; `strict` sends
21
+ * names as given and fails an invalid one before sending.
22
+ */
23
+ export type ToolNameMode = "sanitize" | "strict";
24
+
25
+ /** Why a {@link ToolNameError} fails a request. */
26
+ export type ToolNameReason =
27
+ | "empty"
28
+ | "invalid_utf8"
29
+ | "invalid"
30
+ | "duplicate"
31
+ | "collision";
32
+
33
+ /**
34
+ * A provider's tool-name rule: 1 to `maxLen` bytes of ASCII letters,
35
+ * digits, `_`, `-` and the bytes of `extra`; with `leadLetter`, the
36
+ * first byte is a letter or `_`.
37
+ */
38
+ export interface ToolNameRule {
39
+ /** Names the rule in errors. */
40
+ readonly provider: string;
41
+ readonly maxLen: number;
42
+ readonly extra: string;
43
+ readonly leadLetter: boolean;
44
+ }
45
+
46
+ /** Anthropic Messages API: `^[a-zA-Z0-9_-]{1,128}$`. */
47
+ export const ANTHROPIC_TOOL_NAMES: ToolNameRule = Object.freeze({
48
+ provider: "anthropic",
49
+ maxLen: 128,
50
+ extra: "",
51
+ leadLetter: false,
52
+ });
53
+
54
+ /** OpenAI Chat Completions and compatible servers: `^[a-zA-Z0-9_-]{1,64}$`. */
55
+ export const OPENAI_TOOL_NAMES: ToolNameRule = Object.freeze({
56
+ provider: "openai",
57
+ maxLen: 64,
58
+ extra: "",
59
+ leadLetter: false,
60
+ });
61
+
62
+ /** Gemini `FunctionDeclaration.name`: `^[a-zA-Z_][a-zA-Z0-9_.:-]{0,127}$`. */
63
+ export const GEMINI_TOOL_NAMES: ToolNameRule = Object.freeze({
64
+ provider: "gemini",
65
+ maxLen: 128,
66
+ extra: ".:",
67
+ leadLetter: true,
68
+ });
69
+
70
+ /**
71
+ * A tool name fails the request before anything is sent. Not
72
+ * fallbackable: the caller's tool set needs fixing. `toolName` is the
73
+ * offending name (`name` is the error class name, as on every Error);
74
+ * `other` is the earlier tool a `collision` maps to the same wire name.
75
+ */
76
+ export class ToolNameError extends LLMError {
77
+ readonly provider: string;
78
+ readonly reason: ToolNameReason;
79
+ readonly toolName: string;
80
+ readonly other: string;
81
+
82
+ constructor(
83
+ provider: string,
84
+ reason: ToolNameReason,
85
+ toolName: string,
86
+ other = ""
87
+ ) {
88
+ super(toolNameMessage(provider, reason, toolName, other));
89
+ this.name = "ToolNameError";
90
+ this.provider = provider;
91
+ this.reason = reason;
92
+ this.toolName = toolName;
93
+ this.other = other;
94
+ }
95
+ }
96
+
97
+ function toolNameMessage(
98
+ provider: string,
99
+ reason: ToolNameReason,
100
+ name: string,
101
+ other: string
102
+ ): string {
103
+ const q = JSON.stringify;
104
+ switch (reason) {
105
+ case "empty":
106
+ return `tool name is empty (provider ${q(provider)})`;
107
+ case "invalid_utf8":
108
+ return `tool name ${q(name)} is not valid UTF-8 (provider ${q(provider)})`;
109
+ case "invalid":
110
+ return `tool name ${q(name)} is not valid for provider ${q(provider)}`;
111
+ case "duplicate":
112
+ return `tool name ${q(name)} is defined twice (provider ${q(provider)})`;
113
+ case "collision":
114
+ return `tool names ${q(other)} and ${q(name)} map to the same provider name (provider ${q(provider)})`;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Reads {@link TOOL_NAMES_PARAM} from provider params; absent means
120
+ * `sanitize`. Any other value throws, failing adapter construction.
121
+ */
122
+ export function toolNameModeOf(
123
+ params: Record<string, string> | undefined
124
+ ): ToolNameMode {
125
+ const v = params?.[TOOL_NAMES_PARAM];
126
+ if (v === undefined) return "sanitize";
127
+ const m = v.trim();
128
+ if (m === "sanitize" || m === "strict") return m;
129
+ throw new LLMError(
130
+ `${TOOL_NAMES_PARAM} must be "sanitize" or "strict", got ${JSON.stringify(v)}`
131
+ );
132
+ }
133
+
134
+ /** Hex digits of SHA-256 a shortened name ends with, after a `_`. */
135
+ const HASH_LEN = 8;
136
+
137
+ const UNDERSCORE = 0x5f;
138
+ const encoder = new TextEncoder();
139
+ const decoder = new TextDecoder();
140
+ const LONE_SURROGATE =
141
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
142
+
143
+ function isAlnum(c: number): boolean {
144
+ return (
145
+ (c >= 0x61 && c <= 0x7a) || (c >= 0x41 && c <= 0x5a) || (c >= 0x30 && c <= 0x39)
146
+ );
147
+ }
148
+
149
+ function allowed(rule: ToolNameRule, c: number): boolean {
150
+ if (isAlnum(c) || c === UNDERSCORE || c === 0x2d) return true;
151
+ return c < 0x80 && rule.extra.includes(String.fromCharCode(c));
152
+ }
153
+
154
+ function leadOK(rule: ToolNameRule, c: number): boolean {
155
+ if (!rule.leadLetter) return true;
156
+ return c === UNDERSCORE || (c >= 0x61 && c <= 0x7a) || (c >= 0x41 && c <= 0x5a);
157
+ }
158
+
159
+ function validBytes(rule: ToolNameRule, b: Uint8Array): boolean {
160
+ if (b.length === 0 || b.length > rule.maxLen || !leadOK(rule, b[0]!)) {
161
+ return false;
162
+ }
163
+ for (const c of b) if (!allowed(rule, c)) return false;
164
+ return true;
165
+ }
166
+
167
+ /** Sanitizer output is ASCII bytes; no spread, so long names cannot overflow. */
168
+ function ascii(b: ArrayLike<number>): string {
169
+ return decoder.decode(Uint8Array.from(b));
170
+ }
171
+
172
+ /** Reports whether the provider accepts `name` as is. */
173
+ export function isValidToolName(rule: ToolNameRule, name: string): boolean {
174
+ if (LONE_SURROGATE.test(name)) return false;
175
+ return validBytes(rule, encoder.encode(name));
176
+ }
177
+
178
+ /**
179
+ * Returns `name` as the provider accepts it; a valid name comes back
180
+ * unchanged. Otherwise, over the UTF-8 bytes of `name`: each maximal
181
+ * run of disallowed bytes becomes one `_`; with `leadLetter`, a bad
182
+ * first byte gains a leading `_`; a result over `maxLen`, or with no
183
+ * ASCII letter or digit, keeps its first `maxLen - 9` bytes and gains
184
+ * `_` + 8 hex of SHA-256(name). Throws {@link ToolNameError} for an
185
+ * empty name (`empty`) or a lone surrogate (`invalid_utf8`).
186
+ */
187
+ export function sanitizeToolName(rule: ToolNameRule, name: string): string {
188
+ if (name === "") throw new ToolNameError(rule.provider, "empty", name);
189
+ if (LONE_SURROGATE.test(name)) {
190
+ throw new ToolNameError(rule.provider, "invalid_utf8", name);
191
+ }
192
+ const src = encoder.encode(name);
193
+ if (validBytes(rule, src)) return name;
194
+
195
+ const out: number[] = [];
196
+ let run = false;
197
+ for (const c of src) {
198
+ if (allowed(rule, c)) {
199
+ out.push(c);
200
+ run = false;
201
+ continue;
202
+ }
203
+ if (!run) out.push(UNDERSCORE);
204
+ run = true;
205
+ }
206
+ if (!leadOK(rule, out[0]!)) out.unshift(UNDERSCORE);
207
+ if (out.length <= rule.maxLen && out.some(isAlnum)) return ascii(out);
208
+
209
+ const hash = createHash("sha256").update(src).digest("hex").slice(0, HASH_LEN);
210
+ const keep = Math.min(out.length, rule.maxLen - HASH_LEN - 1);
211
+ return `${ascii(out.slice(0, keep))}_${hash}`;
212
+ }
213
+
214
+ /**
215
+ * One request's tool names: original -> wire and back. Adapters build
216
+ * one per request with {@link ToolNames.build}, send
217
+ * {@link ToolNames.wire} names (tools and replayed history) and return
218
+ * calls through {@link ToolNames.calls}.
219
+ */
220
+ export class ToolNames {
221
+ private readonly toWire = new Map<string, string>();
222
+ private readonly toOrig = new Map<string, string>();
223
+
224
+ private constructor(
225
+ readonly rule: ToolNameRule,
226
+ readonly mode: ToolNameMode
227
+ ) {}
228
+
229
+ /**
230
+ * Checks `defs` against `rule` and builds their mapping. The first
231
+ * failing def, in order, throws a {@link ToolNameError}: `empty`,
232
+ * `invalid_utf8`, `invalid` (strict only), `duplicate`, `collision`
233
+ * (`other` names the earlier def with the same wire name).
234
+ */
235
+ static build(
236
+ rule: ToolNameRule,
237
+ mode: ToolNameMode,
238
+ defs: ReadonlyArray<{ readonly name: string }>
239
+ ): ToolNames {
240
+ const t = new ToolNames(rule, mode);
241
+ for (const { name } of defs) {
242
+ let wire: string;
243
+ if (name === "") {
244
+ throw new ToolNameError(rule.provider, "empty", name);
245
+ } else if (LONE_SURROGATE.test(name)) {
246
+ throw new ToolNameError(rule.provider, "invalid_utf8", name);
247
+ } else if (mode === "strict") {
248
+ if (!isValidToolName(rule, name)) {
249
+ throw new ToolNameError(rule.provider, "invalid", name);
250
+ }
251
+ wire = name;
252
+ } else {
253
+ wire = sanitizeToolName(rule, name);
254
+ }
255
+ if (t.toWire.has(name)) {
256
+ throw new ToolNameError(rule.provider, "duplicate", name);
257
+ }
258
+ const other = t.toOrig.get(wire);
259
+ if (other !== undefined) {
260
+ throw new ToolNameError(rule.provider, "collision", name, other);
261
+ }
262
+ t.toWire.set(name, wire);
263
+ t.toOrig.set(wire, name);
264
+ }
265
+ return t;
266
+ }
267
+
268
+ /**
269
+ * The name to send: a def's wire name; otherwise, as for a call
270
+ * replayed from history, `name` sanitized (`sanitize`) or unchanged
271
+ * (`strict`, or a name the sanitizer refuses).
272
+ */
273
+ wire(name: string): string {
274
+ const w = this.toWire.get(name);
275
+ if (w !== undefined) return w;
276
+ if (this.mode === "strict") return name;
277
+ try {
278
+ return sanitizeToolName(this.rule, name);
279
+ } catch {
280
+ return name;
281
+ }
282
+ }
283
+
284
+ /** The def name a returned wire name stands for; unknown names pass through. */
285
+ original(wire: string): string {
286
+ return this.toOrig.get(wire) ?? wire;
287
+ }
288
+
289
+ /** `defs` with each name replaced by its wire name; input untouched. */
290
+ defs<T extends { name: string }>(defs: ReadonlyArray<T>): T[] {
291
+ return defs.map((d) => ({ ...d, name: this.wire(d.name) }));
292
+ }
293
+
294
+ /** `calls` with each name replaced by its original; input untouched. */
295
+ calls<T extends { name: string }>(calls: ReadonlyArray<T>): T[] {
296
+ return calls.map((c) => ({ ...c, name: this.original(c.name) }));
297
+ }
298
+ }
package/src/llm-uri.ts ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Provider URI parsing, as Go `llm.ParseURI` parses (pinned by
3
+ * contracts/llm-v1 `parse_uri`). Re-exported from `@hop-top/kit/llm`.
4
+ *
5
+ * @internal
6
+ */
7
+
8
+ import type { URI } from "./llm";
9
+ import { redactURI } from "./llm-endpoint";
10
+ import { LLMError } from "./llm-error";
11
+ import { goQuote } from "./llm-quote";
12
+
13
+ /**
14
+ * Parses a provider URI: `scheme://[host:port/]model[?params]`.
15
+ *
16
+ * The scheme is required; the model may be empty. The first path
17
+ * segment is a host (`ollama://localhost:11434/llama3`,
18
+ * `ollama://[::1]:11434/llama3`) when it splits as `host:port` with a
19
+ * non-empty port; otherwise the whole path is the model
20
+ * (`openrouter://openai/gpt-4.1-nano`). The query splits on `&`, each
21
+ * pair on its first `=`, and is not percent-decoded; a param without
22
+ * `=` is `""`, one with an empty name is dropped. `params` is absent
23
+ * when none is left.
24
+ *
25
+ * Throws an {@link LLMError} (`empty URI`, `missing scheme in URI
26
+ * "..."`, `empty scheme in URI "..."`) quoting `raw` with its
27
+ * credentials masked by {@link redactURI}.
28
+ */
29
+ export function parseURI(raw: string): URI {
30
+ if (raw === "") throw new LLMError("empty URI");
31
+ const idx = raw.indexOf("://");
32
+ if (idx < 0) throw new LLMError(`missing scheme in URI ${goQuote(redactURI(raw))}`);
33
+ const scheme = raw.slice(0, idx);
34
+ if (scheme === "") throw new LLMError(`empty scheme in URI ${goQuote(redactURI(raw))}`);
35
+
36
+ let rest = raw.slice(idx + 3);
37
+ let params: Record<string, string> | undefined;
38
+ const q = rest.indexOf("?");
39
+ if (q >= 0) {
40
+ params = parseQuery(rest.slice(q + 1));
41
+ rest = rest.slice(0, q);
42
+ }
43
+
44
+ let host = "";
45
+ let model = rest;
46
+ const slash = rest.indexOf("/");
47
+ if (slash > 0) {
48
+ const hp = splitHostPort(rest.slice(0, slash));
49
+ if (hp && hp[1] !== "") {
50
+ host = joinHostPort(hp[0], hp[1]);
51
+ model = rest.slice(slash + 1);
52
+ }
53
+ }
54
+
55
+ const uri: URI = { scheme, model };
56
+ if (host !== "") uri.host = host;
57
+ if (params && Object.keys(params).length > 0) uri.params = params;
58
+ return uri;
59
+ }
60
+
61
+ function parseQuery(qs: string): Record<string, string> | undefined {
62
+ if (qs === "") return undefined;
63
+ const m: Record<string, string> = {};
64
+ for (const pair of qs.split("&")) {
65
+ const eq = pair.indexOf("=");
66
+ const k = eq < 0 ? pair : pair.slice(0, eq);
67
+ const v = eq < 0 ? "" : pair.slice(eq + 1);
68
+ if (k === "") continue;
69
+ // An own property even for "__proto__": never the prototype.
70
+ Object.defineProperty(m, k, { value: v, enumerable: true, writable: true, configurable: true });
71
+ }
72
+ return m;
73
+ }
74
+
75
+ /** Go `net.SplitHostPort`: undefined where Go returns an error. */
76
+ function splitHostPort(hp: string): [string, string] | undefined {
77
+ const i = hp.lastIndexOf(":");
78
+ if (i < 0) return undefined;
79
+ let host: string;
80
+ let j = 0;
81
+ let k = 0;
82
+ if (hp.startsWith("[")) {
83
+ const end = hp.indexOf("]");
84
+ if (end < 0 || end + 1 !== i) return undefined;
85
+ host = hp.slice(1, end);
86
+ j = 1;
87
+ k = end + 1;
88
+ } else {
89
+ host = hp.slice(0, i);
90
+ if (host.includes(":")) return undefined;
91
+ }
92
+ if (hp.slice(j).includes("[") || hp.slice(k).includes("]")) return undefined;
93
+ return [host, hp.slice(i + 1)];
94
+ }
95
+
96
+ /** Go `net.JoinHostPort`. */
97
+ function joinHostPort(host: string, port: string): string {
98
+ return host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
99
+ }
package/src/llm.test.ts CHANGED
@@ -90,16 +90,35 @@ describe("parseURI", () => {
90
90
  expect(uri.model).toBe("ns/model-v2");
91
91
  });
92
92
 
93
- it("throws on missing scheme", () => {
94
- expect(() => parseURI("gpt-4")).toThrow();
93
+ it("throws on missing scheme, masking credentials", () => {
94
+ expect(() => parseURI("gpt-4?api_key=sk-secret")).toThrow(
95
+ 'missing scheme in URI "gpt-4?api_key=REDACTED"'
96
+ );
97
+ });
98
+
99
+ it("throws on empty scheme", () => {
100
+ expect(() => parseURI("://gpt-4")).toThrow('empty scheme in URI "://gpt-4"');
95
101
  });
96
102
 
97
- it("throws on empty model", () => {
98
- expect(() => parseURI("openai://")).toThrow();
103
+ it("accepts an empty model", () => {
104
+ const uri = parseURI("openai://");
105
+ expect(uri.scheme).toBe("openai");
106
+ expect(uri.model).toBe("");
99
107
  });
100
108
 
101
109
  it("throws on empty string", () => {
102
- expect(() => parseURI("")).toThrow();
110
+ expect(() => parseURI("")).toThrow("empty URI");
111
+ });
112
+
113
+ it("keeps param values as written: no percent-decoding", () => {
114
+ const uri = parseURI("openai://gpt-4?base_url=https%3A%2F%2Fx.test&flag");
115
+ expect(uri.params).toEqual({ base_url: "https%3A%2F%2Fx.test", flag: "" });
116
+ });
117
+
118
+ it("takes an IPv6 host form", () => {
119
+ const uri = parseURI("ollama://[::1]:11434/llama3");
120
+ expect(uri.host).toBe("[::1]:11434");
121
+ expect(uri.model).toBe("llama3");
103
122
  });
104
123
  });
105
124
 
@@ -137,14 +156,16 @@ describe("loadConfig", () => {
137
156
  expect(cfg.provider.model).toBe("gpt-4");
138
157
  });
139
158
 
140
- it("applies env var overrides", () => {
159
+ it("applies env vars where the URI names nothing", () => {
160
+ register("kitenv", () => mockProvider());
141
161
  process.env["LLM_API_KEY"] = "sk-test";
142
162
  process.env["LLM_BASE_URL"] = "https://custom.api.com";
143
163
  process.env["LLM_FALLBACK"] = "anthropic://claude-3,ollama://llama3";
144
164
 
145
- const cfg = loadConfig("openai://gpt-4");
165
+ const cfg = loadConfig("kitenv://gpt-4");
146
166
  expect(cfg.provider.apiKey).toBe("sk-test");
147
167
  expect(cfg.provider.baseURL).toBe("https://custom.api.com");
168
+ clearRegistry();
148
169
  expect(cfg.fallbacks).toEqual([
149
170
  "anthropic://claude-3",
150
171
  "ollama://llama3",
@@ -180,9 +201,7 @@ describe("loadConfig", () => {
180
201
  });
181
202
 
182
203
  it("extracts base_url from URI params", () => {
183
- const cfg = loadConfig(
184
- "openai://gpt-4?base_url=https%3A%2F%2Fcustom.api.com"
185
- );
204
+ const cfg = loadConfig("openai://gpt-4?base_url=https://custom.api.com");
186
205
  expect(cfg.provider.baseURL).toBe("https://custom.api.com");
187
206
  });
188
207
 
@@ -191,16 +210,25 @@ describe("loadConfig", () => {
191
210
  expect(cfg.provider.baseURL).toBe("http://localhost:11434");
192
211
  });
193
212
 
194
- it("env LLM_API_KEY overrides URI api_key param", () => {
213
+ it("URI api_key param outranks LLM_API_KEY", () => {
195
214
  process.env["LLM_API_KEY"] = "env-key";
196
215
  const cfg = loadConfig("openai://gpt-4?api_key=uri-key");
197
- expect(cfg.provider.apiKey).toBe("env-key");
216
+ expect(cfg.provider.apiKey).toBe("uri-key");
198
217
  });
199
218
 
200
- it("env LLM_BASE_URL overrides host-derived baseURL", () => {
219
+ it("URI host outranks LLM_BASE_URL, base_url param outranks the host", () => {
201
220
  process.env["LLM_BASE_URL"] = "https://override.com";
202
- const cfg = loadConfig("ollama://localhost:11434/llama3");
203
- expect(cfg.provider.baseURL).toBe("https://override.com");
221
+ expect(loadConfig("ollama://localhost:11434/llama3").provider.baseURL).toBe(
222
+ "http://localhost:11434"
223
+ );
224
+ expect(
225
+ loadConfig("ollama://localhost:11434/llama3?base_url=http://127.0.0.1:9").provider.baseURL
226
+ ).toBe("http://127.0.0.1:9");
227
+ });
228
+
229
+ it("lends LLM_API_KEY to no scheme without an adapter", () => {
230
+ process.env["LLM_API_KEY"] = "env-key";
231
+ expect(loadConfig("nosuchscheme://m").provider.apiKey).toBeUndefined();
204
232
  });
205
233
  });
206
234
 
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Tests for tool-call linkage and content parts on llm.Message.
3
+ * Covers: checkToolLinkage role rules, Client pass-through, media sources.
4
+ */
5
+
6
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { afterEach, describe, expect, it, vi } from "vitest";
10
+ import {
11
+ LLMError,
12
+ checkToolLinkage,
13
+ clearRegistry,
14
+ createLLM,
15
+ fileSource,
16
+ inlineSource,
17
+ register,
18
+ urlSource,
19
+ type ContentPart,
20
+ type Message,
21
+ type Request,
22
+ type ToolCall,
23
+ } from "./llm";
24
+
25
+ const call: ToolCall = {
26
+ id: "call_1",
27
+ name: "get_weather",
28
+ arguments: { city: "NYC" },
29
+ };
30
+
31
+ // ─── checkToolLinkage ───────────────────────────────────────────────────────
32
+
33
+ describe("checkToolLinkage", () => {
34
+ it("accepts messages that set neither field", () => {
35
+ for (const role of ["system", "user", "assistant", "tool"]) {
36
+ expect(() => checkToolLinkage({ role, content: "x" })).not.toThrow();
37
+ }
38
+ });
39
+
40
+ it("accepts toolCalls on assistant with empty content", () => {
41
+ expect(() =>
42
+ checkToolLinkage({ role: "assistant", content: "", toolCalls: [call] })
43
+ ).not.toThrow();
44
+ });
45
+
46
+ it("accepts toolCallId on tool", () => {
47
+ expect(() =>
48
+ checkToolLinkage({ role: "tool", content: "sunny", toolCallId: "call_1" })
49
+ ).not.toThrow();
50
+ });
51
+
52
+ it("treats an empty toolCalls array as unset", () => {
53
+ expect(() =>
54
+ checkToolLinkage({ role: "user", content: "x", toolCalls: [] })
55
+ ).not.toThrow();
56
+ });
57
+
58
+ it("rejects toolCalls on a tool result", () => {
59
+ expect(() =>
60
+ checkToolLinkage({
61
+ role: "tool",
62
+ content: "",
63
+ toolCallId: "call_1",
64
+ toolCalls: [call],
65
+ })
66
+ ).toThrow(/tool result.*only content/);
67
+ });
68
+
69
+ it.each(["user", "system"])(
70
+ "rejects toolCalls on role %s",
71
+ (role) => {
72
+ expect(() =>
73
+ checkToolLinkage({ role, content: "", toolCalls: [call] })
74
+ ).toThrow(LLMError);
75
+ expect(() =>
76
+ checkToolLinkage({ role, content: "", toolCalls: [call] })
77
+ ).toThrow(/toolCalls.*only on role assistant/);
78
+ }
79
+ );
80
+
81
+ it.each(["user", "system", "assistant"])(
82
+ "rejects toolCallId on role %s",
83
+ (role) => {
84
+ expect(() =>
85
+ checkToolLinkage({ role, content: "x", toolCallId: "call_1" })
86
+ ).toThrow(/toolCallId.*only on role tool/);
87
+ }
88
+ );
89
+
90
+ it("rejects a tool result carrying parts", () => {
91
+ const m: Message = {
92
+ role: "tool",
93
+ content: "",
94
+ toolCallId: "call_1",
95
+ parts: [{ type: "text", text: "sunny" }],
96
+ };
97
+ expect(() => checkToolLinkage(m)).toThrow(/tool result.*only content/);
98
+ });
99
+ });
100
+
101
+ // ─── Client pass-through ────────────────────────────────────────────────────
102
+
103
+ describe("Client carries linkage to the provider", () => {
104
+ afterEach(() => {
105
+ clearRegistry();
106
+ });
107
+
108
+ it("hands toolCalls and toolCallId to callWithTools unchanged", async () => {
109
+ let got: Request | undefined;
110
+ register("linkmock", () => ({
111
+ callWithTools: async (req) => {
112
+ got = req;
113
+ return { content: "ok", toolCalls: [] };
114
+ },
115
+ close: vi.fn(),
116
+ }));
117
+
118
+ const messages: Message[] = [
119
+ { role: "user", content: "Weather?" },
120
+ { role: "assistant", content: "", toolCalls: [call] },
121
+ { role: "tool", content: "sunny", toolCallId: "call_1" },
122
+ ];
123
+ const client = createLLM("linkmock://m");
124
+ await client.callWithTools({ messages }, [
125
+ { name: "get_weather", description: "", parameters: {} },
126
+ ]);
127
+
128
+ expect(got?.messages[1].toolCalls).toEqual([call]);
129
+ expect(got?.messages[2].toolCallId).toBe("call_1");
130
+ });
131
+ });
132
+
133
+ // ─── Media sources ──────────────────────────────────────────────────────────
134
+
135
+ describe("media sources", () => {
136
+ it("inlineSource returns its bytes and MIME type, no URL", async () => {
137
+ const src = inlineSource(new Uint8Array([1, 2, 3]), "image/png");
138
+ expect(src.url()).toBe("");
139
+ expect(src.mimeType()).toBe("image/png");
140
+ expect(Array.from(await src.read())).toEqual([1, 2, 3]);
141
+ });
142
+
143
+ it("urlSource exposes its URL and no MIME type", () => {
144
+ const src = urlSource("https://example.test/cat.png");
145
+ expect(src.url()).toBe("https://example.test/cat.png");
146
+ expect(src.mimeType()).toBe("");
147
+ });
148
+
149
+ it("fileSource infers MIME from extension and reads the file", async () => {
150
+ const dir = mkdtempSync(join(tmpdir(), "kit-llm-"));
151
+ try {
152
+ const p = join(dir, "cat.PNG");
153
+ writeFileSync(p, Buffer.from([9, 8]));
154
+ const src = fileSource(p);
155
+ expect(src.url()).toBe("");
156
+ expect(src.mimeType()).toBe("image/png");
157
+ expect(Array.from(await src.read())).toEqual([9, 8]);
158
+ expect(fileSource(join(dir, "notes")).mimeType()).toBe("");
159
+ expect(fileSource(join(dir, "x.unknownext")).mimeType()).toBe("");
160
+ } finally {
161
+ rmSync(dir, { recursive: true, force: true });
162
+ }
163
+ });
164
+
165
+ it("a ContentPart carries type, text, source, mimeType, metadata", () => {
166
+ const part: ContentPart = {
167
+ type: "image",
168
+ source: urlSource("https://example.test/cat.png"),
169
+ mimeType: "image/png",
170
+ metadata: { alt: "cat" },
171
+ };
172
+ const m: Message = { role: "user", content: "", parts: [part] };
173
+ expect(m.parts?.[0].type).toBe("image");
174
+ });
175
+ });