@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.11
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 +275 -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-3FIKGFKI.js +54 -0
- package/dist/chunk-4FMALWYB.js +669 -0
- package/dist/chunk-4GPCWBBA.js +143 -0
- package/dist/chunk-4UE5TCMQ.js +104 -0
- package/dist/chunk-65VPWMPV.js +1134 -0
- package/dist/chunk-6HFAEZ52.js +29 -0
- package/dist/chunk-6SVOHNIC.js +17 -0
- package/dist/chunk-BDNNPRX6.js +41 -0
- package/dist/chunk-BRNEKPWX.js +37 -0
- package/dist/chunk-BXJ2J27B.js +219 -0
- package/dist/chunk-CSJWB6D3.js +151 -0
- package/dist/chunk-CXBZTONY.js +65 -0
- package/dist/chunk-EE4M2UOF.js +818 -0
- package/dist/chunk-GFRAYYRD.js +817 -0
- package/dist/chunk-IVQHLI56.js +1890 -0
- package/dist/chunk-IZ6Q4SE3.js +178 -0
- package/dist/chunk-JKMQSAJP.js +174 -0
- package/dist/chunk-K7E34Q3A.js +1445 -0
- package/dist/chunk-KVG7YCTS.js +115 -0
- package/dist/chunk-L23O2FFE.js +51 -0
- package/dist/chunk-MFVUENZR.js +1549 -0
- package/dist/chunk-ML7D5DWY.js +263 -0
- package/dist/chunk-MQXYDYRD.js +968 -0
- package/dist/chunk-POR5L2DG.js +247 -0
- package/dist/chunk-QJVSKKRQ.js +369 -0
- package/dist/chunk-QQQYCWSC.js +240 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-RYKLVOVK.js +309 -0
- package/dist/chunk-SNVGDYX7.js +187 -0
- package/dist/chunk-T6OZMPPV.js +68 -0
- package/dist/chunk-UKZIAQA7.js +26 -0
- package/dist/chunk-VGOA5Y7S.js +251 -0
- package/dist/chunk-VWGP4NVJ.js +513 -0
- package/dist/chunk-WBVO43HU.js +355 -0
- package/dist/chunk-WUOAQVOA.js +86 -0
- package/dist/chunk-XJTRY453.js +868 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/cli-RSRk1M36.d.ts +707 -0
- package/dist/cli.d.ts +7 -309
- package/dist/cli.js +125 -945
- 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-CGE5yLBj.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 +185 -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 +135 -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 +17 -381
- package/dist/upgrade-C3RWGwRi.d.ts +125 -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 +192 -24
- 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.root.conformance.test.ts +166 -0
- package/src/cli.test.ts +95 -1
- package/src/cli.ts +234 -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 +298 -0
- package/src/completion.test.ts +268 -145
- package/src/completion.ts +772 -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/delegation.test.ts +299 -0
- package/src/delegation.ts +807 -0
- 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 +250 -0
- package/src/mcp/bridge.ts +286 -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/plan.ts +89 -0
- package/src/policy.ts +472 -0
- 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/sideeffect.ts +105 -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 +415 -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 +120 -31
- package/src/tui/parity.ts +58 -7
- package/src/upgrade.test.ts +291 -0
- package/src/upgrade.ts +116 -7
- 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
- package/src/tui/parity.json +0 -74
package/src/llm-http.ts
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP layer the anthropic and openai adapters share: a JSON POST
|
|
3
|
+
* with bounded retries, no redirects, size-capped bodies and SSE
|
|
4
|
+
* events, and credential scrubbing.
|
|
5
|
+
*
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { LLMError } from "./llm-error";
|
|
10
|
+
import { scrubSecrets } from "./llm-endpoint";
|
|
11
|
+
import { HTTPStatusError, ResponseTooLargeError } from "./llm-errors";
|
|
12
|
+
|
|
13
|
+
/** Default cap on a whole non-streamed response body. */
|
|
14
|
+
export const DEFAULT_MAX_BODY_BYTES = 32 << 20;
|
|
15
|
+
/** Default cap on one SSE event of a stream. */
|
|
16
|
+
export const DEFAULT_MAX_EVENT_BYTES = 8 << 20;
|
|
17
|
+
/** Longest wait a server may ask for between retries. */
|
|
18
|
+
export const MAX_RETRY_AFTER_MS = 60_000;
|
|
19
|
+
/** Retries after the first attempt, as the provider SDKs default. */
|
|
20
|
+
export const DEFAULT_MAX_RETRIES = 2;
|
|
21
|
+
|
|
22
|
+
export interface Limits {
|
|
23
|
+
body: number;
|
|
24
|
+
event: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Reads the `max_body_bytes` and `max_event_bytes` provider params over
|
|
29
|
+
* the defaults; anything but a positive byte count throws.
|
|
30
|
+
*/
|
|
31
|
+
export function limitsFrom(
|
|
32
|
+
provider: string,
|
|
33
|
+
params: Record<string, string> | undefined
|
|
34
|
+
): Limits {
|
|
35
|
+
const l: Limits = { body: DEFAULT_MAX_BODY_BYTES, event: DEFAULT_MAX_EVENT_BYTES };
|
|
36
|
+
for (const [name, key] of [
|
|
37
|
+
["max_body_bytes", "body"],
|
|
38
|
+
["max_event_bytes", "event"],
|
|
39
|
+
] as const) {
|
|
40
|
+
const v = params?.[name];
|
|
41
|
+
if (v === undefined) continue;
|
|
42
|
+
const t = v.trim();
|
|
43
|
+
const n = Number(t);
|
|
44
|
+
if (!/^\d+$/.test(t) || !Number.isSafeInteger(n) || n <= 0) {
|
|
45
|
+
throw new LLMError(`${provider}: ${name} must be a positive byte count`);
|
|
46
|
+
}
|
|
47
|
+
l[key] = n;
|
|
48
|
+
}
|
|
49
|
+
return l;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A non-2xx response, read within the body cap and with every secret
|
|
54
|
+
* scrubbed, for the adapter to classify.
|
|
55
|
+
*/
|
|
56
|
+
export interface ErrorResponse {
|
|
57
|
+
status: number;
|
|
58
|
+
statusText: string;
|
|
59
|
+
headers: Headers;
|
|
60
|
+
body: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface TransportOptions {
|
|
64
|
+
/** Names the provider in errors (`"anthropic"`, a scheme). */
|
|
65
|
+
provider: string;
|
|
66
|
+
/** Credential values: no error message may contain one. */
|
|
67
|
+
secrets: string[];
|
|
68
|
+
limits: Limits;
|
|
69
|
+
maxRetries?: number;
|
|
70
|
+
/** Maps an error response to the adapter's typed error. */
|
|
71
|
+
mapError: (r: ErrorResponse) => Error;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* POSTs `body` as JSON to `url` and returns the 2xx response. Retries,
|
|
76
|
+
* up to `maxRetries`, connection failures and 408, 409, 429 and 5xx
|
|
77
|
+
* responses (an `x-should-retry` header overrides the status), waiting
|
|
78
|
+
* what `retry-after-ms` / `retry-after` ask within (0, 60s], else an
|
|
79
|
+
* exponential backoff. A redirect is not followed: it fails as an
|
|
80
|
+
* {@link HTTPStatusError}. Error bodies are read within the body cap.
|
|
81
|
+
*/
|
|
82
|
+
export async function post(
|
|
83
|
+
opts: TransportOptions,
|
|
84
|
+
url: string,
|
|
85
|
+
headers: Record<string, string>,
|
|
86
|
+
body: unknown
|
|
87
|
+
): Promise<globalThis.Response> {
|
|
88
|
+
const maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
89
|
+
const payload = JSON.stringify(body);
|
|
90
|
+
for (let attempt = 0; ; attempt++) {
|
|
91
|
+
let resp: globalThis.Response;
|
|
92
|
+
try {
|
|
93
|
+
resp = await globalThis.fetch(url, {
|
|
94
|
+
method: "POST",
|
|
95
|
+
headers,
|
|
96
|
+
body: payload,
|
|
97
|
+
redirect: "manual",
|
|
98
|
+
});
|
|
99
|
+
} catch (err) {
|
|
100
|
+
if (attempt < maxRetries) {
|
|
101
|
+
await sleep(backoff(attempt));
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
throw scrubError(networkError(opts.provider, err), opts.secrets);
|
|
105
|
+
}
|
|
106
|
+
if (resp.status >= 300 && resp.status < 400) {
|
|
107
|
+
await resp.body?.cancel().catch(() => undefined);
|
|
108
|
+
throw new HTTPStatusError(resp.status, `${opts.provider}: redirect not followed`);
|
|
109
|
+
}
|
|
110
|
+
if (resp.ok) return resp;
|
|
111
|
+
|
|
112
|
+
const text = await readBody(resp, opts.limits.body, opts.provider).catch(
|
|
113
|
+
(err: unknown) => {
|
|
114
|
+
throw scrubError(err as Error, opts.secrets);
|
|
115
|
+
}
|
|
116
|
+
);
|
|
117
|
+
if (attempt < maxRetries && shouldRetry(resp)) {
|
|
118
|
+
await sleep(retryDelay(resp.headers, attempt));
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
throw scrubError(
|
|
122
|
+
opts.mapError({
|
|
123
|
+
status: resp.status,
|
|
124
|
+
statusText: resp.statusText,
|
|
125
|
+
headers: resp.headers,
|
|
126
|
+
body: scrubSecrets(text, opts.secrets),
|
|
127
|
+
}),
|
|
128
|
+
opts.secrets
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function shouldRetry(resp: globalThis.Response): boolean {
|
|
134
|
+
const h = resp.headers.get("x-should-retry");
|
|
135
|
+
if (h === "true") return true;
|
|
136
|
+
if (h === "false") return false;
|
|
137
|
+
const s = resp.status;
|
|
138
|
+
return s === 408 || s === 409 || s === 429 || s >= 500;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The wait the server asks for, when within (0, 60s]; else backoff. */
|
|
142
|
+
export function retryDelay(headers: Headers, attempt: number): number {
|
|
143
|
+
const ms = retryAfterMs(headers);
|
|
144
|
+
return ms ?? backoff(attempt);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The `retry-after-ms` or `retry-after` wait in ms, when one is set and
|
|
149
|
+
* within (0, {@link MAX_RETRY_AFTER_MS}]; undefined otherwise (absent,
|
|
150
|
+
* zero, negative, NaN, huge or unparsable).
|
|
151
|
+
*/
|
|
152
|
+
export function retryAfterMs(headers: Headers): number | undefined {
|
|
153
|
+
const inRange = (ms: number) => ms > 0 && ms <= MAX_RETRY_AFTER_MS;
|
|
154
|
+
const msHeader = headers.get("retry-after-ms");
|
|
155
|
+
if (msHeader !== null && isNumber(msHeader)) {
|
|
156
|
+
const n = Number(msHeader.trim());
|
|
157
|
+
if (inRange(n)) return n;
|
|
158
|
+
}
|
|
159
|
+
const secHeader = headers.get("retry-after");
|
|
160
|
+
if (secHeader !== null) {
|
|
161
|
+
if (isNumber(secHeader)) {
|
|
162
|
+
const n = Number(secHeader.trim()) * 1000;
|
|
163
|
+
if (inRange(n)) return n;
|
|
164
|
+
} else {
|
|
165
|
+
const at = Date.parse(secHeader);
|
|
166
|
+
if (!Number.isNaN(at) && inRange(at - Date.now())) return at - Date.now();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function isNumber(v: string): boolean {
|
|
173
|
+
return /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(v.trim());
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** 0.5s doubling per retry, at most 8s, less up to 25% jitter. */
|
|
177
|
+
function backoff(attempt: number): number {
|
|
178
|
+
const delay = Math.min(500 * 2 ** attempt, 8000);
|
|
179
|
+
return delay - Math.floor(Math.random() * (delay / 4));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function sleep(ms: number): Promise<void> {
|
|
183
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function networkError(provider: string, err: unknown): LLMError {
|
|
187
|
+
const cause = (err as { cause?: { code?: string; message?: string } }).cause;
|
|
188
|
+
const detail = cause?.message ?? (err as Error)?.message ?? String(err);
|
|
189
|
+
const e = new LLMError(`${provider}: request failed: ${detail}`);
|
|
190
|
+
if (cause?.code) e.code = cause.code;
|
|
191
|
+
return e;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Returns `err` with every secret replaced by `REDACTED` in its message
|
|
196
|
+
* and its cause's: a response body echoing the key never surfaces it.
|
|
197
|
+
*/
|
|
198
|
+
export function scrubError<E extends Error>(err: E, secrets: readonly string[]): E {
|
|
199
|
+
if (!(err instanceof Error) || secrets.length === 0) return err;
|
|
200
|
+
err.message = scrubSecrets(err.message, secrets);
|
|
201
|
+
if (err.stack) err.stack = scrubSecrets(err.stack, secrets);
|
|
202
|
+
const cause = (err as { cause?: unknown }).cause;
|
|
203
|
+
if (cause instanceof Error && cause !== err) scrubError(cause, secrets);
|
|
204
|
+
return err;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Reads a whole body as text, failing with a
|
|
209
|
+
* {@link ResponseTooLargeError} once it passes `max` bytes.
|
|
210
|
+
*/
|
|
211
|
+
export async function readBody(
|
|
212
|
+
resp: globalThis.Response,
|
|
213
|
+
max: number,
|
|
214
|
+
provider: string
|
|
215
|
+
): Promise<string> {
|
|
216
|
+
if (!resp.body) return "";
|
|
217
|
+
const reader = resp.body.getReader();
|
|
218
|
+
const chunks: Uint8Array[] = [];
|
|
219
|
+
let read = 0;
|
|
220
|
+
try {
|
|
221
|
+
for (;;) {
|
|
222
|
+
const { done, value } = await reader.read();
|
|
223
|
+
if (done) break;
|
|
224
|
+
read += value.byteLength;
|
|
225
|
+
if (read > max) {
|
|
226
|
+
await reader.cancel().catch(() => undefined);
|
|
227
|
+
throw new ResponseTooLargeError(provider, "body", max);
|
|
228
|
+
}
|
|
229
|
+
chunks.push(value);
|
|
230
|
+
}
|
|
231
|
+
} finally {
|
|
232
|
+
reader.releaseLock();
|
|
233
|
+
}
|
|
234
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** One server-sent event. */
|
|
238
|
+
export interface SSEEvent {
|
|
239
|
+
event: string;
|
|
240
|
+
data: string;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Yields the events of an SSE body (`\n` or `\r\n` framing, comments
|
|
245
|
+
* skipped, multi-line data joined). An event, counted from the last
|
|
246
|
+
* blank line without carriage returns, longer than `max` bytes fails
|
|
247
|
+
* with a {@link ResponseTooLargeError}. A trailing event without its
|
|
248
|
+
* blank line is not dispatched.
|
|
249
|
+
*/
|
|
250
|
+
export async function* sseEvents(
|
|
251
|
+
resp: globalThis.Response,
|
|
252
|
+
max: number,
|
|
253
|
+
provider: string
|
|
254
|
+
): AsyncGenerator<SSEEvent> {
|
|
255
|
+
if (!resp.body) return;
|
|
256
|
+
const reader = resp.body.getReader();
|
|
257
|
+
const decoder = new TextDecoder();
|
|
258
|
+
let buf: Buffer = Buffer.alloc(0);
|
|
259
|
+
let eventBytes = 0;
|
|
260
|
+
let name = "";
|
|
261
|
+
let data: string[] = [];
|
|
262
|
+
let finished = false;
|
|
263
|
+
try {
|
|
264
|
+
for (;;) {
|
|
265
|
+
const { done, value } = await reader.read();
|
|
266
|
+
if (value) buf = Buffer.concat([buf, value]);
|
|
267
|
+
let nl: number;
|
|
268
|
+
while ((nl = buf.indexOf(0x0a)) >= 0) {
|
|
269
|
+
let line = buf.subarray(0, nl);
|
|
270
|
+
buf = buf.subarray(nl + 1);
|
|
271
|
+
if (line.length > 0 && line[line.length - 1] === 0x0d) {
|
|
272
|
+
line = line.subarray(0, line.length - 1);
|
|
273
|
+
}
|
|
274
|
+
if (line.length === 0) {
|
|
275
|
+
eventBytes = 0;
|
|
276
|
+
if (data.length > 0 || name !== "") {
|
|
277
|
+
yield { event: name, data: data.join("\n") };
|
|
278
|
+
}
|
|
279
|
+
name = "";
|
|
280
|
+
data = [];
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
eventBytes += nonCR(line) + 1;
|
|
284
|
+
if (eventBytes > max) throw new ResponseTooLargeError(provider, "event", max);
|
|
285
|
+
const text = decoder.decode(line);
|
|
286
|
+
if (text.startsWith(":")) continue;
|
|
287
|
+
const colon = text.indexOf(":");
|
|
288
|
+
const field = colon < 0 ? text : text.slice(0, colon);
|
|
289
|
+
let v = colon < 0 ? "" : text.slice(colon + 1);
|
|
290
|
+
if (v.startsWith(" ")) v = v.slice(1);
|
|
291
|
+
if (field === "event") name = v;
|
|
292
|
+
else if (field === "data") data.push(v);
|
|
293
|
+
}
|
|
294
|
+
if (eventBytes + nonCR(buf) > max) {
|
|
295
|
+
throw new ResponseTooLargeError(provider, "event", max);
|
|
296
|
+
}
|
|
297
|
+
if (done) {
|
|
298
|
+
finished = true;
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
} finally {
|
|
303
|
+
if (!finished) await reader.cancel().catch(() => undefined);
|
|
304
|
+
reader.releaseLock();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function nonCR(b: Uint8Array): number {
|
|
309
|
+
let n = 0;
|
|
310
|
+
for (const c of b) if (c !== 0x0d) n++;
|
|
311
|
+
return n;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Joins a base URL and a path with exactly one slash. */
|
|
315
|
+
export function joinURL(base: string, path: string): string {
|
|
316
|
+
return base.replace(/\/+$/, "") + "/" + path.replace(/^\/+/, "");
|
|
317
|
+
}
|
package/src/llm-keys.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider key resolution and the gate that keeps a key kit resolved
|
|
3
|
+
* itself off an endpoint only the URI names. Mirrors Go `llm`
|
|
4
|
+
* (`ResolveAPIKey`, `ApplyAPIKey`, the key-endpoint guard) without a
|
|
5
|
+
* secret store.
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { URI } from "./llm";
|
|
11
|
+
import {
|
|
12
|
+
blankKey,
|
|
13
|
+
checkKeyEndpoint,
|
|
14
|
+
declarationOf,
|
|
15
|
+
isRegistered,
|
|
16
|
+
redactURI,
|
|
17
|
+
trustedOrigin,
|
|
18
|
+
} from "./llm-endpoint";
|
|
19
|
+
import { LLMError } from "./llm-error";
|
|
20
|
+
import { KeyEndpointError, MissingKeyError } from "./llm-errors";
|
|
21
|
+
import { providerBlock, readLLMFile, type LLMFile } from "./llm-file";
|
|
22
|
+
import { parseURI } from "./llm-uri";
|
|
23
|
+
|
|
24
|
+
/** The universal key variable, lent to a scheme that requires a key. */
|
|
25
|
+
export const FALLBACK_ENV_KEY = "LLM_API_KEY";
|
|
26
|
+
|
|
27
|
+
/** `<SCHEME>_API_KEY`: `openrouter` reads `OPENROUTER_API_KEY`. */
|
|
28
|
+
export function envKeyName(scheme: string): string {
|
|
29
|
+
return `${scheme.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_API_KEY`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Where a resolved key came from. */
|
|
33
|
+
export type KeySourceKind = "" | "uri" | "config" | "env" | "fallback";
|
|
34
|
+
|
|
35
|
+
/** A resolved key; `value` is "" when none was found. */
|
|
36
|
+
export interface ResolvedKey {
|
|
37
|
+
value: string;
|
|
38
|
+
source: KeySourceKind;
|
|
39
|
+
/** Set when a required key was found nowhere. */
|
|
40
|
+
missing?: MissingKeyError;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The URI's own `api_key`; undefined when absent or blank. */
|
|
44
|
+
export function uriKey(u: URI): string | undefined {
|
|
45
|
+
const v = u.params?.["api_key"];
|
|
46
|
+
return v !== undefined && !blankKey(v) ? v : undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Resolves `u`'s key, highest precedence first: the URI's `api_key`;
|
|
51
|
+
* llm.yaml `providers.<scheme>.api_key`, then the variable its
|
|
52
|
+
* `api_key_env` names; the scheme's key variables (its declared
|
|
53
|
+
* {@link ProviderKey} or `<SCHEME>_API_KEY`); `LLM_API_KEY` for a
|
|
54
|
+
* registered scheme that requires a key. A scheme no adapter serves
|
|
55
|
+
* takes only what its own llm.yaml block names. Blank counts as unset
|
|
56
|
+
* everywhere.
|
|
57
|
+
*/
|
|
58
|
+
export function resolveKey(u: URI, file: LLMFile): ResolvedKey {
|
|
59
|
+
const own = uriKey(u);
|
|
60
|
+
if (own !== undefined) return { value: own, source: "uri" };
|
|
61
|
+
const block = providerBlock(file, u.scheme);
|
|
62
|
+
if (block && !blankKey(block.apiKey)) return { value: block.apiKey, source: "config" };
|
|
63
|
+
const known = isRegistered(u.scheme);
|
|
64
|
+
const decl = declarationOf(u.scheme)?.key;
|
|
65
|
+
let names = known ? [...(decl?.envVars ?? [envKeyName(u.scheme)])] : [];
|
|
66
|
+
if (block && !blankKey(block.apiKeyEnv)) {
|
|
67
|
+
names = [block.apiKeyEnv, ...names.filter((n) => n !== block.apiKeyEnv)];
|
|
68
|
+
}
|
|
69
|
+
if (names.length === 0) return { value: "", source: "" };
|
|
70
|
+
for (const n of names) {
|
|
71
|
+
const v = process.env[n];
|
|
72
|
+
if (v !== undefined && !blankKey(v)) return { value: v, source: "env" };
|
|
73
|
+
}
|
|
74
|
+
const required = known && decl?.optional !== true;
|
|
75
|
+
if (!required) return { value: "", source: "" };
|
|
76
|
+
const fb = process.env[FALLBACK_ENV_KEY];
|
|
77
|
+
if (fb !== undefined && !blankKey(fb)) return { value: fb, source: "fallback" };
|
|
78
|
+
return {
|
|
79
|
+
value: "",
|
|
80
|
+
source: "",
|
|
81
|
+
missing: new MissingKeyError(u.scheme, u.model, [...names, FALLBACK_ENV_KEY]),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The endpoint a URI itself names: its `base_url`, else its host. */
|
|
86
|
+
export function uriEndpoint(u: URI): string {
|
|
87
|
+
const b = u.params?.["base_url"];
|
|
88
|
+
if (b) return b;
|
|
89
|
+
return u.host ? `http://${u.host}` : "";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Checks that `key`, resolved from `source`, may go where `u` points.
|
|
94
|
+
* A key from the URI itself is the caller's choice for any https host.
|
|
95
|
+
* Any other key goes to a URI-named endpoint only when it is loopback
|
|
96
|
+
* or shares an origin with the scheme's declared endpoints, its llm.yaml
|
|
97
|
+
* `base_url` or `LLM_BASE_URL`. Plain http to a remote host is refused
|
|
98
|
+
* whatever the source. Throws a {@link KeyEndpointError}.
|
|
99
|
+
*/
|
|
100
|
+
export function guardKeyEndpoint(u: URI, key: string, source: KeySourceKind): void {
|
|
101
|
+
const endpoint = uriEndpoint(u);
|
|
102
|
+
if (blankKey(key) || endpoint === "") return;
|
|
103
|
+
checkKeyEndpoint(u.scheme, key, endpoint);
|
|
104
|
+
if (source === "uri") return;
|
|
105
|
+
if (!trustedOrigin(u.scheme, endpoint, [], true)) {
|
|
106
|
+
throw new KeyEndpointError(u.scheme, redactURI(endpoint));
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Removes a blank `api_key` param from `u`: it is no key. */
|
|
111
|
+
export function dropBlankURIKey(u: URI): void {
|
|
112
|
+
const v = u.params?.["api_key"];
|
|
113
|
+
if (v === undefined || !blankKey(v)) return;
|
|
114
|
+
delete u.params!["api_key"];
|
|
115
|
+
if (Object.keys(u.params!).length === 0) delete u.params;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** `raw` without any `name` param; the `?` goes too when none is left. */
|
|
119
|
+
function stripURIParam(raw: string, name: string): string {
|
|
120
|
+
const s = raw.indexOf("://");
|
|
121
|
+
if (s < 0) return raw;
|
|
122
|
+
const q = raw.indexOf("?", s + 3);
|
|
123
|
+
if (q < 0) return raw;
|
|
124
|
+
const kept = raw
|
|
125
|
+
.slice(q + 1)
|
|
126
|
+
.split("&")
|
|
127
|
+
.filter((p) => p.split("=", 1)[0] !== name);
|
|
128
|
+
return kept.length === 0 ? raw.slice(0, q) : `${raw.slice(0, q + 1)}${kept.join("&")}`;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Returns `uri` with the provider's key set as its `api_key` param,
|
|
133
|
+
* resolved as {@link loadConfig} resolves it, after the same endpoint
|
|
134
|
+
* guard. `uri` comes back unchanged when it carries a non-blank
|
|
135
|
+
* `api_key` (a blank one is removed first), when its scheme takes no
|
|
136
|
+
* key, and when no adapter serves the scheme and its llm.yaml block
|
|
137
|
+
* names none. A required key found nowhere throws a
|
|
138
|
+
* {@link MissingKeyError}. Go `ApplyAPIKey` without a secret store.
|
|
139
|
+
*
|
|
140
|
+
* The result holds the key: never log it. Errors never carry it.
|
|
141
|
+
*/
|
|
142
|
+
export function applyAPIKey(uri: string): string {
|
|
143
|
+
let parsed: URI;
|
|
144
|
+
try {
|
|
145
|
+
parsed = parseURI(uri);
|
|
146
|
+
} catch {
|
|
147
|
+
// The parse error quotes its input, which may carry a key.
|
|
148
|
+
throw new LLMError("llm: apply API key: provider URI must be scheme://model");
|
|
149
|
+
}
|
|
150
|
+
const named = parsed.params?.["api_key"];
|
|
151
|
+
if (named !== undefined && blankKey(named)) {
|
|
152
|
+
uri = stripURIParam(uri, "api_key");
|
|
153
|
+
dropBlankURIKey(parsed);
|
|
154
|
+
}
|
|
155
|
+
const key = resolveKey(parsed, readLLMFile());
|
|
156
|
+
if (key.missing) throw key.missing;
|
|
157
|
+
guardKeyEndpoint(parsed, key.value, key.source);
|
|
158
|
+
if (key.source === "uri" || key.value === "") return uri;
|
|
159
|
+
// The query splits on & and is not unescaped: a key holding a
|
|
160
|
+
// separator cannot travel as a param intact.
|
|
161
|
+
if (/[&?#]/.test(key.value)) {
|
|
162
|
+
throw new LLMError(
|
|
163
|
+
`llm: ${parsed.scheme} API key contains a character a provider URI cannot carry (& ? #)`
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
return `${uri}${uri.includes("?") ? "&" : "?"}api_key=${key.value}`;
|
|
167
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Runs the media_fetch section of contracts/llm-v1/vectors.json: what a
|
|
2
|
+
// URL media source refuses to download. Go is canonical; a failure here
|
|
3
|
+
// means this SDK drifted, not that a vector should change.
|
|
4
|
+
|
|
5
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
6
|
+
|
|
7
|
+
import { HTTPStatusError, LLMError, urlSource } from "./llm";
|
|
8
|
+
import { MediaTooLargeError, MediaURLRefusedError, _setMediaFetchSeams } from "./llm-media";
|
|
9
|
+
import { fakeServer, loadVectors, strictKeys, type FakeServer } from "../test/llm/conformance-helpers";
|
|
10
|
+
|
|
11
|
+
interface MediaFetchVector {
|
|
12
|
+
name: string;
|
|
13
|
+
url: string;
|
|
14
|
+
max_bytes?: number;
|
|
15
|
+
server?: {
|
|
16
|
+
status: number;
|
|
17
|
+
headers?: Record<string, string>;
|
|
18
|
+
body?: string;
|
|
19
|
+
body_size?: number;
|
|
20
|
+
};
|
|
21
|
+
error_kind?: string;
|
|
22
|
+
message?: string;
|
|
23
|
+
want_body?: string;
|
|
24
|
+
want_size?: number;
|
|
25
|
+
attempts?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const vectors = loadVectors<{ media_fetch: MediaFetchVector[] }>().media_fetch;
|
|
29
|
+
|
|
30
|
+
function kind(e: unknown): string {
|
|
31
|
+
if (e instanceof MediaURLRefusedError) return "refused";
|
|
32
|
+
if (e instanceof MediaTooLargeError) return "too_large";
|
|
33
|
+
if (e instanceof HTTPStatusError && e.statusCode! >= 300 && e.statusCode! < 400) return "redirect";
|
|
34
|
+
if (e instanceof LLMError && e.message.includes(": http ")) return "http_status";
|
|
35
|
+
return `other: ${String(e)}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
let srv: FakeServer | undefined;
|
|
39
|
+
let restore: (() => void) | undefined;
|
|
40
|
+
|
|
41
|
+
afterEach(async () => {
|
|
42
|
+
restore?.();
|
|
43
|
+
restore = undefined;
|
|
44
|
+
await srv?.close();
|
|
45
|
+
srv = undefined;
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe("llm-v1 conformance: media_fetch", () => {
|
|
49
|
+
it("has vectors", () => expect(vectors.length).toBeGreaterThan(0));
|
|
50
|
+
|
|
51
|
+
it.each(vectors.map((v) => [v.name, v] as const))("%s", async (_n, v) => {
|
|
52
|
+
strictKeys(v, [
|
|
53
|
+
"name", "url", "max_bytes", "server", "error_kind", "message", "want_body", "want_size", "attempts",
|
|
54
|
+
], "media_fetch");
|
|
55
|
+
let url = v.url;
|
|
56
|
+
if (v.server) {
|
|
57
|
+
const s = v.server;
|
|
58
|
+
strictKeys(s, ["status", "headers", "body", "body_size"], "server");
|
|
59
|
+
expect(url.startsWith("/"), "a served url is a path").toBe(true);
|
|
60
|
+
srv = await fakeServer((_hit, res) => {
|
|
61
|
+
res.writeHead(s.status, s.headers ?? {});
|
|
62
|
+
res.end(s.body_size ? "x".repeat(s.body_size) : (s.body ?? ""));
|
|
63
|
+
});
|
|
64
|
+
url = srv.url + url;
|
|
65
|
+
// The loopback server stands in for a public host; every other
|
|
66
|
+
// check stays.
|
|
67
|
+
restore = _setMediaFetchSeams({
|
|
68
|
+
allow: (a, isPublic) => /^127\./.test(a) || a === "::1" || isPublic(a),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const src = urlSource(url, v.max_bytes ? { maxBytes: v.max_bytes } : {});
|
|
72
|
+
if (v.error_kind) {
|
|
73
|
+
const err = await src.read().then(
|
|
74
|
+
() => undefined,
|
|
75
|
+
(e: unknown) => e,
|
|
76
|
+
);
|
|
77
|
+
expect(err, "want an error").toBeDefined();
|
|
78
|
+
expect(kind(err)).toBe(v.error_kind);
|
|
79
|
+
if (v.message) expect((err as Error).message).toBe(v.message);
|
|
80
|
+
} else {
|
|
81
|
+
const got = await src.read();
|
|
82
|
+
if (v.want_body) expect(Buffer.from(got).toString()).toBe(v.want_body);
|
|
83
|
+
if (v.want_size) expect(got.length).toBe(v.want_size);
|
|
84
|
+
}
|
|
85
|
+
if (v.attempts !== undefined) expect(srv?.hits.length).toBe(v.attempts);
|
|
86
|
+
});
|
|
87
|
+
});
|