@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.
- package/CHANGELOG.md +52 -0
- package/LICENSE +1 -1
- package/README.md +47 -575
- package/dist/{aim-CTp-kJW2.d.ts → aim-DZHwwiIc.d.ts} +1 -1
- package/dist/aim.d.ts +1 -1
- package/dist/aim.js +13 -414
- package/dist/{alias-dhhr08Ei.d.ts → alias-BOj0-VAr.d.ts} +1 -1
- package/dist/alias.d.ts +1 -1
- package/dist/alias.js +18 -206
- package/dist/{api-miiso81x.d.ts → api-DAexsu2H.d.ts} +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +10 -164
- package/dist/auth.js +6 -40
- package/dist/chunk-3FIKGFKI.js +54 -0
- package/dist/chunk-4UE5TCMQ.js +104 -0
- package/dist/chunk-6HFAEZ52.js +29 -0
- package/dist/chunk-6SVOHNIC.js +17 -0
- package/dist/chunk-72XZWQX7.js +504 -0
- package/dist/chunk-ABQSE7AI.js +513 -0
- package/dist/chunk-BDNNPRX6.js +41 -0
- package/dist/chunk-BRNEKPWX.js +37 -0
- package/dist/chunk-CSJWB6D3.js +151 -0
- package/dist/chunk-GGWJRWWA.js +309 -0
- package/dist/chunk-IQXEISMC.js +142 -0
- package/dist/chunk-IXVQ62NZ.js +334 -0
- package/dist/chunk-JTMPNXVQ.js +1491 -0
- package/dist/chunk-KVG7YCTS.js +115 -0
- package/dist/chunk-L23O2FFE.js +51 -0
- package/dist/chunk-MQXYDYRD.js +968 -0
- package/dist/chunk-MUIQVU6E.js +251 -0
- package/dist/chunk-POR5L2DG.js +247 -0
- package/dist/chunk-PSFYJGDG.js +1445 -0
- package/dist/chunk-QJVSKKRQ.js +369 -0
- package/dist/chunk-QPUCXQXT.js +67 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-S45UHXQF.js +182 -0
- package/dist/chunk-T46YPHKN.js +669 -0
- package/dist/chunk-UKZIAQA7.js +26 -0
- package/dist/chunk-WBVO43HU.js +355 -0
- package/dist/chunk-WUOAQVOA.js +86 -0
- package/dist/chunk-WWUKGJB5.js +90 -0
- package/dist/chunk-YGYQUFGY.js +219 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/chunk-ZC5TZYZJ.js +609 -0
- package/dist/{cli-DLygZLi9.d.ts → cli-8rfITnv4.d.ts} +13 -4
- package/dist/cli.d.ts +4 -4
- package/dist/cli.js +51 -1057
- package/dist/{config-BUY7_W2n.d.ts → config-Bm9fBXch.d.ts} +35 -4
- package/dist/config.d.ts +1 -1
- package/dist/config.js +6 -78
- package/dist/errcorrect.js +8 -68
- package/dist/{error-DISJKeDu.d.ts → error-Do8Qji43.d.ts} +88 -1
- package/dist/id/index.d.ts +1 -1
- package/dist/id/index.js +14 -65
- package/dist/{index-MLrRDvEG.d.ts → index-B-pqGHhU.d.ts} +113 -19
- package/dist/{index-Bc5c7Ty5.d.ts → index-DEyjGoo2.d.ts} +1 -1
- package/dist/{index-QSffbLnj.d.ts → index-VLDcI5NF.d.ts} +3 -2
- package/dist/index.d.ts +18 -15
- package/dist/index.js +39 -6722
- package/dist/llm-DYuR7_uX.d.ts +1069 -0
- package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
- package/dist/llm-anthropic.d.ts +2 -0
- package/dist/llm-anthropic.js +13 -0
- package/dist/llm-openai-DyFrucmV.d.ts +87 -0
- package/dist/llm-openai.d.ts +2 -0
- package/dist/llm-openai.js +19 -0
- package/dist/llm.d.ts +1 -1
- package/dist/llm.js +101 -356
- package/dist/mcp/index.d.ts +2 -1
- package/dist/mcp/index.js +155 -1453
- package/dist/{netpolicy-asvCfwi8.d.ts → netpolicy-Brx5XZUB.d.ts} +16 -3
- package/dist/netpolicy.d.ts +1 -1
- package/dist/netpolicy.js +25 -118
- package/dist/{output-4aXs91GY.d.ts → output-CjZWmL8s.d.ts} +28 -4
- package/dist/output.d.ts +2 -2
- package/dist/output.js +137 -971
- package/dist/progress.js +6 -55
- package/dist/provenance.js +6 -31
- package/dist/routellm-B0nv59mH.d.ts +111 -0
- package/dist/routellm.d.ts +2 -2
- package/dist/routellm.js +13 -255
- package/dist/{rpc-D5xLEf8V.d.ts → rpc-D31Lg0Kc.d.ts} +1 -1
- package/dist/rpc.d.ts +2 -2
- package/dist/rpc.js +4 -98
- package/dist/safety.js +6 -43
- package/dist/scope.js +20 -377
- package/dist/{serve-DE-jscpb.d.ts → serve-D8yWMrTc.d.ts} +2 -2
- package/dist/serve.d.ts +2 -2
- package/dist/serve.js +75 -1019
- package/dist/sqlstore.js +6 -39
- package/dist/stream.js +8 -51
- package/dist/telemetry/index.js +24 -608
- package/dist/tui/index.d.ts +5 -5
- package/dist/tui/index.js +17 -374
- package/dist/upgrade.js +6 -114
- package/dist/xdg.js +14 -128
- package/package.json +130 -25
- package/src/README.md +15 -0
- package/src/cli.help-command.test.ts +105 -0
- package/src/cli.test.ts +95 -1
- package/src/cli.ts +78 -13
- package/src/completion-values.test.ts +10 -10
- package/src/compliance.test.ts +196 -2
- package/src/compliance.ts +440 -20
- package/src/config.test.ts +187 -1
- package/src/config.ts +173 -7
- package/src/gen/crud_pb.ts +7 -7
- package/src/id/README.md +38 -0
- package/src/id/contract.test.ts +1 -1
- package/src/id/index.test.ts +1 -1
- package/src/id/index.ts +3 -2
- package/src/index.test.ts +12 -0
- package/src/index.ts +2 -0
- package/src/llm-anthropic.conformance.test.ts +1135 -0
- package/src/llm-anthropic.test.ts +152 -0
- package/src/llm-anthropic.ts +940 -0
- package/src/llm-choice-hermetic.test.ts +335 -0
- package/src/llm-config.test.ts +232 -0
- package/src/llm-config.ts +106 -0
- package/src/llm-endpoint.ts +254 -0
- package/src/llm-error.ts +17 -0
- package/src/llm-errors.ts +152 -0
- package/src/llm-file.ts +126 -0
- package/src/llm-http.ts +317 -0
- package/src/llm-keys.ts +167 -0
- package/src/llm-media.conformance.test.ts +87 -0
- package/src/llm-media.test.ts +279 -0
- package/src/llm-media.ts +322 -0
- package/src/llm-openai.conformance.test.ts +407 -0
- package/src/llm-openai.test.ts +510 -0
- package/src/llm-openai.ts +708 -0
- package/src/llm-payload.ts +155 -0
- package/src/llm-quote.ts +46 -0
- package/src/llm-routellm.conformance.test.ts +44 -0
- package/src/llm-toolnames.conformance.test.ts +112 -0
- package/src/llm-toolnames.test.ts +132 -0
- package/src/llm-toolnames.ts +298 -0
- package/src/llm-uri.ts +99 -0
- package/src/llm.test.ts +43 -15
- package/src/llm.toolcall.test.ts +175 -0
- package/src/llm.ts +602 -190
- package/src/mcp/README.md +57 -0
- package/src/mcp/conformance.test.ts +24 -3
- package/src/mcp/dispatch.ts +4 -4
- package/src/mcp/identity.test.ts +166 -0
- package/src/mcp/identity.ts +72 -0
- package/src/mcp/index.ts +6 -0
- package/src/mcp/legacy.ts +21 -8
- package/src/mcp/mcp.test.ts +14 -4
- package/src/mcp/modern-confirm.ts +1 -1
- package/src/mcp/modern.ts +12 -11
- package/src/mcp/tasks.ts +1 -1
- package/src/mcp/types.ts +80 -8
- package/src/netpolicy.test.ts +78 -0
- package/src/netpolicy.ts +28 -3
- package/src/output/README.md +46 -0
- package/src/output/builtins.ts +5 -5
- package/src/output/error.ts +144 -1
- package/src/output/formatters/README.md +50 -0
- package/src/output.ts +24 -1
- package/src/published-types.test.ts +115 -0
- package/src/routellm.test.ts +209 -28
- package/src/routellm.toolcall.test.ts +521 -0
- package/src/routellm.ts +213 -177
- package/src/router/README.md +44 -0
- package/src/router/server.test.ts +41 -0
- package/src/router/server.ts +11 -0
- package/src/safety.test.ts +19 -9
- package/src/scope-defaults.json +29 -29
- package/src/serve.ts +1 -1
- package/src/telemetry/README.md +48 -0
- package/src/telemetry/client.ts +5 -5
- package/src/toolspec.test.ts +2 -2
- package/src/triton/README.md +34 -0
- package/src/tui/README.md +42 -0
- package/src/wizard.test.ts +7 -7
- package/test/llm/conformance-helpers.ts +100 -0
- package/test/output/dispatch.test.ts +1 -2
- package/test/output/error.test.ts +33 -2
- package/test/output/smoke-capture.ts +2 -2
- package/test/output/smoke.test.ts +2 -2
- package/test/output/taxonomy-contract.test.ts +148 -0
- package/test/setup-env.ts +16 -0
- package/tsconfig.json +3 -1
- package/tsconfig.test.json +10 -0
- package/vitest.config.ts +9 -0
- package/dist/llm-B5XUWH8T.d.ts +0 -231
- package/dist/routellm-PGSt2D1y.d.ts +0 -75
|
@@ -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("
|
|
98
|
-
|
|
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
|
|
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("
|
|
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("
|
|
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("
|
|
216
|
+
expect(cfg.provider.apiKey).toBe("uri-key");
|
|
198
217
|
});
|
|
199
218
|
|
|
200
|
-
it("
|
|
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
|
-
|
|
203
|
-
|
|
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
|
+
});
|