@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.ts
CHANGED
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
* LLM client facade — mirrors Go `llm` package interfaces as TS types.
|
|
5
5
|
*
|
|
6
6
|
* Provides URI parsing, config loading, provider registry, Client facade
|
|
7
|
-
* with fallback, and typed errors.
|
|
8
|
-
*
|
|
7
|
+
* with fallback, and typed errors. Adapters register their URI schemes
|
|
8
|
+
* on import: `@hop-top/kit/anthropic` (`anthropic://`),
|
|
9
|
+
* `@hop-top/kit/openai` (`openai://` and OpenAI-compatible schemes)
|
|
10
|
+
* and `@hop-top/kit/routellm`. Register your own via {@link register}.
|
|
9
11
|
*
|
|
10
12
|
* @example
|
|
11
13
|
* ```ts
|
|
@@ -17,11 +19,161 @@
|
|
|
17
19
|
* ```
|
|
18
20
|
*/
|
|
19
21
|
|
|
22
|
+
import { readFile } from "node:fs/promises";
|
|
23
|
+
import { extname } from "node:path";
|
|
24
|
+
import { LLMError } from "./llm-error";
|
|
25
|
+
import {
|
|
26
|
+
APIError,
|
|
27
|
+
HTTPStatusError,
|
|
28
|
+
KeyEndpointError,
|
|
29
|
+
MissingKeyError,
|
|
30
|
+
ResponseTooLargeError,
|
|
31
|
+
StreamTruncatedError,
|
|
32
|
+
} from "./llm-errors";
|
|
33
|
+
import { ToolNameError } from "./llm-toolnames";
|
|
34
|
+
import {
|
|
35
|
+
DEFAULT_MAX_MEDIA_BYTES,
|
|
36
|
+
MediaTooLargeError,
|
|
37
|
+
MediaURLRefusedError,
|
|
38
|
+
fetchMedia,
|
|
39
|
+
isPublicAddress,
|
|
40
|
+
} from "./llm-media";
|
|
41
|
+
|
|
42
|
+
export * from "./llm-toolnames";
|
|
43
|
+
export { DEFAULT_MAX_MEDIA_BYTES, MediaTooLargeError, MediaURLRefusedError, isPublicAddress };
|
|
44
|
+
export {
|
|
45
|
+
APIError,
|
|
46
|
+
HTTPStatusError,
|
|
47
|
+
KeyEndpointError,
|
|
48
|
+
MissingKeyError,
|
|
49
|
+
ResponseTooLargeError,
|
|
50
|
+
StreamTruncatedError,
|
|
51
|
+
};
|
|
52
|
+
import {
|
|
53
|
+
clearDeclarations,
|
|
54
|
+
declarationOf,
|
|
55
|
+
setDeclaration,
|
|
56
|
+
type Declaration,
|
|
57
|
+
} from "./llm-endpoint";
|
|
58
|
+
import { loadConfig, type LoadOptions } from "./llm-config";
|
|
59
|
+
import { parseURI } from "./llm-uri";
|
|
60
|
+
export {
|
|
61
|
+
checkKeyEndpoint,
|
|
62
|
+
credentialsTrusted,
|
|
63
|
+
redactURI,
|
|
64
|
+
type ProviderKey,
|
|
65
|
+
} from "./llm-endpoint";
|
|
66
|
+
export { loadConfig, parseURI, type LoadOptions };
|
|
67
|
+
export { applyAPIKey } from "./llm-keys";
|
|
68
|
+
export {
|
|
69
|
+
requestStartedPayload,
|
|
70
|
+
responseReceivedPayload,
|
|
71
|
+
type CallOp,
|
|
72
|
+
type RequestStartedPayload,
|
|
73
|
+
type ResponseReceivedPayload,
|
|
74
|
+
} from "./llm-payload";
|
|
75
|
+
|
|
20
76
|
// ─── Data types ──────────────────────────────────────────────────────────────
|
|
21
77
|
|
|
78
|
+
/** Classifies a content part in a multimodal message. */
|
|
79
|
+
export type PartType = "text" | "image" | "audio" | "video";
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Binary media input for a {@link ContentPart}.
|
|
83
|
+
*
|
|
84
|
+
* Built by {@link inlineSource}, {@link urlSource} or {@link fileSource}.
|
|
85
|
+
*/
|
|
86
|
+
export interface MediaSource {
|
|
87
|
+
/** Non-empty when the source is URL-backed. */
|
|
88
|
+
url(): string;
|
|
89
|
+
/** Inferred MIME type, or `""`. */
|
|
90
|
+
mimeType(): string;
|
|
91
|
+
/** Reads the media bytes. */
|
|
92
|
+
read(): Promise<Uint8Array>;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A single typed element within a multimodal message.
|
|
97
|
+
*
|
|
98
|
+
* Rule: if a {@link Message} has non-empty `parts`, they are used
|
|
99
|
+
* instead of its `content`.
|
|
100
|
+
*/
|
|
101
|
+
export interface ContentPart {
|
|
102
|
+
type: PartType;
|
|
103
|
+
text?: string;
|
|
104
|
+
source?: MediaSource;
|
|
105
|
+
mimeType?: string;
|
|
106
|
+
metadata?: Record<string, unknown>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A single role+content pair in a conversation.
|
|
111
|
+
*
|
|
112
|
+
* Multimodal rule: non-empty `parts` take precedence over `content`.
|
|
113
|
+
*
|
|
114
|
+
* Tool-call linkage: an agentic loop replays a tool round as two kinds
|
|
115
|
+
* of message.
|
|
116
|
+
*
|
|
117
|
+
* - Role `"assistant"` with `toolCalls`: the calls the model made,
|
|
118
|
+
* copied from {@link ToolResponse.toolCalls}. `content` carries any
|
|
119
|
+
* text the model produced alongside them and may be `""`.
|
|
120
|
+
* - Role `"tool"` with `toolCallId`: one tool's result, in `content`.
|
|
121
|
+
* `toolCallId` equals the {@link ToolCall.id} it answers. Send one
|
|
122
|
+
* message per call.
|
|
123
|
+
*
|
|
124
|
+
* `toolCalls` is valid only on role `"assistant"` and `toolCallId` only
|
|
125
|
+
* on role `"tool"`; adapters reject either field on any other role, a
|
|
126
|
+
* tool result carrying `parts`, and linkage the provider cannot express,
|
|
127
|
+
* rather than degrading it to plain text ({@link checkToolLinkage}).
|
|
128
|
+
* Messages that set neither field map exactly as before.
|
|
129
|
+
*/
|
|
22
130
|
export interface Message {
|
|
23
131
|
role: string;
|
|
24
132
|
content: string;
|
|
133
|
+
parts?: ContentPart[];
|
|
134
|
+
/** Tool invocations of an assistant turn. */
|
|
135
|
+
toolCalls?: ToolCall[];
|
|
136
|
+
/** Links a role `"tool"` result to the {@link ToolCall} it answers. */
|
|
137
|
+
toolCallId?: string;
|
|
138
|
+
/**
|
|
139
|
+
* Replays an assistant turn's thinking blocks, exactly as the provider
|
|
140
|
+
* returned them ({@link Response.thinking}, {@link ToolResponse.thinking}
|
|
141
|
+
* or {@link StreamOutcome.thinking}). Required with tool use when
|
|
142
|
+
* thinking is enabled. Assistant only.
|
|
143
|
+
*/
|
|
144
|
+
thinking?: ThinkingBlock[];
|
|
145
|
+
/**
|
|
146
|
+
* Marks a prompt-cache breakpoint after this message: on a system
|
|
147
|
+
* message its text, otherwise its last content block.
|
|
148
|
+
*/
|
|
149
|
+
cacheControl?: CacheControl;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* One block of a model's extended thinking. `signature` verifies
|
|
154
|
+
* `thinking`; a redacted block carries only `redacted`, the provider's
|
|
155
|
+
* opaque data. Pass blocks back exactly as received.
|
|
156
|
+
*/
|
|
157
|
+
export interface ThinkingBlock {
|
|
158
|
+
thinking: string;
|
|
159
|
+
signature: string;
|
|
160
|
+
redacted: string;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A prompt-cache breakpoint. `ttl` is `""` or absent (the provider
|
|
165
|
+
* default, five minutes on Anthropic), `"5m"` or `"1h"`.
|
|
166
|
+
*/
|
|
167
|
+
export interface CacheControl {
|
|
168
|
+
ttl?: string;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Enables extended thinking with a token budget, which must be below
|
|
173
|
+
* the request's max tokens.
|
|
174
|
+
*/
|
|
175
|
+
export interface ThinkingConfig {
|
|
176
|
+
budgetTokens: number;
|
|
25
177
|
}
|
|
26
178
|
|
|
27
179
|
export interface Request {
|
|
@@ -31,6 +183,75 @@ export interface Request {
|
|
|
31
183
|
maxTokens?: number;
|
|
32
184
|
stopSequences?: string[];
|
|
33
185
|
extensions?: Record<string, unknown>;
|
|
186
|
+
/** Enables extended thinking; thinking deltas then stream as {@link Token.thinking}. */
|
|
187
|
+
thinking?: ThinkingConfig;
|
|
188
|
+
/**
|
|
189
|
+
* Makes a stream also yield incremental tool-call events
|
|
190
|
+
* ({@link Token.toolCall}) and usage snapshots ({@link Token.usage}).
|
|
191
|
+
* Unset, a stream yields exactly the tokens it always has. Ignored by
|
|
192
|
+
* `complete` and `callWithTools`.
|
|
193
|
+
*/
|
|
194
|
+
streamEvents?: boolean;
|
|
195
|
+
/**
|
|
196
|
+
* Constrains tool use on a tool-calling request (`callWithTools`,
|
|
197
|
+
* `streamWithTools`); unset leaves the provider default. See
|
|
198
|
+
* {@link ToolChoice}.
|
|
199
|
+
*/
|
|
200
|
+
toolChoice?: ToolChoice;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Whether the model must call a tool. */
|
|
204
|
+
export type ToolChoiceMode = "auto" | "any" | "none" | "tool";
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Constrains tool use: `auto` lets the model decide (the providers'
|
|
208
|
+
* default), `any` makes it call at least one tool of its pick, `none`
|
|
209
|
+
* forbids tool calls although tools are defined, `tool` makes it call
|
|
210
|
+
* the tool `name`: its {@link ToolDef.name} as defined, before any
|
|
211
|
+
* provider name mapping. Set `name` with mode `tool` only.
|
|
212
|
+
*
|
|
213
|
+
* Adapters reject an invalid choice ({@link checkToolChoice}) before
|
|
214
|
+
* sending, and so does a call without tools (`complete`, `stream`).
|
|
215
|
+
*/
|
|
216
|
+
export interface ToolChoice {
|
|
217
|
+
mode: ToolChoiceMode;
|
|
218
|
+
name?: string;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const TOOL_CHOICE_MODES: readonly string[] = ["auto", "any", "none", "tool"];
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Throws an {@link LLMError} saying why `c` cannot go with `tools`: a
|
|
225
|
+
* mode that is not a {@link ToolChoiceMode}, no tools, a name missing
|
|
226
|
+
* with mode `tool` or set with another mode, or naming no tool in
|
|
227
|
+
* `tools`. Undefined `c` is valid. Adapters prefix the message with
|
|
228
|
+
* their scheme.
|
|
229
|
+
*/
|
|
230
|
+
export function checkToolChoice(
|
|
231
|
+
c: ToolChoice | undefined,
|
|
232
|
+
tools: ReadonlyArray<{ name: string }>
|
|
233
|
+
): void {
|
|
234
|
+
if (!c) return;
|
|
235
|
+
const q = (v: string) => JSON.stringify(v);
|
|
236
|
+
if (!TOOL_CHOICE_MODES.includes(c.mode)) {
|
|
237
|
+
throw new LLMError(`unknown tool_choice mode ${q(String(c.mode))}`);
|
|
238
|
+
}
|
|
239
|
+
if (tools.length === 0) {
|
|
240
|
+
throw new LLMError(`tool_choice ${q(c.mode)} needs tools`);
|
|
241
|
+
}
|
|
242
|
+
const name = c.name ?? "";
|
|
243
|
+
if (c.mode !== "tool") {
|
|
244
|
+
if (name !== "") {
|
|
245
|
+
throw new LLMError(`tool_choice ${q(c.mode)} takes no tool name`);
|
|
246
|
+
}
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (name === "") {
|
|
250
|
+
throw new LLMError(`tool_choice ${q(c.mode)} needs a tool name`);
|
|
251
|
+
}
|
|
252
|
+
if (!tools.some((t) => t.name === name)) {
|
|
253
|
+
throw new LLMError(`tool_choice names unknown tool ${q(name)}`);
|
|
254
|
+
}
|
|
34
255
|
}
|
|
35
256
|
|
|
36
257
|
export interface Response {
|
|
@@ -38,25 +259,124 @@ export interface Response {
|
|
|
38
259
|
role: string;
|
|
39
260
|
usage?: Usage;
|
|
40
261
|
finishReason?: string;
|
|
262
|
+
/** The turn's thinking blocks, to replay unchanged. */
|
|
263
|
+
thinking?: ThinkingBlock[];
|
|
41
264
|
}
|
|
42
265
|
|
|
43
266
|
export interface Usage {
|
|
44
267
|
promptTokens: number;
|
|
45
268
|
completionTokens: number;
|
|
269
|
+
/**
|
|
270
|
+
* Input tokens read from or written to the prompt cache, apart from
|
|
271
|
+
* `promptTokens`.
|
|
272
|
+
*/
|
|
273
|
+
cacheReadTokens?: number;
|
|
274
|
+
cacheCreationTokens?: number;
|
|
275
|
+
/** Every input and output token, cache ones included. */
|
|
46
276
|
totalTokens: number;
|
|
47
277
|
}
|
|
48
278
|
|
|
279
|
+
/** A model's rate per million tokens, by kind. */
|
|
280
|
+
export interface Price {
|
|
281
|
+
input: number;
|
|
282
|
+
output: number;
|
|
283
|
+
cacheRead: number;
|
|
284
|
+
cacheWrite: number;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Cost of `u` at `p`, cache reads and writes at their own rates. */
|
|
288
|
+
export function usageCost(u: Usage, p: Price): number {
|
|
289
|
+
return (
|
|
290
|
+
(u.promptTokens * p.input +
|
|
291
|
+
u.completionTokens * p.output +
|
|
292
|
+
(u.cacheReadTokens ?? 0) * p.cacheRead +
|
|
293
|
+
(u.cacheCreationTokens ?? 0) * p.cacheWrite) /
|
|
294
|
+
1e6
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* A single streaming chunk. The final token has `done: true`; nothing
|
|
300
|
+
* follows it. A token carries one thing: a text delta (`content`), a
|
|
301
|
+
* thinking delta (`thinking`), a tool-call event (`toolCall`), a usage
|
|
302
|
+
* snapshot (`usage`), or the end (`done`); `content` is `""` on all but
|
|
303
|
+
* a text delta.
|
|
304
|
+
*/
|
|
49
305
|
export interface Token {
|
|
50
306
|
content: string;
|
|
307
|
+
/**
|
|
308
|
+
* A thinking delta, sent only when the request enabled
|
|
309
|
+
* {@link Request.thinking}; `content` is then empty.
|
|
310
|
+
*/
|
|
311
|
+
thinking?: string;
|
|
312
|
+
/**
|
|
313
|
+
* An incremental tool-call event, sent only when the request set
|
|
314
|
+
* {@link Request.streamEvents}. See {@link ToolCallEvent}.
|
|
315
|
+
*/
|
|
316
|
+
toolCall?: ToolCallEvent;
|
|
317
|
+
/**
|
|
318
|
+
* The turn's usage so far, sent only when the request set
|
|
319
|
+
* {@link Request.streamEvents}, each time the provider reports it. A
|
|
320
|
+
* cumulative snapshot, never a delta: counts never go down, and the
|
|
321
|
+
* last one equals the finished turn's usage ({@link StreamOutcome.usage}).
|
|
322
|
+
*/
|
|
323
|
+
usage?: Usage;
|
|
51
324
|
done: boolean;
|
|
52
325
|
}
|
|
53
326
|
|
|
327
|
+
/**
|
|
328
|
+
* The step of a streamed tool call: `start` opens it (`index`, `id`,
|
|
329
|
+
* `name`), `delta` carries a fragment of its JSON arguments, `end`
|
|
330
|
+
* closes it (`call` holds it complete).
|
|
331
|
+
*/
|
|
332
|
+
export type ToolCallEventKind = "start" | "delta" | "end";
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* One step of a tool call as it streams.
|
|
336
|
+
*
|
|
337
|
+
* For each call: one start, then any deltas, then one end, in that
|
|
338
|
+
* order; events of parallel calls may interleave and are told apart by
|
|
339
|
+
* `index`, the call's position in {@link StreamOutcome.toolCalls}. A
|
|
340
|
+
* call that started but never ended (the stream failed, was cancelled
|
|
341
|
+
* or closed) did not complete: no end event is made up for it.
|
|
342
|
+
*/
|
|
343
|
+
export interface ToolCallEvent {
|
|
344
|
+
kind: ToolCallEventKind;
|
|
345
|
+
index: number;
|
|
346
|
+
/**
|
|
347
|
+
* Set on start and end. `name` is the tool's name as the caller
|
|
348
|
+
* defined it, whatever name went over the wire.
|
|
349
|
+
*/
|
|
350
|
+
id?: string;
|
|
351
|
+
name?: string;
|
|
352
|
+
/**
|
|
353
|
+
* A raw fragment of the arguments' JSON, on delta only; fragments
|
|
354
|
+
* concatenate to the complete arguments and are not valid JSON alone.
|
|
355
|
+
*/
|
|
356
|
+
argumentsDelta?: string;
|
|
357
|
+
/**
|
|
358
|
+
* The complete call, on end only: exactly the entry at `index` in
|
|
359
|
+
* {@link StreamOutcome.toolCalls}.
|
|
360
|
+
*/
|
|
361
|
+
call?: ToolCall;
|
|
362
|
+
}
|
|
363
|
+
|
|
54
364
|
export interface ToolDef {
|
|
55
365
|
name: string;
|
|
56
366
|
description: string;
|
|
57
367
|
parameters: unknown;
|
|
368
|
+
/** Marks a prompt-cache breakpoint after this tool. */
|
|
369
|
+
cacheControl?: CacheControl;
|
|
58
370
|
}
|
|
59
371
|
|
|
372
|
+
/**
|
|
373
|
+
* A single tool invocation returned by the model.
|
|
374
|
+
*
|
|
375
|
+
* `id` is the handle a tool result quotes back in
|
|
376
|
+
* {@link Message.toolCallId}. `arguments` is the parsed JSON value, or a
|
|
377
|
+
* JSON-encoded string (Go's `json.RawMessage`); adapters send a string
|
|
378
|
+
* as is and encode anything else.
|
|
379
|
+
*/
|
|
60
380
|
export interface ToolCall {
|
|
61
381
|
id: string;
|
|
62
382
|
name: string;
|
|
@@ -66,6 +386,29 @@ export interface ToolCall {
|
|
|
66
386
|
export interface ToolResponse {
|
|
67
387
|
content: string;
|
|
68
388
|
toolCalls: ToolCall[];
|
|
389
|
+
/** The turn's thinking blocks, to replay unchanged. */
|
|
390
|
+
thinking?: ThinkingBlock[];
|
|
391
|
+
finishReason?: string;
|
|
392
|
+
usage?: Usage;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** What a finished stream folded into. */
|
|
396
|
+
export interface StreamOutcome {
|
|
397
|
+
content: string;
|
|
398
|
+
/** The turn's thinking blocks in order; replay them unchanged. */
|
|
399
|
+
thinking: ThinkingBlock[];
|
|
400
|
+
toolCalls: ToolCall[];
|
|
401
|
+
finishReason: string;
|
|
402
|
+
usage: Usage;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* A token stream whose finished turn can be read back: `outcome()` is
|
|
407
|
+
* defined only once the final token (`done`) was yielded; after an
|
|
408
|
+
* error it stays undefined.
|
|
409
|
+
*/
|
|
410
|
+
export interface ToolStream extends AsyncIterable<Token> {
|
|
411
|
+
outcome(): StreamOutcome | undefined;
|
|
69
412
|
}
|
|
70
413
|
|
|
71
414
|
// ─── Core interfaces ─────────────────────────────────────────────────────────
|
|
@@ -82,8 +425,17 @@ export interface ToolCaller {
|
|
|
82
425
|
callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse>;
|
|
83
426
|
}
|
|
84
427
|
|
|
428
|
+
/**
|
|
429
|
+
* Streams a tool-calling completion: text deltas as tokens, then the
|
|
430
|
+
* whole turn (tool calls, stop reason, usage) from
|
|
431
|
+
* {@link ToolStream.outcome}.
|
|
432
|
+
*/
|
|
433
|
+
export interface ToolStreamer {
|
|
434
|
+
streamWithTools(req: Request, tools: ToolDef[]): ToolStream;
|
|
435
|
+
}
|
|
436
|
+
|
|
85
437
|
export interface Provider
|
|
86
|
-
extends Partial<Completer & Streamer & ToolCaller> {
|
|
438
|
+
extends Partial<Completer & Streamer & ToolCaller & ToolStreamer> {
|
|
87
439
|
close(): void;
|
|
88
440
|
}
|
|
89
441
|
|
|
@@ -108,20 +460,19 @@ export interface ResolvedConfig {
|
|
|
108
460
|
uri: URI;
|
|
109
461
|
provider: ProviderConfig;
|
|
110
462
|
fallbacks: string[];
|
|
463
|
+
/**
|
|
464
|
+
* Set by the `hermetic` option ({@link LoadOptions}): the adapter
|
|
465
|
+
* reads nothing ambient while it builds and runs, no environment
|
|
466
|
+
* variable (`ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`,
|
|
467
|
+
* `ANTHROPIC_WORKSPACE_ID`, `<SCHEME>_API_KEY`, `ROUTELLM_*`,
|
|
468
|
+
* `LLM_BASE_URL`) and no llm.yaml. Only this config counts.
|
|
469
|
+
*/
|
|
470
|
+
hermetic?: boolean;
|
|
111
471
|
}
|
|
112
472
|
|
|
113
473
|
// ─── Errors ──────────────────────────────────────────────────────────────────
|
|
114
474
|
|
|
115
|
-
export
|
|
116
|
-
statusCode?: number;
|
|
117
|
-
code?: string;
|
|
118
|
-
|
|
119
|
-
constructor(message: string) {
|
|
120
|
-
super(message);
|
|
121
|
-
this.name = "LLMError";
|
|
122
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
475
|
+
export { LLMError };
|
|
125
476
|
|
|
126
477
|
export class ProviderNotFoundError extends LLMError {
|
|
127
478
|
scheme: string;
|
|
@@ -147,13 +498,42 @@ export class CapabilityNotSupportedError extends LLMError {
|
|
|
147
498
|
}
|
|
148
499
|
}
|
|
149
500
|
|
|
501
|
+
/**
|
|
502
|
+
* The provider refused the credential (HTTP 401). A 403 is the narrower
|
|
503
|
+
* {@link PermissionDeniedError}, still an `AuthError`.
|
|
504
|
+
*/
|
|
150
505
|
export class AuthError extends LLMError {
|
|
151
506
|
provider: string;
|
|
152
507
|
|
|
153
|
-
|
|
154
|
-
|
|
508
|
+
/** `cause` is the provider's error response, when there is one. */
|
|
509
|
+
constructor(provider: string, cause?: Error) {
|
|
510
|
+
super(
|
|
511
|
+
`authentication failed for provider: ${provider}` +
|
|
512
|
+
(cause ? `: ${cause.message}` : "")
|
|
513
|
+
);
|
|
155
514
|
this.name = "AuthError";
|
|
156
515
|
this.provider = provider;
|
|
516
|
+
if (cause) this.cause = cause;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* The credential was accepted but may not do what was asked (HTTP 403,
|
|
522
|
+
* an Anthropic `permission_error`): a key without access to the model,
|
|
523
|
+
* workspace or feature. Retrying with the same key will not help.
|
|
524
|
+
*
|
|
525
|
+
* It is an auth error too: `err instanceof AuthError` holds, with the
|
|
526
|
+
* same `provider` and `cause`, so code written before the split keeps
|
|
527
|
+
* treating a 403 as an auth failure. Test `PermissionDeniedError` first
|
|
528
|
+
* to tell the two apart.
|
|
529
|
+
*/
|
|
530
|
+
export class PermissionDeniedError extends AuthError {
|
|
531
|
+
constructor(provider: string, cause?: Error) {
|
|
532
|
+
super(provider, cause);
|
|
533
|
+
this.message =
|
|
534
|
+
`permission denied for provider: ${provider}` +
|
|
535
|
+
(cause ? `: ${cause.message}` : "");
|
|
536
|
+
this.name = "PermissionDeniedError";
|
|
157
537
|
}
|
|
158
538
|
}
|
|
159
539
|
|
|
@@ -198,11 +578,18 @@ export class FallbackExhaustedError extends LLMError {
|
|
|
198
578
|
* Returns true when `err` should trigger a fallback attempt.
|
|
199
579
|
*
|
|
200
580
|
* Fallbackable conditions:
|
|
201
|
-
* - LLMError with statusCode >= 500
|
|
581
|
+
* - LLMError with statusCode >= 500 (an {@link HTTPStatusError} from a
|
|
582
|
+
* 5xx response or an overloaded stream)
|
|
202
583
|
* - RateLimitError (429)
|
|
203
584
|
* - Connection/timeout errors (ECONNREFUSED, ETIMEDOUT, ECONNRESET)
|
|
585
|
+
*
|
|
586
|
+
* Never fallbackable: a {@link ToolNameError} (the caller's tool set
|
|
587
|
+
* needs fixing), a {@link StreamTruncatedError} (tokens may already be
|
|
588
|
+
* consumed), a {@link ResponseTooLargeError}, a {@link KeyEndpointError}
|
|
589
|
+
* and an {@link APIError} below 500.
|
|
204
590
|
*/
|
|
205
591
|
export function isFallbackable(err: Error): boolean {
|
|
592
|
+
if (err instanceof ToolNameError) return false;
|
|
206
593
|
if (err instanceof RateLimitError) return true;
|
|
207
594
|
if (err instanceof LLMError) {
|
|
208
595
|
if (err.code && isConnectionError(err.code)) return true;
|
|
@@ -227,151 +614,142 @@ function isConnectionError(code: string): boolean {
|
|
|
227
614
|
return CONNECTION_CODES.has(code);
|
|
228
615
|
}
|
|
229
616
|
|
|
230
|
-
// ───
|
|
617
|
+
// ─── Message rules ───────────────────────────────────────────────────────────
|
|
231
618
|
|
|
232
619
|
/**
|
|
233
|
-
*
|
|
234
|
-
*
|
|
235
|
-
*
|
|
620
|
+
* Enforces the provider-independent tool-call linkage rules on one
|
|
621
|
+
* message: `toolCalls` only on role `"assistant"`, `toolCallId` only on
|
|
622
|
+
* role `"tool"`, and a tool result carries only `content` (no
|
|
623
|
+
* `toolCalls`, no `parts`). Throws {@link LLMError} otherwise, checking
|
|
624
|
+
* in the Go adapters' order. An empty `toolCalls` array counts as unset.
|
|
236
625
|
*
|
|
237
|
-
*
|
|
238
|
-
*
|
|
239
|
-
* Otherwise the entire path is the model name.
|
|
626
|
+
* Adapters call it before mapping a message, then add the rules their
|
|
627
|
+
* provider needs (for example a required `toolCallId`).
|
|
240
628
|
*/
|
|
241
|
-
export function
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
const scheme = raw.slice(0, idx);
|
|
249
|
-
if (!scheme) {
|
|
250
|
-
throw new LLMError(`invalid LLM URI (empty scheme): ${raw}`);
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
let rest = raw.slice(idx + sep.length);
|
|
254
|
-
if (!rest) {
|
|
255
|
-
throw new LLMError(`invalid LLM URI (empty model): ${raw}`);
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// Extract query params
|
|
259
|
-
let params: Record<string, string> | undefined;
|
|
260
|
-
const qIdx = rest.indexOf("?");
|
|
261
|
-
if (qIdx >= 0) {
|
|
262
|
-
const qs = rest.slice(qIdx + 1);
|
|
263
|
-
rest = rest.slice(0, qIdx);
|
|
264
|
-
params = {};
|
|
265
|
-
for (const pair of qs.split("&")) {
|
|
266
|
-
const eqIdx = pair.indexOf("=");
|
|
267
|
-
if (eqIdx > 0) {
|
|
268
|
-
params[pair.slice(0, eqIdx)] = decodeURIComponent(
|
|
269
|
-
pair.slice(eqIdx + 1)
|
|
270
|
-
);
|
|
271
|
-
}
|
|
629
|
+
export function checkToolLinkage(m: Message): void {
|
|
630
|
+
const hasCalls = (m.toolCalls?.length ?? 0) > 0;
|
|
631
|
+
if (m.role === "tool") {
|
|
632
|
+
if (hasCalls || (m.parts?.length ?? 0) > 0) {
|
|
633
|
+
throw new LLMError(
|
|
634
|
+
`tool result "${m.toolCallId ?? ""}" carries only content`
|
|
635
|
+
);
|
|
272
636
|
}
|
|
637
|
+
return;
|
|
273
638
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
639
|
+
if (m.toolCallId) {
|
|
640
|
+
throw new LLMError(
|
|
641
|
+
`toolCallId is valid only on role tool, got "${m.role}"`
|
|
642
|
+
);
|
|
277
643
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
let model: string;
|
|
283
|
-
|
|
284
|
-
const hostPortMatch = rest.match(/^([^/]+:\d+)\/(.+)$/);
|
|
285
|
-
if (hostPortMatch) {
|
|
286
|
-
host = hostPortMatch[1];
|
|
287
|
-
model = hostPortMatch[2];
|
|
288
|
-
} else {
|
|
289
|
-
model = rest;
|
|
644
|
+
if (hasCalls && m.role !== "assistant") {
|
|
645
|
+
throw new LLMError(
|
|
646
|
+
`toolCalls are valid only on role assistant, got "${m.role}"`
|
|
647
|
+
);
|
|
290
648
|
}
|
|
649
|
+
}
|
|
291
650
|
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
651
|
+
// ─── Media sources ───────────────────────────────────────────────────────────
|
|
652
|
+
|
|
653
|
+
/** In-memory media bytes with a caller-supplied MIME type. */
|
|
654
|
+
export function inlineSource(data: Uint8Array, mimeType: string): MediaSource {
|
|
655
|
+
return {
|
|
656
|
+
url: () => "",
|
|
657
|
+
mimeType: () => mimeType,
|
|
658
|
+
read: async () => data,
|
|
659
|
+
};
|
|
296
660
|
}
|
|
297
661
|
|
|
298
|
-
|
|
662
|
+
/** Options for {@link urlSource}. */
|
|
663
|
+
export interface URLSourceOptions {
|
|
664
|
+
/** Body cap in bytes (default {@link DEFAULT_MAX_MEDIA_BYTES}). */
|
|
665
|
+
maxBytes?: number;
|
|
666
|
+
}
|
|
299
667
|
|
|
300
668
|
/**
|
|
301
|
-
*
|
|
302
|
-
*
|
|
303
|
-
* When `uriStr` is empty/undefined, falls back to `LLM_PROVIDER`
|
|
304
|
-
* env var as a full default URI. If neither is provided, throws.
|
|
305
|
-
*
|
|
306
|
-
* URI query params `api_key` and `base_url` populate provider
|
|
307
|
-
* config. If `uri.host` is set, it derives a baseURL. Env vars
|
|
308
|
-
* `LLM_API_KEY` and `LLM_BASE_URL` override last.
|
|
669
|
+
* URL-backed media; `read()` downloads lazily.
|
|
309
670
|
*
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
*
|
|
314
|
-
*
|
|
671
|
+
* The download is guarded against server-side request forgery: http or
|
|
672
|
+
* https only, public addresses only (checked on what is dialed, so DNS
|
|
673
|
+
* rebinding cannot redirect it), no redirects, no proxy, at most
|
|
674
|
+
* `maxBytes` (32 MiB by default; {@link MediaTooLargeError} past it),
|
|
675
|
+
* 30s, and `--offline`. Refusals are {@link MediaURLRefusedError}.
|
|
676
|
+
* Adapters whose provider accepts a URL (Anthropic images and PDFs,
|
|
677
|
+
* OpenAI images) send the URL and never read it. Local or private
|
|
678
|
+
* media: read it yourself and pass {@link inlineSource} or
|
|
679
|
+
* {@link fileSource}.
|
|
315
680
|
*/
|
|
316
|
-
export function
|
|
317
|
-
const
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
)
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
const uri = parseURI(effective);
|
|
325
|
-
|
|
326
|
-
const fallbackEnv = process.env["LLM_FALLBACK"];
|
|
327
|
-
const fallbacks = fallbackEnv
|
|
328
|
-
? fallbackEnv.split(",").map((s) => s.trim()).filter(Boolean)
|
|
329
|
-
: [];
|
|
330
|
-
|
|
331
|
-
const provider: ProviderConfig = {
|
|
332
|
-
model: uri.model,
|
|
681
|
+
export function urlSource(url: string, opts: URLSourceOptions = {}): MediaSource {
|
|
682
|
+
const maxBytes = opts.maxBytes && opts.maxBytes > 0 ? opts.maxBytes : DEFAULT_MAX_MEDIA_BYTES;
|
|
683
|
+
return {
|
|
684
|
+
url: () => url,
|
|
685
|
+
mimeType: () => "",
|
|
686
|
+
read: () => fetchMedia(url, maxBytes),
|
|
333
687
|
};
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
// Extract api_key and base_url from URI query params
|
|
337
|
-
if (uri.params?.api_key) {
|
|
338
|
-
provider.apiKey = uri.params.api_key;
|
|
339
|
-
}
|
|
340
|
-
if (uri.params?.base_url) {
|
|
341
|
-
provider.baseURL = uri.params.base_url;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
// Derive baseURL from host if present
|
|
345
|
-
if (uri.host) {
|
|
346
|
-
provider.baseURL = `http://${uri.host}`;
|
|
347
|
-
}
|
|
688
|
+
}
|
|
348
689
|
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
690
|
+
const MIME_BY_EXT: Record<string, string> = {
|
|
691
|
+
".png": "image/png",
|
|
692
|
+
".jpg": "image/jpeg",
|
|
693
|
+
".jpeg": "image/jpeg",
|
|
694
|
+
".gif": "image/gif",
|
|
695
|
+
".webp": "image/webp",
|
|
696
|
+
".pdf": "application/pdf",
|
|
697
|
+
".mp3": "audio/mpeg",
|
|
698
|
+
".wav": "audio/wav",
|
|
699
|
+
".ogg": "audio/ogg",
|
|
700
|
+
".mp4": "video/mp4",
|
|
701
|
+
".webm": "video/webm",
|
|
702
|
+
".mov": "video/quicktime",
|
|
703
|
+
};
|
|
354
704
|
|
|
355
|
-
|
|
705
|
+
/**
|
|
706
|
+
* File on disk, read on `read()`. The MIME type comes from the
|
|
707
|
+
* extension (common image, PDF, audio and video types); unknown
|
|
708
|
+
* extensions give `""`, so set {@link ContentPart.mimeType} instead.
|
|
709
|
+
*/
|
|
710
|
+
export function fileSource(path: string): MediaSource {
|
|
711
|
+
return {
|
|
712
|
+
url: () => "",
|
|
713
|
+
mimeType: () => MIME_BY_EXT[extname(path).toLowerCase()] ?? "",
|
|
714
|
+
read: async () => new Uint8Array(await readFile(path)),
|
|
715
|
+
};
|
|
356
716
|
}
|
|
357
717
|
|
|
358
718
|
// ─── Registry ────────────────────────────────────────────────────────────────
|
|
359
719
|
|
|
360
720
|
export type Factory = (cfg: ResolvedConfig) => Provider;
|
|
361
721
|
|
|
722
|
+
/**
|
|
723
|
+
* What an adapter states about its scheme: the endpoints its
|
|
724
|
+
* credentials may go to besides loopback, `LLM_BASE_URL` and the
|
|
725
|
+
* adapter's own base URL variable (see {@link credentialsTrusted}).
|
|
726
|
+
*/
|
|
727
|
+
export type { Declaration };
|
|
728
|
+
|
|
362
729
|
const registry = new Map<string, Factory>();
|
|
363
730
|
|
|
364
731
|
/** Register a provider factory for the given URI scheme. */
|
|
365
|
-
export function register(
|
|
732
|
+
export function register(
|
|
733
|
+
scheme: string,
|
|
734
|
+
factory: Factory,
|
|
735
|
+
decl?: Declaration
|
|
736
|
+
): void {
|
|
366
737
|
if (registry.has(scheme)) {
|
|
367
738
|
throw new LLMError(`provider already registered for scheme: ${scheme}`);
|
|
368
739
|
}
|
|
369
740
|
registry.set(scheme, factory);
|
|
741
|
+
setDeclaration(scheme, decl);
|
|
370
742
|
}
|
|
371
743
|
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
744
|
+
export { declarationOf };
|
|
745
|
+
|
|
746
|
+
/**
|
|
747
|
+
* Resolve a URI to a Provider instance via the registry. With
|
|
748
|
+
* `opts.hermetic` neither the config nor the adapter reads anything
|
|
749
|
+
* ambient (see {@link LoadOptions}).
|
|
750
|
+
*/
|
|
751
|
+
export function resolve(uriStr: string, opts: LoadOptions = {}): Provider {
|
|
752
|
+
const cfg = loadConfig(uriStr, opts);
|
|
375
753
|
const factory = registry.get(cfg.uri.scheme);
|
|
376
754
|
if (!factory) {
|
|
377
755
|
throw new ProviderNotFoundError(cfg.uri.scheme);
|
|
@@ -382,11 +760,12 @@ export function resolve(uriStr: string): Provider {
|
|
|
382
760
|
/** Clear the registry (for tests). */
|
|
383
761
|
export function clearRegistry(): void {
|
|
384
762
|
registry.clear();
|
|
763
|
+
clearDeclarations();
|
|
385
764
|
}
|
|
386
765
|
|
|
387
766
|
// ─── Client ──────────────────────────────────────────────────────────────────
|
|
388
767
|
|
|
389
|
-
export interface ClientOptions {
|
|
768
|
+
export interface ClientOptions extends LoadOptions {
|
|
390
769
|
fallback?: string[];
|
|
391
770
|
onRequest?: (req: Request) => void;
|
|
392
771
|
onResponse?: (resp: Response, durationMs: number) => void;
|
|
@@ -398,6 +777,11 @@ export interface Client {
|
|
|
398
777
|
complete(req: Request): Promise<Response>;
|
|
399
778
|
stream(req: Request): AsyncIterable<Token>;
|
|
400
779
|
callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse>;
|
|
780
|
+
/**
|
|
781
|
+
* Streams a tool-calling completion; falls back like {@link stream},
|
|
782
|
+
* before the first token only.
|
|
783
|
+
*/
|
|
784
|
+
streamWithTools(req: Request, tools: ToolDef[]): ToolStream;
|
|
401
785
|
capabilities(): string[];
|
|
402
786
|
provider(): Provider;
|
|
403
787
|
close(): void;
|
|
@@ -410,13 +794,14 @@ export interface Client {
|
|
|
410
794
|
* On fallbackable errors, it tries each fallback URI in order.
|
|
411
795
|
*/
|
|
412
796
|
export function createLLM(uri: string, opts?: ClientOptions): Client {
|
|
413
|
-
const
|
|
797
|
+
const load: LoadOptions = { hermetic: opts?.hermetic };
|
|
798
|
+
const cfg = loadConfig(uri, load);
|
|
414
799
|
|
|
415
800
|
// Merge fallbacks: opts > env > none
|
|
416
801
|
const fallbackURIs = opts?.fallback ?? cfg.fallbacks;
|
|
417
802
|
|
|
418
803
|
// Resolve primary; cache fallback providers for close()
|
|
419
|
-
const primary = resolve(uri);
|
|
804
|
+
const primary = resolve(uri, load);
|
|
420
805
|
const allURIs = [uri, ...fallbackURIs];
|
|
421
806
|
const resolvedProviders = new Map<number, Provider>();
|
|
422
807
|
resolvedProviders.set(0, primary);
|
|
@@ -424,7 +809,7 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
|
|
|
424
809
|
function resolveAt(index: number): Provider {
|
|
425
810
|
let p = resolvedProviders.get(index);
|
|
426
811
|
if (!p) {
|
|
427
|
-
p = resolve(allURIs[index]);
|
|
812
|
+
p = resolve(allURIs[index], load);
|
|
428
813
|
resolvedProviders.set(index, p);
|
|
429
814
|
}
|
|
430
815
|
return p;
|
|
@@ -469,6 +854,76 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
|
|
|
469
854
|
throw new FallbackExhaustedError(errors);
|
|
470
855
|
}
|
|
471
856
|
|
|
857
|
+
// Routes a stream through fallback: on creation or first-token
|
|
858
|
+
// failure with a fallbackable/capability error, the next provider is
|
|
859
|
+
// tried. Once a token arrived, errors pass through.
|
|
860
|
+
function fallbackStream(
|
|
861
|
+
request: Request,
|
|
862
|
+
op: "stream" | "streamWithTools",
|
|
863
|
+
open: (p: Provider) => AsyncIterable<Token>
|
|
864
|
+
): ToolStream {
|
|
865
|
+
let inner: AsyncIterator<Token> | null = null;
|
|
866
|
+
let source: AsyncIterable<Token> | null = null;
|
|
867
|
+
let initialized = false;
|
|
868
|
+
|
|
869
|
+
async function first(): Promise<IteratorResult<Token>> {
|
|
870
|
+
opts?.onRequest?.(request);
|
|
871
|
+
const errors: Error[] = [];
|
|
872
|
+
for (let i = 0; i < allURIs.length; i++) {
|
|
873
|
+
try {
|
|
874
|
+
const p = resolveAt(i);
|
|
875
|
+
if (typeof p[op] !== "function") {
|
|
876
|
+
throw new CapabilityNotSupportedError(
|
|
877
|
+
op,
|
|
878
|
+
parseURI(allURIs[i]).scheme
|
|
879
|
+
);
|
|
880
|
+
}
|
|
881
|
+
const iterable = open(p);
|
|
882
|
+
const iter = iterable[Symbol.asyncIterator]();
|
|
883
|
+
// Attempt first read to detect immediate failures
|
|
884
|
+
const head = await iter.next();
|
|
885
|
+
inner = iter;
|
|
886
|
+
source = iterable;
|
|
887
|
+
return head;
|
|
888
|
+
} catch (err) {
|
|
889
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
890
|
+
errors.push(e);
|
|
891
|
+
opts?.onError?.(e);
|
|
892
|
+
const canContinue =
|
|
893
|
+
isFallbackable(e) || e instanceof CapabilityNotSupportedError;
|
|
894
|
+
if (!canContinue || i === allURIs.length - 1) {
|
|
895
|
+
if (errors.length > 1) throw new FallbackExhaustedError(errors);
|
|
896
|
+
throw e;
|
|
897
|
+
}
|
|
898
|
+
opts?.onFallback?.(i, i + 1, e);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
throw new FallbackExhaustedError(errors);
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
return {
|
|
905
|
+
[Symbol.asyncIterator]() {
|
|
906
|
+
return {
|
|
907
|
+
async next(): Promise<IteratorResult<Token>> {
|
|
908
|
+
if (!initialized) {
|
|
909
|
+
initialized = true;
|
|
910
|
+
return first();
|
|
911
|
+
}
|
|
912
|
+
return inner!.next();
|
|
913
|
+
},
|
|
914
|
+
async return(): Promise<IteratorResult<Token>> {
|
|
915
|
+
await inner?.return?.();
|
|
916
|
+
return { value: undefined, done: true };
|
|
917
|
+
},
|
|
918
|
+
};
|
|
919
|
+
},
|
|
920
|
+
outcome(): StreamOutcome | undefined {
|
|
921
|
+
const s = source as Partial<ToolStream> | null;
|
|
922
|
+
return typeof s?.outcome === "function" ? s.outcome() : undefined;
|
|
923
|
+
},
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
|
|
472
927
|
return {
|
|
473
928
|
async complete(request: Request): Promise<Response> {
|
|
474
929
|
opts?.onRequest?.(request);
|
|
@@ -481,63 +936,13 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
|
|
|
481
936
|
},
|
|
482
937
|
|
|
483
938
|
stream(request: Request): AsyncIterable<Token> {
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
return {
|
|
492
|
-
async next(): Promise<IteratorResult<Token>> {
|
|
493
|
-
if (!initialized) {
|
|
494
|
-
initialized = true;
|
|
495
|
-
opts?.onRequest?.(request);
|
|
496
|
-
|
|
497
|
-
const errors: Error[] = [];
|
|
498
|
-
for (let i = 0; i < allURIs.length; i++) {
|
|
499
|
-
try {
|
|
500
|
-
const p = resolveAt(i);
|
|
501
|
-
if (
|
|
502
|
-
!("stream" in p) ||
|
|
503
|
-
typeof p.stream !== "function"
|
|
504
|
-
) {
|
|
505
|
-
throw new CapabilityNotSupportedError(
|
|
506
|
-
"stream",
|
|
507
|
-
parseURI(allURIs[i]).scheme
|
|
508
|
-
);
|
|
509
|
-
}
|
|
510
|
-
const iterable = p.stream(request);
|
|
511
|
-
const iter = iterable[Symbol.asyncIterator]();
|
|
512
|
-
// Attempt first read to detect immediate failures
|
|
513
|
-
const first = await iter.next();
|
|
514
|
-
inner = iter;
|
|
515
|
-
return first;
|
|
516
|
-
} catch (err) {
|
|
517
|
-
const e =
|
|
518
|
-
err instanceof Error
|
|
519
|
-
? err
|
|
520
|
-
: new Error(String(err));
|
|
521
|
-
errors.push(e);
|
|
522
|
-
opts?.onError?.(e);
|
|
523
|
-
const canContinue =
|
|
524
|
-
isFallbackable(e) ||
|
|
525
|
-
e instanceof CapabilityNotSupportedError;
|
|
526
|
-
if (!canContinue || i === allURIs.length - 1) {
|
|
527
|
-
if (errors.length > 1)
|
|
528
|
-
throw new FallbackExhaustedError(errors);
|
|
529
|
-
throw e;
|
|
530
|
-
}
|
|
531
|
-
opts?.onFallback?.(i, i + 1, e);
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
throw new FallbackExhaustedError(errors);
|
|
535
|
-
}
|
|
536
|
-
return inner!.next();
|
|
537
|
-
},
|
|
538
|
-
};
|
|
539
|
-
},
|
|
540
|
-
};
|
|
939
|
+
return fallbackStream(request, "stream", (p) => p.stream!(request));
|
|
940
|
+
},
|
|
941
|
+
|
|
942
|
+
streamWithTools(request: Request, tools: ToolDef[]): ToolStream {
|
|
943
|
+
return fallbackStream(request, "streamWithTools", (p) =>
|
|
944
|
+
p.streamWithTools!(request, tools)
|
|
945
|
+
);
|
|
541
946
|
},
|
|
542
947
|
|
|
543
948
|
async callWithTools(
|
|
@@ -550,7 +955,13 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
|
|
|
550
955
|
p.callWithTools!(request, tools)
|
|
551
956
|
);
|
|
552
957
|
opts?.onResponse?.(
|
|
553
|
-
{
|
|
958
|
+
{
|
|
959
|
+
content: resp.content,
|
|
960
|
+
role: "assistant",
|
|
961
|
+
usage: resp.usage,
|
|
962
|
+
finishReason: resp.finishReason,
|
|
963
|
+
thinking: resp.thinking,
|
|
964
|
+
},
|
|
554
965
|
Date.now() - start
|
|
555
966
|
);
|
|
556
967
|
return resp;
|
|
@@ -561,6 +972,7 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
|
|
|
561
972
|
if (primary.complete) caps.push("complete");
|
|
562
973
|
if (primary.stream) caps.push("stream");
|
|
563
974
|
if (primary.callWithTools) caps.push("callWithTools");
|
|
975
|
+
if (primary.streamWithTools) caps.push("streamWithTools");
|
|
564
976
|
return caps;
|
|
565
977
|
},
|
|
566
978
|
|