@hop-top/kit 0.5.0-alpha.3 → 0.5.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/CHANGELOG.md +52 -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-IXVQ62NZ.js +334 -0
  26. package/dist/chunk-JTMPNXVQ.js +1491 -0
  27. package/dist/chunk-KVG7YCTS.js +115 -0
  28. package/dist/chunk-L23O2FFE.js +51 -0
  29. package/dist/chunk-MQXYDYRD.js +968 -0
  30. package/dist/chunk-MUIQVU6E.js +251 -0
  31. package/dist/chunk-POR5L2DG.js +247 -0
  32. package/dist/chunk-PSFYJGDG.js +1445 -0
  33. package/dist/chunk-QJVSKKRQ.js +369 -0
  34. package/dist/chunk-QPUCXQXT.js +67 -0
  35. package/dist/chunk-R5U7XKVJ.js +16 -0
  36. package/dist/chunk-S45UHXQF.js +182 -0
  37. package/dist/chunk-T46YPHKN.js +669 -0
  38. package/dist/chunk-UKZIAQA7.js +26 -0
  39. package/dist/chunk-WBVO43HU.js +355 -0
  40. package/dist/chunk-WUOAQVOA.js +86 -0
  41. package/dist/chunk-WWUKGJB5.js +90 -0
  42. package/dist/chunk-YGYQUFGY.js +219 -0
  43. package/dist/chunk-YOBAUCVN.js +583 -0
  44. package/dist/chunk-ZC5TZYZJ.js +609 -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 +51 -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.help-command.test.ts +105 -0
  100. package/src/cli.test.ts +95 -1
  101. package/src/cli.ts +78 -13
  102. package/src/completion-values.test.ts +10 -10
  103. package/src/compliance.test.ts +196 -2
  104. package/src/compliance.ts +440 -20
  105. package/src/config.test.ts +187 -1
  106. package/src/config.ts +173 -7
  107. package/src/gen/crud_pb.ts +7 -7
  108. package/src/id/README.md +38 -0
  109. package/src/id/contract.test.ts +1 -1
  110. package/src/id/index.test.ts +1 -1
  111. package/src/id/index.ts +3 -2
  112. package/src/index.test.ts +12 -0
  113. package/src/index.ts +2 -0
  114. package/src/llm-anthropic.conformance.test.ts +1135 -0
  115. package/src/llm-anthropic.test.ts +152 -0
  116. package/src/llm-anthropic.ts +940 -0
  117. package/src/llm-choice-hermetic.test.ts +335 -0
  118. package/src/llm-config.test.ts +232 -0
  119. package/src/llm-config.ts +106 -0
  120. package/src/llm-endpoint.ts +254 -0
  121. package/src/llm-error.ts +17 -0
  122. package/src/llm-errors.ts +152 -0
  123. package/src/llm-file.ts +126 -0
  124. package/src/llm-http.ts +317 -0
  125. package/src/llm-keys.ts +167 -0
  126. package/src/llm-media.conformance.test.ts +87 -0
  127. package/src/llm-media.test.ts +279 -0
  128. package/src/llm-media.ts +322 -0
  129. package/src/llm-openai.conformance.test.ts +407 -0
  130. package/src/llm-openai.test.ts +510 -0
  131. package/src/llm-openai.ts +708 -0
  132. package/src/llm-payload.ts +155 -0
  133. package/src/llm-quote.ts +46 -0
  134. package/src/llm-routellm.conformance.test.ts +44 -0
  135. package/src/llm-toolnames.conformance.test.ts +112 -0
  136. package/src/llm-toolnames.test.ts +132 -0
  137. package/src/llm-toolnames.ts +298 -0
  138. package/src/llm-uri.ts +99 -0
  139. package/src/llm.test.ts +43 -15
  140. package/src/llm.toolcall.test.ts +175 -0
  141. package/src/llm.ts +602 -190
  142. package/src/mcp/README.md +57 -0
  143. package/src/mcp/conformance.test.ts +24 -3
  144. package/src/mcp/dispatch.ts +4 -4
  145. package/src/mcp/identity.test.ts +166 -0
  146. package/src/mcp/identity.ts +72 -0
  147. package/src/mcp/index.ts +6 -0
  148. package/src/mcp/legacy.ts +21 -8
  149. package/src/mcp/mcp.test.ts +14 -4
  150. package/src/mcp/modern-confirm.ts +1 -1
  151. package/src/mcp/modern.ts +12 -11
  152. package/src/mcp/tasks.ts +1 -1
  153. package/src/mcp/types.ts +80 -8
  154. package/src/netpolicy.test.ts +78 -0
  155. package/src/netpolicy.ts +28 -3
  156. package/src/output/README.md +46 -0
  157. package/src/output/builtins.ts +5 -5
  158. package/src/output/error.ts +144 -1
  159. package/src/output/formatters/README.md +50 -0
  160. package/src/output.ts +24 -1
  161. package/src/published-types.test.ts +115 -0
  162. package/src/routellm.test.ts +209 -28
  163. package/src/routellm.toolcall.test.ts +521 -0
  164. package/src/routellm.ts +213 -177
  165. package/src/router/README.md +44 -0
  166. package/src/router/server.test.ts +41 -0
  167. package/src/router/server.ts +11 -0
  168. package/src/safety.test.ts +19 -9
  169. package/src/scope-defaults.json +29 -29
  170. package/src/serve.ts +1 -1
  171. package/src/telemetry/README.md +48 -0
  172. package/src/telemetry/client.ts +5 -5
  173. package/src/toolspec.test.ts +2 -2
  174. package/src/triton/README.md +34 -0
  175. package/src/tui/README.md +42 -0
  176. package/src/wizard.test.ts +7 -7
  177. package/test/llm/conformance-helpers.ts +100 -0
  178. package/test/output/dispatch.test.ts +1 -2
  179. package/test/output/error.test.ts +33 -2
  180. package/test/output/smoke-capture.ts +2 -2
  181. package/test/output/smoke.test.ts +2 -2
  182. package/test/output/taxonomy-contract.test.ts +148 -0
  183. package/test/setup-env.ts +16 -0
  184. package/tsconfig.json +3 -1
  185. package/tsconfig.test.json +10 -0
  186. package/vitest.config.ts +9 -0
  187. package/dist/llm-B5XUWH8T.d.ts +0 -231
  188. package/dist/routellm-PGSt2D1y.d.ts +0 -75
package/src/routellm.ts CHANGED
@@ -3,24 +3,37 @@
3
3
  *
4
4
  * RouteLLM adapter — registers the `routellm` URI scheme.
5
5
  *
6
- * URI format: `routellm://router_name:threshold` (e.g. `routellm://mf:0.7`).
6
+ * The model field takes either shape a RouteLLM server advertises on
7
+ * `/v1/models`, as in Go:
7
8
  *
8
- * Delegates HTTP completions to an OpenAI-compatible endpoint on the
9
- * RouteLLM server, translating the model field into the server's
10
- * expected `router-[name]-[threshold]` format.
9
+ * - `router_name:threshold` — `routellm://mf:0.7`, sent as the server's
10
+ * `router-[name]-[threshold]` model. The client picks both.
11
+ * - tier name — `routellm://private`, sent verbatim. The server resolves
12
+ * router and threshold from its own tier config.
13
+ *
14
+ * Delegates to the openai adapter (`@hop-top/kit/openai`) pointed
15
+ * at the RouteLLM server's OpenAI-compatible endpoint.
16
+ * Importing this module registers the openai schemes too.
11
17
  */
12
18
 
13
19
  import {
14
20
  type Completer,
15
21
  type Streamer,
22
+ type ToolCaller,
23
+ type ToolStreamer,
24
+ type ToolDef,
25
+ type ToolResponse,
26
+ type ToolStream,
16
27
  type Request,
17
28
  type Response,
18
- type Token,
19
29
  type ResolvedConfig,
20
30
  type Provider,
21
31
  LLMError,
32
+ TOOL_NAMES_PARAM,
22
33
  register,
34
+ toolNameModeOf,
23
35
  } from "./llm";
36
+ import { OpenAIAdapter, apiRootV1 } from "./llm-openai";
24
37
 
25
38
  // ─── RouterConfig ─────────────────────────────────────────────────────────────
26
39
 
@@ -55,10 +68,13 @@ function defaultRouterConfig(): RouterConfig {
55
68
 
56
69
  /**
57
70
  * Extract and validate RouteLLM configuration from provider extras.
58
- * Environment variables override all other sources.
71
+ * Environment variables (`ROUTELLM_BASE_URL`, `ROUTELLM_STRONG_MODEL`,
72
+ * `ROUTELLM_WEAK_MODEL`, `ROUTELLM_ROUTERS`) override all other
73
+ * sources; with `opts.hermetic` none is read.
59
74
  */
60
75
  export function parseRouterConfig(
61
- extras?: Record<string, unknown>
76
+ extras?: Record<string, unknown>,
77
+ opts: { hermetic?: boolean } = {}
62
78
  ): RouterConfig {
63
79
  const cfg = defaultRouterConfig();
64
80
 
@@ -107,6 +123,8 @@ export function parseRouterConfig(
107
123
  }
108
124
  }
109
125
 
126
+ if (opts.hermetic) return cfg;
127
+
110
128
  // Environment variable overrides (highest precedence).
111
129
  const envBaseUrl = process.env["ROUTELLM_BASE_URL"];
112
130
  if (envBaseUrl) cfg.baseUrl = envBaseUrl;
@@ -130,225 +148,237 @@ export function parseRouterConfig(
130
148
 
131
149
  // ─── Model field parsing ──────────────────────────────────────────────────────
132
150
 
151
+ /**
152
+ * The model field classified. `isTier` selects `tier`; otherwise
153
+ * `routerName` and `threshold` hold the client-selected pair. The
154
+ * unused shape stays at `""` / `0`.
155
+ */
133
156
  export interface ParsedModel {
157
+ isTier: boolean;
158
+ tier: string;
134
159
  routerName: string;
135
160
  threshold: number;
136
161
  }
137
162
 
163
+ const MODEL_REQUIRED =
164
+ "model field is required (router_name:threshold or tier name)";
165
+
166
+ const DECIMAL_FLOAT = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
167
+ const HEX_FLOAT =
168
+ /^([+-]?)0[xX]([0-9a-fA-F]*)(?:\.([0-9a-fA-F]*))?[pP]([+-]?\d+)$/;
169
+
138
170
  /**
139
- * Split a model string of the form `router_name:threshold` into its
140
- * components.
171
+ * Go's underscore rule for float literals: an underscore must sit
172
+ * between digits, or between a base prefix and a digit.
141
173
  */
142
- export function parseModelField(model: string): ParsedModel {
143
- if (!model) {
144
- throw new LLMError(
145
- "model field is required (format: router_name:threshold)"
146
- );
174
+ function underscoreOK(text: string): boolean {
175
+ let s = text;
176
+ if (s[0] === "+" || s[0] === "-") s = s.slice(1);
177
+ let saw = "^"; // ^ start, 0 digit or prefix, _ underscore, ! other
178
+ let i = 0;
179
+ let hex = false;
180
+ const p = s[1]?.toLowerCase();
181
+ if (s.length >= 2 && s[0] === "0" && (p === "b" || p === "o" || p === "x")) {
182
+ i = 2;
183
+ saw = "0";
184
+ hex = p === "x";
147
185
  }
148
-
149
- const idx = model.indexOf(":");
150
- if (idx < 0) {
151
- throw new LLMError(
152
- `invalid model "${model}": expected format ` +
153
- "router_name:threshold (e.g. mf:0.7)"
154
- );
186
+ for (; i < s.length; i++) {
187
+ const c = s[i]!;
188
+ if ((c >= "0" && c <= "9") || (hex && /[a-fA-F]/.test(c))) {
189
+ saw = "0";
190
+ continue;
191
+ }
192
+ if (c === "_") {
193
+ if (saw !== "0") return false;
194
+ saw = "_";
195
+ continue;
196
+ }
197
+ if (saw === "_") return false;
198
+ saw = "!";
155
199
  }
200
+ return saw !== "_";
201
+ }
156
202
 
157
- const routerName = model.slice(0, idx);
158
- const rawThreshold = model.slice(idx + 1);
203
+ /**
204
+ * A finite float in the syntax Go's `strconv.ParseFloat` accepts
205
+ * (decimal or hex mantissa, underscores between digits), else
206
+ * `undefined`. Infinities, NaN and out-of-range values are not.
207
+ */
208
+ function parseFiniteFloat(text: string): number | undefined {
209
+ if (text.includes("_")) {
210
+ if (!underscoreOK(text)) return undefined;
211
+ text = text.replace(/_/g, "");
212
+ }
213
+ let v: number;
214
+ if (DECIMAL_FLOAT.test(text)) {
215
+ v = Number(text);
216
+ } else {
217
+ const m = HEX_FLOAT.exec(text);
218
+ if (!m) return undefined;
219
+ const [, sign, int = "", frac = "", exp = "0"] = m;
220
+ if (!int && !frac) return undefined;
221
+ v = parseInt(int + frac || "0", 16) * 2 ** (Number(exp) - 4 * frac.length);
222
+ if (sign === "-") v = -v;
223
+ }
224
+ return Number.isFinite(v) ? v : undefined;
225
+ }
159
226
 
160
- if (!routerName || !rawThreshold) {
161
- throw new LLMError(
162
- `invalid model "${model}": expected format ` +
163
- "router_name:threshold (e.g. mf:0.7)"
164
- );
227
+ /**
228
+ * Format a float as Go's `strconv.FormatFloat(f, 'f', -1, 64)`: the
229
+ * shortest round-tripping digits, never an exponent, `-0` kept.
230
+ */
231
+ function formatFloat(v: number): string {
232
+ if (Object.is(v, -0)) return "-0";
233
+ const sign = v < 0 ? "-" : "";
234
+ const repr = String(Math.abs(v));
235
+ const e = repr.indexOf("e");
236
+ if (e < 0) return sign + repr;
237
+ const exp = Number(repr.slice(e + 1));
238
+ const digits = repr.slice(0, e).replace(".", "");
239
+ const point = 1 + exp; // position of the decimal point in digits
240
+ if (point <= 0) return `${sign}0.${"0".repeat(-point)}${digits}`;
241
+ if (point >= digits.length) {
242
+ return sign + digits + "0".repeat(point - digits.length);
165
243
  }
244
+ return `${sign}${digits.slice(0, point)}.${digits.slice(point)}`;
245
+ }
166
246
 
167
- const threshold = Number(rawThreshold);
168
- if (Number.isNaN(threshold)) {
169
- throw new LLMError(`invalid threshold "${rawThreshold}": not a number`);
247
+ /**
248
+ * Classify the model field as a `router_name:threshold` pair or a tier
249
+ * name, exactly as Go does.
250
+ *
251
+ * The shapes are told apart by the text after the last colon: when it
252
+ * parses as a finite float (Go `ParseFloat` syntax) the model is a
253
+ * router pair, else a tier sent verbatim — so a tier name may contain
254
+ * colons and `mf:abc` is a tier. A leading or trailing colon leaves a
255
+ * tier. The threshold range is checked by the adapter, not here; an
256
+ * unknown tier fails at the server.
257
+ */
258
+ export function parseModelField(model: string): ParsedModel {
259
+ if (!model) throw new LLMError(MODEL_REQUIRED);
260
+
261
+ const idx = model.lastIndexOf(":");
262
+ if (idx > 0 && idx < model.length - 1) {
263
+ const threshold = parseFiniteFloat(model.slice(idx + 1));
264
+ if (threshold !== undefined) {
265
+ return {
266
+ isTier: false,
267
+ tier: "",
268
+ routerName: model.slice(0, idx),
269
+ threshold,
270
+ };
271
+ }
170
272
  }
171
273
 
172
- return { routerName, threshold };
274
+ return { isTier: true, tier: model, routerName: "", threshold: 0 };
173
275
  }
174
276
 
175
277
  // ─── Adapter ──────────────────────────────────────────────────────────────────
176
278
 
177
279
  /**
178
- * RouteLLM adapter implementing Completer and Streamer.
280
+ * RouteLLM adapter: complete, stream, callWithTools and streamWithTools.
179
281
  *
180
- * Delegates to an OpenAI-compatible HTTP endpoint on the RouteLLM
181
- * server using the standard fetch API.
282
+ * Delegates to an inner {@link OpenAIAdapter} pointed at the RouteLLM
283
+ * server's OpenAI-compatible `/v1` API, so tool calling, tool names
284
+ * (openai rule, `?tool_names=`), size limits, retries and the
285
+ * credential guard are the openai adapter's.
182
286
  */
183
- export class RouteLLMAdapter implements Completer, Streamer {
287
+ export class RouteLLMAdapter
288
+ implements Completer, Streamer, ToolCaller, ToolStreamer
289
+ {
184
290
  readonly config: RouterConfig;
291
+ /** Client-selected router; `""` for a tier. */
185
292
  readonly routerName: string;
293
+ /** Client-selected threshold; `0` for a tier (see {@link isTier}). */
186
294
  readonly threshold: number;
295
+ /** Server-resolved tier name; `""` for a router pair. */
296
+ readonly tier: string;
297
+ /** The API root requests go to: the resolved base URL plus `/v1`. */
298
+ readonly baseURL: string;
187
299
 
188
- private readonly _baseUrl: string;
189
- private readonly _serverModel: string;
190
- private readonly _apiKey: string;
300
+ private readonly inner: OpenAIAdapter;
191
301
 
192
302
  constructor(cfg: ResolvedConfig) {
193
- this.config = parseRouterConfig(cfg.provider.extras);
303
+ this.config = parseRouterConfig(cfg.provider.extras, { hermetic: cfg.hermetic });
304
+ // The server speaks the OpenAI wire: its tool-name rule applies.
305
+ // Checked here so an unknown mode fails construction.
306
+ toolNameModeOf(cfg.provider.params);
194
307
 
195
308
  const model = cfg.provider.model || cfg.uri.model;
309
+ if (!model) throw new LLMError(`routellm: ${MODEL_REQUIRED}`);
196
310
  const parsed = parseModelField(model);
197
311
  this.routerName = parsed.routerName;
198
312
  this.threshold = parsed.threshold;
313
+ this.tier = parsed.tier;
199
314
 
200
- if (this.threshold < 0 || this.threshold > 1) {
201
- throw new LLMError(
202
- `routellm: threshold ${this.threshold} out of range [0, 1]`
203
- );
315
+ // A tier travels verbatim; a router pair becomes
316
+ // router-[name]-[threshold].
317
+ let serverModel = parsed.tier;
318
+ if (!parsed.isTier) {
319
+ if (this.threshold < 0 || this.threshold > 1) {
320
+ throw new LLMError(
321
+ `routellm: threshold ${this.threshold.toFixed(4)} out of range [0, 1]`
322
+ );
323
+ }
324
+ serverModel = `router-${this.routerName}-${formatFloat(this.threshold)}`;
204
325
  }
205
326
 
206
- // Build server model name: router-[name]-[threshold]
207
- this._serverModel = `router-${this.routerName}-${this.threshold}`;
327
+ // Resolve base URL: provider (URI base_url or host, LLM_BASE_URL) >
328
+ // router config (ROUTELLM_BASE_URL > extras routellm.base_url) >
329
+ // default, as in Go.
330
+ this.baseURL = apiRootV1(cfg.provider.baseURL || this.config.baseUrl);
208
331
 
209
- // Resolve base URL: config > provider > default.
210
- let baseUrl = this.config.baseUrl;
211
- if (baseUrl === "http://localhost:6060" && cfg.provider.baseURL) {
212
- baseUrl = cfg.provider.baseURL;
332
+ // The inner adapter takes the params it owns.
333
+ const params: Record<string, string> = {};
334
+ for (const k of [TOOL_NAMES_PARAM, "max_body_bytes", "max_event_bytes"]) {
335
+ const v = cfg.provider.params?.[k];
336
+ if (v !== undefined) params[k] = v;
213
337
  }
214
- this._baseUrl = baseUrl;
215
- this._apiKey = cfg.provider.apiKey ?? "";
338
+ this.inner = new OpenAIAdapter(
339
+ {
340
+ uri: { scheme: "routellm", model },
341
+ provider: {
342
+ apiKey: cfg.provider.apiKey,
343
+ baseURL: this.baseURL,
344
+ model: serverModel,
345
+ params,
346
+ },
347
+ fallbacks: [],
348
+ hermetic: cfg.hermetic,
349
+ },
350
+ { label: "routellm" }
351
+ );
216
352
  }
217
353
 
218
- async complete(req: Request): Promise<Response> {
219
- const body = this._buildBody(req, false);
220
- const resp = await this._post("/v1/chat/completions", body);
221
-
222
- const data = (await resp.json()) as OpenAIChatResponse;
223
- const choice = data.choices?.[0];
224
- const content = choice?.message?.content ?? "";
225
- const finishReason = choice?.finish_reason ?? "";
226
-
227
- const usage = data.usage
228
- ? {
229
- promptTokens: data.usage.prompt_tokens ?? 0,
230
- completionTokens: data.usage.completion_tokens ?? 0,
231
- totalTokens: data.usage.total_tokens ?? 0,
232
- }
233
- : undefined;
234
-
235
- return { content, role: "assistant", usage, finishReason };
354
+ /**
355
+ * Whether the adapter targets a server-resolved tier rather than a
356
+ * client-selected pair; use it instead of `threshold === 0`, which is
357
+ * also a valid client threshold.
358
+ */
359
+ isTier(): boolean {
360
+ return this.tier !== "";
236
361
  }
237
362
 
238
- async *stream(req: Request): AsyncGenerator<Token> {
239
- const body = this._buildBody(req, true);
240
- const resp = await this._post("/v1/chat/completions", body);
241
-
242
- if (!resp.body) {
243
- throw new LLMError("routellm: streaming response has no body");
244
- }
245
-
246
- const reader = resp.body.getReader();
247
- const decoder = new TextDecoder();
248
- let buf = "";
249
-
250
- try {
251
- for (;;) {
252
- const { done, value } = await reader.read();
253
- if (done) break;
254
-
255
- buf += decoder.decode(value, { stream: true });
256
- const lines = buf.split("\n");
257
- buf = lines.pop() ?? "";
258
-
259
- for (const line of lines) {
260
- const trimmed = line.trim();
261
- if (!trimmed || !trimmed.startsWith("data: ")) continue;
262
- const payload = trimmed.slice(6);
263
- if (payload === "[DONE]") {
264
- yield { content: "", done: true };
265
- return;
266
- }
267
-
268
- const chunk = JSON.parse(payload) as OpenAIStreamChunk;
269
- const delta = chunk.choices?.[0]?.delta;
270
- const content = delta?.content ?? "";
271
- const isDone = chunk.choices?.[0]?.finish_reason != null;
272
- yield { content, done: isDone };
273
- }
274
- }
275
- } finally {
276
- reader.releaseLock();
277
- }
363
+ complete(req: Request): Promise<Response> {
364
+ return this.inner.complete(req);
278
365
  }
279
366
 
280
- close(): void {
281
- // No persistent resources to release.
367
+ stream(req: Request): ToolStream {
368
+ return this.inner.stream(req);
282
369
  }
283
370
 
284
- // ── private ────────────────────────────────────────────────────
285
-
286
- private _buildBody(
287
- req: Request,
288
- stream: boolean
289
- ): Record<string, unknown> {
290
- const body: Record<string, unknown> = {
291
- model: this._serverModel,
292
- messages: req.messages.map((m) => ({
293
- role: m.role,
294
- content: m.content,
295
- })),
296
- stream,
297
- };
298
- if (req.temperature !== undefined) body["temperature"] = req.temperature;
299
- if (req.maxTokens !== undefined) body["max_tokens"] = req.maxTokens;
300
- if (req.stopSequences?.length) body["stop"] = req.stopSequences;
301
- return body;
371
+ callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse> {
372
+ return this.inner.callWithTools(req, tools);
302
373
  }
303
374
 
304
- private async _post(
305
- path: string,
306
- body: Record<string, unknown>
307
- ): Promise<globalThis.Response> {
308
- const url = `${this._baseUrl}${path}`;
309
- const headers: Record<string, string> = {
310
- "Content-Type": "application/json",
311
- };
312
- if (this._apiKey) {
313
- headers["Authorization"] = `Bearer ${this._apiKey}`;
314
- }
315
-
316
- const resp = await fetch(url, {
317
- method: "POST",
318
- headers,
319
- body: JSON.stringify(body),
320
- });
321
-
322
- if (!resp.ok) {
323
- const text = await resp.text().catch(() => "");
324
- throw new LLMError(
325
- `routellm: HTTP ${resp.status} from ${url}: ${text}`
326
- );
327
- }
328
-
329
- return resp;
375
+ streamWithTools(req: Request, tools: ToolDef[]): ToolStream {
376
+ return this.inner.streamWithTools(req, tools);
330
377
  }
331
- }
332
-
333
- // ─── OpenAI-compatible response types (internal) ──────────────────────────────
334
-
335
- interface OpenAIChatResponse {
336
- choices?: {
337
- message?: { content?: string; role?: string };
338
- finish_reason?: string;
339
- }[];
340
- usage?: {
341
- prompt_tokens?: number;
342
- completion_tokens?: number;
343
- total_tokens?: number;
344
- };
345
- }
346
378
 
347
- interface OpenAIStreamChunk {
348
- choices?: {
349
- delta?: { content?: string; role?: string };
350
- finish_reason?: string | null;
351
- }[];
379
+ close(): void {
380
+ this.inner.close();
381
+ }
352
382
  }
353
383
 
354
384
  // ─── Registration ─────────────────────────────────────────────────────────────
@@ -358,8 +388,14 @@ function routellmFactory(cfg: ResolvedConfig): Provider {
358
388
  return {
359
389
  complete: (req) => adapter.complete(req),
360
390
  stream: (req) => adapter.stream(req),
391
+ callWithTools: (req, tools) => adapter.callWithTools(req, tools),
392
+ streamWithTools: (req, tools) => adapter.streamWithTools(req, tools),
361
393
  close: () => adapter.close(),
362
394
  };
363
395
  }
364
396
 
365
- register("routellm", routellmFactory);
397
+ // A local router: ROUTELLM_API_KEY is sent when set and never
398
+ // required, so LLM_API_KEY is not lent to it.
399
+ register("routellm", routellmFactory, {
400
+ key: { envVars: ["ROUTELLM_API_KEY"], optional: true },
401
+ });
@@ -0,0 +1,44 @@
1
+ # router
2
+
3
+ ## What it answers
4
+
5
+ How a prompt is scored and sent to a strong or a weak model: the RouteLLM `Router` interface, the scoring routers (`random`, `mf`, `sw`, `bert`), the `Controller` that owns thresholds and middleware, and a Hono handler exposing `/v1/chat/completions`. Wrong module for calling a RouteLLM server from a client (`@hop-top/kit/routellm` registers the `routellm://` URI scheme) and for provider clients (`@hop-top/kit/llm`).
6
+
7
+ ## Use it when
8
+
9
+ - pick a model for a prompt in-process: `new Controller({ strongModel, weakModel, routers })` then `controller.route(prompt, routerName, threshold)`
10
+ - add a scorer: implement `Router.score(prompt): Promise<number>` in `[0, 1]`
11
+ - pre-route by intent: `IntentModelSelector` middleware in [`intent.ts`](intent.ts)
12
+ - serve OpenAI-compatible routing: [`server.ts`](server.ts)
13
+
14
+ ## Quick start
15
+
16
+ ```ts
17
+ import { Controller } from './controller';
18
+ import { RandomRouter } from './random';
19
+
20
+ const controller = new Controller({
21
+ strongModel: 'gpt-4',
22
+ weakModel: 'gpt-3.5-turbo',
23
+ routers: { random: new RandomRouter() },
24
+ });
25
+ console.log(await controller.route('hello', 'random', 0.5));
26
+ ```
27
+
28
+ ## Contract
29
+
30
+ - `score` returns the strong-model win-rate estimate; `score >= threshold` selects `pair.strong`, else `pair.weak`.
31
+ - Server model names use the `router-<name>-<threshold>` form parsed by `parseModelName`.
32
+ - Not on the package exports map and not in the `tsup` build: reachable only by relative import inside `src/`.
33
+ - `bert` scores through the KServe client in [`../triton`](../triton/README.md); `mf` and `sw` take an embedding function.
34
+
35
+ ## Neighbours
36
+
37
+ - `@hop-top/kit/routellm`: client-side `routellm://name:threshold` adapter
38
+ - `@hop-top/kit/llm`: provider registry and `Client` facade
39
+ - [`../triton`](../triton/README.md): inference transport for `bert`
40
+ - Go: `go/console/cli/router`, the `kit llm router` subcommand tree
41
+
42
+ ## See also
43
+
44
+ - [`docs/adopters/reference/go-primitives.md`](../../../../docs/adopters/reference/go-primitives.md)
@@ -191,3 +191,44 @@ describe("server /v1/chat/completions", () => {
191
191
  expect(router.score).toHaveBeenCalledWith("route me");
192
192
  });
193
193
  });
194
+
195
+ describe("server tool-call linkage", () => {
196
+ it("forwards assistant tool_calls and tool_call_id upstream", async () => {
197
+ const upstream = mockUpstream();
198
+ const app = makeApp(0.9, upstream);
199
+
200
+ const body: ChatCompletionRequest = {
201
+ model: "router-mf-0.5",
202
+ messages: [
203
+ { role: "user", content: "Weather?" },
204
+ {
205
+ role: "assistant",
206
+ content: "",
207
+ tool_calls: [
208
+ {
209
+ id: "call_1",
210
+ type: "function",
211
+ function: { name: "get_weather", arguments: '{"city":"NYC"}' },
212
+ },
213
+ ],
214
+ },
215
+ { role: "tool", content: "sunny", tool_call_id: "call_1" },
216
+ ],
217
+ };
218
+
219
+ const res = await app.request("/v1/chat/completions", {
220
+ method: "POST",
221
+ headers: { "Content-Type": "application/json" },
222
+ body: JSON.stringify(body),
223
+ });
224
+
225
+ expect(res.status).toBe(200);
226
+ const sent = (upstream as ReturnType<typeof vi.fn>).mock
227
+ .calls[0][0] as ChatCompletionRequest;
228
+ expect(sent.messages[1].tool_calls?.[0].id).toBe("call_1");
229
+ expect(sent.messages[1].tool_calls?.[0].function.arguments).toBe(
230
+ '{"city":"NYC"}',
231
+ );
232
+ expect(sent.messages[2].tool_call_id).toBe("call_1");
233
+ });
234
+ });
@@ -16,6 +16,17 @@ import { RoutingError } from "./router";
16
16
  export interface ChatMessage {
17
17
  role: string;
18
18
  content: string;
19
+ /** Assistant turn: the tool calls the model made. */
20
+ tool_calls?: ChatToolCall[];
21
+ /** Role `tool`: the `ChatToolCall.id` this result answers. */
22
+ tool_call_id?: string;
23
+ }
24
+
25
+ /** An OpenAI assistant tool call; `arguments` is a JSON-encoded string. */
26
+ export interface ChatToolCall {
27
+ id: string;
28
+ type?: string;
29
+ function: { name: string; arguments: string };
19
30
  }
20
31
 
21
32
  export interface ChatCompletionRequest {
@@ -1,11 +1,21 @@
1
1
  import { describe, it, expect, afterEach } from 'vitest';
2
2
  import { safetyGuard } from './safety';
3
3
 
4
+ // A piped (non-TTY) stdout has no `isTTY` at all; `@types/node` types it
5
+ // as a plain `boolean`, so model the absent value via defineProperty.
6
+ function setStdoutTTY(value: boolean | undefined): void {
7
+ Object.defineProperty(process.stdout, 'isTTY', {
8
+ value,
9
+ configurable: true,
10
+ writable: true,
11
+ });
12
+ }
13
+
4
14
  describe('safetyGuard', () => {
5
- const origIsTTY = process.stdout.isTTY;
15
+ const origIsTTY: boolean | undefined = process.stdout.isTTY;
6
16
 
7
17
  afterEach(() => {
8
- process.stdout.isTTY = origIsTTY;
18
+ setStdoutTTY(origIsTTY);
9
19
  });
10
20
 
11
21
  it('read level always passes', () => {
@@ -13,27 +23,27 @@ describe('safetyGuard', () => {
13
23
  });
14
24
 
15
25
  it('read level passes even in non-TTY', () => {
16
- process.stdout.isTTY = undefined;
26
+ setStdoutTTY(undefined);
17
27
  expect(() => safetyGuard('read')).not.toThrow();
18
28
  });
19
29
 
20
30
  it('caution level passes in TTY', () => {
21
- process.stdout.isTTY = true;
31
+ setStdoutTTY(true);
22
32
  expect(() => safetyGuard('caution')).not.toThrow();
23
33
  });
24
34
 
25
35
  it('caution level requires --force in non-TTY', () => {
26
- process.stdout.isTTY = undefined;
36
+ setStdoutTTY(undefined);
27
37
  expect(() => safetyGuard('caution')).toThrow(/--force/);
28
38
  });
29
39
 
30
40
  it('caution level passes with force in non-TTY', () => {
31
- process.stdout.isTTY = undefined;
41
+ setStdoutTTY(undefined);
32
42
  expect(() => safetyGuard('caution', { force: true })).not.toThrow();
33
43
  });
34
44
 
35
45
  it('dangerous level throws without --force', () => {
36
- process.stdout.isTTY = true;
46
+ setStdoutTTY(true);
37
47
  expect(() => safetyGuard('dangerous')).toThrow(/--force/);
38
48
  });
39
49
 
@@ -42,12 +52,12 @@ describe('safetyGuard', () => {
42
52
  });
43
53
 
44
54
  it('dangerous level requires --force in non-TTY', () => {
45
- process.stdout.isTTY = undefined;
55
+ setStdoutTTY(undefined);
46
56
  expect(() => safetyGuard('dangerous')).toThrow(/--force/);
47
57
  });
48
58
 
49
59
  it('dangerous level passes with --force in non-TTY', () => {
50
- process.stdout.isTTY = undefined;
60
+ setStdoutTTY(undefined);
51
61
  expect(() => safetyGuard('dangerous', { force: true })).not.toThrow();
52
62
  });
53
63
  });