@hop-top/kit 0.5.0-alpha.2 → 0.5.0-alpha.4
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 +60 -0
- package/LICENSE +1 -1
- package/README.md +48 -480
- package/dist/{aim-CTp-kJW2.d.ts → aim-DZHwwiIc.d.ts} +1 -1
- package/dist/aim.d.ts +1 -1
- package/dist/aim.js +13 -414
- package/dist/{alias-dhhr08Ei.d.ts → alias-BOj0-VAr.d.ts} +1 -1
- package/dist/alias.d.ts +1 -1
- package/dist/alias.js +18 -206
- package/dist/{api-miiso81x.d.ts → api-DAexsu2H.d.ts} +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +10 -164
- package/dist/auth.js +6 -40
- package/dist/chunk-3FIKGFKI.js +54 -0
- package/dist/chunk-4UE5TCMQ.js +104 -0
- package/dist/chunk-6HFAEZ52.js +29 -0
- package/dist/chunk-6SVOHNIC.js +17 -0
- package/dist/chunk-72XZWQX7.js +504 -0
- package/dist/chunk-ABQSE7AI.js +513 -0
- package/dist/chunk-BDNNPRX6.js +41 -0
- package/dist/chunk-BRNEKPWX.js +37 -0
- package/dist/chunk-CSJWB6D3.js +151 -0
- package/dist/chunk-GGWJRWWA.js +309 -0
- package/dist/chunk-IQXEISMC.js +142 -0
- package/dist/chunk-JTMPNXVQ.js +1491 -0
- package/dist/chunk-KVG7YCTS.js +115 -0
- package/dist/chunk-L23O2FFE.js +51 -0
- package/dist/chunk-MQXYDYRD.js +968 -0
- package/dist/chunk-MUIQVU6E.js +251 -0
- package/dist/chunk-POR5L2DG.js +247 -0
- package/dist/chunk-PSFYJGDG.js +1445 -0
- package/dist/chunk-QJVSKKRQ.js +369 -0
- package/dist/chunk-QPUCXQXT.js +67 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-S45UHXQF.js +182 -0
- package/dist/chunk-T46YPHKN.js +669 -0
- package/dist/chunk-UIOOOK6M.js +334 -0
- package/dist/chunk-UKZIAQA7.js +26 -0
- package/dist/chunk-WBVO43HU.js +355 -0
- package/dist/chunk-WTYDHXPW.js +574 -0
- package/dist/chunk-WUOAQVOA.js +86 -0
- package/dist/chunk-WWUKGJB5.js +90 -0
- package/dist/chunk-YGYQUFGY.js +219 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/{cli-DgOEOsPB.d.ts → cli-8rfITnv4.d.ts} +13 -4
- package/dist/cli.d.ts +4 -3
- package/dist/cli.js +50 -1056
- package/dist/{config-BUY7_W2n.d.ts → config-Bm9fBXch.d.ts} +35 -4
- package/dist/config.d.ts +1 -1
- package/dist/config.js +6 -78
- package/dist/errcorrect.js +8 -68
- package/dist/error-Do8Qji43.d.ts +231 -0
- package/dist/id/index.d.ts +1 -1
- package/dist/id/index.js +14 -65
- package/dist/{index-MLrRDvEG.d.ts → index-B-pqGHhU.d.ts} +113 -19
- package/dist/{index--C7Mtsmm.d.ts → index-DEyjGoo2.d.ts} +1 -1
- package/dist/{index-QSffbLnj.d.ts → index-VLDcI5NF.d.ts} +3 -2
- package/dist/index.d.ts +18 -13
- package/dist/index.js +40 -5792
- package/dist/llm-DYuR7_uX.d.ts +1069 -0
- package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
- package/dist/llm-anthropic.d.ts +2 -0
- package/dist/llm-anthropic.js +13 -0
- package/dist/llm-openai-DyFrucmV.d.ts +87 -0
- package/dist/llm-openai.d.ts +2 -0
- package/dist/llm-openai.js +19 -0
- package/dist/llm.d.ts +1 -1
- package/dist/llm.js +101 -356
- package/dist/mcp/index.d.ts +2 -1
- package/dist/mcp/index.js +155 -1453
- package/dist/{netpolicy-asvCfwi8.d.ts → netpolicy-Brx5XZUB.d.ts} +16 -3
- package/dist/netpolicy.d.ts +1 -1
- package/dist/netpolicy.js +25 -118
- package/dist/{output-VFFLqor9.d.ts → output-CjZWmL8s.d.ts} +29 -130
- package/dist/output.d.ts +2 -1
- package/dist/output.js +137 -958
- package/dist/progress.js +6 -55
- package/dist/provenance.js +6 -31
- package/dist/routellm-B0nv59mH.d.ts +111 -0
- package/dist/routellm.d.ts +2 -2
- package/dist/routellm.js +13 -255
- package/dist/{rpc-D5xLEf8V.d.ts → rpc-D31Lg0Kc.d.ts} +1 -1
- package/dist/rpc.d.ts +2 -2
- package/dist/rpc.js +4 -98
- package/dist/safety.js +6 -43
- package/dist/scope.js +20 -377
- package/dist/serve-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.js +8 -51
- package/dist/telemetry/index.js +24 -608
- package/dist/tui/index.d.ts +5 -4
- package/dist/tui/index.js +17 -373
- package/dist/upgrade.js +6 -114
- package/dist/xdg.js +14 -128
- package/package.json +135 -25
- package/src/README.md +15 -0
- package/src/cli.test.ts +56 -1
- package/src/cli.ts +24 -4
- package/src/completion-values.test.ts +10 -10
- package/src/compliance.test.ts +196 -2
- package/src/compliance.ts +440 -20
- package/src/config.test.ts +187 -1
- package/src/config.ts +173 -7
- package/src/gen/crud_pb.ts +7 -7
- package/src/id/README.md +38 -0
- package/src/id/contract.test.ts +1 -1
- package/src/id/index.test.ts +1 -1
- package/src/id/index.ts +3 -2
- package/src/index.test.ts +12 -0
- package/src/index.ts +3 -0
- package/src/llm-anthropic.conformance.test.ts +1135 -0
- package/src/llm-anthropic.test.ts +152 -0
- package/src/llm-anthropic.ts +940 -0
- package/src/llm-choice-hermetic.test.ts +335 -0
- package/src/llm-config.test.ts +232 -0
- package/src/llm-config.ts +106 -0
- package/src/llm-endpoint.ts +254 -0
- package/src/llm-error.ts +17 -0
- package/src/llm-errors.ts +152 -0
- package/src/llm-file.ts +126 -0
- package/src/llm-http.ts +317 -0
- package/src/llm-keys.ts +167 -0
- package/src/llm-media.conformance.test.ts +87 -0
- package/src/llm-media.test.ts +279 -0
- package/src/llm-media.ts +322 -0
- package/src/llm-openai.conformance.test.ts +407 -0
- package/src/llm-openai.test.ts +510 -0
- package/src/llm-openai.ts +708 -0
- package/src/llm-payload.ts +155 -0
- package/src/llm-quote.ts +46 -0
- package/src/llm-routellm.conformance.test.ts +44 -0
- package/src/llm-toolnames.conformance.test.ts +112 -0
- package/src/llm-toolnames.test.ts +132 -0
- package/src/llm-toolnames.ts +298 -0
- package/src/llm-uri.ts +99 -0
- package/src/llm.test.ts +43 -15
- package/src/llm.toolcall.test.ts +175 -0
- package/src/llm.ts +602 -190
- package/src/mcp/README.md +57 -0
- package/src/mcp/conformance.test.ts +24 -3
- package/src/mcp/dispatch.ts +4 -4
- package/src/mcp/identity.test.ts +166 -0
- package/src/mcp/identity.ts +72 -0
- package/src/mcp/index.ts +6 -0
- package/src/mcp/legacy.ts +21 -8
- package/src/mcp/mcp.test.ts +14 -4
- package/src/mcp/modern-confirm.ts +1 -1
- package/src/mcp/modern.ts +12 -11
- package/src/mcp/tasks.ts +1 -1
- package/src/mcp/types.ts +80 -8
- package/src/netpolicy.test.ts +78 -0
- package/src/netpolicy.ts +28 -3
- package/src/output/README.md +46 -0
- package/src/output/builtins.ts +5 -5
- package/src/output/error.ts +167 -1
- package/src/output/formatters/README.md +50 -0
- package/src/output.ts +26 -1
- package/src/published-types.test.ts +115 -0
- package/src/routellm.test.ts +209 -28
- package/src/routellm.toolcall.test.ts +521 -0
- package/src/routellm.ts +213 -177
- package/src/router/README.md +44 -0
- package/src/router/server.test.ts +41 -0
- package/src/router/server.ts +11 -0
- package/src/safety.test.ts +19 -9
- package/src/scope-defaults.json +29 -29
- package/src/serve.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/telemetry/README.md +48 -0
- package/src/telemetry/client.ts +5 -5
- package/src/toolspec.test.ts +2 -2
- package/src/triton/README.md +34 -0
- package/src/tui/README.md +42 -0
- package/src/wizard.test.ts +7 -7
- package/test/llm/conformance-helpers.ts +100 -0
- package/test/output/dispatch.test.ts +1 -2
- package/test/output/error.test.ts +38 -2
- package/test/output/smoke-capture.ts +2 -2
- package/test/output/smoke.test.ts +2 -2
- package/test/output/taxonomy-contract.test.ts +148 -0
- package/test/setup-env.ts +16 -0
- package/tsconfig.json +3 -1
- package/tsconfig.test.json +10 -0
- package/vitest.config.ts +9 -0
- package/dist/llm-B5XUWH8T.d.ts +0 -231
- package/dist/routellm-PGSt2D1y.d.ts +0 -75
|
@@ -0,0 +1,940 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
*
|
|
4
|
+
* Anthropic Messages API adapter — registers the `anthropic` URI scheme
|
|
5
|
+
* on import. Implements complete, stream, callWithTools and
|
|
6
|
+
* streamWithTools, with extended thinking and prompt caching.
|
|
7
|
+
*
|
|
8
|
+
* URI: `anthropic://<model>[?params]`. Params: `tool_names`
|
|
9
|
+
* (`sanitize` | `strict`), `max_body_bytes`, `max_event_bytes`. The key
|
|
10
|
+
* resolves as `loadConfig` resolves it (the URI's `api_key`, llm.yaml,
|
|
11
|
+
* `ANTHROPIC_API_KEY`, then `LLM_API_KEY`);
|
|
12
|
+
* `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` and
|
|
13
|
+
* `ANTHROPIC_WORKSPACE_ID` are read from the environment. The token and
|
|
14
|
+
* workspace header go only to a trusted origin (the default endpoint,
|
|
15
|
+
* `ANTHROPIC_BASE_URL`, llm.yaml `base_url`, `LLM_BASE_URL`, loopback);
|
|
16
|
+
* no credential goes over plain http to a remote host. A hermetic config
|
|
17
|
+
* ({@link ResolvedConfig.hermetic}) reads none of these variables.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* import "@hop-top/kit/anthropic";
|
|
22
|
+
* import { createLLM } from "@hop-top/kit/llm";
|
|
23
|
+
*
|
|
24
|
+
* const llm = createLLM("anthropic://claude-sonnet-4-5");
|
|
25
|
+
* const r = await llm.complete({ messages: [{ role: "user", content: "Hi" }] });
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import {
|
|
30
|
+
ANTHROPIC_TOOL_NAMES,
|
|
31
|
+
AuthError,
|
|
32
|
+
LLMError,
|
|
33
|
+
ModelError,
|
|
34
|
+
PermissionDeniedError,
|
|
35
|
+
RateLimitError,
|
|
36
|
+
ToolNames,
|
|
37
|
+
checkToolChoice,
|
|
38
|
+
register,
|
|
39
|
+
toolNameModeOf,
|
|
40
|
+
type CacheControl,
|
|
41
|
+
type Completer,
|
|
42
|
+
type ContentPart,
|
|
43
|
+
type Message,
|
|
44
|
+
type Provider,
|
|
45
|
+
type Request,
|
|
46
|
+
type ResolvedConfig,
|
|
47
|
+
type Response,
|
|
48
|
+
type StreamOutcome,
|
|
49
|
+
type Streamer,
|
|
50
|
+
type ThinkingBlock,
|
|
51
|
+
type Token,
|
|
52
|
+
type ToolCall,
|
|
53
|
+
type ToolCaller,
|
|
54
|
+
type ToolChoice,
|
|
55
|
+
type ToolDef,
|
|
56
|
+
type ToolNameMode,
|
|
57
|
+
type ToolResponse,
|
|
58
|
+
type ToolStream,
|
|
59
|
+
type ToolStreamer,
|
|
60
|
+
type Usage,
|
|
61
|
+
} from "./llm";
|
|
62
|
+
import {
|
|
63
|
+
checkKeyEndpoint,
|
|
64
|
+
credentialsTrusted,
|
|
65
|
+
redactURI,
|
|
66
|
+
} from "./llm-endpoint";
|
|
67
|
+
import { APIError, HTTPStatusError, StreamTruncatedError } from "./llm-errors";
|
|
68
|
+
import {
|
|
69
|
+
joinURL,
|
|
70
|
+
limitsFrom,
|
|
71
|
+
post,
|
|
72
|
+
readBody,
|
|
73
|
+
scrubError,
|
|
74
|
+
sseEvents,
|
|
75
|
+
type ErrorResponse,
|
|
76
|
+
type Limits,
|
|
77
|
+
type TransportOptions,
|
|
78
|
+
} from "./llm-http";
|
|
79
|
+
|
|
80
|
+
const SCHEME = "anthropic";
|
|
81
|
+
/** The Messages API's default endpoint. */
|
|
82
|
+
export const ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com";
|
|
83
|
+
const API_VERSION = "2023-06-01";
|
|
84
|
+
const DEFAULT_MAX_TOKENS = 1024;
|
|
85
|
+
/** The API's least thinking budget. */
|
|
86
|
+
const MIN_THINKING_BUDGET = 1024;
|
|
87
|
+
/** Joins consecutive system messages into one text. */
|
|
88
|
+
const SYSTEM_SEPARATOR = "\n\n";
|
|
89
|
+
|
|
90
|
+
/** An API error type and the HTTP status it stands for. */
|
|
91
|
+
const EVENT_STATUS: Record<string, number> = {
|
|
92
|
+
invalid_request_error: 400,
|
|
93
|
+
authentication_error: 401,
|
|
94
|
+
billing_error: 402,
|
|
95
|
+
permission_error: 403,
|
|
96
|
+
not_found_error: 404,
|
|
97
|
+
request_too_large: 413,
|
|
98
|
+
rate_limit_error: 429,
|
|
99
|
+
api_error: 500,
|
|
100
|
+
timeout_error: 504,
|
|
101
|
+
overloaded_error: 529,
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
type Block = Record<string, unknown>;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Anthropic Messages API adapter over fetch. Construct it directly with
|
|
108
|
+
* a resolved config, or import the module and resolve an `anthropic://`
|
|
109
|
+
* URI.
|
|
110
|
+
*/
|
|
111
|
+
export class AnthropicAdapter
|
|
112
|
+
implements Completer, Streamer, ToolCaller, ToolStreamer
|
|
113
|
+
{
|
|
114
|
+
readonly model: string;
|
|
115
|
+
readonly baseURL: string;
|
|
116
|
+
private readonly headers: Record<string, string>;
|
|
117
|
+
private readonly secrets: string[];
|
|
118
|
+
private readonly limits: Limits;
|
|
119
|
+
private readonly toolNames: ToolNameMode;
|
|
120
|
+
|
|
121
|
+
constructor(cfg: ResolvedConfig) {
|
|
122
|
+
const key = cfg.provider.apiKey ?? "";
|
|
123
|
+
if (key.trim() === "") throw new LLMError("anthropic: API key required");
|
|
124
|
+
this.limits = limitsFrom(SCHEME, cfg.provider.params);
|
|
125
|
+
try {
|
|
126
|
+
this.toolNames = toolNameModeOf(cfg.provider.params);
|
|
127
|
+
} catch (err) {
|
|
128
|
+
throw new LLMError(`anthropic: ${(err as Error).message}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// A hermetic adapter reads no environment variable.
|
|
132
|
+
const env = envReader(cfg);
|
|
133
|
+
const envBase = env("ANTHROPIC_BASE_URL");
|
|
134
|
+
if (envBase !== undefined) checkBaseURL("ANTHROPIC_BASE_URL", envBase);
|
|
135
|
+
if (cfg.provider.baseURL) checkBaseURL("base URL", cfg.provider.baseURL);
|
|
136
|
+
const base = cfg.provider.baseURL || envBase || ANTHROPIC_DEFAULT_BASE_URL;
|
|
137
|
+
this.baseURL = base;
|
|
138
|
+
this.model = cfg.provider.model || cfg.uri?.model || "";
|
|
139
|
+
|
|
140
|
+
// Every credential passes one gate: none over plain http to a
|
|
141
|
+
// remote host or to a malformed endpoint; the env token and
|
|
142
|
+
// workspace header only to a trusted origin.
|
|
143
|
+
checkKeyEndpoint(SCHEME, key, base);
|
|
144
|
+
this.headers = {
|
|
145
|
+
"content-type": "application/json",
|
|
146
|
+
accept: "application/json",
|
|
147
|
+
"anthropic-version": API_VERSION,
|
|
148
|
+
"x-api-key": key,
|
|
149
|
+
};
|
|
150
|
+
const token = env("ANTHROPIC_AUTH_TOKEN") ?? "";
|
|
151
|
+
const extra: Record<string, string> = {};
|
|
152
|
+
if (token.trim() !== "") {
|
|
153
|
+
checkKeyEndpoint(SCHEME, token, base);
|
|
154
|
+
extra["authorization"] = `Bearer ${token}`;
|
|
155
|
+
}
|
|
156
|
+
const ws = env("ANTHROPIC_WORKSPACE_ID") ?? "";
|
|
157
|
+
if (ws !== "") extra["anthropic-workspace-id"] = ws;
|
|
158
|
+
const trusted = [ANTHROPIC_DEFAULT_BASE_URL];
|
|
159
|
+
if (envBase) trusted.push(envBase);
|
|
160
|
+
// With neither, the trust check (which reads LLM_BASE_URL) is not
|
|
161
|
+
// asked.
|
|
162
|
+
if (Object.keys(extra).length > 0 && credentialsTrusted(SCHEME, base, ...trusted)) {
|
|
163
|
+
Object.assign(this.headers, extra);
|
|
164
|
+
}
|
|
165
|
+
this.secrets = [key, token].filter((s) => s.trim() !== "");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
close(): void {
|
|
169
|
+
// fetch holds no per-adapter resources.
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async complete(req: Request): Promise<Response> {
|
|
173
|
+
const names = this.toolNameMap([]);
|
|
174
|
+
const body = await this.buildBody(req, names);
|
|
175
|
+
setToolChoice(body, req.toolChoice, [], names);
|
|
176
|
+
const msg = await this.send(body, req);
|
|
177
|
+
return {
|
|
178
|
+
content: textOf(msg),
|
|
179
|
+
role: "assistant",
|
|
180
|
+
finishReason: msg.stop_reason ?? "",
|
|
181
|
+
usage: usageOf(msg.usage),
|
|
182
|
+
thinking: thinkingBlocks(msg),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse> {
|
|
187
|
+
const names = this.toolNameMap(tools);
|
|
188
|
+
const body = await this.buildBody(req, names);
|
|
189
|
+
body["tools"] = mapTools(names.defs(tools));
|
|
190
|
+
setToolChoice(body, req.toolChoice, tools, names);
|
|
191
|
+
const msg = await this.send(body, req);
|
|
192
|
+
return toolResponseOf(msg, names);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
stream(req: Request): ToolStream {
|
|
196
|
+
return this.openStream(req, undefined);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
streamWithTools(req: Request, tools: ToolDef[]): ToolStream {
|
|
200
|
+
return this.openStream(req, tools);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ── private ────────────────────────────────────────────────────
|
|
204
|
+
|
|
205
|
+
private toolNameMap(tools: ReadonlyArray<{ name: string }>): ToolNames {
|
|
206
|
+
return ToolNames.build(ANTHROPIC_TOOL_NAMES, this.toolNames, tools);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private transport(req: Request): TransportOptions {
|
|
210
|
+
const model = req.model || this.model;
|
|
211
|
+
return {
|
|
212
|
+
provider: SCHEME,
|
|
213
|
+
secrets: this.secrets,
|
|
214
|
+
limits: this.limits,
|
|
215
|
+
mapError: (r) => mapErrorResponse(r, model),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private async send(body: Block, req: Request): Promise<WireMessage> {
|
|
220
|
+
const opts = this.transport(req);
|
|
221
|
+
const resp = await post(opts, this.url(), this.headers, body);
|
|
222
|
+
const text = await readBody(resp, this.limits.body, SCHEME).catch((e) => {
|
|
223
|
+
throw scrubError(e as Error, this.secrets);
|
|
224
|
+
});
|
|
225
|
+
try {
|
|
226
|
+
return JSON.parse(text) as WireMessage;
|
|
227
|
+
} catch {
|
|
228
|
+
throw new LLMError("anthropic: response is not valid JSON");
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
private url(): string {
|
|
233
|
+
return joinURL(this.baseURL, "v1/messages");
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private openStream(req: Request, tools: ToolDef[] | undefined): ToolStream {
|
|
237
|
+
let outcome: StreamOutcome | undefined;
|
|
238
|
+
const gen = this.run(req, tools, (o) => {
|
|
239
|
+
outcome = o;
|
|
240
|
+
});
|
|
241
|
+
return {
|
|
242
|
+
[Symbol.asyncIterator]: () => gen,
|
|
243
|
+
outcome: () => outcome,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
private async *run(
|
|
248
|
+
req: Request,
|
|
249
|
+
tools: ToolDef[] | undefined,
|
|
250
|
+
done: (o: StreamOutcome) => void
|
|
251
|
+
): AsyncGenerator<Token> {
|
|
252
|
+
const names = this.toolNameMap(tools ?? []);
|
|
253
|
+
const body = await this.buildBody(req, names);
|
|
254
|
+
if (tools) body["tools"] = mapTools(names.defs(tools));
|
|
255
|
+
setToolChoice(body, req.toolChoice, tools ?? [], names);
|
|
256
|
+
body["stream"] = true;
|
|
257
|
+
const opts = this.transport(req);
|
|
258
|
+
const resp = await post(opts, this.url(), {
|
|
259
|
+
...this.headers,
|
|
260
|
+
accept: "text/event-stream",
|
|
261
|
+
}, body);
|
|
262
|
+
const acc = new Accumulator();
|
|
263
|
+
const events = req.streamEvents ? new EventMapper(acc, names) : undefined;
|
|
264
|
+
try {
|
|
265
|
+
for await (const ev of sseEvents(resp, this.limits.event, SCHEME)) {
|
|
266
|
+
let evt: StreamEvent;
|
|
267
|
+
try {
|
|
268
|
+
evt = JSON.parse(ev.data) as StreamEvent;
|
|
269
|
+
} catch {
|
|
270
|
+
throw new LLMError("anthropic: stream event is not valid JSON");
|
|
271
|
+
}
|
|
272
|
+
if (evt.type === "error") {
|
|
273
|
+
throw streamError(evt.error, req.model || this.model);
|
|
274
|
+
}
|
|
275
|
+
acc.add(evt);
|
|
276
|
+
const d = evt.delta ?? {};
|
|
277
|
+
if (evt.type === "content_block_delta" && d.type === "text_delta") {
|
|
278
|
+
yield { content: d.text ?? "", done: false };
|
|
279
|
+
} else if (
|
|
280
|
+
evt.type === "content_block_delta" &&
|
|
281
|
+
d.type === "thinking_delta" &&
|
|
282
|
+
req.thinking
|
|
283
|
+
) {
|
|
284
|
+
yield { content: "", thinking: d.thinking ?? "", done: false };
|
|
285
|
+
} else if (evt.type === "message_stop") {
|
|
286
|
+
done(acc.outcome(names));
|
|
287
|
+
yield { content: "", done: true };
|
|
288
|
+
return;
|
|
289
|
+
} else {
|
|
290
|
+
const tok = events?.map(evt);
|
|
291
|
+
if (tok) yield tok;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
} catch (err) {
|
|
295
|
+
throw scrubError(err as Error, this.secrets);
|
|
296
|
+
}
|
|
297
|
+
// No message_stop: the response is incomplete.
|
|
298
|
+
throw new StreamTruncatedError(SCHEME);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
private async buildBody(req: Request, names: ToolNames): Promise<Block> {
|
|
302
|
+
const maxTokens =
|
|
303
|
+
req.maxTokens !== undefined && req.maxTokens > 0
|
|
304
|
+
? req.maxTokens
|
|
305
|
+
: DEFAULT_MAX_TOKENS;
|
|
306
|
+
const { system, messages } = await extractSystem(req.messages, names);
|
|
307
|
+
const body: Block = {
|
|
308
|
+
model: req.model || this.model,
|
|
309
|
+
max_tokens: maxTokens,
|
|
310
|
+
messages,
|
|
311
|
+
};
|
|
312
|
+
if (system.length > 0) body["system"] = system;
|
|
313
|
+
if (req.thinking) {
|
|
314
|
+
const b = req.thinking.budgetTokens;
|
|
315
|
+
if (b < MIN_THINKING_BUDGET) {
|
|
316
|
+
throw new LLMError(
|
|
317
|
+
`anthropic: thinking budget_tokens must be at least ${MIN_THINKING_BUDGET}, got ${b}`
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
if (b >= maxTokens) {
|
|
321
|
+
throw new LLMError(
|
|
322
|
+
`anthropic: thinking budget_tokens (${b}) must be less than max_tokens (${maxTokens})`
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
body["thinking"] = { type: "enabled", budget_tokens: b };
|
|
326
|
+
}
|
|
327
|
+
if (req.temperature !== undefined) body["temperature"] = req.temperature;
|
|
328
|
+
if (req.stopSequences?.length) body["stop_sequences"] = req.stopSequences;
|
|
329
|
+
return body;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Reads the environment, or nothing for a hermetic config. */
|
|
334
|
+
function envReader(cfg: ResolvedConfig): (k: string) => string | undefined {
|
|
335
|
+
return cfg.hermetic ? () => undefined : (k) => process.env[k];
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function checkBaseURL(what: string, base: string): void {
|
|
339
|
+
try {
|
|
340
|
+
new URL(base);
|
|
341
|
+
} catch {
|
|
342
|
+
throw new LLMError(`anthropic: invalid ${what}: ${JSON.stringify(redactURI(base))}`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ─── Request mapping ─────────────────────────────────────────────────────────
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Separates the system messages from the conversation: the API takes
|
|
350
|
+
* system as a top-level field. See {@link systemBlocks}.
|
|
351
|
+
*/
|
|
352
|
+
async function extractSystem(
|
|
353
|
+
msgs: Message[],
|
|
354
|
+
names: ToolNames
|
|
355
|
+
): Promise<{ system: Block[]; messages: Block[] }> {
|
|
356
|
+
const system = systemBlocks(msgs);
|
|
357
|
+
const out: { role: string; content: Block[] }[] = [];
|
|
358
|
+
|
|
359
|
+
for (let i = 0; i < msgs.length; i++) {
|
|
360
|
+
const m = msgs[i]!;
|
|
361
|
+
if (m.role === "system") continue;
|
|
362
|
+
checkLinkageRole(m);
|
|
363
|
+
|
|
364
|
+
if (m.role === "tool") {
|
|
365
|
+
const block = toolResultBlock(m);
|
|
366
|
+
setCache(block, m.cacheControl);
|
|
367
|
+
// Consecutive results answer one assistant turn and belong in a
|
|
368
|
+
// single user message.
|
|
369
|
+
if (i > 0 && msgs[i - 1]!.role === "tool" && out.length > 0) {
|
|
370
|
+
out[out.length - 1]!.content.push(block);
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
out.push({ role: "user", content: [block] });
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
let blocks: Block[] = [];
|
|
378
|
+
const calls = m.toolCalls ?? [];
|
|
379
|
+
if (m.parts?.length) {
|
|
380
|
+
blocks = await mapParts(m.parts);
|
|
381
|
+
} else if (calls.length === 0 || m.content !== "") {
|
|
382
|
+
blocks.push({ type: "text", text: m.content });
|
|
383
|
+
}
|
|
384
|
+
blocks.push(...toolUseBlocks(calls, names));
|
|
385
|
+
if (blocks.length > 0) setCache(blocks[blocks.length - 1]!, m.cacheControl);
|
|
386
|
+
// Thinking blocks lead the turn, unchanged and in order.
|
|
387
|
+
blocks = [...replayThinking(m.thinking ?? []), ...blocks];
|
|
388
|
+
out.push({ role: m.role, content: blocks });
|
|
389
|
+
}
|
|
390
|
+
return { system, messages: out };
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Every system message, wherever it sits, as the system field: their
|
|
395
|
+
* content joined in order with a blank line ({@link SYSTEM_SEPARATOR}),
|
|
396
|
+
* empty ones skipped. A `cacheControl` on a system message ends a text
|
|
397
|
+
* block there and carries that breakpoint, so each breakpoint caches
|
|
398
|
+
* exactly the text up to it; the next system message starts a new
|
|
399
|
+
* block. No system text yields no blocks.
|
|
400
|
+
*/
|
|
401
|
+
function systemBlocks(msgs: Message[]): Block[] {
|
|
402
|
+
const out: Block[] = [];
|
|
403
|
+
let text = "";
|
|
404
|
+
for (const m of msgs) {
|
|
405
|
+
if (m.role !== "system") continue;
|
|
406
|
+
if (m.content !== "") {
|
|
407
|
+
text = text === "" ? m.content : text + SYSTEM_SEPARATOR + m.content;
|
|
408
|
+
}
|
|
409
|
+
if (!m.cacheControl || text === "") continue;
|
|
410
|
+
out.push({ type: "text", text, cache_control: cacheParam(m.cacheControl) });
|
|
411
|
+
text = "";
|
|
412
|
+
}
|
|
413
|
+
if (text !== "") out.push({ type: "text", text });
|
|
414
|
+
return out;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Rejects tool-call linkage on a role that cannot carry it: toolCalls
|
|
419
|
+
* and thinking belong to assistant turns, toolCallId to tool results.
|
|
420
|
+
*/
|
|
421
|
+
function checkLinkageRole(m: Message): void {
|
|
422
|
+
if ((m.toolCalls?.length ?? 0) > 0 && m.role !== "assistant") {
|
|
423
|
+
throw new LLMError(
|
|
424
|
+
`anthropic: ToolCalls are valid only on role assistant, got ${JSON.stringify(m.role)}`
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
if ((m.thinking?.length ?? 0) > 0 && m.role !== "assistant") {
|
|
428
|
+
throw new LLMError(
|
|
429
|
+
`anthropic: Thinking is valid only on role assistant, got ${JSON.stringify(m.role)}`
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
if (m.toolCallId && m.role !== "tool") {
|
|
433
|
+
throw new LLMError(
|
|
434
|
+
`anthropic: ToolCallID is valid only on role tool, got ${JSON.stringify(m.role)}`
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function toolResultBlock(m: Message): Block {
|
|
440
|
+
if (!m.toolCallId) {
|
|
441
|
+
throw new LLMError("anthropic: tool result needs ToolCallID");
|
|
442
|
+
}
|
|
443
|
+
if (m.parts?.length) {
|
|
444
|
+
throw new LLMError(
|
|
445
|
+
`anthropic: tool result ${JSON.stringify(m.toolCallId)} carries only Content`
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
const res: Block = { type: "tool_result", tool_use_id: m.toolCallId };
|
|
449
|
+
// The API rejects empty text blocks, so an empty result sends none.
|
|
450
|
+
if (m.content) res["content"] = [{ type: "text", text: m.content }];
|
|
451
|
+
return res;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** An assistant turn's calls as tool_use blocks, under their wire names. */
|
|
455
|
+
function toolUseBlocks(calls: ToolCall[], names: ToolNames): Block[] {
|
|
456
|
+
return calls.map((tc) => {
|
|
457
|
+
if (!tc.id) {
|
|
458
|
+
throw new LLMError(`anthropic: tool call ${JSON.stringify(tc.name)} needs an ID`);
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
type: "tool_use",
|
|
462
|
+
id: tc.id,
|
|
463
|
+
name: names.wire(tc.name),
|
|
464
|
+
input: inputOf(tc),
|
|
465
|
+
};
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** A call's arguments as a JSON value: a string must parse; none is `{}`. */
|
|
470
|
+
function inputOf(tc: ToolCall): unknown {
|
|
471
|
+
const args = tc.arguments;
|
|
472
|
+
if (args === undefined || args === null || args === "") return {};
|
|
473
|
+
if (typeof args !== "string") return args;
|
|
474
|
+
try {
|
|
475
|
+
return JSON.parse(args);
|
|
476
|
+
} catch {
|
|
477
|
+
throw new LLMError(
|
|
478
|
+
`anthropic: tool call ${JSON.stringify(tc.id)} arguments are not valid JSON`
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function replayThinking(tbs: ThinkingBlock[]): Block[] {
|
|
484
|
+
return tbs.map((tb) =>
|
|
485
|
+
tb.redacted
|
|
486
|
+
? { type: "redacted_thinking", data: tb.redacted }
|
|
487
|
+
: { type: "thinking", thinking: tb.thinking, signature: tb.signature }
|
|
488
|
+
);
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** A cache breakpoint as the wire takes it; undefined for none. */
|
|
492
|
+
function cacheParam(cc: CacheControl | undefined): Block | undefined {
|
|
493
|
+
if (!cc) return undefined;
|
|
494
|
+
const ttl = cc.ttl ?? "";
|
|
495
|
+
if (ttl === "") return { type: "ephemeral" };
|
|
496
|
+
if (ttl === "5m" || ttl === "1h") return { type: "ephemeral", ttl };
|
|
497
|
+
throw new LLMError(
|
|
498
|
+
`anthropic: cache_control ttl must be "5m" or "1h", got ${JSON.stringify(ttl)}`
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function setCache(block: Block, cc: CacheControl | undefined): void {
|
|
503
|
+
const p = cacheParam(cc);
|
|
504
|
+
if (p) block["cache_control"] = p;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
async function mapParts(parts: ContentPart[]): Promise<Block[]> {
|
|
508
|
+
const out: Block[] = [];
|
|
509
|
+
for (const p of parts) {
|
|
510
|
+
switch (p.type) {
|
|
511
|
+
case "text":
|
|
512
|
+
out.push({ type: "text", text: p.text ?? "" });
|
|
513
|
+
break;
|
|
514
|
+
case "image": {
|
|
515
|
+
const mime = p.mimeType || p.source?.mimeType() || "";
|
|
516
|
+
if (!mime) throw new LLMError("anthropic: image part needs a MIME type");
|
|
517
|
+
if (!p.source) throw new LLMError("anthropic: nil media source");
|
|
518
|
+
// The API takes a URL source for images and PDFs: the provider
|
|
519
|
+
// fetches it, so nothing is downloaded here.
|
|
520
|
+
const url = p.source.url();
|
|
521
|
+
if (url) {
|
|
522
|
+
out.push({ type: mime === "application/pdf" ? "document" : "image", source: { type: "url", url } });
|
|
523
|
+
break;
|
|
524
|
+
}
|
|
525
|
+
const data = Buffer.from(await p.source.read()).toString("base64");
|
|
526
|
+
out.push(
|
|
527
|
+
mime === "application/pdf"
|
|
528
|
+
? { type: "document", source: { type: "base64", media_type: mime, data } }
|
|
529
|
+
: { type: "image", source: { type: "base64", media_type: mime, data } }
|
|
530
|
+
);
|
|
531
|
+
break;
|
|
532
|
+
}
|
|
533
|
+
default:
|
|
534
|
+
throw new LLMError(`anthropic: unsupported modality ${JSON.stringify(p.type)}`);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
return out;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Sets the body's `tool_choice` for `c`, checked against `tools`; a
|
|
542
|
+
* named tool goes by the name the request sends for it. Unset `c` sends
|
|
543
|
+
* none.
|
|
544
|
+
*/
|
|
545
|
+
function setToolChoice(
|
|
546
|
+
body: Block,
|
|
547
|
+
c: ToolChoice | undefined,
|
|
548
|
+
tools: ReadonlyArray<{ name: string }>,
|
|
549
|
+
names: ToolNames
|
|
550
|
+
): void {
|
|
551
|
+
try {
|
|
552
|
+
checkToolChoice(c, tools);
|
|
553
|
+
} catch (err) {
|
|
554
|
+
throw new LLMError(`anthropic: ${(err as Error).message}`);
|
|
555
|
+
}
|
|
556
|
+
if (!c) return;
|
|
557
|
+
body["tool_choice"] =
|
|
558
|
+
c.mode === "tool" ? { type: "tool", name: names.wire(c.name ?? "") } : { type: c.mode };
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Tool definitions as the API takes them. `input_schema` is required: a
|
|
563
|
+
* tool without parameters, or with ones that are not a JSON object,
|
|
564
|
+
* takes an empty object schema.
|
|
565
|
+
*/
|
|
566
|
+
function mapTools(defs: ToolDef[]): Block[] {
|
|
567
|
+
return defs.map((d) => {
|
|
568
|
+
const t: Block = {
|
|
569
|
+
name: d.name,
|
|
570
|
+
description: d.description ?? "",
|
|
571
|
+
input_schema: schemaOf(d.parameters),
|
|
572
|
+
};
|
|
573
|
+
const cc = cacheParam(d.cacheControl);
|
|
574
|
+
if (cc) t["cache_control"] = cc;
|
|
575
|
+
return t;
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function schemaOf(params: unknown): Block {
|
|
580
|
+
let v = params;
|
|
581
|
+
if (typeof v === "string") {
|
|
582
|
+
try {
|
|
583
|
+
v = JSON.parse(v);
|
|
584
|
+
} catch {
|
|
585
|
+
v = undefined;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (typeof v !== "object" || v === null || Array.isArray(v)) {
|
|
589
|
+
return { type: "object", properties: {} };
|
|
590
|
+
}
|
|
591
|
+
return { type: "object", ...(v as Block) };
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// ─── Response mapping ────────────────────────────────────────────────────────
|
|
595
|
+
|
|
596
|
+
interface WireBlock {
|
|
597
|
+
type: string;
|
|
598
|
+
text?: string;
|
|
599
|
+
id?: string;
|
|
600
|
+
name?: string;
|
|
601
|
+
input?: unknown;
|
|
602
|
+
thinking?: string;
|
|
603
|
+
signature?: string;
|
|
604
|
+
data?: string;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
interface WireUsage {
|
|
608
|
+
input_tokens?: number;
|
|
609
|
+
output_tokens?: number;
|
|
610
|
+
cache_read_input_tokens?: number | null;
|
|
611
|
+
cache_creation_input_tokens?: number | null;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
interface WireMessage {
|
|
615
|
+
content?: WireBlock[];
|
|
616
|
+
stop_reason?: string | null;
|
|
617
|
+
usage?: WireUsage;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function textOf(msg: WireMessage): string {
|
|
621
|
+
return (msg.content ?? [])
|
|
622
|
+
.filter((b) => b.type === "text")
|
|
623
|
+
.map((b) => b.text ?? "")
|
|
624
|
+
.join("");
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function usageOf(u: WireUsage | undefined): Usage {
|
|
628
|
+
const out = {
|
|
629
|
+
promptTokens: u?.input_tokens ?? 0,
|
|
630
|
+
completionTokens: u?.output_tokens ?? 0,
|
|
631
|
+
cacheReadTokens: u?.cache_read_input_tokens ?? 0,
|
|
632
|
+
cacheCreationTokens: u?.cache_creation_input_tokens ?? 0,
|
|
633
|
+
totalTokens: 0,
|
|
634
|
+
};
|
|
635
|
+
out.totalTokens =
|
|
636
|
+
out.promptTokens +
|
|
637
|
+
out.completionTokens +
|
|
638
|
+
out.cacheReadTokens +
|
|
639
|
+
out.cacheCreationTokens;
|
|
640
|
+
return out;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function thinkingBlocks(msg: WireMessage): ThinkingBlock[] {
|
|
644
|
+
const out: ThinkingBlock[] = [];
|
|
645
|
+
for (const b of msg.content ?? []) {
|
|
646
|
+
if (b.type === "thinking") {
|
|
647
|
+
out.push({ thinking: b.thinking ?? "", signature: b.signature ?? "", redacted: "" });
|
|
648
|
+
} else if (b.type === "redacted_thinking") {
|
|
649
|
+
out.push({ thinking: "", signature: "", redacted: b.data ?? "" });
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
return out;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/** A tool_use block as a call carrying the name the caller defined. */
|
|
656
|
+
function toolCallOf(b: WireBlock, names: ToolNames): ToolCall {
|
|
657
|
+
return { id: b.id ?? "", name: names.original(b.name ?? ""), arguments: b.input ?? {} };
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** Maps `msg`; each call carries the name the caller defined. */
|
|
661
|
+
function toolResponseOf(msg: WireMessage, names: ToolNames): ToolResponse {
|
|
662
|
+
const calls: ToolCall[] = [];
|
|
663
|
+
for (const b of msg.content ?? []) {
|
|
664
|
+
if (b.type === "tool_use") calls.push(toolCallOf(b, names));
|
|
665
|
+
}
|
|
666
|
+
return {
|
|
667
|
+
content: textOf(msg),
|
|
668
|
+
toolCalls: calls,
|
|
669
|
+
thinking: thinkingBlocks(msg),
|
|
670
|
+
finishReason: msg.stop_reason ?? "",
|
|
671
|
+
usage: usageOf(msg.usage),
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// ─── Streaming ───────────────────────────────────────────────────────────────
|
|
676
|
+
|
|
677
|
+
interface StreamEvent {
|
|
678
|
+
type: string;
|
|
679
|
+
index?: number;
|
|
680
|
+
message?: WireMessage;
|
|
681
|
+
content_block?: WireBlock;
|
|
682
|
+
delta?: {
|
|
683
|
+
type?: string;
|
|
684
|
+
text?: string;
|
|
685
|
+
thinking?: string;
|
|
686
|
+
signature?: string;
|
|
687
|
+
partial_json?: string;
|
|
688
|
+
stop_reason?: string | null;
|
|
689
|
+
};
|
|
690
|
+
usage?: WireUsage;
|
|
691
|
+
error?: { type?: string; message?: string };
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** A block being streamed; tool input accumulates as raw JSON. */
|
|
695
|
+
interface AccBlock extends WireBlock {
|
|
696
|
+
inputRaw?: string;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* Folds stream events into the finished message, as the Go SDK's
|
|
701
|
+
* Message.Accumulate does: blocks start in index order, deltas address
|
|
702
|
+
* a started block, usage totals overwrite.
|
|
703
|
+
*/
|
|
704
|
+
class Accumulator {
|
|
705
|
+
private content: AccBlock[] = [];
|
|
706
|
+
private stopReason = "";
|
|
707
|
+
private usage_: WireUsage = {};
|
|
708
|
+
|
|
709
|
+
add(evt: StreamEvent): void {
|
|
710
|
+
switch (evt.type) {
|
|
711
|
+
case "message_start": {
|
|
712
|
+
const m = evt.message ?? {};
|
|
713
|
+
this.content = (m.content ?? []).map((b) => ({ ...b }));
|
|
714
|
+
this.stopReason = m.stop_reason ?? "";
|
|
715
|
+
this.usage_ = { ...(m.usage ?? {}) };
|
|
716
|
+
break;
|
|
717
|
+
}
|
|
718
|
+
case "message_delta": {
|
|
719
|
+
this.stopReason = evt.delta?.stop_reason ?? "";
|
|
720
|
+
const u = evt.usage ?? {};
|
|
721
|
+
this.usage_.output_tokens = u.output_tokens ?? 0;
|
|
722
|
+
if (u.input_tokens !== undefined) this.usage_.input_tokens = u.input_tokens;
|
|
723
|
+
if (u.cache_read_input_tokens != null) {
|
|
724
|
+
this.usage_.cache_read_input_tokens = u.cache_read_input_tokens;
|
|
725
|
+
}
|
|
726
|
+
if (u.cache_creation_input_tokens != null) {
|
|
727
|
+
this.usage_.cache_creation_input_tokens = u.cache_creation_input_tokens;
|
|
728
|
+
}
|
|
729
|
+
break;
|
|
730
|
+
}
|
|
731
|
+
case "content_block_start": {
|
|
732
|
+
if (evt.index !== this.content.length) {
|
|
733
|
+
throw new LLMError(
|
|
734
|
+
`anthropic: received event of type content_block_start for content block at index ${evt.index}, expected index ${this.content.length}`
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
const b: AccBlock = { ...(evt.content_block ?? { type: "" }) };
|
|
738
|
+
if (b.type === "tool_use") b.inputRaw = JSON.stringify(b.input ?? {});
|
|
739
|
+
this.content.push(b);
|
|
740
|
+
break;
|
|
741
|
+
}
|
|
742
|
+
case "content_block_delta": {
|
|
743
|
+
const i = evt.index ?? -1;
|
|
744
|
+
if (i < 0 || i >= this.content.length) {
|
|
745
|
+
throw new LLMError(
|
|
746
|
+
`anthropic: received event of type content_block_delta for content block at index ${i}, only ${this.content.length} blocks exist`
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
const b = this.content[i]!;
|
|
750
|
+
const d = evt.delta ?? {};
|
|
751
|
+
switch (d.type) {
|
|
752
|
+
case "text_delta":
|
|
753
|
+
b.text = (b.text ?? "") + (d.text ?? "");
|
|
754
|
+
break;
|
|
755
|
+
case "input_json_delta":
|
|
756
|
+
if (d.partial_json) {
|
|
757
|
+
b.inputRaw =
|
|
758
|
+
b.inputRaw === "{}" || b.inputRaw === undefined
|
|
759
|
+
? d.partial_json
|
|
760
|
+
: b.inputRaw + d.partial_json;
|
|
761
|
+
}
|
|
762
|
+
break;
|
|
763
|
+
case "thinking_delta":
|
|
764
|
+
b.thinking = (b.thinking ?? "") + (d.thinking ?? "");
|
|
765
|
+
break;
|
|
766
|
+
case "signature_delta":
|
|
767
|
+
b.signature = (b.signature ?? "") + (d.signature ?? "");
|
|
768
|
+
break;
|
|
769
|
+
}
|
|
770
|
+
break;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** The usage folded so far. */
|
|
776
|
+
usage(): Usage {
|
|
777
|
+
return usageOf(this.usage_);
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/** The block at content index `i`, undefined when none started. */
|
|
781
|
+
block(i: number): AccBlock | undefined {
|
|
782
|
+
return this.content[i];
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/** The tool_use block at `i` as its finished call. */
|
|
786
|
+
call(i: number, names: ToolNames): ToolCall {
|
|
787
|
+
return toolCallOf(finished(this.content[i]!), names);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
outcome(names: ToolNames): StreamOutcome {
|
|
791
|
+
const msg: WireMessage = {
|
|
792
|
+
content: this.content.map(finished),
|
|
793
|
+
stop_reason: this.stopReason,
|
|
794
|
+
usage: this.usage_,
|
|
795
|
+
};
|
|
796
|
+
const tr = toolResponseOf(msg, names);
|
|
797
|
+
return {
|
|
798
|
+
content: tr.content,
|
|
799
|
+
thinking: tr.thinking ?? [],
|
|
800
|
+
toolCalls: tr.toolCalls,
|
|
801
|
+
finishReason: tr.finishReason ?? "",
|
|
802
|
+
usage: tr.usage!,
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/** A streamed block as the finished message holds it: tool input parsed. */
|
|
808
|
+
function finished(b: AccBlock): WireBlock {
|
|
809
|
+
return b.type === "tool_use" ? { ...b, input: parseInput(b.inputRaw) } : b;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* Maps accumulated stream events to tool-call and usage tokens, for a
|
|
814
|
+
* request that asked for them ({@link Request.streamEvents}).
|
|
815
|
+
*/
|
|
816
|
+
class EventMapper {
|
|
817
|
+
/** A tool_use block's content index to its call index. */
|
|
818
|
+
private readonly calls = new Map<number, number>();
|
|
819
|
+
|
|
820
|
+
constructor(
|
|
821
|
+
private readonly acc: Accumulator,
|
|
822
|
+
private readonly names: ToolNames
|
|
823
|
+
) {}
|
|
824
|
+
|
|
825
|
+
/** The token `evt`, already folded into the accumulator, makes. */
|
|
826
|
+
map(evt: StreamEvent): Token | undefined {
|
|
827
|
+
const at = evt.index ?? -1;
|
|
828
|
+
switch (evt.type) {
|
|
829
|
+
case "message_start":
|
|
830
|
+
case "message_delta":
|
|
831
|
+
return { content: "", usage: this.acc.usage(), done: false };
|
|
832
|
+
case "content_block_start": {
|
|
833
|
+
const b = this.acc.block(at);
|
|
834
|
+
if (b?.type !== "tool_use") return undefined;
|
|
835
|
+
const index = this.calls.size;
|
|
836
|
+
this.calls.set(at, index);
|
|
837
|
+
return {
|
|
838
|
+
content: "",
|
|
839
|
+
toolCall: { kind: "start", index, id: b.id ?? "", name: this.names.original(b.name ?? "") },
|
|
840
|
+
done: false,
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
case "content_block_delta": {
|
|
844
|
+
const index = this.calls.get(at);
|
|
845
|
+
const d = evt.delta ?? {};
|
|
846
|
+
if (index === undefined || d.type !== "input_json_delta" || !d.partial_json) {
|
|
847
|
+
return undefined;
|
|
848
|
+
}
|
|
849
|
+
return {
|
|
850
|
+
content: "",
|
|
851
|
+
toolCall: { kind: "delta", index, argumentsDelta: d.partial_json },
|
|
852
|
+
done: false,
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
case "content_block_stop": {
|
|
856
|
+
const index = this.calls.get(at);
|
|
857
|
+
if (index === undefined) return undefined;
|
|
858
|
+
const call = this.acc.call(at, this.names);
|
|
859
|
+
return {
|
|
860
|
+
content: "",
|
|
861
|
+
toolCall: { kind: "end", index, id: call.id, name: call.name, call },
|
|
862
|
+
done: false,
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
return undefined;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/** Streamed tool input: parsed JSON, or the raw text when it is not JSON. */
|
|
871
|
+
function parseInput(raw: string | undefined): unknown {
|
|
872
|
+
if (raw === undefined || raw === "") return {};
|
|
873
|
+
try {
|
|
874
|
+
return JSON.parse(raw);
|
|
875
|
+
} catch {
|
|
876
|
+
return raw;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// ─── Errors ──────────────────────────────────────────────────────────────────
|
|
881
|
+
|
|
882
|
+
interface WireError {
|
|
883
|
+
type?: string;
|
|
884
|
+
message?: string;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
function mapErrorResponse(r: ErrorResponse, model: string): Error {
|
|
888
|
+
let e: WireError = {};
|
|
889
|
+
try {
|
|
890
|
+
e = (JSON.parse(r.body) as { error?: WireError }).error ?? {};
|
|
891
|
+
} catch {
|
|
892
|
+
// not a JSON error body
|
|
893
|
+
}
|
|
894
|
+
const detail = e.message !== undefined
|
|
895
|
+
? `${e.type ?? "error"}: ${e.message}`
|
|
896
|
+
: r.body.slice(0, 2048);
|
|
897
|
+
return classify(r.status, e.type ?? "", `anthropic: ${r.status} ${detail}`.trim(), model);
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/**
|
|
901
|
+
* An SSE error event arrives on a 200 response: classify it by the
|
|
902
|
+
* status its error type stands for (overloaded_error is a 529).
|
|
903
|
+
*/
|
|
904
|
+
function streamError(e: WireError | undefined, model: string): Error {
|
|
905
|
+
const type = e?.type ?? "";
|
|
906
|
+
const status = EVENT_STATUS[type] ?? 0;
|
|
907
|
+
return classify(status, type, `anthropic: stream error: ${type}: ${e?.message ?? ""}`, model);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
function classify(status: number, type: string, message: string, model: string): Error {
|
|
911
|
+
const api = new APIError(SCHEME, status, type, message);
|
|
912
|
+
switch (status) {
|
|
913
|
+
case 401:
|
|
914
|
+
return new AuthError(SCHEME, api);
|
|
915
|
+
case 403:
|
|
916
|
+
return new PermissionDeniedError(SCHEME, api);
|
|
917
|
+
case 429:
|
|
918
|
+
return new RateLimitError(SCHEME);
|
|
919
|
+
case 404:
|
|
920
|
+
return new ModelError(model, SCHEME);
|
|
921
|
+
}
|
|
922
|
+
if (status >= 500) return new HTTPStatusError(status, message);
|
|
923
|
+
return api;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// ─── Registration ────────────────────────────────────────────────────────────
|
|
927
|
+
|
|
928
|
+
function anthropicFactory(cfg: ResolvedConfig): Provider {
|
|
929
|
+
// loadConfig resolved and guarded the key.
|
|
930
|
+
const a = new AnthropicAdapter(cfg);
|
|
931
|
+
return {
|
|
932
|
+
complete: (req) => a.complete(req),
|
|
933
|
+
stream: (req) => a.stream(req),
|
|
934
|
+
callWithTools: (req, tools) => a.callWithTools(req, tools),
|
|
935
|
+
streamWithTools: (req, tools) => a.streamWithTools(req, tools),
|
|
936
|
+
close: () => a.close(),
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
register(SCHEME, anthropicFactory, { endpoints: [ANTHROPIC_DEFAULT_BASE_URL] });
|