@buildanagent/gateway 0.0.0-stage → 0.1.0-alpha.1
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/LICENSE +52 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +305 -2
- package/dist/adapters/anthropic/adapter.d.ts +25 -0
- package/dist/adapters/anthropic/adapter.js +183 -0
- package/dist/adapters/anthropic/adapter.js.map +1 -0
- package/dist/adapters/anthropic/failure.d.ts +27 -0
- package/dist/adapters/anthropic/failure.js +53 -0
- package/dist/adapters/anthropic/failure.js.map +1 -0
- package/dist/adapters/anthropic/index.d.ts +3 -0
- package/dist/adapters/anthropic/index.js +3 -0
- package/dist/adapters/anthropic/index.js.map +1 -0
- package/dist/adapters/anthropic/request.d.ts +53 -0
- package/dist/adapters/anthropic/request.js +250 -0
- package/dist/adapters/anthropic/request.js.map +1 -0
- package/dist/adapters/anthropic/response.d.ts +38 -0
- package/dist/adapters/anthropic/response.js +237 -0
- package/dist/adapters/anthropic/response.js.map +1 -0
- package/dist/adapters/anthropic/usage.d.ts +26 -0
- package/dist/adapters/anthropic/usage.js +39 -0
- package/dist/adapters/anthropic/usage.js.map +1 -0
- package/dist/adapters/openai-chat/adapter.d.ts +18 -0
- package/dist/adapters/openai-chat/adapter.js +86 -0
- package/dist/adapters/openai-chat/adapter.js.map +1 -0
- package/dist/adapters/openai-chat/compat.d.ts +58 -0
- package/dist/adapters/openai-chat/compat.js +19 -0
- package/dist/adapters/openai-chat/compat.js.map +1 -0
- package/dist/adapters/openai-chat/failure.d.ts +32 -0
- package/dist/adapters/openai-chat/failure.js +40 -0
- package/dist/adapters/openai-chat/failure.js.map +1 -0
- package/dist/adapters/openai-chat/index.d.ts +4 -0
- package/dist/adapters/openai-chat/index.js +3 -0
- package/dist/adapters/openai-chat/index.js.map +1 -0
- package/dist/adapters/openai-chat/request.d.ts +47 -0
- package/dist/adapters/openai-chat/request.js +227 -0
- package/dist/adapters/openai-chat/request.js.map +1 -0
- package/dist/adapters/openai-chat/response.d.ts +22 -0
- package/dist/adapters/openai-chat/response.js +203 -0
- package/dist/adapters/openai-chat/response.js.map +1 -0
- package/dist/adapters/openai-chat/usage.d.ts +22 -0
- package/dist/adapters/openai-chat/usage.js +25 -0
- package/dist/adapters/openai-chat/usage.js.map +1 -0
- package/dist/adapters/strict-schema.d.ts +67 -0
- package/dist/adapters/strict-schema.js +269 -0
- package/dist/adapters/strict-schema.js.map +1 -0
- package/dist/adapters/wire.d.ts +98 -0
- package/dist/adapters/wire.js +187 -0
- package/dist/adapters/wire.js.map +1 -0
- package/dist/catalog.d.ts +65 -0
- package/dist/catalog.js +145 -0
- package/dist/catalog.js.map +1 -0
- package/dist/catalog.json +120 -0
- package/dist/classify.d.ts +25 -0
- package/dist/classify.js +37 -0
- package/dist/classify.js.map +1 -0
- package/dist/complete.d.ts +9 -0
- package/dist/complete.js +13 -0
- package/dist/complete.js.map +1 -0
- package/dist/cost.d.ts +44 -0
- package/dist/cost.js +132 -0
- package/dist/cost.js.map +1 -0
- package/dist/create-model.d.ts +7 -0
- package/dist/create-model.js +81 -0
- package/dist/create-model.js.map +1 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +11 -0
- package/dist/middleware.js +22 -0
- package/dist/middleware.js.map +1 -0
- package/dist/names.d.ts +72 -0
- package/dist/names.js +175 -0
- package/dist/names.js.map +1 -0
- package/dist/provider-config.d.ts +15 -0
- package/dist/provider-config.js +23 -0
- package/dist/provider-config.js.map +1 -0
- package/dist/request-dump.d.ts +28 -0
- package/dist/request-dump.js +52 -0
- package/dist/request-dump.js.map +1 -0
- package/dist/request-policy.d.ts +18 -0
- package/dist/request-policy.js +27 -0
- package/dist/request-policy.js.map +1 -0
- package/dist/retry.d.ts +33 -0
- package/dist/retry.js +219 -0
- package/dist/retry.js.map +1 -0
- package/dist/runtime-types.d.ts +112 -0
- package/dist/runtime-types.js +2 -0
- package/dist/runtime-types.js.map +1 -0
- package/dist/spec.d.ts +67 -0
- package/dist/spec.js +2 -0
- package/dist/spec.js.map +1 -0
- package/dist/sse.d.ts +15 -0
- package/dist/sse.js +73 -0
- package/dist/sse.js.map +1 -0
- package/dist/stream-contract.d.ts +23 -0
- package/dist/stream-contract.js +101 -0
- package/dist/stream-contract.js.map +1 -0
- package/dist/testing/guards.d.ts +16 -0
- package/dist/testing/guards.js +48 -0
- package/dist/testing/guards.js.map +1 -0
- package/dist/testing/index.d.ts +12 -0
- package/dist/testing/index.js +13 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/mock-transport.d.ts +49 -0
- package/dist/testing/mock-transport.js +101 -0
- package/dist/testing/mock-transport.js.map +1 -0
- package/dist/testing/random.d.ts +3 -0
- package/dist/testing/random.js +13 -0
- package/dist/testing/random.js.map +1 -0
- package/dist/testing/setup.d.ts +1 -0
- package/dist/testing/setup.js +12 -0
- package/dist/testing/setup.js.map +1 -0
- package/dist/transform-messages.d.ts +32 -0
- package/dist/transform-messages.js +291 -0
- package/dist/transform-messages.js.map +1 -0
- package/dist/types.d.ts +143 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/usage.d.ts +16 -0
- package/dist/usage.js +31 -0
- package/dist/usage.js.map +1 -0
- package/package.json +50 -3
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { ProviderConfig } from "../../runtime-types.js";
|
|
2
|
+
import type { ModelAdapter } from "../../spec.js";
|
|
3
|
+
/** The Messages API version every request pins. */
|
|
4
|
+
export declare const ANTHROPIC_VERSION = "2026-10-21";
|
|
5
|
+
/** The beta that adds `thinking.block_binding` and the response's `input_transformations`. */
|
|
6
|
+
export declare const THINKING_BINDING_BETA = "thinking-binding-controls-2026-08-01";
|
|
7
|
+
/**
|
|
8
|
+
* Creates an adapter for Anthropic's Messages API. Every request goes to `{baseURL}/v1/messages` through
|
|
9
|
+
* `config.transport`, streams its response, and sends `anthropic-version: 2026-10-21` and the key from
|
|
10
|
+
* `config.apiKey`, which is the only key it sends. Throws a `GatewayError` with code `missing_api_key` when the key
|
|
11
|
+
* is missing or empty.
|
|
12
|
+
*
|
|
13
|
+
* The model's caps come from `options.caps`, which `createModel()` sets; a direct call without them uses
|
|
14
|
+
* `defaultCaps`. Caller headers from `config.headers` are sent with lower-case names; a caller `anthropic-beta` is
|
|
15
|
+
* merged with the adapter's beta, and a caller `x-api-key` or `authorization` is dropped.
|
|
16
|
+
*
|
|
17
|
+
* `providerOptions.anthropic` takes a `conversationId`, which marks requests of one conversation, and an `extraBody`,
|
|
18
|
+
* whose fields join the request body wherever the adapter sets no field of the same name. Without a
|
|
19
|
+
* `conversationId`, the adapter tells conversations apart by their system prompt and the text of their first
|
|
20
|
+
* message, so conversations that share both also share the `drop_block` setting; pass a `conversationId` for each
|
|
21
|
+
* conversation to keep them apart. The
|
|
22
|
+
* adapter remembers the last 1,000 conversations that needed `drop_block`. `temperature`, `top_p` and `top_k` are
|
|
23
|
+
* never sent, because this API version rejects them; the call streams a `warning` instead.
|
|
24
|
+
*/
|
|
25
|
+
export declare function anthropic(config: ProviderConfig): ModelAdapter;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `anthropic()`: the Anthropic Messages adapter over the gateway's `Transport` (D2). It streams every call and pins
|
|
3
|
+
* the API version.
|
|
4
|
+
*
|
|
5
|
+
* The thinking prefix check (HD3 rules 4 and 5): every request sends the `thinking-binding-controls-2026-08-01`
|
|
6
|
+
* beta header, so a 200 response lists each thinking block that failed the check and reached the model anyway in its
|
|
7
|
+
* `input_transformations`, and each such entry becomes a warning. A 400 that says a block "is bound to a different
|
|
8
|
+
* conversation" is retried once with `thinking.block_binding.prefix_mismatch_behavior: "drop_block"`, and the
|
|
9
|
+
* adapter sends that setting on every later request of the conversation, because the API applies it only to the
|
|
10
|
+
* request that carries it (Prefix checks on thinking blocks,
|
|
11
|
+
* https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/prefix-checks, as of November 2026).
|
|
12
|
+
*/
|
|
13
|
+
import { fnv1a } from "../../names.js";
|
|
14
|
+
import { resolveProviderConfig } from "../../provider-config.js";
|
|
15
|
+
import { payloadOf, readEventStream, sendRequest } from "../wire.js";
|
|
16
|
+
import { failureEvent, failureFromResponse, isPrefixMismatch } from "./failure.js";
|
|
17
|
+
import { anthropicOptions, buildRequest } from "./request.js";
|
|
18
|
+
import { MessageAssembler } from "./response.js";
|
|
19
|
+
/** The Messages API version every request pins. */
|
|
20
|
+
export const ANTHROPIC_VERSION = "2026-10-21";
|
|
21
|
+
/** The beta that adds `thinking.block_binding` and the response's `input_transformations`. */
|
|
22
|
+
export const THINKING_BINDING_BETA = "thinking-binding-controls-2026-08-01";
|
|
23
|
+
const DEFAULT_BASE_URL = "https://api.anthropic.com";
|
|
24
|
+
// The adapter's `defaultCaps`: the one fallback for a model with no caps, which `createModel()` uses for a model its
|
|
25
|
+
// catalog lacks and a direct `stream()` call without `options.caps` uses for any model. Every Claude model takes
|
|
26
|
+
// images, but an unlisted one may be an older model that rejects adaptive thinking, so it is sent no thinking setting
|
|
27
|
+
// and its own default applies.
|
|
28
|
+
const DEFAULT_CAPS = { contextWindow: 200_000, maxOutputTokens: 32_000, images: true, reasoning: false };
|
|
29
|
+
// How many conversations the adapter remembers as needing `drop_block`. A conversation pushed out sends the setting
|
|
30
|
+
// no more; its next mismatch costs one more 400 and puts it back.
|
|
31
|
+
const DROP_BLOCK_MEMORY = 1_000;
|
|
32
|
+
/** A set of keys that keeps the `limit` most recently used, so a long-lived adapter's memory stays bounded. */
|
|
33
|
+
class RecentKeys {
|
|
34
|
+
#keys = new Set();
|
|
35
|
+
#limit;
|
|
36
|
+
constructor(limit) {
|
|
37
|
+
this.#limit = limit;
|
|
38
|
+
}
|
|
39
|
+
/** True when the key is held; a hit counts as a use. */
|
|
40
|
+
has(key) {
|
|
41
|
+
if (!this.#keys.has(key))
|
|
42
|
+
return false;
|
|
43
|
+
this.add(key);
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
add(key) {
|
|
47
|
+
this.#keys.delete(key);
|
|
48
|
+
this.#keys.add(key);
|
|
49
|
+
// A Set iterates in insertion order, so its first key is the least recently used.
|
|
50
|
+
const oldest = this.#keys.size > this.#limit ? this.#keys.values().next().value : undefined;
|
|
51
|
+
if (oldest !== undefined)
|
|
52
|
+
this.#keys.delete(oldest);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The conversation a call belongs to: its caller-given id, or else an FNV-1a hash of its system prompt and first
|
|
57
|
+
* message. Two conversations that share both share the hash, so one's `drop_block` reaches the other; a
|
|
58
|
+
* `conversationId` keeps them apart.
|
|
59
|
+
*/
|
|
60
|
+
function conversationKey(context, options) {
|
|
61
|
+
const id = anthropicOptions(options).conversationId;
|
|
62
|
+
if (id !== undefined)
|
|
63
|
+
return `id:${id}`;
|
|
64
|
+
return `fp:${fnv1a(JSON.stringify([context.system, fingerprintOf(context.messages[0])]))}`;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The part of a message the fingerprint hashes: its role and each block's text, or the block's type for any other
|
|
68
|
+
* block. An image's base64 data stays out, so a large image never gets stringified on every call.
|
|
69
|
+
*/
|
|
70
|
+
function fingerprintOf(message) {
|
|
71
|
+
if (message === undefined)
|
|
72
|
+
return null;
|
|
73
|
+
const blocks = message.content;
|
|
74
|
+
return [message.role, blocks.map((block) => (block.type === "text" ? block.text : `[${block.type}]`))];
|
|
75
|
+
}
|
|
76
|
+
/** The body with the binding setting, which the API accepts only beside adaptive thinking. */
|
|
77
|
+
function withBinding(body, dropBlock) {
|
|
78
|
+
const thinking = body.thinking;
|
|
79
|
+
if (!dropBlock || typeof thinking !== "object" || thinking === null)
|
|
80
|
+
return body;
|
|
81
|
+
if (thinking.type !== "adaptive")
|
|
82
|
+
return body;
|
|
83
|
+
return { ...body, thinking: { ...thinking, block_binding: { prefix_mismatch_behavior: "drop_block" } } };
|
|
84
|
+
}
|
|
85
|
+
function bindingApplies(body) {
|
|
86
|
+
return withBinding(body, true) !== body;
|
|
87
|
+
}
|
|
88
|
+
// Header names the adapter sets itself. A caller's key header is dropped, because `config.apiKey` is the only key
|
|
89
|
+
// the adapter sends.
|
|
90
|
+
const CALLER_HEADERS_DROPPED = new Set(["x-api-key", "authorization", "anthropic-beta"]);
|
|
91
|
+
/**
|
|
92
|
+
* The caller's headers with lower-case names, without the ones the adapter owns, and the betas they ask for. Header
|
|
93
|
+
* names are case-insensitive, so `Anthropic-Beta` and `anthropic-beta` are one header.
|
|
94
|
+
*/
|
|
95
|
+
function callerHeaders(headers) {
|
|
96
|
+
const rest = {};
|
|
97
|
+
const betas = [];
|
|
98
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
99
|
+
const lower = name.toLowerCase();
|
|
100
|
+
if (lower === "anthropic-beta")
|
|
101
|
+
betas.push(...value.split(",").map((beta) => beta.trim()));
|
|
102
|
+
if (!CALLER_HEADERS_DROPPED.has(lower))
|
|
103
|
+
rest[lower] = value;
|
|
104
|
+
}
|
|
105
|
+
return { rest, betas };
|
|
106
|
+
}
|
|
107
|
+
function requestFor(state, body, signal) {
|
|
108
|
+
const { config } = state;
|
|
109
|
+
const { rest, betas } = callerHeaders(config.headers);
|
|
110
|
+
const beta = [...new Set([...betas, THINKING_BINDING_BETA])].filter(Boolean).join(",");
|
|
111
|
+
const headers = {
|
|
112
|
+
...rest,
|
|
113
|
+
"content-type": "application/json",
|
|
114
|
+
accept: "text/event-stream",
|
|
115
|
+
"anthropic-version": ANTHROPIC_VERSION,
|
|
116
|
+
"anthropic-beta": beta,
|
|
117
|
+
"x-api-key": config.apiKey,
|
|
118
|
+
};
|
|
119
|
+
const url = `${config.baseURL.replace(/\/+$/, "")}/v1/messages`;
|
|
120
|
+
return new Request(url, { method: "POST", headers, body: JSON.stringify(body), ...(signal ? { signal } : {}) });
|
|
121
|
+
}
|
|
122
|
+
async function* streamMessage(state, model, context, options) {
|
|
123
|
+
yield { type: "start" };
|
|
124
|
+
const plan = buildRequest(model, context, options, options.caps ?? DEFAULT_CAPS);
|
|
125
|
+
// Each attempt warns again; the gateway's retries stream a repeated warning only once per call.
|
|
126
|
+
yield* plan.warnings;
|
|
127
|
+
const key = conversationKey(context, options);
|
|
128
|
+
for (;;) {
|
|
129
|
+
const dropBlock = state.dropBlock.has(key);
|
|
130
|
+
const request = requestFor(state, payloadOf(withBinding(plan.body, dropBlock), options), options.signal);
|
|
131
|
+
const response = yield* sendRequest(state.config.transport, request, model, options.signal);
|
|
132
|
+
if (response === undefined)
|
|
133
|
+
return;
|
|
134
|
+
if (response.ok) {
|
|
135
|
+
const assembler = new MessageAssembler(model, plan.names, plan.cacheTtl);
|
|
136
|
+
yield* readEventStream(response, model, assembler, options.signal);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const failure = await failureFromResponse(response);
|
|
140
|
+
if (!isPrefixMismatch(failure) || dropBlock || !bindingApplies(plan.body)) {
|
|
141
|
+
yield failureEvent(model, failure);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
state.dropBlock.add(key);
|
|
145
|
+
yield {
|
|
146
|
+
type: "warning",
|
|
147
|
+
code: "thinking_prefix_mismatch",
|
|
148
|
+
message: `${failure.message} Retrying with drop_block.`,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Creates an adapter for Anthropic's Messages API. Every request goes to `{baseURL}/v1/messages` through
|
|
154
|
+
* `config.transport`, streams its response, and sends `anthropic-version: 2026-10-21` and the key from
|
|
155
|
+
* `config.apiKey`, which is the only key it sends. Throws a `GatewayError` with code `missing_api_key` when the key
|
|
156
|
+
* is missing or empty.
|
|
157
|
+
*
|
|
158
|
+
* The model's caps come from `options.caps`, which `createModel()` sets; a direct call without them uses
|
|
159
|
+
* `defaultCaps`. Caller headers from `config.headers` are sent with lower-case names; a caller `anthropic-beta` is
|
|
160
|
+
* merged with the adapter's beta, and a caller `x-api-key` or `authorization` is dropped.
|
|
161
|
+
*
|
|
162
|
+
* `providerOptions.anthropic` takes a `conversationId`, which marks requests of one conversation, and an `extraBody`,
|
|
163
|
+
* whose fields join the request body wherever the adapter sets no field of the same name. Without a
|
|
164
|
+
* `conversationId`, the adapter tells conversations apart by their system prompt and the text of their first
|
|
165
|
+
* message, so conversations that share both also share the `drop_block` setting; pass a `conversationId` for each
|
|
166
|
+
* conversation to keep them apart. The
|
|
167
|
+
* adapter remembers the last 1,000 conversations that needed `drop_block`. `temperature`, `top_p` and `top_k` are
|
|
168
|
+
* never sent, because this API version rejects them; the call streams a `warning` instead.
|
|
169
|
+
*/
|
|
170
|
+
export function anthropic(config) {
|
|
171
|
+
const state = {
|
|
172
|
+
config: resolveProviderConfig(config, { baseURL: DEFAULT_BASE_URL }),
|
|
173
|
+
dropBlock: new RecentKeys(DROP_BLOCK_MEMORY),
|
|
174
|
+
};
|
|
175
|
+
return {
|
|
176
|
+
specificationVersion: "v1",
|
|
177
|
+
api: "anthropic-messages",
|
|
178
|
+
provider: "anthropic",
|
|
179
|
+
defaultCaps: DEFAULT_CAPS,
|
|
180
|
+
stream: (model, context, options) => streamMessage(state, model, context, options),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
//# sourceMappingURL=adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAA+B,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AAI9F,OAAO,EAAa,SAAS,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAChF,OAAO,EAAE,YAAY,E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AAE,EAAE,OAAO,EAAE,gBAAgB,EAAE,CAAC;QACpE,SAAS,EAAE,IAAI,UAAU,CAAC,iBAAiB,CAAC;KAC7C,CAAC;IACF,OAAO;QACL,oBAAoB,EAAE,IAAI;QAC1B,GAAG,EAAE,oBAAoB;QACzB,QAAQ,EAAE,WAAW;QACrB,WAAW,EAAE,YAAY;QACzB,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;KACnF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `anthropic()`: the Anthropic Messages adapter over the gateway's `Transport` (D2). It streams every call and pins\n * the API version.\n *\n * The thinking prefix check (HD3 rules 4 and 5): every request sends the `thinking-binding-controls-2026-08-01`\n * beta header, so a 200 response lists each thinking block that failed the check and reached the model anyway in its\n * `input_transformations`, and each such entry becomes a warning. A 400 that says a block \"is bound to a different\n * conversation\" is retried once with `thinking.block_binding.prefix_mismatch_behavior: \"drop_block\"`, and the\n * adapter sends that setting on every later request of the conversation, because the API applies it only to the\n * request that carries it (Prefix checks on thinking blocks,\n * https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/prefix-checks, as of November 2026).\n */\nimport { fnv1a } from \"../../names.js\";\nimport { type ResolvedProviderConfig, resolveProviderConfig } from \"../../provider-config.js\";\nimport type { ProviderConfig } from \"../../runtime-types.js\";\nimport type { ModelAdapter, ModelEvent, StreamOptions } from \"../../spec.js\";\nimport type { ContentBlock, Message, ModelCaps, ModelContext, ModelRef } from \"../../types.js\";\nimport { type Json, payloadOf, readEventStream, sendRequest } from \"../wire.js\";\nimport { failureEvent, failureFromResponse, isPrefixMismatch } from \"./failure.js\";\nimport { anthropicOptions, buildRequest } from \"./request.js\";\nimport { MessageAssembler } from \"./response.js\";\n\n/** The Messages API version every request pins. */\nexport const ANTHROPIC_VERSION = \"2026-10-21\";\n/** The beta that adds `thinking.block_binding` and the response's `input_transformations`. */\nexport const THINKING_BINDING_BETA = \"thinking-binding-controls-2026-08-01\";\nconst DEFAULT_BASE_URL = \"https://api.anthropic.com\";\n\n// The adapter's `defaultCaps`: the one fallback for a model with no caps, which `createModel()` uses for a model its\n// catalog lacks and a direct `stream()` call without `options.caps` uses for any model. Every Claude model takes\n// images, but an unlisted one may be an older model that rejects adaptive thinking, so it is sent no thinking setting\n// and its own default applies.\nconst DEFAULT_CAPS: ModelCaps = { contextWindow: 200_000, maxOutputTokens: 32_000, images: true, reasoning: false };\n\n// How many conversations the adapter remembers as needing `drop_block`. A conversation pushed out sends the setting\n// no more; its next mismatch costs one more 400 and puts it back.\nconst DROP_BLOCK_MEMORY = 1_000;\n\n/** A set of keys that keeps the `limit` most recently used, so a long-lived adapter's memory stays bounded. */\nclass RecentKeys {\n readonly #keys = new Set<string>();\n readonly #limit: number;\n\n constructor(limit: number) {\n this.#limit = limit;\n }\n\n /** True when the key is held; a hit counts as a use. */\n has(key: string): boolean {\n if (!this.#keys.has(key)) return false;\n this.add(key);\n return true;\n }\n\n add(key: string): void {\n this.#keys.delete(key);\n this.#keys.add(key);\n // A Set iterates in insertion order, so its first key is the least recently used.\n const oldest = this.#keys.size > this.#limit ? this.#keys.values().next().value : undefined;\n if (oldest !== undefined) this.#keys.delete(oldest);\n }\n}\n\n/** What one adapter keeps between calls: the conversations that must send `drop_block`. */\ninterface AdapterState {\n readonly config: ResolvedProviderConfig;\n readonly dropBlock: RecentKeys;\n}\n\n/**\n * The conversation a call belongs to: its caller-given id, or else an FNV-1a hash of its system prompt and first\n * message. Two conversations that share both share the hash, so one's `drop_block` reaches the other; a\n * `conversationId` keeps them apart.\n */\nfunction conversationKey(context: ModelContext, options: StreamOptions): string {\n const id = anthropicOptions(options).conversationId;\n if (id !== undefined) return `id:${id}`;\n return `fp:${fnv1a(JSON.stringify([context.system, fingerprintOf(context.messages[0])]))}`;\n}\n\n/**\n * The part of a message the fingerprint hashes: its role and each block's text, or the block's type for any other\n * block. An image's base64 data stays out, so a large image never gets stringified on every call.\n */\nfunction fingerprintOf(message: Message | undefined): unknown {\n if (message === undefined) return null;\n const blocks: readonly ContentBlock[] = message.content;\n return [message.role, blocks.map((block) => (block.type === \"text\" ? block.text : `[${block.type}]`))];\n}\n\n/** The body with the binding setting, which the API accepts only beside adaptive thinking. */\nfunction withBinding(body: Json, dropBlock: boolean): Json {\n const thinking = body.thinking;\n if (!dropBlock || typeof thinking !== \"object\" || thinking === null) return body;\n if ((thinking as Json).type !== \"adaptive\") return body;\n return { ...body, thinking: { ...thinking, block_binding: { prefix_mismatch_behavior: \"drop_block\" } } };\n}\n\nfunction bindingApplies(body: Json): boolean {\n return withBinding(body, true) !== body;\n}\n\n// Header names the adapter sets itself. A caller's key header is dropped, because `config.apiKey` is the only key\n// the adapter sends.\nconst CALLER_HEADERS_DROPPED = new Set([\"x-api-key\", \"authorization\", \"anthropic-beta\"]);\n\n/**\n * The caller's headers with lower-case names, without the ones the adapter owns, and the betas they ask for. Header\n * names are case-insensitive, so `Anthropic-Beta` and `anthropic-beta` are one header.\n */\nfunction callerHeaders(headers: Readonly<Record<string, string>>): { rest: Record<string, string>; betas: string[] } {\n const rest: Record<string, string> = {};\n const betas: string[] = [];\n for (const [name, value] of Object.entries(headers)) {\n const lower = name.toLowerCase();\n if (lower === \"anthropic-beta\") betas.push(...value.split(\",\").map((beta) => beta.trim()));\n if (!CALLER_HEADERS_DROPPED.has(lower)) rest[lower] = value;\n }\n return { rest, betas };\n}\n\nfunction requestFor(state: AdapterState, body: unknown, signal: AbortSignal | undefined): Request {\n const { config } = state;\n const { rest, betas } = callerHeaders(config.headers);\n const beta = [...new Set([...betas, THINKING_BINDING_BETA])].filter(Boolean).join(\",\");\n const headers = {\n ...rest,\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n \"anthropic-version\": ANTHROPIC_VERSION,\n \"anthropic-beta\": beta,\n \"x-api-key\": config.apiKey,\n };\n const url = `${config.baseURL.replace(/\\/+$/, \"\")}/v1/messages`;\n return new Request(url, { method: \"POST\", headers, body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n}\n\nasync function* streamMessage(\n state: AdapterState,\n model: ModelRef,\n context: ModelContext,\n options: StreamOptions,\n): AsyncGenerator<ModelEvent> {\n yield { type: \"start\" };\n const plan = buildRequest(model, context, options, options.caps ?? DEFAULT_CAPS);\n // Each attempt warns again; the gateway's retries stream a repeated warning only once per call.\n yield* plan.warnings;\n const key = conversationKey(context, options);\n for (;;) {\n const dropBlock = state.dropBlock.has(key);\n const request = requestFor(state, payloadOf(withBinding(plan.body, dropBlock), options), options.signal);\n const response = yield* sendRequest(state.config.transport, request, model, options.signal);\n if (response === undefined) return;\n if (response.ok) {\n const assembler = new MessageAssembler(model, plan.names, plan.cacheTtl);\n yield* readEventStream(response, model, assembler, options.signal);\n return;\n }\n const failure = await failureFromResponse(response);\n if (!isPrefixMismatch(failure) || dropBlock || !bindingApplies(plan.body)) {\n yield failureEvent(model, failure);\n return;\n }\n state.dropBlock.add(key);\n yield {\n type: \"warning\",\n code: \"thinking_prefix_mismatch\",\n message: `${failure.message} Retrying with drop_block.`,\n };\n }\n}\n\n/**\n * Creates an adapter for Anthropic's Messages API. Every request goes to `{baseURL}/v1/messages` through\n * `config.transport`, streams its response, and sends `anthropic-version: 2026-10-21` and the key from\n * `config.apiKey`, which is the only key it sends. Throws a `GatewayError` with code `missing_api_key` when the key\n * is missing or empty.\n *\n * The model's caps come from `options.caps`, which `createModel()` sets; a direct call without them uses\n * `defaultCaps`. Caller headers from `config.headers` are sent with lower-case names; a caller `anthropic-beta` is\n * merged with the adapter's beta, and a caller `x-api-key` or `authorization` is dropped.\n *\n * `providerOptions.anthropic` takes a `conversationId`, which marks requests of one conversation, and an `extraBody`,\n * whose fields join the request body wherever the adapter sets no field of the same name. Without a\n * `conversationId`, the adapter tells conversations apart by their system prompt and the text of their first\n * message, so conversations that share both also share the `drop_block` setting; pass a `conversationId` for each\n * conversation to keep them apart. The\n * adapter remembers the last 1,000 conversations that needed `drop_block`. `temperature`, `top_p` and `top_k` are\n * never sent, because this API version rejects them; the call streams a `warning` instead.\n */\nexport function anthropic(config: ProviderConfig): ModelAdapter {\n const state: AdapterState = {\n config: resolveProviderConfig(config, { baseURL: DEFAULT_BASE_URL }),\n dropBlock: new RecentKeys(DROP_BLOCK_MEMORY),\n };\n return {\n specificationVersion: \"v1\",\n api: \"anthropic-messages\",\n provider: \"anthropic\",\n defaultCaps: DEFAULT_CAPS,\n stream: (model, context, options) => streamMessage(state, model, context, options),\n };\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Failed requests and streams, as `error` terminals (Errors, https://platform.claude.com/docs/en/api/errors, and
|
|
3
|
+
* the Messages API reference's error codes, https://platform.claude.com/docs/en/api/messages/create, both as of
|
|
4
|
+
* November 2026). An error body is `{ "type": "error", "error": { "type", "message" }, "request_id" }`, and some
|
|
5
|
+
* errors add `error.details.error_code`. A stream that already returned 200 reports a later error as an `error`
|
|
6
|
+
* event with the same `error` object and no status of its own.
|
|
7
|
+
*
|
|
8
|
+
* A 429 may carry a `retry-after` header that gives the number of seconds to wait before a retry; the
|
|
9
|
+
* spend-cap 429 never does (Rate limits, response headers, https://platform.claude.com/docs/en/api/rate-limits, as of
|
|
10
|
+
* November 2026). The adapter puts the hint on the error as `retryAfterMs`.
|
|
11
|
+
*/
|
|
12
|
+
import type { ModelEvent } from "../../spec.js";
|
|
13
|
+
import type { ModelRef } from "../../types.js";
|
|
14
|
+
import { type PartialReply, type WireFailure } from "../wire.js";
|
|
15
|
+
/** Reads an error object, from an HTTP error body or an `error` stream event. */
|
|
16
|
+
export declare function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure;
|
|
17
|
+
/**
|
|
18
|
+
* Reads a failed HTTP response's error body and its retry-after hint; a body that is not JSON keeps its text as the
|
|
19
|
+
* message.
|
|
20
|
+
*/
|
|
21
|
+
export declare function failureFromResponse(response: Response): Promise<WireFailure>;
|
|
22
|
+
/** True for the prefix-check 400, which the adapter answers by retrying with `drop_block`. */
|
|
23
|
+
export declare function isPrefixMismatch(failure: WireFailure): boolean;
|
|
24
|
+
/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */
|
|
25
|
+
export declare function failureEvent(model: ModelRef, failure: WireFailure, partial?: PartialReply): Extract<ModelEvent, {
|
|
26
|
+
type: "error";
|
|
27
|
+
}>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { failureTerminal, isObject, readErrorBody, retryAfterMs, } from "../wire.js";
|
|
2
|
+
// The HTTP status each error type stands for, so a stream error classifies like the HTTP error it would have been.
|
|
3
|
+
const STATUS_OF_TYPE = {
|
|
4
|
+
invalid_request_error: 400,
|
|
5
|
+
authentication_error: 401,
|
|
6
|
+
billing_error: 402,
|
|
7
|
+
permission_error: 403,
|
|
8
|
+
not_found_error: 404,
|
|
9
|
+
conflict_error: 409,
|
|
10
|
+
request_too_large: 413,
|
|
11
|
+
rate_limit_error: 429,
|
|
12
|
+
api_error: 500,
|
|
13
|
+
timeout_error: 504,
|
|
14
|
+
overloaded_error: 529,
|
|
15
|
+
};
|
|
16
|
+
// The fix page says to match this error on this sentence alone, because the rest of the message can change (Fix a
|
|
17
|
+
// thinking block bound to a different conversation, "Handle the error in code",
|
|
18
|
+
// https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/fix-bound-to-a-different-conversation,
|
|
19
|
+
// as of November 2026).
|
|
20
|
+
const PREFIX_MISMATCH = "The block is bound to a different conversation";
|
|
21
|
+
/** Reads an error object, from an HTTP error body or an `error` stream event. */
|
|
22
|
+
export function failureFrom(body, status, fallback) {
|
|
23
|
+
const error = isObject(body) && isObject(body.error) ? body.error : undefined;
|
|
24
|
+
const details = error && isObject(error.details) ? error.details : undefined;
|
|
25
|
+
return {
|
|
26
|
+
...(status === undefined ? {} : { status }),
|
|
27
|
+
...(typeof error?.type === "string" ? { type: error.type } : {}),
|
|
28
|
+
...(typeof details?.error_code === "string" ? { errorCode: details.error_code } : {}),
|
|
29
|
+
message: typeof error?.message === "string" ? error.message : fallback,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Reads a failed HTTP response's error body and its retry-after hint; a body that is not JSON keeps its text as the
|
|
34
|
+
* message.
|
|
35
|
+
*/
|
|
36
|
+
export async function failureFromResponse(response) {
|
|
37
|
+
const { body, text } = await readErrorBody(response);
|
|
38
|
+
const wait = retryAfterMs(response.headers);
|
|
39
|
+
return {
|
|
40
|
+
...failureFrom(body, response.status, text || `HTTP ${response.status}`),
|
|
41
|
+
...(wait === undefined ? {} : { retryAfterMs: wait }),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** True for the prefix-check 400, which the adapter answers by retrying with `drop_block`. */
|
|
45
|
+
export function isPrefixMismatch(failure) {
|
|
46
|
+
return (failure.status ?? STATUS_OF_TYPE[failure.type ?? ""]) === 400 && failure.message.includes(PREFIX_MISMATCH);
|
|
47
|
+
}
|
|
48
|
+
/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */
|
|
49
|
+
export function failureEvent(model, failure, partial = {}) {
|
|
50
|
+
const code = isPrefixMismatch(failure) ? "thinking_prefix_mismatch" : undefined;
|
|
51
|
+
return failureTerminal(model, failure, STATUS_OF_TYPE, partial, code);
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=failure.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"failure.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/failure.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,eAAe,EACf,QAAQ,EAER,aAAa,EACb,YAAY,GAEb,MAAM,YAAY,CAAC;AAEpB,mHAAmH;AACnH,MAAM,cAAc,GAAqC;IACvD,qBAAqB,EAAE,GAAG;IAC1B,oBAAoB,EAAE,GAAG;IACzB,aAAa,EAAE,GAAG;IAClB,gBAAgB,EAAE,GAAG;IACrB,eAAe,EAAE,GAAG;IACpB,cAAc,EAAE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AC1D,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,MAAM,aAAa,CAAC,QAAQ,CAAC,CAAC;IACrD,MAAM,IAAI,GAAG,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC5C,OAAO;QACL,GAAG,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,IAAI,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC;QACxE,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;KACtD,CAAC;AACJ,CAAC;AAED,8FAA8F;AAC9F,MAAM,UAAU,gBAAgB,CAAC,OAAoB;IACnD,OAAO,CAAC,OAAO,CAAC,MAAM,IAAI,cAAc,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,KAAK,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC;AACrH,CAAC;AAED,kGAAkG;AAClG,MAAM,UAAU,YAAY,CAC1B,KAAe,EACf,OAAoB,EACpB,OAAO,GAAiB,EAAE;IAE1B,MAAM,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC,SAAS,CAAC;IAChF,OAAO,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;AACxE,CAAC","sourcesContent":["/**\n * Failed requests and streams, as `error` terminals (Errors, https://platform.claude.com/docs/en/api/errors, and\n * the Messages API reference's error codes, https://platform.claude.com/docs/en/api/messages/create, both as of\n * November 2026). An error body is `{ \"type\": \"error\", \"error\": { \"type\", \"message\" }, \"request_id\" }`, and some\n * errors add `error.details.error_code`. A stream that already returned 200 reports a later error as an `error`\n * event with the same `error` object and no status of its own.\n *\n * A 429 may carry a `retry-after` header that gives the number of seconds to wait before a retry; the\n * spend-cap 429 never does (Rate limits, response headers, https://platform.claude.com/docs/en/api/rate-limits, as of\n * November 2026). The adapter puts the hint on the error as `retryAfterMs`.\n */\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ModelRef } from \"../../types.js\";\nimport {\n failureTerminal,\n isObject,\n type PartialReply,\n readErrorBody,\n retryAfterMs,\n type WireFailure,\n} from \"../wire.js\";\n\n// The HTTP status each error type stands for, so a stream error classifies like the HTTP error it would have been.\nconst STATUS_OF_TYPE: Readonly<Record<string, number>> = {\n invalid_request_error: 400,\n authentication_error: 401,\n billing_error: 402,\n permission_error: 403,\n not_found_error: 404,\n conflict_error: 409,\n request_too_large: 413,\n rate_limit_error: 429,\n api_error: 500,\n timeout_error: 504,\n overloaded_error: 529,\n};\n\n// The fix page says to match this error on this sentence alone, because the rest of the message can change (Fix a\n// thinking block bound to a different conversation, \"Handle the error in code\",\n// https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/fix-bound-to-a-different-conversation,\n// as of November 2026).\nconst PREFIX_MISMATCH = \"The block is bound to a different conversation\";\n\n/** Reads an error object, from an HTTP error body or an `error` stream event. */\nexport function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure {\n const error = isObject(body) && isObject(body.error) ? body.error : undefined;\n const details = error && isObject(error.details) ? error.details : undefined;\n return {\n ...(status === undefined ? {} : { status }),\n ...(typeof error?.type === \"string\" ? { type: error.type } : {}),\n ...(typeof details?.error_code === \"string\" ? { errorCode: details.error_code } : {}),\n message: typeof error?.message === \"string\" ? error.message : fallback,\n };\n}\n\n/**\n * Reads a failed HTTP response's error body and its retry-after hint; a body that is not JSON keeps its text as the\n * message.\n */\nexport async function failureFromResponse(response: Response): Promise<WireFailure> {\n const { body, text } = await readErrorBody(response);\n const wait = retryAfterMs(response.headers);\n return {\n ...failureFrom(body, response.status, text || `HTTP ${response.status}`),\n ...(wait === undefined ? {} : { retryAfterMs: wait }),\n };\n}\n\n/** True for the prefix-check 400, which the adapter answers by retrying with `drop_block`. */\nexport function isPrefixMismatch(failure: WireFailure): boolean {\n return (failure.status ?? STATUS_OF_TYPE[failure.type ?? \"\"]) === 400 && failure.message.includes(PREFIX_MISMATCH);\n}\n\n/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */\nexport function failureEvent(\n model: ModelRef,\n failure: WireFailure,\n partial: PartialReply = {},\n): Extract<ModelEvent, { type: \"error\" }> {\n const code = isPrefixMismatch(failure) ? \"thinking_prefix_mismatch\" : undefined;\n return failureTerminal(model, failure, STATUS_OF_TYPE, partial, code);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/index.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/** `@buildanagent/gateway/anthropic`: the Anthropic Messages adapter. */\nexport { ANTHROPIC_VERSION, anthropic, THINKING_BINDING_BETA } from \"./adapter.js\";\nexport type { AnthropicProviderOptions } from \"./request.js\";\n"]}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the Messages API request body from a `ModelContext` (Messages API reference,
|
|
3
|
+
* https://platform.claude.com/docs/en/api/messages/create, as of November 2026).
|
|
4
|
+
*
|
|
5
|
+
* - Messages pass through `transformMessages()` first; tool results become `tool_result` blocks in a user message,
|
|
6
|
+
* all results of one turn in one message, as the tool-use docs ask. `caps.reasoning` decides only whether the body
|
|
7
|
+
* asks for thinking: signed Anthropic thinking is replayed either way, because the API checks it against its
|
|
8
|
+
* signature rather than the model's caps, and dropping it would lose a turn's reasoning for a model the catalog
|
|
9
|
+
* merely doesn't mark as reasoning.
|
|
10
|
+
* - Tool names go through the run's `ToolNameMap`; tools are sent strict when their schema can be
|
|
11
|
+
* (`../strict-schema.ts`).
|
|
12
|
+
* - Caching puts at most three `cache_control` breakpoints, on the system prompt, the last tool and the last block
|
|
13
|
+
* of the last user message, below the API's limit of 4 (Prompt caching,
|
|
14
|
+
* https://platform.claude.com/docs/en/build-with-claude/prompt-caching, as of November 2026).
|
|
15
|
+
* - `temperature`, `top_p` and `top_k` are never sent: on API version 2026-10-21 any of them is a 400 "even at the
|
|
16
|
+
* parameter's default value" (https://platform.claude.com/docs/en/api/migration-2026-10-21, as of November 2026).
|
|
17
|
+
*/
|
|
18
|
+
import { type ToolNameMap } from "../../names.js";
|
|
19
|
+
import type { ModelEvent, StreamOptions } from "../../spec.js";
|
|
20
|
+
import type { ModelCaps, ModelContext, ModelRef } from "../../types.js";
|
|
21
|
+
import { type Json } from "../wire.js";
|
|
22
|
+
type Warning = Extract<ModelEvent, {
|
|
23
|
+
type: "warning";
|
|
24
|
+
}>;
|
|
25
|
+
/** A prefix on an `OpaqueToken` value that marks a `redacted_thinking` block's `data`, not a thinking signature. */
|
|
26
|
+
export declare const REDACTED_THINKING_PREFIX = "redacted_thinking:";
|
|
27
|
+
/** What the adapter reads from `providerOptions.anthropic`. */
|
|
28
|
+
export interface AnthropicProviderOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Names the conversation, so the adapter can remember a choice that must hold for its later requests. Without it,
|
|
31
|
+
* the adapter recognises a conversation by its system prompt and first message.
|
|
32
|
+
*/
|
|
33
|
+
readonly conversationId?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Extra fields for the request body, such as `output_config` or `thinking: { display: "summarized" }`. The fields
|
|
36
|
+
* the adapter sets itself (`model`, `max_tokens`, `stream`, `system`, `messages`, `tools`, and `thinking.type` for a
|
|
37
|
+
* reasoning model) win over these, and sampling fields are dropped; either streams an `unsupported_option` warning.
|
|
38
|
+
*/
|
|
39
|
+
readonly extraBody?: Readonly<Record<string, unknown>>;
|
|
40
|
+
}
|
|
41
|
+
/** One request's body and what reading its response needs. */
|
|
42
|
+
export interface RequestPlan {
|
|
43
|
+
readonly body: Json;
|
|
44
|
+
readonly warnings: readonly Warning[];
|
|
45
|
+
readonly names: ToolNameMap;
|
|
46
|
+
/** The TTL the breakpoints asked for, used when a response reports cache writes without their split. */
|
|
47
|
+
readonly cacheTtl: "5m" | "1h";
|
|
48
|
+
}
|
|
49
|
+
/** Reads `providerOptions.anthropic`, ignoring fields of the wrong type. */
|
|
50
|
+
export declare function anthropicOptions(options: StreamOptions): AnthropicProviderOptions;
|
|
51
|
+
/** Builds one call's request body. The adapter adds the thinking-binding setting to it before each HTTP request. */
|
|
52
|
+
export declare function buildRequest(model: ModelRef, context: ModelContext, options: StreamOptions, caps: ModelCaps): RequestPlan;
|
|
53
|
+
export {};
|