@hop-top/kit 0.5.0-alpha.0 → 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.
- package/CHANGELOG.md +262 -0
- package/LICENSE +1 -1
- package/LICENSE-cobra.txt +174 -0
- package/NOTICE +15 -0
- package/README.md +55 -259
- package/dist/aim-DZHwwiIc.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/aim.js +13 -414
- package/dist/alias-D9_qFlyP.d.ts +174 -0
- package/dist/alias.d.ts +2 -73
- package/dist/alias.js +27 -207
- package/dist/api-DAexsu2H.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/api.js +10 -164
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/auth.js +6 -40
- package/dist/chunk-2JV3A7OP.js +1894 -0
- 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-BLS2OBIQ.js +263 -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-GHPJJV5L.js +613 -0
- package/dist/chunk-IXVQ62NZ.js +334 -0
- package/dist/chunk-JKMQSAJP.js +174 -0
- package/dist/chunk-JZ22ZUFA.js +1131 -0
- package/dist/chunk-K7VCKJ27.js +814 -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-NLMS7HGP.js +178 -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-QQQYCWSC.js +240 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-SNVGDYX7.js +187 -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-XJTRY453.js +868 -0
- package/dist/chunk-YGYQUFGY.js +219 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/cli-C5B5tnpA.d.ts +400 -0
- package/dist/cli.d.ts +7 -309
- package/dist/cli.js +70 -885
- package/dist/completion-csVun6SP.d.ts +112 -0
- package/dist/completion-values-By-mnjNt.d.ts +142 -0
- package/dist/completion-values.d.ts +1 -0
- package/dist/completion-values.js +29 -0
- package/dist/completion.d.ts +3 -0
- package/dist/completion.js +34 -0
- package/dist/compliance-AxFf-uMy.d.ts +60 -0
- package/dist/compliance.d.ts +1 -0
- package/dist/compliance.js +17 -0
- package/dist/config-CaK60ByQ.d.ts +241 -0
- package/dist/config.d.ts +1 -97
- package/dist/config.js +8 -78
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/errcorrect.js +8 -68
- package/dist/error-Do8Qji43.d.ts +231 -0
- package/dist/id/index.d.ts +2 -83
- package/dist/id/index.js +14 -65
- package/dist/index-BKJZClJx.d.ts +1486 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-DCe1boBz.d.ts +328 -0
- package/dist/index-VLDcI5NF.d.ts +95 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +132 -0
- 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 -188
- package/dist/llm.js +101 -356
- package/dist/log-CkaxMX3U.d.ts +115 -0
- package/dist/log.d.ts +2 -0
- package/dist/log.js +14 -0
- package/dist/mcp/index.d.ts +4 -0
- package/dist/mcp/index.js +184 -0
- package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +25 -0
- package/dist/output-CjZWmL8s.d.ts +420 -0
- package/dist/output.d.ts +3 -213
- package/dist/output.js +137 -447
- package/dist/parity-CvMuYcVI.d.ts +61 -0
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/progress.js +6 -55
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/provenance.js +6 -31
- package/dist/routellm-B0nv59mH.d.ts +111 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/routellm.js +13 -255
- package/dist/rpc-D31Lg0Kc.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/rpc.js +4 -98
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/safety.js +6 -43
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/scope.js +20 -377
- package/dist/serve-D8yWMrTc.d.ts +646 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.js +75 -0
- package/dist/sqlstore.js +6 -39
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/stream.js +8 -51
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +26 -599
- package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
- package/dist/toolspec.d.ts +2 -0
- package/dist/toolspec.js +37 -0
- package/dist/tui/index.d.ts +6 -298
- package/dist/tui/index.js +18 -322
- package/dist/upgrade-p_zh3pvV.d.ts +102 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/upgrade.js +6 -114
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/dist/xdg.js +14 -128
- package/package.json +236 -46
- package/src/README.md +15 -0
- package/src/alias.conformance.test.ts +250 -0
- package/src/alias.test.ts +206 -2
- package/src/alias.ts +196 -21
- package/src/cli.help-command.test.ts +105 -0
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.test.ts +95 -1
- package/src/cli.ts +195 -25
- package/src/completion-scripts.ts +16 -0
- package/src/completion-values.test.ts +76 -16
- package/src/completion-values.ts +170 -66
- package/src/completion.conformance.test.ts +297 -0
- package/src/completion.test.ts +256 -145
- package/src/completion.ts +767 -121
- package/src/compliance.test.ts +196 -2
- package/src/compliance.ts +440 -20
- package/src/config-merge.test.ts +425 -0
- package/src/config.test.ts +228 -1
- package/src/config.ts +429 -16
- 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 +71 -0
- package/src/index.ts +46 -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/log.parity.test.ts +105 -0
- package/src/log.test.ts +270 -1
- package/src/log.ts +228 -49
- package/src/mcp/README.md +63 -0
- package/src/mcp/args-separator.test.ts +164 -0
- package/src/mcp/args.test.ts +223 -0
- package/src/mcp/args.ts +160 -0
- package/src/mcp/audit.test.ts +520 -0
- package/src/mcp/audit.ts +70 -0
- package/src/mcp/bridge.test.ts +222 -0
- package/src/mcp/bridge.ts +291 -0
- package/src/mcp/conformance.test.ts +357 -0
- package/src/mcp/dispatch.ts +359 -0
- package/src/mcp/identity.test.ts +166 -0
- package/src/mcp/identity.ts +72 -0
- package/src/mcp/index.ts +176 -0
- package/src/mcp/legacy-notify.test.ts +59 -0
- package/src/mcp/legacy.ts +367 -0
- package/src/mcp/mcp.test.ts +707 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +484 -0
- package/src/mcp/modern.ts +788 -0
- package/src/mcp/stdio.test.ts +313 -0
- package/src/mcp/stdio.ts +254 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/toolname.test.ts +147 -0
- package/src/mcp/types.ts +689 -0
- package/src/netpolicy.test.ts +280 -0
- package/src/netpolicy.ts +256 -0
- package/src/output/README.md +46 -0
- package/src/output/builtins.ts +5 -5
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +459 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/README.md +50 -0
- package/src/output/formatters/csv.ts +48 -12
- package/src/output/formatters/json.ts +4 -25
- package/src/output/formatters/project.ts +34 -0
- package/src/output/formatters/table.ts +8 -6
- package/src/output/formatters/text.ts +7 -3
- package/src/output/formatters/yaml.ts +5 -22
- package/src/output/projection.test.ts +298 -0
- package/src/output/projection.ts +33 -59
- package/src/output/template.ts +11 -21
- package/src/output.surface.test.ts +41 -0
- package/src/output.ts +64 -3
- package/src/published-types.test.ts +133 -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.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/telemetry/README.md +48 -0
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +12 -6
- package/src/telemetry/offline.test.ts +64 -0
- package/src/toolspec-internal.ts +279 -0
- package/src/toolspec-manifest.test.ts +167 -0
- package/src/toolspec-manifest.ts +410 -0
- package/src/toolspec-spec-schemas.ts +12 -0
- package/src/toolspec-spec.test.ts +273 -0
- package/src/toolspec-spec.ts +458 -0
- package/src/toolspec.from-command.test.ts +350 -0
- package/src/toolspec.test.ts +2 -2
- package/src/toolspec.ts +222 -0
- package/src/triton/README.md +34 -0
- package/src/tui/README.md +42 -0
- package/src/tui/parity.test.ts +142 -0
- package/src/tui/parity.ts +59 -13
- package/src/wizard.test.ts +7 -7
- package/test/llm/conformance-helpers.ts +100 -0
- package/test/output/csv.test.ts +164 -0
- package/test/output/dispatch.test.ts +1 -2
- package/test/output/error.test.ts +277 -0
- 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/test/toolspec/fixture.ts +79 -0
- package/tsconfig.json +3 -1
- package/tsconfig.test.json +10 -0
- package/vitest.config.ts +9 -0
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where credentials may go: URI redaction, endpoint parsing, the
|
|
3
|
+
* plain-http and trusted-origin gates, and adapter declarations.
|
|
4
|
+
* Re-exported from `@hop-top/kit/llm`; mirrors Go `llm` (`RedactURI`,
|
|
5
|
+
* `CheckKeyEndpoint`, `CredentialsTrusted`).
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { KeyEndpointError } from "./llm-errors";
|
|
11
|
+
import { providerBlock, readLLMFile } from "./llm-file";
|
|
12
|
+
import { isLoopback } from "./netpolicy";
|
|
13
|
+
|
|
14
|
+
// ─── Redaction ───────────────────────────────────────────────────────────────
|
|
15
|
+
|
|
16
|
+
const REDACTED = "REDACTED";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Masks the credentials in a provider URI or URL: the value of every
|
|
20
|
+
* credential-named query param (`api_key`, `key`, `*_token`, ...) and
|
|
21
|
+
* userinfo before an `@`. Tolerates malformed input; a `name@version`
|
|
22
|
+
* model id is kept.
|
|
23
|
+
*/
|
|
24
|
+
export function redactURI(raw: string): string {
|
|
25
|
+
let out = "";
|
|
26
|
+
for (;;) {
|
|
27
|
+
const m = /[?&]/.exec(raw);
|
|
28
|
+
if (!m) return out + redactSegment(raw);
|
|
29
|
+
out += redactSegment(raw.slice(0, m.index)) + m[0];
|
|
30
|
+
raw = raw.slice(m.index + 1);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function redactSegment(seg: string): string {
|
|
35
|
+
const eq = seg.indexOf("=");
|
|
36
|
+
if (eq < 0) return redactUserinfo(seg, false);
|
|
37
|
+
const k = seg.slice(0, eq);
|
|
38
|
+
const v = seg.slice(eq + 1);
|
|
39
|
+
if (k.includes("://")) return redactUserinfo(seg, false);
|
|
40
|
+
if (credentialParam(k)) return v === "" ? seg : `${k}=${REDACTED}`;
|
|
41
|
+
return `${k}=${redactUserinfo(v, true)}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function redactUserinfo(s: string, strict: boolean): string {
|
|
45
|
+
let start = 0;
|
|
46
|
+
let scheme = "";
|
|
47
|
+
const i = s.indexOf("://");
|
|
48
|
+
if (i >= 0) {
|
|
49
|
+
start = i + 3;
|
|
50
|
+
scheme = s.slice(0, i).toLowerCase();
|
|
51
|
+
}
|
|
52
|
+
const rest = s.slice(start);
|
|
53
|
+
let end = rest.indexOf("/");
|
|
54
|
+
const hasPath = end >= 0;
|
|
55
|
+
if (!hasPath) end = rest.length;
|
|
56
|
+
const at = rest.slice(0, end).lastIndexOf("@");
|
|
57
|
+
if (at <= 0) return s;
|
|
58
|
+
const credential =
|
|
59
|
+
strict ||
|
|
60
|
+
scheme === "http" ||
|
|
61
|
+
scheme === "https" ||
|
|
62
|
+
(hasPath && start > 0) ||
|
|
63
|
+
rest.slice(0, at).includes(":");
|
|
64
|
+
if (!credential) return s; // a "name@version" model id
|
|
65
|
+
return s.slice(0, start) + REDACTED + rest.slice(at);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const CREDENTIAL_NAMES = new Set([
|
|
69
|
+
"key", "apikey", "token", "secret", "password", "passwd", "pwd",
|
|
70
|
+
"auth", "authorization", "signature", "sig", "credential", "credentials",
|
|
71
|
+
]);
|
|
72
|
+
const CREDENTIAL_SUFFIXES = [
|
|
73
|
+
"_key", "apikey", "_token", "_secret", "_password",
|
|
74
|
+
"_signature", "_credential", "_credentials",
|
|
75
|
+
];
|
|
76
|
+
|
|
77
|
+
function credentialParam(name: string): boolean {
|
|
78
|
+
try {
|
|
79
|
+
name = decodeURIComponent(name.replace(/\+/g, " "));
|
|
80
|
+
} catch {
|
|
81
|
+
// keep the raw name
|
|
82
|
+
}
|
|
83
|
+
name = name.trim().toLowerCase().replace(/-/g, "_");
|
|
84
|
+
if (CREDENTIAL_NAMES.has(name)) return true;
|
|
85
|
+
return CREDENTIAL_SUFFIXES.some((s) => name.endsWith(s));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Returns `msg` with every secret replaced by `REDACTED`. Blank secrets
|
|
90
|
+
* are ignored.
|
|
91
|
+
*/
|
|
92
|
+
export function scrubSecrets(msg: string, secrets: readonly string[]): string {
|
|
93
|
+
for (const s of secrets) {
|
|
94
|
+
if (s.trim() !== "") msg = msg.split(s).join(REDACTED);
|
|
95
|
+
}
|
|
96
|
+
return msg;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ─── Endpoints ───────────────────────────────────────────────────────────────
|
|
100
|
+
|
|
101
|
+
interface Endpoint {
|
|
102
|
+
scheme: string;
|
|
103
|
+
host: string;
|
|
104
|
+
port: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Parses `raw` for a credential check with the WHATWG URL parser fetch
|
|
109
|
+
* uses. Undefined, and no credential may go to `raw`, when it does not
|
|
110
|
+
* parse, has no host, or carries userinfo, a backslash, a
|
|
111
|
+
* percent-escape, whitespace or a control character: forms where
|
|
112
|
+
* parsers disagree on the host.
|
|
113
|
+
*/
|
|
114
|
+
function parseEndpoint(raw: string): Endpoint | undefined {
|
|
115
|
+
if (/[\\%]/.test(raw) || /[\u0000- \u007f\s]/.test(raw)) {
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
let u: URL;
|
|
119
|
+
try {
|
|
120
|
+
u = new URL(raw);
|
|
121
|
+
} catch {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
const authority = raw.slice(raw.indexOf("//") + 2).split(/[/?#]/)[0] ?? "";
|
|
125
|
+
if (!u.host || !u.hostname || u.username || u.password || authority.includes("@")) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const scheme = u.protocol.replace(/:$/, "").toLowerCase();
|
|
129
|
+
let port = u.port;
|
|
130
|
+
if (port === "") {
|
|
131
|
+
if (scheme === "https") port = "443";
|
|
132
|
+
else if (scheme === "http") port = "80";
|
|
133
|
+
}
|
|
134
|
+
return { scheme, host: u.hostname.toLowerCase(), port };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function origin(e: Endpoint): string {
|
|
138
|
+
return `${e.scheme}://${e.host}:${e.port}`;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** @internal A key that is empty or only whitespace: no key. */
|
|
142
|
+
export function blankKey(key: string | undefined): boolean {
|
|
143
|
+
return (key ?? "").trim() === "";
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Throws a {@link KeyEndpointError} for a non-blank `key` bound for a
|
|
148
|
+
* malformed endpoint, or over plain http to a host other than loopback.
|
|
149
|
+
* Adapters call it on the base URL they settle on.
|
|
150
|
+
*/
|
|
151
|
+
export function checkKeyEndpoint(
|
|
152
|
+
scheme: string,
|
|
153
|
+
key: string | undefined,
|
|
154
|
+
baseURL: string
|
|
155
|
+
): void {
|
|
156
|
+
if (blankKey(key) || baseURL === "") return;
|
|
157
|
+
const e = parseEndpoint(baseURL);
|
|
158
|
+
if (!e) {
|
|
159
|
+
throw new KeyEndpointError(scheme, redactURI(baseURL), { malformed: true });
|
|
160
|
+
}
|
|
161
|
+
if (e.scheme === "http" && !isLoopback(e.host)) {
|
|
162
|
+
throw new KeyEndpointError(scheme, redactURI(baseURL), { insecure: true });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ─── Declarations ────────────────────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* A scheme's credential: the variables holding its key, highest
|
|
170
|
+
* precedence first. `optional` marks a key a provider runs without
|
|
171
|
+
* (a local runtime): `LLM_API_KEY` is then not lent to it. No
|
|
172
|
+
* `envVars` and `optional` is a scheme that takes no key at all.
|
|
173
|
+
*/
|
|
174
|
+
export interface ProviderKey {
|
|
175
|
+
envVars: string[];
|
|
176
|
+
optional?: boolean;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* What an adapter states about its scheme: the endpoints credentials
|
|
181
|
+
* kit resolved itself may go to (see {@link credentialsTrusted}), and
|
|
182
|
+
* its credential when the `<SCHEME>_API_KEY` convention does not fit.
|
|
183
|
+
*/
|
|
184
|
+
export interface Declaration {
|
|
185
|
+
endpoints?: string[];
|
|
186
|
+
key?: ProviderKey;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const declarations = new Map<string, Declaration>();
|
|
190
|
+
const registered = new Set<string>();
|
|
191
|
+
|
|
192
|
+
/** @internal Records that `scheme` has an adapter; `register` calls it. */
|
|
193
|
+
export function setDeclaration(scheme: string, decl?: Declaration): void {
|
|
194
|
+
registered.add(scheme);
|
|
195
|
+
if (decl) declarations.set(scheme, decl);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** @internal */
|
|
199
|
+
export function clearDeclarations(): void {
|
|
200
|
+
declarations.clear();
|
|
201
|
+
registered.clear();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The declaration `scheme` registered with, if any. */
|
|
205
|
+
export function declarationOf(scheme: string): Declaration | undefined {
|
|
206
|
+
return declarations.get(scheme);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** @internal Whether an adapter is registered for `scheme`. */
|
|
210
|
+
export function isRegistered(scheme: string): boolean {
|
|
211
|
+
return registered.has(scheme);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Reports whether credentials kit resolved itself, not taken from the
|
|
216
|
+
* URI (an env or llm.yaml key, a bearer token, a workspace header), may
|
|
217
|
+
* go to `baseURL` for `scheme`: it is loopback, or shares an origin
|
|
218
|
+
* with the scheme's declared endpoints, its llm.yaml `base_url`,
|
|
219
|
+
* `LLM_BASE_URL` or one of `extra` (the adapter's default endpoint and
|
|
220
|
+
* its own base URL variable). Every credential path decides here.
|
|
221
|
+
*/
|
|
222
|
+
export function credentialsTrusted(
|
|
223
|
+
scheme: string,
|
|
224
|
+
baseURL: string,
|
|
225
|
+
...extra: string[]
|
|
226
|
+
): boolean {
|
|
227
|
+
return trustedOrigin(scheme, baseURL, extra, true);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* @internal {@link credentialsTrusted}; `ambient` false (hermetic)
|
|
232
|
+
* consults neither `LLM_BASE_URL` nor llm.yaml.
|
|
233
|
+
*/
|
|
234
|
+
export function trustedOrigin(
|
|
235
|
+
scheme: string,
|
|
236
|
+
baseURL: string,
|
|
237
|
+
extra: readonly string[],
|
|
238
|
+
ambient: boolean
|
|
239
|
+
): boolean {
|
|
240
|
+
const e = parseEndpoint(baseURL);
|
|
241
|
+
if (!e) return false;
|
|
242
|
+
if (isLoopback(e.host)) return true;
|
|
243
|
+
const trusted = [...(declarations.get(scheme)?.endpoints ?? []), ...extra];
|
|
244
|
+
if (ambient) {
|
|
245
|
+
const file = providerBlock(readLLMFile(), scheme)?.baseURL;
|
|
246
|
+
if (file) trusted.push(file);
|
|
247
|
+
const env = process.env["LLM_BASE_URL"];
|
|
248
|
+
if (env) trusted.push(env);
|
|
249
|
+
}
|
|
250
|
+
return trusted.some((t) => {
|
|
251
|
+
const te = t ? parseEndpoint(t) : undefined;
|
|
252
|
+
return te !== undefined && origin(te) === origin(e);
|
|
253
|
+
});
|
|
254
|
+
}
|
package/src/llm-error.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base error of the llm layer. Lives apart from `llm.ts` so modules
|
|
3
|
+
* that `llm.ts` re-exports can extend it without an import cycle.
|
|
4
|
+
* Import it from `@hop-top/kit/llm`.
|
|
5
|
+
*
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
export class LLMError extends Error {
|
|
9
|
+
statusCode?: number;
|
|
10
|
+
code?: string;
|
|
11
|
+
|
|
12
|
+
constructor(message: string) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "LLMError";
|
|
15
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed errors the HTTP adapters return, re-exported from
|
|
3
|
+
* `@hop-top/kit/llm`. Apart from `llm.ts` so the adapters' transport
|
|
4
|
+
* can raise them without an import cycle.
|
|
5
|
+
*
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { LLMError } from "./llm-error";
|
|
10
|
+
import { goQuote } from "./llm-quote";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* An HTTP error response kit classifies by status: a 5xx (fallbackable)
|
|
14
|
+
* or a redirect, which is never followed.
|
|
15
|
+
*/
|
|
16
|
+
export class HTTPStatusError extends LLMError {
|
|
17
|
+
readonly status: string;
|
|
18
|
+
|
|
19
|
+
constructor(statusCode: number, status: string) {
|
|
20
|
+
super(`http ${statusCode}: ${status}`);
|
|
21
|
+
this.name = "HTTPStatusError";
|
|
22
|
+
this.statusCode = statusCode;
|
|
23
|
+
this.status = status;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A provider error response no other class covers (a 4xx such as an
|
|
29
|
+
* invalid request). `type` is the provider's error type, when it gave
|
|
30
|
+
* one. Not fallbackable.
|
|
31
|
+
*/
|
|
32
|
+
export class APIError extends LLMError {
|
|
33
|
+
readonly provider: string;
|
|
34
|
+
readonly type: string;
|
|
35
|
+
|
|
36
|
+
constructor(provider: string, statusCode: number, type: string, message: string) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "APIError";
|
|
39
|
+
this.provider = provider;
|
|
40
|
+
this.statusCode = statusCode;
|
|
41
|
+
this.type = type;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A stream ended before the provider's terminal event: the response is
|
|
47
|
+
* incomplete, never a success. Not fallbackable: tokens may already
|
|
48
|
+
* have been consumed.
|
|
49
|
+
*/
|
|
50
|
+
export class StreamTruncatedError extends LLMError {
|
|
51
|
+
readonly provider: string;
|
|
52
|
+
|
|
53
|
+
constructor(provider: string) {
|
|
54
|
+
super(
|
|
55
|
+
`stream truncated (provider ${JSON.stringify(provider)}): ended before its final event`
|
|
56
|
+
);
|
|
57
|
+
this.name = "StreamTruncatedError";
|
|
58
|
+
this.provider = provider;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A response body, or one streamed event, exceeded its size limit
|
|
64
|
+
* (`max_body_bytes`, `max_event_bytes`). Not fallbackable.
|
|
65
|
+
*/
|
|
66
|
+
export class ResponseTooLargeError extends LLMError {
|
|
67
|
+
readonly provider: string;
|
|
68
|
+
/** The part that overran: `"body"` or `"event"`. */
|
|
69
|
+
readonly what: "body" | "event";
|
|
70
|
+
readonly limit: number;
|
|
71
|
+
|
|
72
|
+
constructor(provider: string, what: "body" | "event", limit: number) {
|
|
73
|
+
super(
|
|
74
|
+
`response ${what} exceeds ${limit} bytes (provider ${JSON.stringify(provider)})`
|
|
75
|
+
);
|
|
76
|
+
this.name = "ResponseTooLargeError";
|
|
77
|
+
this.provider = provider;
|
|
78
|
+
this.what = what;
|
|
79
|
+
this.limit = limit;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A provider key kit will not send to an endpoint. `endpoint` is masked
|
|
85
|
+
* by `redactURI`; the key never appears.
|
|
86
|
+
*/
|
|
87
|
+
export class KeyEndpointError extends LLMError {
|
|
88
|
+
readonly scheme: string;
|
|
89
|
+
readonly endpoint: string;
|
|
90
|
+
/** Set when the refusal is plain http to a remote host. */
|
|
91
|
+
readonly insecure: boolean;
|
|
92
|
+
/**
|
|
93
|
+
* Set when the endpoint carries userinfo, a backslash, a
|
|
94
|
+
* percent-escape, whitespace or a control character, or does not
|
|
95
|
+
* parse: no credential goes to it.
|
|
96
|
+
*/
|
|
97
|
+
readonly malformed: boolean;
|
|
98
|
+
|
|
99
|
+
constructor(
|
|
100
|
+
scheme: string,
|
|
101
|
+
endpoint: string,
|
|
102
|
+
opts: { insecure?: boolean; malformed?: boolean } = {}
|
|
103
|
+
) {
|
|
104
|
+
super(keyEndpointMessage(scheme, endpoint, opts));
|
|
105
|
+
this.name = "KeyEndpointError";
|
|
106
|
+
this.scheme = scheme;
|
|
107
|
+
this.endpoint = endpoint;
|
|
108
|
+
this.insecure = opts.insecure ?? false;
|
|
109
|
+
this.malformed = opts.malformed ?? false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function keyEndpointMessage(
|
|
114
|
+
scheme: string,
|
|
115
|
+
endpoint: string,
|
|
116
|
+
opts: { insecure?: boolean; malformed?: boolean }
|
|
117
|
+
): string {
|
|
118
|
+
const q = goQuote(endpoint);
|
|
119
|
+
if (opts.malformed) {
|
|
120
|
+
return (
|
|
121
|
+
`llm: refusing to send the ${scheme} API key to ${q}: an endpoint must parse and carry ` +
|
|
122
|
+
"no userinfo, backslash, percent-escape, whitespace or control character"
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
if (opts.insecure) {
|
|
126
|
+
return `llm: refusing to send the ${scheme} API key over plain http to ${q}; use https or a loopback host`;
|
|
127
|
+
}
|
|
128
|
+
return (
|
|
129
|
+
`llm: refusing to send the ${scheme} API key to ${q}, which only the URI names; ` +
|
|
130
|
+
"set it as llm.yaml base_url or LLM_BASE_URL, or pass api_key in the URI"
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* No key was found for a scheme whose adapter requires one. Carries
|
|
136
|
+
* names only, never a value: `envVars` lists every variable consulted,
|
|
137
|
+
* highest precedence first, ending with `LLM_API_KEY`.
|
|
138
|
+
*/
|
|
139
|
+
export class MissingKeyError extends LLMError {
|
|
140
|
+
readonly scheme: string;
|
|
141
|
+
readonly model: string;
|
|
142
|
+
readonly envVars: string[];
|
|
143
|
+
|
|
144
|
+
constructor(scheme: string, model: string, envVars: string[]) {
|
|
145
|
+
const m = model !== "" ? ` (model ${goQuote(model)})` : "";
|
|
146
|
+
super(`llm: no API key for provider ${goQuote(scheme)}${m}: set ${envVars.join(" or ")}`);
|
|
147
|
+
this.name = "MissingKeyError";
|
|
148
|
+
this.scheme = scheme;
|
|
149
|
+
this.model = model;
|
|
150
|
+
this.envVars = envVars;
|
|
151
|
+
}
|
|
152
|
+
}
|
package/src/llm-file.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* llm.yaml: `{configDir("hop")}/llm.yaml`, read as Go `llm` reads it.
|
|
3
|
+
* Best-effort: a missing, unreadable or malformed file is an empty
|
|
4
|
+
* config. Read on each call, never cached. A hermetic config does not
|
|
5
|
+
* call it.
|
|
6
|
+
*
|
|
7
|
+
* ```yaml
|
|
8
|
+
* default: anthropic://claude-sonnet-4-5
|
|
9
|
+
* fallback: [openai://gpt-4.1]
|
|
10
|
+
* providers:
|
|
11
|
+
* anthropic:
|
|
12
|
+
* api_key: ... # or api_key_env: MY_ANTHROPIC_KEY
|
|
13
|
+
* base_url: https://gw.corp.example
|
|
14
|
+
* model: claude-sonnet-4-5
|
|
15
|
+
* routellm: {...} # any other key: ProviderConfig.extras
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @internal
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { readFileSync } from "node:fs";
|
|
22
|
+
import { join } from "node:path";
|
|
23
|
+
import * as yaml from "js-yaml";
|
|
24
|
+
|
|
25
|
+
import { configDir } from "./xdg";
|
|
26
|
+
|
|
27
|
+
/** One `providers.<name>` block. */
|
|
28
|
+
export interface LLMFileProvider {
|
|
29
|
+
apiKey: string;
|
|
30
|
+
apiKeyEnv: string;
|
|
31
|
+
baseURL: string;
|
|
32
|
+
model: string;
|
|
33
|
+
/** The block's other keys, typed as YAML types them. */
|
|
34
|
+
extras: Record<string, unknown>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The parts of llm.yaml the llm core reads. */
|
|
38
|
+
export interface LLMFile {
|
|
39
|
+
default: string;
|
|
40
|
+
fallback: string[];
|
|
41
|
+
providers: Map<string, LLMFileProvider>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const EMPTY: LLMFile = { default: "", fallback: [], providers: new Map() };
|
|
45
|
+
|
|
46
|
+
const FIELDS = new Set(["api_key", "api_key_env", "base_url", "model"]);
|
|
47
|
+
|
|
48
|
+
/** Reads llm.yaml; an empty config when there is none to read. */
|
|
49
|
+
export function readLLMFile(): LLMFile {
|
|
50
|
+
let text: string;
|
|
51
|
+
try {
|
|
52
|
+
text = readFileSync(join(configDir("hop"), "llm.yaml"), "utf8");
|
|
53
|
+
} catch {
|
|
54
|
+
return emptyFile();
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
// Fields decode as Go decodes them into strings: every scalar as
|
|
58
|
+
// written (FAILSAFE). Extras keep their YAML types (CORE).
|
|
59
|
+
return decode(
|
|
60
|
+
yaml.load(text, { schema: yaml.FAILSAFE_SCHEMA }),
|
|
61
|
+
yaml.load(text, { schema: yaml.CORE_SCHEMA })
|
|
62
|
+
);
|
|
63
|
+
} catch {
|
|
64
|
+
return emptyFile();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The block configuring `scheme`, if llm.yaml has one. */
|
|
69
|
+
export function providerBlock(file: LLMFile, scheme: string): LLMFileProvider | undefined {
|
|
70
|
+
return file.providers.get(scheme);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function emptyFile(): LLMFile {
|
|
74
|
+
return { ...EMPTY, fallback: [], providers: new Map() };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
class Shape extends Error {}
|
|
78
|
+
|
|
79
|
+
function isMap(v: unknown): v is Record<string, unknown> {
|
|
80
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A string field: absent or null is "", a scalar is its text. */
|
|
84
|
+
function str(v: unknown): string {
|
|
85
|
+
if (v === undefined || v === null) return "";
|
|
86
|
+
if (typeof v !== "string") throw new Shape();
|
|
87
|
+
return v;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Builds the config from the file parsed twice; a field of the wrong
|
|
92
|
+
* shape empties the whole file, as a failed Go decode does.
|
|
93
|
+
*/
|
|
94
|
+
function decode(raw: unknown, typed: unknown): LLMFile {
|
|
95
|
+
if (raw === undefined || raw === null) return emptyFile();
|
|
96
|
+
if (!isMap(raw)) throw new Shape();
|
|
97
|
+
const t = isMap(typed) ? typed : {};
|
|
98
|
+
const out = emptyFile();
|
|
99
|
+
out.default = str(raw["default"]);
|
|
100
|
+
const fb = raw["fallback"];
|
|
101
|
+
if (fb !== undefined && fb !== null) {
|
|
102
|
+
if (!Array.isArray(fb)) throw new Shape();
|
|
103
|
+
out.fallback = fb.map(str);
|
|
104
|
+
}
|
|
105
|
+
const ps = raw["providers"];
|
|
106
|
+
if (ps === undefined || ps === null) return out;
|
|
107
|
+
if (!isMap(ps)) throw new Shape();
|
|
108
|
+
const tps = isMap(t["providers"]) ? t["providers"] : {};
|
|
109
|
+
for (const [name, block] of Object.entries(ps)) {
|
|
110
|
+
const b = block === null ? {} : block;
|
|
111
|
+
if (!isMap(b)) throw new Shape();
|
|
112
|
+
const tb = isMap(tps[name]) ? (tps[name] as Record<string, unknown>) : {};
|
|
113
|
+
const extras: Record<string, unknown> = {};
|
|
114
|
+
for (const k of Object.keys(b)) {
|
|
115
|
+
if (!FIELDS.has(k) && k !== "__proto__") extras[k] = tb[k];
|
|
116
|
+
}
|
|
117
|
+
out.providers.set(name, {
|
|
118
|
+
apiKey: str(b["api_key"]),
|
|
119
|
+
apiKeyEnv: str(b["api_key_env"]),
|
|
120
|
+
baseURL: str(b["base_url"]),
|
|
121
|
+
model: str(b["model"]),
|
|
122
|
+
extras,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|