@eum-agent/llm-protocol-anthropic 1.0.1 → 1.1.0
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/dist/index.js +210 -63
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -2,6 +2,16 @@ import { z } from "zod";
|
|
|
2
2
|
import Anthropic, { APIConnectionError, APIError } from "@anthropic-ai/sdk";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { setImmediate } from "node:timers/promises";
|
|
5
|
+
//#region src/logo.ts
|
|
6
|
+
/** Official Anthropic mark reused from the supplier extension's vendored SVG. */
|
|
7
|
+
const protocolLogo = "data:image/svg+xml,%3Csvg%20fill%3D%22currentColor%22%20fill-rule%3D%22evenodd%22%20height%3D%2224%22%20style%3D%22flex%3Anone%3Bline-height%3A1%22%20viewBox%3D%220%200%2024%2024%22%20width%3D%2224%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ctitle%3EAnthropic%3C%2Ftitle%3E%3Cpath%20d%3D%22M13.827%203.52h3.603L24%2020h-3.603l-6.57-16.48zm-7.258%200h3.767L16.906%2020h-3.674l-1.343-3.461H5.017l-1.344%203.46H0L6.57%203.522zm4.132%209.959L8.453%207.687%206.205%2013.48H10.7z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E";
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/protocol/address.ts
|
|
10
|
+
/** Preserves the configured API version and prefix before appending a resource path. */
|
|
11
|
+
function messagesBaseUrl(baseUrl) {
|
|
12
|
+
return typeof baseUrl === "string" ? baseUrl.replace(/\/+$/, "") : "";
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
5
15
|
//#region src/protocol/facts.ts
|
|
6
16
|
/** Parameter ranges and request limits for this provider wire. */
|
|
7
17
|
const facts = {
|
|
@@ -163,7 +173,7 @@ function toContentBlockParams(part, at, context) {
|
|
|
163
173
|
} : {
|
|
164
174
|
type: "thinking",
|
|
165
175
|
thinking: part.text,
|
|
166
|
-
...context.unsignedThinking ?
|
|
176
|
+
...context.unsignedThinking ? {} : { signature: part.signature ?? "" }
|
|
167
177
|
}];
|
|
168
178
|
case "tool-use": return [{
|
|
169
179
|
type: "tool_use",
|
|
@@ -191,12 +201,10 @@ function toContentBlockParams(part, at, context) {
|
|
|
191
201
|
/**
|
|
192
202
|
* Whether this endpoint can send one message's thinking group back.
|
|
193
203
|
*
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
* failing every continuation. Endpoint, model and prefix attribution must all
|
|
199
|
-
* match because a change to any covered input can invalidate the signature.
|
|
204
|
+
* Signed replay requires a signature and matching endpoint, model and prefix.
|
|
205
|
+
* Unsigned replay accepts optional returned proof but sends only visible text;
|
|
206
|
+
* issuer and model attribution still must match. Incomplete history is omitted.
|
|
207
|
+
* Signed mode never fabricates proof that the server cannot verify.
|
|
200
208
|
* One incompatible member drops the whole group so no middle block is removed.
|
|
201
209
|
*
|
|
202
210
|
* Comparing endpoint ids is deliberately coarser than "same signer": two keys
|
|
@@ -206,11 +214,10 @@ function toContentBlockParams(part, at, context) {
|
|
|
206
214
|
function thinkingGroupIsSendable(message, options, prefix) {
|
|
207
215
|
if (!message.content.some((part) => part.type === "text" && part.text !== "" || part.type === "tool-use")) return false;
|
|
208
216
|
if (options.reasoningReplay === "omit" || message.outputTruncation?.incompleteThinking) return false;
|
|
209
|
-
if (options.reasoningReplay === "unsigned-thinking") return true;
|
|
210
217
|
const thinking = message.content.filter((part) => part.type === "thinking");
|
|
211
218
|
if (thinking.length === 0) return true;
|
|
212
219
|
const model = options.model ?? "";
|
|
213
|
-
return thinking.every((part) => part.signature !== void 0 && part.issuer !== void 0 && part.issuer === options.endpoint && part.originModel === model && part.prefix === prefix);
|
|
220
|
+
return thinking.every((part) => (options.reasoningReplay === "unsigned-thinking" || part.signature !== void 0) && part.issuer !== void 0 && part.issuer === options.endpoint && part.originModel === model && (options.reasoningReplay === "unsigned-thinking" || part.prefix === prefix));
|
|
214
221
|
}
|
|
215
222
|
/** A text block with nothing in it: Anthropic refuses one. */
|
|
216
223
|
function isEmptyText(part) {
|
|
@@ -230,11 +237,6 @@ function noteBlock(notes) {
|
|
|
230
237
|
text
|
|
231
238
|
}];
|
|
232
239
|
}
|
|
233
|
-
/**
|
|
234
|
-
* Appends blocks to the conversation's last user message, or as a user
|
|
235
|
-
* message of their own after an assistant one. The Messages API combines
|
|
236
|
-
* consecutive messages of one role, so both forms are one user turn.
|
|
237
|
-
*/
|
|
238
240
|
function appendUser(messages, blocks) {
|
|
239
241
|
if (blocks.length === 0) return;
|
|
240
242
|
const last = messages.at(-1);
|
|
@@ -258,7 +260,14 @@ function appendUser(messages, blocks) {
|
|
|
258
260
|
*/
|
|
259
261
|
function render(messages, trailing, sendThinking, context) {
|
|
260
262
|
const out = [];
|
|
263
|
+
const updates = new Map(context.effortUpdates?.map((update) => [update.beforeUserMessageId, update.effort]));
|
|
261
264
|
messages.forEach((message, index) => {
|
|
265
|
+
const effort = updates.get(message.id);
|
|
266
|
+
if (effort !== void 0) out.push({
|
|
267
|
+
role: "system",
|
|
268
|
+
content: [],
|
|
269
|
+
output_config: { effort }
|
|
270
|
+
});
|
|
262
271
|
if (message.role === "assistant") appendUser(out, noteBlock(message.volatile));
|
|
263
272
|
const content = blocksOf(message, index, sendThinking(message, index), context);
|
|
264
273
|
if (content.length === 0) return;
|
|
@@ -304,10 +313,13 @@ function prefixOf(system, tools, messages, support) {
|
|
|
304
313
|
* signature: everything before that message, its own recorded notes included
|
|
305
314
|
* — they ended the request it answered. `messageIndex` names the message.
|
|
306
315
|
*/
|
|
307
|
-
function anthropicPrefixBefore(request, messageIndex, media, support) {
|
|
316
|
+
function anthropicPrefixBefore(request, messageIndex, media, support, effortUpdates) {
|
|
308
317
|
const before = request.messages.slice(0, messageIndex);
|
|
309
318
|
const notes = request.messages[messageIndex]?.volatile;
|
|
310
|
-
return prefixOf(systemOf(request), toolsOf(request), render(before, notes, () => false,
|
|
319
|
+
return prefixOf(systemOf(request), toolsOf(request), render(before, notes, () => false, {
|
|
320
|
+
...fingerprintContext(request, media, support),
|
|
321
|
+
effortUpdates
|
|
322
|
+
}), support);
|
|
311
323
|
}
|
|
312
324
|
/** The send plan, from the options' media context or the permissive default. */
|
|
313
325
|
function planOf(request, media, support) {
|
|
@@ -330,19 +342,24 @@ function fingerprintContext(request, media, support) {
|
|
|
330
342
|
* carried, its notes included, rendered the way `anthropicPrefixBefore`
|
|
331
343
|
* renders it on the next step and without cache marks.
|
|
332
344
|
*/
|
|
333
|
-
function anthropicRequestPrefix(request, media, support) {
|
|
334
|
-
return prefixOf(systemOf(request), toolsOf(request), render(request.messages, request.volatile, () => false,
|
|
345
|
+
function anthropicRequestPrefix(request, media, support, effortUpdates) {
|
|
346
|
+
return prefixOf(systemOf(request), toolsOf(request), render(request.messages, request.volatile, () => false, {
|
|
347
|
+
...fingerprintContext(request, media, support),
|
|
348
|
+
effortUpdates
|
|
349
|
+
}), support);
|
|
335
350
|
}
|
|
336
351
|
/** Counts provider-retained thinking state that is actually replayed. */
|
|
337
352
|
function anthropicHiddenInputTokens(request, options) {
|
|
353
|
+
if (options.reasoningReplay === "unsigned-thinking") return 0;
|
|
338
354
|
return request.messages.reduce((total, message, index) => {
|
|
339
|
-
if (!thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support))) return total;
|
|
355
|
+
if (!thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support, options.effortUpdates))) return total;
|
|
340
356
|
return total + Math.max(0, ...message.content.map((part) => part.type === "thinking" ? part.outputTokens ?? 0 : 0));
|
|
341
357
|
}, 0);
|
|
342
358
|
}
|
|
343
359
|
const EPHEMERAL = { type: "ephemeral" };
|
|
344
360
|
/** Marks the last markable block of one message. */
|
|
345
361
|
function markLast(message) {
|
|
362
|
+
if (message.role === "system") return message;
|
|
346
363
|
if (typeof message.content === "string") return message;
|
|
347
364
|
const content = [...message.content];
|
|
348
365
|
for (let index = content.length - 1; index >= 0; index -= 1) {
|
|
@@ -380,7 +397,7 @@ function toAnthropicRequest(request, options) {
|
|
|
380
397
|
const ordinaryMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
381
398
|
const thinkingOn = options.thinking !== void 0 && options.thinking.type !== "disabled";
|
|
382
399
|
const maxTokens = summary ? Math.min(request.summaryMaxTokens, Number.isInteger(ordinaryMaxTokens) && ordinaryMaxTokens > 0 ? ordinaryMaxTokens : request.summaryMaxTokens) + (thinkingOn ? SUMMARY_THINKING_HEADROOM : 0) : ordinaryMaxTokens;
|
|
383
|
-
const system = request.system?.map((text, index, all) => index === all.length - 1 ? {
|
|
400
|
+
const system = request.system?.map((text, index, all) => index === all.length - 1 && options.cacheBreakpoints !== false ? {
|
|
384
401
|
type: "text",
|
|
385
402
|
text,
|
|
386
403
|
cache_control: EPHEMERAL
|
|
@@ -389,10 +406,11 @@ function toAnthropicRequest(request, options) {
|
|
|
389
406
|
text
|
|
390
407
|
});
|
|
391
408
|
const tools = toolsOf(request);
|
|
392
|
-
const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support)), {
|
|
409
|
+
const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support, options.effortUpdates)), {
|
|
393
410
|
plan: planOf(request, options.media, options.support),
|
|
394
411
|
rendering: "wire",
|
|
395
|
-
unsignedThinking: options.reasoningReplay === "unsigned-thinking"
|
|
412
|
+
unsignedThinking: options.reasoningReplay === "unsigned-thinking",
|
|
413
|
+
effortUpdates: options.effortUpdates
|
|
396
414
|
});
|
|
397
415
|
return {
|
|
398
416
|
model: options.model ?? "",
|
|
@@ -401,7 +419,7 @@ function toAnthropicRequest(request, options) {
|
|
|
401
419
|
...options.effort === void 0 ? {} : { output_config: { effort: options.effort } },
|
|
402
420
|
...options.thinking === void 0 ? {} : { thinking: options.thinking },
|
|
403
421
|
...options.temperature === void 0 ? {} : { temperature: options.temperature },
|
|
404
|
-
messages: withConversationBreakpoints(messages),
|
|
422
|
+
messages: options.cacheBreakpoints === false ? messages : withConversationBreakpoints(messages),
|
|
405
423
|
...system === void 0 ? {} : { system },
|
|
406
424
|
...tools === void 0 ? {} : { tools },
|
|
407
425
|
...request.toolChoice === "none" && tools !== void 0 ? { tool_choice: { type: "none" } } : {},
|
|
@@ -590,6 +608,7 @@ async function* mapAnthropicStream(events, attribution, support) {
|
|
|
590
608
|
const finalContent = [];
|
|
591
609
|
const incompleteToolCalls = [];
|
|
592
610
|
let incompleteThinking = false;
|
|
611
|
+
let ordinaryInputTokens = 0;
|
|
593
612
|
let inputTokens = 0;
|
|
594
613
|
let outputTokens = 0;
|
|
595
614
|
let cache = {};
|
|
@@ -599,7 +618,8 @@ async function* mapAnthropicStream(events, attribution, support) {
|
|
|
599
618
|
for await (const event of events) switch (event.type) {
|
|
600
619
|
case "message_start": {
|
|
601
620
|
const usage = event.message.usage;
|
|
602
|
-
|
|
621
|
+
ordinaryInputTokens = usage.input_tokens;
|
|
622
|
+
inputTokens = ordinaryInputTokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
|
|
603
623
|
outputTokens = event.message.usage.output_tokens;
|
|
604
624
|
cache = {
|
|
605
625
|
...typeof usage.cache_read_input_tokens === "number" ? { cacheReadTokens: usage.cache_read_input_tokens } : {},
|
|
@@ -697,11 +717,17 @@ async function* mapAnthropicStream(events, attribution, support) {
|
|
|
697
717
|
blocks.delete(event.index);
|
|
698
718
|
break;
|
|
699
719
|
}
|
|
700
|
-
case "message_delta":
|
|
720
|
+
case "message_delta": {
|
|
701
721
|
stopReason = event.delta.stop_reason ?? stopReason;
|
|
702
722
|
if (event.delta.stop_details?.type === "refusal") refusalCategory = event.delta.stop_details.category ?? "unspecified";
|
|
703
|
-
|
|
723
|
+
const usage = event.usage;
|
|
724
|
+
if (typeof usage.input_tokens === "number") ordinaryInputTokens = usage.input_tokens;
|
|
725
|
+
if (typeof usage.cache_read_input_tokens === "number") cache.cacheReadTokens = usage.cache_read_input_tokens;
|
|
726
|
+
if (typeof usage.cache_creation_input_tokens === "number") cache.cacheWriteTokens = usage.cache_creation_input_tokens;
|
|
727
|
+
inputTokens = ordinaryInputTokens + (cache.cacheReadTokens ?? 0) + (cache.cacheWriteTokens ?? 0);
|
|
728
|
+
outputTokens = usage.output_tokens;
|
|
704
729
|
break;
|
|
730
|
+
}
|
|
705
731
|
case "message_stop": stopped = true;
|
|
706
732
|
}
|
|
707
733
|
if (!stopped) throw support.interruptedFailure();
|
|
@@ -738,7 +764,7 @@ async function* mapAnthropicStream(events, attribution, support) {
|
|
|
738
764
|
retryable: false,
|
|
739
765
|
finishReason
|
|
740
766
|
});
|
|
741
|
-
const attributedContent = finalContent.map((part) => part.type === "thinking" &&
|
|
767
|
+
const attributedContent = finalContent.map((part) => part.type === "thinking" && attribution !== void 0 ? {
|
|
742
768
|
...part,
|
|
743
769
|
originModel: attribution.originModel,
|
|
744
770
|
prefix: attribution.prefix,
|
|
@@ -776,6 +802,8 @@ async function* mapAnthropicStream(events, attribution, support) {
|
|
|
776
802
|
*/
|
|
777
803
|
/** Lets a budget-thinking model think between tool calls. */
|
|
778
804
|
const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
|
|
805
|
+
/** Enables effort-only system messages on declared supporting models. */
|
|
806
|
+
const MID_CONVERSATION_EFFORT_BETA = "mid-conversation-output-config-2026-07-01";
|
|
779
807
|
/** The budget a budget-thinking model gets when a person set none. */
|
|
780
808
|
const DEFAULT_BUDGET = 16e3;
|
|
781
809
|
const BUDGET_FLOOR = 1024;
|
|
@@ -788,8 +816,10 @@ const BUDGET_FLOOR = 1024;
|
|
|
788
816
|
* default one under `max_tokens`, or no thinking at all when `max_tokens`
|
|
789
817
|
* leaves no room for the smallest budget. Thinking off is `disabled`. While
|
|
790
818
|
* thinking is on no temperature goes out: Anthropic refuses one then.
|
|
819
|
+
* Endpoint policies can instead omit thinking, enable it without a budget,
|
|
820
|
+
* or suppress native effort, display and beta extensions.
|
|
791
821
|
*/
|
|
792
|
-
function anthropicOptions(plan, model, budgetOnly = []) {
|
|
822
|
+
function anthropicOptions(plan, model, budgetOnly = [], policy = {}) {
|
|
793
823
|
const on = plan.thinking === true;
|
|
794
824
|
const maxTokens = plan.maxTokens;
|
|
795
825
|
const budget = () => {
|
|
@@ -798,43 +828,56 @@ function anthropicOptions(plan, model, budgetOnly = []) {
|
|
|
798
828
|
const wanted = plan.budgetTokens ?? Math.min(DEFAULT_BUDGET, Math.floor((maxTokens ?? 0) / 2));
|
|
799
829
|
return Math.min(Math.max(wanted, BUDGET_FLOOR), ceiling);
|
|
800
830
|
};
|
|
801
|
-
const byBudget = plan.budgetTokens !== void 0 || budgetOnly.some((one) => model.startsWith(one));
|
|
831
|
+
const byBudget = policy.thinkingMode === "budget" || plan.budgetTokens !== void 0 || budgetOnly.some((one) => model.startsWith(one));
|
|
802
832
|
const tokens = on && byBudget ? budget() : void 0;
|
|
803
|
-
const thinking = !on ? plan.thinking === false ? { type: "disabled" } : void 0 : byBudget ? tokens === void 0 ? void 0 : {
|
|
833
|
+
const thinking = policy.thinkingMode === "omit" ? void 0 : !on ? plan.thinking === false ? { type: "disabled" } : void 0 : policy.thinkingMode === "enabled" ? { type: "enabled" } : byBudget ? tokens === void 0 ? void 0 : {
|
|
804
834
|
type: "enabled",
|
|
805
835
|
budget_tokens: tokens
|
|
806
836
|
} : {
|
|
807
837
|
type: "adaptive",
|
|
808
|
-
display: "summarized"
|
|
838
|
+
...policy.thinkingSummary === false ? {} : { display: "summarized" }
|
|
809
839
|
};
|
|
810
840
|
return {
|
|
811
|
-
...plan.effort === void 0 || !on ? {} : { effort: plan.effort },
|
|
841
|
+
...plan.effort === void 0 || !on || policy.thinkingEffort === false ? {} : { effort: plan.effort },
|
|
812
842
|
...plan.temperature === void 0 || on ? {} : { temperature: plan.temperature },
|
|
813
843
|
...maxTokens === void 0 ? {} : { maxTokens },
|
|
814
844
|
...thinking === void 0 ? {} : { thinking },
|
|
815
|
-
...thinking?.type === "enabled" ? { betas: [INTERLEAVED_THINKING_BETA] } : {}
|
|
845
|
+
...thinking?.type === "enabled" && policy.thinkingBeta !== false ? { betas: [INTERLEAVED_THINKING_BETA] } : {}
|
|
816
846
|
};
|
|
817
847
|
}
|
|
818
848
|
/** Creates an Anthropic port with synchronous request inspection and safe stream retries. */
|
|
819
849
|
function createAnthropicModelPort(options) {
|
|
820
850
|
function clientForAttempt(reportProgress) {
|
|
821
|
-
|
|
822
|
-
|
|
851
|
+
if (options.client) return options.client;
|
|
852
|
+
const client = new Anthropic({
|
|
853
|
+
apiKey: options.allowUnauthenticated && !options.apiKey ? "not-used" : options.apiKey ?? "",
|
|
854
|
+
...options.allowUnauthenticated && !options.apiKey ? {
|
|
855
|
+
authToken: null,
|
|
856
|
+
defaultHeaders: {
|
|
857
|
+
"x-api-key": null,
|
|
858
|
+
Authorization: null
|
|
859
|
+
}
|
|
860
|
+
} : {},
|
|
823
861
|
fetch: async (...args) => frameSseResponse(options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress), args[1]?.signal),
|
|
824
862
|
baseURL: options.baseURL ?? "",
|
|
825
863
|
maxRetries: 0
|
|
826
864
|
});
|
|
865
|
+
return { messages: { create: (body, requestOptions) => client.post("/messages", {
|
|
866
|
+
body,
|
|
867
|
+
...requestOptions,
|
|
868
|
+
stream: true
|
|
869
|
+
}) } };
|
|
827
870
|
}
|
|
828
|
-
function build(request) {
|
|
871
|
+
function build(request, inspection = false) {
|
|
829
872
|
const capacity = options.catalogue?.()?.limit;
|
|
830
|
-
const plan = options.params === void 0 ? void 0 : anthropicOptions(options.params(request.params ?? {}), options.model ?? "", options.budgetOnly);
|
|
873
|
+
const plan = options.params === void 0 ? void 0 : anthropicOptions(options.params(request.params ?? {}), options.model ?? "", options.budgetOnly, options);
|
|
831
874
|
const { media: mediaOf, ...rest } = options;
|
|
832
875
|
const media = mediaOf?.(request.params ?? {});
|
|
833
876
|
const base = media === void 0 ? rest : {
|
|
834
877
|
...rest,
|
|
835
878
|
media
|
|
836
879
|
};
|
|
837
|
-
|
|
880
|
+
let requestOptions = plan === void 0 ? base : {
|
|
838
881
|
...base,
|
|
839
882
|
...plan,
|
|
840
883
|
extra: {
|
|
@@ -842,17 +885,50 @@ function createAnthropicModelPort(options) {
|
|
|
842
885
|
...options.support.extraParams(request.params ?? {})
|
|
843
886
|
}
|
|
844
887
|
};
|
|
845
|
-
const
|
|
888
|
+
const declaredDefault = options.effortCacheModels?.[options.model ?? ""];
|
|
889
|
+
const replay = options.support.planEffortCache({
|
|
890
|
+
request,
|
|
891
|
+
inspection,
|
|
892
|
+
effort: requestOptions.effort,
|
|
893
|
+
capability: options.effortCache === false ? {
|
|
894
|
+
status: "unsupported",
|
|
895
|
+
reason: "configuration-updates-unavailable"
|
|
896
|
+
} : requestOptions.thinking?.type !== "adaptive" ? {
|
|
897
|
+
status: "unsupported",
|
|
898
|
+
reason: "adaptive-thinking-required"
|
|
899
|
+
} : {
|
|
900
|
+
status: "supported",
|
|
901
|
+
...declaredDefault ? { defaultEffort: declaredDefault } : {}
|
|
902
|
+
},
|
|
903
|
+
bindingFingerprint: options.support.inspectionFingerprint({
|
|
904
|
+
connectionFingerprint: options.connectionFingerprint,
|
|
905
|
+
endpoint: options.endpoint,
|
|
906
|
+
baseURL: options.baseURL,
|
|
907
|
+
model: options.model,
|
|
908
|
+
system: request.system,
|
|
909
|
+
tools: request.tools,
|
|
910
|
+
thinking: requestOptions.thinking,
|
|
911
|
+
extra: requestOptions.extra,
|
|
912
|
+
reasoningReplay: requestOptions.reasoningReplay
|
|
913
|
+
})
|
|
914
|
+
});
|
|
915
|
+
requestOptions = {
|
|
916
|
+
...requestOptions,
|
|
917
|
+
effort: replay.baseEffort,
|
|
918
|
+
effortUpdates: replay.updates
|
|
919
|
+
};
|
|
920
|
+
const betas = [...plan?.betas ?? [], ...replay.updates.length ? [MID_CONVERSATION_EFFORT_BETA] : []];
|
|
846
921
|
return {
|
|
847
922
|
params: toAnthropicRequest(request, requestOptions),
|
|
848
923
|
requestOptions,
|
|
849
924
|
capacity,
|
|
925
|
+
replayData: replay.replayData,
|
|
850
926
|
headers: betas === void 0 || betas.length === 0 ? void 0 : { "anthropic-beta": betas.join(",") }
|
|
851
927
|
};
|
|
852
928
|
}
|
|
853
929
|
return {
|
|
854
930
|
inspect(request) {
|
|
855
|
-
const { params, requestOptions, capacity } = build(request);
|
|
931
|
+
const { params, requestOptions, capacity } = build(request, true);
|
|
856
932
|
const outputReserve = Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? params.max_tokens : capacity?.output ?? 0;
|
|
857
933
|
return options.support.inspect({
|
|
858
934
|
body: params,
|
|
@@ -869,6 +945,7 @@ function createAnthropicModelPort(options) {
|
|
|
869
945
|
}).tokens,
|
|
870
946
|
fingerprint: {
|
|
871
947
|
rendering: "anthropic-messages-v3",
|
|
948
|
+
baseURL: options.baseURL,
|
|
872
949
|
endpoint: options.endpoint ?? options.baseURL,
|
|
873
950
|
model: params.model,
|
|
874
951
|
purpose: request.purpose,
|
|
@@ -886,8 +963,8 @@ function createAnthropicModelPort(options) {
|
|
|
886
963
|
},
|
|
887
964
|
stream(request, signal, observer) {
|
|
888
965
|
signal.throwIfAborted();
|
|
889
|
-
const { params, headers, requestOptions } = build(request);
|
|
890
|
-
const prefix = anthropicRequestPrefix(request, requestOptions.media, options.support);
|
|
966
|
+
const { params, headers, requestOptions, replayData } = build(request);
|
|
967
|
+
const prefix = anthropicRequestPrefix(request, requestOptions.media, options.support, requestOptions.effortUpdates);
|
|
891
968
|
return options.support.withChatAttempts({
|
|
892
969
|
signal,
|
|
893
970
|
...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
|
|
@@ -941,7 +1018,10 @@ function createAnthropicModelPort(options) {
|
|
|
941
1018
|
prefix
|
|
942
1019
|
}, options.support)) {
|
|
943
1020
|
if (chunk.kind === "final") outcome = "ok";
|
|
944
|
-
yield chunk
|
|
1021
|
+
yield chunk.kind === "final" && replayData !== void 0 ? {
|
|
1022
|
+
...chunk,
|
|
1023
|
+
replayData
|
|
1024
|
+
} : chunk;
|
|
945
1025
|
}
|
|
946
1026
|
} catch (error) {
|
|
947
1027
|
outcome = attemptSignal.aborted ? "cancelled" : "error";
|
|
@@ -1010,8 +1090,7 @@ async function readBody(response, maxBytes) {
|
|
|
1010
1090
|
}
|
|
1011
1091
|
}
|
|
1012
1092
|
function baseUrlOf(probe) {
|
|
1013
|
-
|
|
1014
|
-
return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
|
|
1093
|
+
return messagesBaseUrl(probe.config.baseUrl);
|
|
1015
1094
|
}
|
|
1016
1095
|
/** Attaches the status so the runtime can tell an authentication failure from
|
|
1017
1096
|
* an endpoint that answered something else. The body is passed through as
|
|
@@ -1024,7 +1103,7 @@ async function get(probe, path, fetcher) {
|
|
|
1024
1103
|
return fetcher(`${baseUrlOf(probe)}${path}`, {
|
|
1025
1104
|
method: "GET",
|
|
1026
1105
|
headers: {
|
|
1027
|
-
"x-api-key": probe.secrets.apiKey ?? "",
|
|
1106
|
+
...probe.options.allowUnauthenticated === true && !probe.secrets.apiKey ? {} : { "x-api-key": probe.secrets.apiKey ?? "" },
|
|
1028
1107
|
"anthropic-version": VERSION
|
|
1029
1108
|
},
|
|
1030
1109
|
signal: probe.signal
|
|
@@ -1084,7 +1163,7 @@ function offerOf(row, id) {
|
|
|
1084
1163
|
};
|
|
1085
1164
|
}
|
|
1086
1165
|
const probeAnthropic = {
|
|
1087
|
-
/** Every model the endpoint lists. `/
|
|
1166
|
+
/** Every model the endpoint lists. `/models` is paged — it answers with
|
|
1088
1167
|
* one page plus `has_more`/`last_id` — so this walks the pages with
|
|
1089
1168
|
* `after_id` until the endpoint says there are no more. A mirror that
|
|
1090
1169
|
* reports neither field answers in one page, as it always did. */
|
|
@@ -1093,7 +1172,7 @@ const probeAnthropic = {
|
|
|
1093
1172
|
let afterId;
|
|
1094
1173
|
let remaining = probe.maxResponseBytes ?? 8388608;
|
|
1095
1174
|
for (let page = 0; page < MAX_PAGES; page += 1) {
|
|
1096
|
-
const response = await get(probe, `/
|
|
1175
|
+
const response = await get(probe, `/models${afterId === void 0 ? "" : `?after_id=${encodeURIComponent(afterId)}`}`, fetcher);
|
|
1097
1176
|
if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
|
|
1098
1177
|
const received = await readBody(response, remaining);
|
|
1099
1178
|
remaining -= received.bytes;
|
|
@@ -1112,19 +1191,19 @@ const probeAnthropic = {
|
|
|
1112
1191
|
* is also the test: an endpoint that answers it has a working key, and one
|
|
1113
1192
|
* that refuses says why.
|
|
1114
1193
|
*
|
|
1115
|
-
* An endpoint that serves `/
|
|
1116
|
-
* 404. The test then sends `/
|
|
1194
|
+
* An endpoint that serves `/messages` alone answers the listing with
|
|
1195
|
+
* 404. The test then sends `/messages` an empty body, which no model
|
|
1117
1196
|
* runs: an unauthenticated refusal (401, 403) is a wrong key, any other
|
|
1118
1197
|
* client error means the key got through, and a second 404 is an address
|
|
1119
1198
|
* that serves neither. */
|
|
1120
1199
|
async testConnection(probe, fetcher = globalThis.fetch) {
|
|
1121
|
-
const listed = await get(probe, "/
|
|
1200
|
+
const listed = await get(probe, "/models?limit=1", fetcher);
|
|
1122
1201
|
if (listed.ok) return;
|
|
1123
1202
|
if (listed.status !== 404) await refuse(listed);
|
|
1124
|
-
const asked = await fetcher(`${baseUrlOf(probe)}/
|
|
1203
|
+
const asked = await fetcher(`${baseUrlOf(probe)}/messages`, {
|
|
1125
1204
|
method: "POST",
|
|
1126
1205
|
headers: {
|
|
1127
|
-
"x-api-key": probe.secrets.apiKey ?? "",
|
|
1206
|
+
...probe.options.allowUnauthenticated === true && !probe.secrets.apiKey ? {} : { "x-api-key": probe.secrets.apiKey ?? "" },
|
|
1128
1207
|
"anthropic-version": VERSION,
|
|
1129
1208
|
"content-type": "application/json"
|
|
1130
1209
|
},
|
|
@@ -1136,21 +1215,71 @@ const probeAnthropic = {
|
|
|
1136
1215
|
}
|
|
1137
1216
|
};
|
|
1138
1217
|
//#endregion
|
|
1218
|
+
//#region src/support.ts
|
|
1219
|
+
/** Normalizes official facts without requiring an installed Chat capability. */
|
|
1220
|
+
function normalizeOffers(input) {
|
|
1221
|
+
return Object.fromEntries(input.offers.map((offer) => [offer.model, {
|
|
1222
|
+
id: offer.model,
|
|
1223
|
+
...offer.name === void 0 ? {} : { name: offer.name },
|
|
1224
|
+
...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
|
|
1225
|
+
...offer.efforts?.length ? { reasoning_options: [{
|
|
1226
|
+
type: "effort",
|
|
1227
|
+
values: [...offer.efforts]
|
|
1228
|
+
}] } : {},
|
|
1229
|
+
...offer.temperature === void 0 ? {} : { temperature: offer.temperature },
|
|
1230
|
+
...offer.toolCall === void 0 ? {} : { tool_call: offer.toolCall },
|
|
1231
|
+
...offer.input === void 0 ? {} : { attachment: offer.input.some((one) => one !== "text") },
|
|
1232
|
+
...offer.input === void 0 && offer.output === void 0 ? {} : { modalities: {
|
|
1233
|
+
...offer.input === void 0 ? {} : { input: [...offer.input] },
|
|
1234
|
+
...offer.output === void 0 ? {} : { output: [...offer.output] }
|
|
1235
|
+
} },
|
|
1236
|
+
...!offer.contextWindow && !offer.maxOutput ? {} : { limit: {
|
|
1237
|
+
...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
|
|
1238
|
+
...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
|
|
1239
|
+
} },
|
|
1240
|
+
...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
|
|
1241
|
+
}]));
|
|
1242
|
+
}
|
|
1243
|
+
/** The owner-qualified accessor is read per operation; withdrawal never exposes an old service. */
|
|
1244
|
+
function lazySupport(read) {
|
|
1245
|
+
return new Proxy({}, { get(_target, key) {
|
|
1246
|
+
if (key === "normalizeListing") return normalizeOffers;
|
|
1247
|
+
const service = read();
|
|
1248
|
+
if (!service) throw new Error("Chat model support is unavailable");
|
|
1249
|
+
const value = Reflect.get(service, key);
|
|
1250
|
+
return typeof value === "function" ? value.bind(service) : value;
|
|
1251
|
+
} });
|
|
1252
|
+
}
|
|
1253
|
+
//#endregion
|
|
1139
1254
|
//#region src/protocol.ts
|
|
1140
1255
|
/** Supplier options interpreted by the Messages implementation. */
|
|
1141
1256
|
const AnthropicProtocolOptions = z.strictObject({
|
|
1257
|
+
allowUnauthenticated: z.boolean().optional(),
|
|
1142
1258
|
reasoningReplay: z.enum([
|
|
1143
1259
|
"omit",
|
|
1144
1260
|
"signed-thinking",
|
|
1145
1261
|
"unsigned-thinking"
|
|
1146
1262
|
]).optional(),
|
|
1147
|
-
|
|
1263
|
+
effortCache: z.boolean().optional(),
|
|
1264
|
+
cacheBreakpoints: z.boolean().optional(),
|
|
1265
|
+
thinkingMode: z.enum([
|
|
1266
|
+
"adaptive",
|
|
1267
|
+
"budget",
|
|
1268
|
+
"enabled",
|
|
1269
|
+
"omit"
|
|
1270
|
+
]).optional(),
|
|
1271
|
+
thinkingEffort: z.boolean().optional(),
|
|
1272
|
+
thinkingBeta: z.boolean().optional(),
|
|
1273
|
+
thinkingSummary: z.boolean().optional(),
|
|
1274
|
+
budgetOnly: z.array(z.string()).optional(),
|
|
1275
|
+
effortCacheModels: z.record(z.string(), z.string().min(1)).optional()
|
|
1148
1276
|
});
|
|
1149
1277
|
/** Registers request mapping, streaming, inspection and probes with host-owned resources. */
|
|
1150
1278
|
function anthropicProtocolType(support, fetch) {
|
|
1151
1279
|
return {
|
|
1152
1280
|
type: "anthropic",
|
|
1153
|
-
label: "Anthropic Messages",
|
|
1281
|
+
label: "Anthropic Messages API",
|
|
1282
|
+
logo: protocolLogo,
|
|
1154
1283
|
fields: [{
|
|
1155
1284
|
key: "baseUrl",
|
|
1156
1285
|
kind: "url",
|
|
@@ -1160,19 +1289,36 @@ function anthropicProtocolType(support, fetch) {
|
|
|
1160
1289
|
userConfigurable: true,
|
|
1161
1290
|
optionsSchema: AnthropicProtocolOptions,
|
|
1162
1291
|
facts,
|
|
1292
|
+
effortCacheCapability(input) {
|
|
1293
|
+
const options = AnthropicProtocolOptions.parse(input.options ?? {});
|
|
1294
|
+
if (options.effortCache === false) return {
|
|
1295
|
+
status: "unsupported",
|
|
1296
|
+
reason: "configuration-updates-unavailable"
|
|
1297
|
+
};
|
|
1298
|
+
const defaultEffort = options.effortCacheModels?.[input.model];
|
|
1299
|
+
if (input.params.thinking === false || input.params.budgetTokens !== void 0) return {
|
|
1300
|
+
status: "unsupported",
|
|
1301
|
+
reason: "adaptive-thinking-required"
|
|
1302
|
+
};
|
|
1303
|
+
return {
|
|
1304
|
+
status: "supported",
|
|
1305
|
+
...defaultEffort ? { defaultEffort } : {}
|
|
1306
|
+
};
|
|
1307
|
+
},
|
|
1163
1308
|
prepareParams: (input) => support.prepareParams(input, facts),
|
|
1164
|
-
chat: {
|
|
1309
|
+
adapters: { chat: {
|
|
1165
1310
|
fileKinds: ["image"],
|
|
1166
1311
|
supportsModel: () => true,
|
|
1167
1312
|
createPort(call) {
|
|
1168
1313
|
const options = AnthropicProtocolOptions.parse(call.options);
|
|
1169
1314
|
return createAnthropicModelPort({
|
|
1315
|
+
connectionFingerprint: call.connectionFingerprint,
|
|
1170
1316
|
support,
|
|
1171
1317
|
fetch,
|
|
1172
1318
|
model: call.model,
|
|
1173
1319
|
endpoint: call.providerId,
|
|
1174
1320
|
apiKey: call.secrets.apiKey ?? "",
|
|
1175
|
-
baseURL:
|
|
1321
|
+
baseURL: messagesBaseUrl(call.config.baseUrl),
|
|
1176
1322
|
...options,
|
|
1177
1323
|
catalogue: () => support.catalogue(call.providerId, call.model),
|
|
1178
1324
|
media: (stored) => support.mediaContextOf({
|
|
@@ -1191,9 +1337,9 @@ function anthropicProtocolType(support, fetch) {
|
|
|
1191
1337
|
})
|
|
1192
1338
|
});
|
|
1193
1339
|
}
|
|
1194
|
-
},
|
|
1195
|
-
normalizeListing: (input) =>
|
|
1196
|
-
listModels: (probe) => probeAnthropic.listModels(probe, fetch),
|
|
1340
|
+
} },
|
|
1341
|
+
normalizeListing: (input) => normalizeOffers(input),
|
|
1342
|
+
listModels: async (probe) => ({ offers: await probeAnthropic.listModels(probe, fetch) }),
|
|
1197
1343
|
testConnection: (probe) => probeAnthropic.testConnection(probe, fetch)
|
|
1198
1344
|
};
|
|
1199
1345
|
}
|
|
@@ -1203,11 +1349,12 @@ function anthropicProtocolType(support, fetch) {
|
|
|
1203
1349
|
const TOOL_NAMES = [];
|
|
1204
1350
|
const plugin = {
|
|
1205
1351
|
name: "@eum-agent/llm-protocol-anthropic",
|
|
1206
|
-
requires: ["
|
|
1352
|
+
requires: ["network"],
|
|
1353
|
+
optionalServices: ["model-support"],
|
|
1207
1354
|
apply(ctx) {
|
|
1208
|
-
const support = ctx.services.
|
|
1355
|
+
const support = lazySupport(() => ctx.services.find("model-support"));
|
|
1209
1356
|
const network = ctx.services.get("network");
|
|
1210
|
-
ctx.
|
|
1357
|
+
ctx.modelProtocols.register(anthropicProtocolType(support, network.fetch));
|
|
1211
1358
|
}
|
|
1212
1359
|
};
|
|
1213
1360
|
//#endregion
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"en-US": "Anthropic Model Protocol",
|
|
5
5
|
"zh-CN": "模型协议 · Anthropic"
|
|
6
6
|
},
|
|
7
|
-
"version": "1.0
|
|
7
|
+
"version": "1.1.0",
|
|
8
8
|
"type": "module",
|
|
9
9
|
"description": "Public Anthropic model communication protocol",
|
|
10
10
|
"license": "MIT",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"dist"
|
|
18
18
|
],
|
|
19
19
|
"devDependencies": {
|
|
20
|
-
"@eum-agent/plugin": "1.0
|
|
20
|
+
"@eum-agent/plugin": "1.1.0"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"zod": "^4.4.3",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"yaoguang": {
|
|
28
28
|
"kind": "extension",
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@eum-agent/llm-management": "1.0
|
|
30
|
+
"@eum-agent/llm-management": "1.1.0"
|
|
31
31
|
},
|
|
32
32
|
"foundationDependencies": {
|
|
33
33
|
"@eum-agent/infra-local": "1.0.1"
|