@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,155 @@
1
+ /**
2
+ * Metadata-only payloads for the llm lifecycle events
3
+ * `kit.ai.request.started` and `kit.ai.response.received`, as the Go
4
+ * client publishes them. Re-exported from `@hop-top/kit/llm`.
5
+ *
6
+ * The TypeScript client publishes no bus events: its `onRequest` and
7
+ * `onResponse` hooks run in process with the full request and response.
8
+ * A caller that forwards those events (to a bus, a log, a peer) builds
9
+ * the payload here instead of sending the request, so no prompt text,
10
+ * tool name or argument, extension value or media leaves the process.
11
+ */
12
+
13
+ import type { Message, Request, Response, ThinkingBlock, ToolCall } from "./llm";
14
+
15
+ /** The call a payload describes. */
16
+ export type CallOp = "complete" | "stream" | "tool_call" | "stream_tools";
17
+
18
+ /**
19
+ * `kit.ai.request.started`: a request described without its content.
20
+ * Keys are the wire spelling; optional ones are absent when empty.
21
+ */
22
+ export interface RequestStartedPayload {
23
+ op: CallOp;
24
+ /** {@link Request.model}; absent means the adapter's own. */
25
+ model?: string;
26
+ messages: number;
27
+ /** Messages counted by role. */
28
+ roles?: Record<string, number>;
29
+ /** Content parts of multimodal messages counted by type. */
30
+ parts?: Record<string, number>;
31
+ /**
32
+ * UTF-8 length of the messages' text: content, text parts, tool call
33
+ * arguments and thinking text. Media is not counted.
34
+ */
35
+ content_bytes: number;
36
+ /** Tools offered (`tool_call`, `stream_tools`). */
37
+ tools: number;
38
+ max_tokens: number;
39
+ has_temperature: boolean;
40
+ thinking: boolean;
41
+ stop_sequences: number;
42
+ /** {@link Request.extensions} keys, sorted; never their values. */
43
+ extension_keys?: string[];
44
+ }
45
+
46
+ /** `kit.ai.response.received`: a finished call without its content. */
47
+ export interface ResponseReceivedPayload {
48
+ op: CallOp;
49
+ finish_reason?: string;
50
+ usage: {
51
+ prompt_tokens: number;
52
+ completion_tokens: number;
53
+ cache_read_tokens: number;
54
+ cache_creation_tokens: number;
55
+ total_tokens: number;
56
+ };
57
+ /**
58
+ * UTF-8 length of the response's text: content, tool call arguments
59
+ * and thinking text.
60
+ */
61
+ content_bytes: number;
62
+ /** Calls the model made (`tool_call`). */
63
+ tool_calls: number;
64
+ /** Whole milliseconds the call took. */
65
+ duration_ms: number;
66
+ }
67
+
68
+ /**
69
+ * The `kit.ai.request.started` payload for `req` on a call of kind
70
+ * `op` offering `tools` tools.
71
+ */
72
+ export function requestStartedPayload(
73
+ op: CallOp,
74
+ req: Request,
75
+ tools: number
76
+ ): RequestStartedPayload {
77
+ const p: RequestStartedPayload = {
78
+ op,
79
+ messages: req.messages.length,
80
+ content_bytes: 0,
81
+ tools,
82
+ max_tokens: req.maxTokens ?? 0,
83
+ has_temperature: req.temperature !== undefined,
84
+ thinking: req.thinking !== undefined,
85
+ stop_sequences: req.stopSequences?.length ?? 0,
86
+ };
87
+ if (req.model) p.model = req.model;
88
+ for (const m of req.messages) {
89
+ p.roles ??= {};
90
+ p.roles[m.role] = (p.roles[m.role] ?? 0) + 1;
91
+ p.content_bytes += messageBytes(m);
92
+ for (const part of m.parts ?? []) {
93
+ p.parts ??= {};
94
+ p.parts[part.type] = (p.parts[part.type] ?? 0) + 1;
95
+ if (part.type === "text") p.content_bytes += bytes(part.text);
96
+ }
97
+ }
98
+ const keys = Object.keys(req.extensions ?? {}).sort();
99
+ if (keys.length > 0) p.extension_keys = keys;
100
+ return p;
101
+ }
102
+
103
+ /**
104
+ * The `kit.ai.response.received` payload for `resp`, with the calls the
105
+ * model made (`tool_call`), after `durationMs`.
106
+ */
107
+ export function responseReceivedPayload(
108
+ op: CallOp,
109
+ resp: Response,
110
+ toolCalls: readonly ToolCall[],
111
+ durationMs: number
112
+ ): ResponseReceivedPayload {
113
+ const u = resp.usage;
114
+ const p: ResponseReceivedPayload = {
115
+ op,
116
+ usage: {
117
+ prompt_tokens: u?.promptTokens ?? 0,
118
+ completion_tokens: u?.completionTokens ?? 0,
119
+ cache_read_tokens: u?.cacheReadTokens ?? 0,
120
+ cache_creation_tokens: u?.cacheCreationTokens ?? 0,
121
+ total_tokens: u?.totalTokens ?? 0,
122
+ },
123
+ content_bytes:
124
+ bytes(resp.content) + callBytes(toolCalls) + thinkingBytes(resp.thinking),
125
+ tool_calls: toolCalls.length,
126
+ duration_ms: Math.max(0, Math.floor(durationMs)),
127
+ };
128
+ if (resp.finishReason) p.finish_reason = resp.finishReason;
129
+ return p;
130
+ }
131
+
132
+ function messageBytes(m: Message): number {
133
+ return bytes(m.content) + callBytes(m.toolCalls ?? []) + thinkingBytes(m.thinking);
134
+ }
135
+
136
+ function bytes(s: string | undefined): number {
137
+ return s ? Buffer.byteLength(s, "utf8") : 0;
138
+ }
139
+
140
+ /** Arguments as sent: a JSON string as is, anything else encoded. */
141
+ function callBytes(calls: readonly ToolCall[]): number {
142
+ let n = 0;
143
+ for (const c of calls) {
144
+ const a = c.arguments;
145
+ if (a === undefined || a === null) continue;
146
+ n += bytes(typeof a === "string" ? a : JSON.stringify(a));
147
+ }
148
+ return n;
149
+ }
150
+
151
+ function thinkingBytes(tbs: readonly ThinkingBlock[] | undefined): number {
152
+ let n = 0;
153
+ for (const tb of tbs ?? []) n += bytes(tb.thinking);
154
+ return n;
155
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Go `%q` quoting, for error texts the llm-v1 vectors pin byte for
3
+ * byte across ports.
4
+ *
5
+ * @internal
6
+ */
7
+
8
+ const ESCAPES: Record<string, string> = {
9
+ '"': '\\"',
10
+ "\\": "\\\\",
11
+ "\u0007": "\\a",
12
+ "\b": "\\b",
13
+ "\f": "\\f",
14
+ "\n": "\\n",
15
+ "\r": "\\r",
16
+ "\t": "\\t",
17
+ "\v": "\\v",
18
+ };
19
+
20
+ const PRINTABLE = /^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;
21
+
22
+ /** Quotes `s` as Go's `strconv.Quote` (and `%q`) does. */
23
+ export function goQuote(s: string): string {
24
+ let out = '"';
25
+ for (const ch of s) {
26
+ const esc = ESCAPES[ch];
27
+ if (esc !== undefined) {
28
+ out += esc;
29
+ continue;
30
+ }
31
+ const c = ch.codePointAt(0)!;
32
+ if (c >= 0xd800 && c <= 0xdfff) {
33
+ // A lone surrogate reaches Go as U+FFFD, which prints as itself.
34
+ out += "�";
35
+ } else if (ch === " " || PRINTABLE.test(ch)) {
36
+ out += ch;
37
+ } else if (c < 0x20 || c === 0x7f) {
38
+ out += "\\x" + c.toString(16).padStart(2, "0");
39
+ } else if (c < 0x10000) {
40
+ out += "\\u" + c.toString(16).padStart(4, "0");
41
+ } else {
42
+ out += "\\U" + c.toString(16).padStart(8, "0");
43
+ }
44
+ }
45
+ return out + '"';
46
+ }
@@ -0,0 +1,44 @@
1
+ // Runs the routellm_base_url section of contracts/llm-v1/vectors.json:
2
+ // the API root the routellm adapter resolves from the provider base URL,
3
+ // the router config (extras, ROUTELLM_BASE_URL) and the default. Go is
4
+ // canonical; a failure here means this SDK drifted, not that a vector
5
+ // should change.
6
+
7
+ import { afterEach, describe, expect, it } from "vitest";
8
+
9
+ import { RouteLLMAdapter } from "./routellm";
10
+ import { loadVectors, strictKeys } from "../test/llm/conformance-helpers";
11
+
12
+ interface BaseURLVector {
13
+ name: string;
14
+ base_url: string;
15
+ extras: Record<string, unknown>;
16
+ env: Record<string, string>;
17
+ hermetic: boolean;
18
+ want: string;
19
+ }
20
+
21
+ const vectors = loadVectors<{ routellm_base_url: BaseURLVector[] }>().routellm_base_url;
22
+
23
+ const saved = process.env["ROUTELLM_BASE_URL"];
24
+ afterEach(() => {
25
+ if (saved === undefined) delete process.env["ROUTELLM_BASE_URL"];
26
+ else process.env["ROUTELLM_BASE_URL"] = saved;
27
+ });
28
+
29
+ describe("llm-v1 conformance: routellm_base_url", () => {
30
+ it("has vectors", () => expect(vectors.length).toBeGreaterThan(0));
31
+
32
+ it.each(vectors.map((v) => [v.name, v] as const))("%s", (_n, v) => {
33
+ strictKeys(v, ["name", "base_url", "extras", "env", "hermetic", "want"], "routellm_base_url");
34
+ delete process.env["ROUTELLM_BASE_URL"];
35
+ for (const [k, val] of Object.entries(v.env)) process.env[k] = val;
36
+ const a = new RouteLLMAdapter({
37
+ uri: { scheme: "routellm", model: "mf:0.5" },
38
+ provider: { model: "mf:0.5", baseURL: v.base_url || undefined, extras: v.extras },
39
+ fallbacks: [],
40
+ hermetic: v.hermetic,
41
+ });
42
+ expect(a.baseURL).toBe(v.want);
43
+ });
44
+ });
@@ -0,0 +1,112 @@
1
+ // Runs the provider-neutral `tool_names` section of
2
+ // contracts/llm-v1/vectors.json. Go is canonical; a failure here means
3
+ // this SDK drifted, not that a vector should change.
4
+ //
5
+ // The anthropic sections, `anthropic_tool_names` among them, run in
6
+ // llm-anthropic.conformance.test.ts; the openai and routellm adapters'
7
+ // share of the spec is covered in llm-openai.test.ts and
8
+ // routellm.toolcall.test.ts.
9
+
10
+ import { existsSync, readFileSync } from "node:fs";
11
+ import { dirname, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ import { describe, expect, it } from "vitest";
15
+
16
+ import {
17
+ ANTHROPIC_TOOL_NAMES,
18
+ GEMINI_TOOL_NAMES,
19
+ OPENAI_TOOL_NAMES,
20
+ ToolNameError,
21
+ ToolNames,
22
+ isValidToolName,
23
+ sanitizeToolName,
24
+ type ToolNameMode,
25
+ type ToolNameRule,
26
+ } from "./llm";
27
+
28
+ interface ToolNamesVector {
29
+ name: string;
30
+ rule: string;
31
+ mode?: string;
32
+ tools: string[];
33
+ want?: string[];
34
+ calls?: string[];
35
+ want_calls?: string[];
36
+ error?: { reason: string; name: string; other: string };
37
+ }
38
+
39
+ const VECTOR_KEYS = new Set([
40
+ "name", "rule", "mode", "tools", "want", "calls", "want_calls", "error",
41
+ ]);
42
+ const ERROR_KEYS = new Set(["reason", "name", "other"]);
43
+
44
+ const RULES: Record<string, ToolNameRule> = {
45
+ anthropic: ANTHROPIC_TOOL_NAMES,
46
+ openai: OPENAI_TOOL_NAMES,
47
+ gemini: GEMINI_TOOL_NAMES,
48
+ };
49
+
50
+ function locate(): string {
51
+ let dir = dirname(fileURLToPath(import.meta.url));
52
+ for (let i = 0; i < 10; i++) {
53
+ const p = resolve(dir, "contracts/llm-v1/vectors.json");
54
+ if (existsSync(p)) return p;
55
+ dir = dirname(dir);
56
+ }
57
+ throw new Error("contracts/llm-v1/vectors.json not found");
58
+ }
59
+
60
+ const file = JSON.parse(readFileSync(locate(), "utf8")) as {
61
+ version: string;
62
+ tool_names: ToolNamesVector[];
63
+ };
64
+
65
+ describe("llm-v1 conformance: tool_names", () => {
66
+ it("is v1 and not empty", () => {
67
+ expect(file.version).toBe("v1");
68
+ expect(file.tool_names.length).toBeGreaterThan(0);
69
+ });
70
+
71
+ for (const v of file.tool_names) {
72
+ it(v.name, () => {
73
+ for (const k of Object.keys(v)) expect(VECTOR_KEYS).toContain(k);
74
+ for (const k of Object.keys(v.error ?? {})) expect(ERROR_KEYS).toContain(k);
75
+ const rule = RULES[v.rule];
76
+ expect(rule, `unknown rule ${v.rule}`).toBeDefined();
77
+ if (!rule) return;
78
+ const mode = (v.mode || "sanitize") as ToolNameMode;
79
+ expect(["sanitize", "strict"]).toContain(mode);
80
+ const defs = v.tools.map((name) => ({ name }));
81
+
82
+ if (v.error) {
83
+ let err: unknown;
84
+ try {
85
+ ToolNames.build(rule, mode, defs);
86
+ } catch (e) {
87
+ err = e;
88
+ }
89
+ expect(err).toBeInstanceOf(ToolNameError);
90
+ const te = err as ToolNameError;
91
+ expect(te.reason).toBe(v.error.reason);
92
+ expect(te.toolName).toBe(v.error.name);
93
+ expect(te.other).toBe(v.error.other);
94
+ expect(te.provider).toBe(rule.provider);
95
+ return;
96
+ }
97
+
98
+ const names = ToolNames.build(rule, mode, defs);
99
+ const got = v.tools.map((n) => names.wire(n));
100
+ expect(got).toEqual(v.want);
101
+ for (const w of got) expect(isValidToolName(rule, w)).toBe(true);
102
+ if (mode === "sanitize") {
103
+ v.tools.forEach((n, i) =>
104
+ expect(sanitizeToolName(rule, n)).toBe(v.want?.[i])
105
+ );
106
+ }
107
+ expect((v.calls ?? []).map((c) => names.original(c))).toEqual(
108
+ v.want_calls ?? []
109
+ );
110
+ });
111
+ }
112
+ });
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Unit tests for tool-name rules, the sanitizer and the per-request
3
+ * table. The cross-language vectors run in
4
+ * llm-toolnames.conformance.test.ts; these cover what JSON vectors
5
+ * cannot carry (lone surrogates), the error type and the mode param.
6
+ */
7
+
8
+ import { describe, expect, it } from "vitest";
9
+ import {
10
+ ANTHROPIC_TOOL_NAMES,
11
+ GEMINI_TOOL_NAMES,
12
+ LLMError,
13
+ OPENAI_TOOL_NAMES,
14
+ ToolNameError,
15
+ ToolNames,
16
+ isFallbackable,
17
+ isValidToolName,
18
+ sanitizeToolName,
19
+ toolNameModeOf,
20
+ } from "./llm";
21
+
22
+ function thrown(fn: () => unknown): ToolNameError {
23
+ try {
24
+ fn();
25
+ } catch (e) {
26
+ expect(e).toBeInstanceOf(ToolNameError);
27
+ return e as ToolNameError;
28
+ }
29
+ throw new Error("expected a ToolNameError");
30
+ }
31
+
32
+ describe("sanitizeToolName", () => {
33
+ it("matches the spec examples", () => {
34
+ expect(sanitizeToolName(OPENAI_TOOL_NAMES, "pane.open")).toBe("pane_open");
35
+ expect(sanitizeToolName(OPENAI_TOOL_NAMES, "mcp://fs/read_file")).toBe(
36
+ "mcp_fs_read_file"
37
+ );
38
+ expect(sanitizeToolName(OPENAI_TOOL_NAMES, "café.menu")).toBe("caf_menu");
39
+ expect(sanitizeToolName(OPENAI_TOOL_NAMES, "検索")).toBe("__1b6b1a6f");
40
+ expect(sanitizeToolName(OPENAI_TOOL_NAMES, "a".repeat(65))).toBe(
41
+ "a".repeat(55) + "_635361c4"
42
+ );
43
+ expect(sanitizeToolName(GEMINI_TOOL_NAMES, "pane.open")).toBe("pane.open");
44
+ expect(sanitizeToolName(GEMINI_TOOL_NAMES, "1tool")).toBe("_1tool");
45
+ });
46
+
47
+ it("collapses a run of disallowed bytes to one underscore", () => {
48
+ expect(sanitizeToolName(ANTHROPIC_TOOL_NAMES, "a..//::b")).toBe("a_b");
49
+ // A 4-byte emoji is one run, not four separators.
50
+ expect(sanitizeToolName(ANTHROPIC_TOOL_NAMES, "x🔧y")).toBe("x_y");
51
+ });
52
+
53
+ it("hashes the original UTF-8 bytes, 8 hex digits", () => {
54
+ const out = sanitizeToolName(ANTHROPIC_TOOL_NAMES, "...");
55
+ expect(out).toMatch(/^__[0-9a-f]{8}$/);
56
+ expect(out).toBe("__ab5df625");
57
+ });
58
+
59
+ it("refuses empty and lone-surrogate names", () => {
60
+ const empty = thrown(() => sanitizeToolName(ANTHROPIC_TOOL_NAMES, ""));
61
+ expect(empty.reason).toBe("empty");
62
+ for (const bad of ["a\uD800", "\uDC00b", "x\uDBFFy"]) {
63
+ const err = thrown(() => sanitizeToolName(ANTHROPIC_TOOL_NAMES, bad));
64
+ expect(err.reason).toBe("invalid_utf8");
65
+ expect(err.toolName).toBe(bad);
66
+ expect(err.provider).toBe("anthropic");
67
+ }
68
+ // A well-formed surrogate pair is fine.
69
+ expect(sanitizeToolName(ANTHROPIC_TOOL_NAMES, "a🔧")).toBe("a_");
70
+ });
71
+
72
+ it("measures length in bytes, not UTF-16 units", () => {
73
+ // 63 ASCII bytes + 2-byte é: 65 bytes, sanitized to 64 then valid.
74
+ expect(sanitizeToolName(OPENAI_TOOL_NAMES, "a".repeat(63) + "é")).toBe(
75
+ "a".repeat(63) + "_"
76
+ );
77
+ expect(isValidToolName(OPENAI_TOOL_NAMES, "a".repeat(64))).toBe(true);
78
+ expect(isValidToolName(OPENAI_TOOL_NAMES, "a".repeat(65))).toBe(false);
79
+ });
80
+ });
81
+
82
+ describe("ToolNames", () => {
83
+ it("fails with a typed, non-fallbackable error", () => {
84
+ const err = thrown(() =>
85
+ ToolNames.build(ANTHROPIC_TOOL_NAMES, "sanitize", [
86
+ { name: "pane.open" },
87
+ { name: "pane:open" },
88
+ ])
89
+ );
90
+ expect(err).toBeInstanceOf(LLMError);
91
+ expect(err.reason).toBe("collision");
92
+ expect(err.toolName).toBe("pane:open");
93
+ expect(err.other).toBe("pane.open");
94
+ expect(err.name).toBe("ToolNameError");
95
+ expect(err.message).toContain("pane.open");
96
+ expect(isFallbackable(err)).toBe(false);
97
+ });
98
+
99
+ it("maps history names forward per mode", () => {
100
+ const san = ToolNames.build(OPENAI_TOOL_NAMES, "sanitize", []);
101
+ expect(san.wire("pane.open")).toBe("pane_open");
102
+ expect(san.wire("")).toBe("");
103
+ expect(san.wire("a\uD800")).toBe("a\uD800");
104
+ const strict = ToolNames.build(OPENAI_TOOL_NAMES, "strict", []);
105
+ expect(strict.wire("pane.open")).toBe("pane.open");
106
+ });
107
+
108
+ it("maps calls back without touching the input", () => {
109
+ const t = ToolNames.build(ANTHROPIC_TOOL_NAMES, "sanitize", [
110
+ { name: "pane.open" },
111
+ ]);
112
+ const calls = [{ id: "1", name: "pane_open", arguments: {} }];
113
+ expect(t.calls(calls)[0]?.name).toBe("pane.open");
114
+ expect(calls[0]?.name).toBe("pane_open");
115
+ expect(t.defs([{ name: "pane.open", description: "", parameters: {} }]))
116
+ .toEqual([{ name: "pane_open", description: "", parameters: {} }]);
117
+ });
118
+ });
119
+
120
+ describe("toolNameModeOf", () => {
121
+ it("defaults to sanitize and accepts both modes", () => {
122
+ expect(toolNameModeOf(undefined)).toBe("sanitize");
123
+ expect(toolNameModeOf({})).toBe("sanitize");
124
+ expect(toolNameModeOf({ tool_names: "sanitize" })).toBe("sanitize");
125
+ expect(toolNameModeOf({ tool_names: " strict " })).toBe("strict");
126
+ });
127
+
128
+ it("refuses any other value", () => {
129
+ expect(() => toolNameModeOf({ tool_names: "loose" })).toThrow(LLMError);
130
+ expect(() => toolNameModeOf({ tool_names: "" })).toThrow(/tool_names/);
131
+ });
132
+ });