@eum-agent/llm-protocol-anthropic 0.0.0-stage → 1.0.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.
Files changed (3) hide show
  1. package/dist/index.js +939 -0
  2. package/package.json +42 -3
  3. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,939 @@
1
+ import { z } from "zod";
2
+ import Anthropic, { APIConnectionError, APIError } from "@anthropic-ai/sdk";
3
+ import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
4
+ import { createHash } from "node:crypto";
5
+ //#region src/protocol/facts.ts
6
+ /** Parameter ranges and request limits for this provider wire. */
7
+ const facts = {
8
+ maxTokensRequired: true,
9
+ maxTokensFallback: 8192,
10
+ temperature: {
11
+ min: 0,
12
+ max: 1,
13
+ step: .05,
14
+ default: 1
15
+ },
16
+ thinkingSwitch: true,
17
+ limits: {
18
+ requestBytes: 33554432,
19
+ images: 100
20
+ }
21
+ };
22
+ //#endregion
23
+ //#region src/protocol/errors.ts
24
+ /**
25
+ * SDK exception → port error. `@anthropic-ai/sdk`'s
26
+ * `APIError` carries the response `.headers` and the raw `.error` body
27
+ * verbatim — either can echo a credential (a misbehaving proxy reflecting
28
+ * the `x-api-key`/`Authorization` request header back on an error
29
+ * response). The port error is a *fresh* object: its message is built from
30
+ * HTTP status and the SDK's own `type` discriminant such as
31
+ * `'rate_limit_error'`, the headers object is never attached, and the body
32
+ * travels as `providerText`, which the runtime's guard redacts against the
33
+ * endpoint's credentials before showing it.
34
+ */
35
+ /** Thrown by `stream()` once retries are exhausted (or the failure was
36
+ * never retryable to begin with) — the one error shape the call-model
37
+ * effect ever surfaces to the kernel. A plain `Error` subclass: the driver
38
+ * (kernel's driver.ts) only ever reads `.message` off whatever an effect
39
+ * handler throws, so `.message` alone is what has to stay both informative
40
+ * and credential-free. */
41
+ var ModelCallError = class extends Error {
42
+ status;
43
+ retryable;
44
+ /** The endpoint's own error body, unredacted. The runtime's guard removes
45
+ * every credential of the endpoint from it before it reaches a reason. */
46
+ providerText;
47
+ /** What the status alone says the refusal is (`failureKindOf`). */
48
+ kind;
49
+ constructor(message, options) {
50
+ super(message);
51
+ this.name = "ModelCallError";
52
+ this.status = options.status;
53
+ this.retryable = options.retryable;
54
+ this.providerText = options.providerText;
55
+ this.kind = options.status === 413 ? "request-too-large" : void 0;
56
+ }
57
+ };
58
+ /** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
59
+ * every other status is not — retrying a bad request or an authentication
60
+ * failure only spends the backoff budget on a call that will never succeed. */
61
+ function isRetryableStatus(status) {
62
+ return status === 408 || status === 409 || status === 429 || status !== void 0 && status >= 500;
63
+ }
64
+ /** The provider's own `retry-after` header, in milliseconds — read for the
65
+ * backoff delay only; the header value itself carries no credential. */
66
+ function retryAfterMs(error) {
67
+ if (!(error instanceof APIError)) return void 0;
68
+ const header = error.headers?.get("retry-after");
69
+ if (!header) return void 0;
70
+ const seconds = Number(header);
71
+ if (!Number.isFinite(seconds)) return void 0;
72
+ return seconds * 1e3;
73
+ }
74
+ /** Converts any exception the SDK call can throw into a `ModelCallError`.
75
+ * Never reads `error.headers` into the result; the body goes to
76
+ * `providerText` alone. */
77
+ /** Error types an event stream reports mid-reply that a second attempt can
78
+ * get past: the stream carries no status, only this. */
79
+ const RETRYABLE_TYPES = /* @__PURE__ */ new Set([
80
+ "overloaded_error",
81
+ "api_error",
82
+ "rate_limit_error"
83
+ ]);
84
+ function streamErrorType(error) {
85
+ const body = error.error;
86
+ const inner = body?.error?.type ?? body?.type;
87
+ return typeof inner === "string" ? inner : void 0;
88
+ }
89
+ function toPortError(error) {
90
+ if (error instanceof APIError) {
91
+ const status = error.status;
92
+ const retryable = error instanceof APIConnectionError || isRetryableStatus(status) || status === void 0 && RETRYABLE_TYPES.has(streamErrorType(error) ?? "");
93
+ const type = error.type;
94
+ return new ModelCallError(`Anthropic API error (status ${status ?? "unknown"}${type ? `, type ${type}` : ""})`, {
95
+ status,
96
+ retryable,
97
+ providerText: providerTextOf(error)
98
+ });
99
+ }
100
+ return new ModelCallError(`Anthropic call failed: ${error instanceof Error ? error.message : String(error)}`, { retryable: false });
101
+ }
102
+ /** The parsed error body when the SDK parsed one, else the SDK's message,
103
+ * which carries the raw body text. Never the headers. */
104
+ function providerTextOf(error) {
105
+ const text = error.error === void 0 ? error.message : JSON.stringify(error.error);
106
+ return text === void 0 || text.trim() === "" ? void 0 : text;
107
+ }
108
+ //#endregion
109
+ //#region src/protocol/request.ts
110
+ /**
111
+ * `ModelRequest` (kernel's vocabulary, provider-neutral) → Anthropic's
112
+ * `MessageCreateParamsStreaming`. Everything this side must fix for the
113
+ * outbound request lands here: `system` as the top-level parameter (not a
114
+ * message), tool results kept as one message with several `tool_result`
115
+ * blocks (the transcript shape, already Anthropic's own), and the thinking
116
+ * configuration the port decided. Always streamed — 128K of output without
117
+ * streaming risks an HTTP timeout.
118
+ *
119
+ * **Every request extends the previous one.** A reply's recorded volatile
120
+ * notes are rendered just before it, as a text block at the end of the user
121
+ * content that precedes it — exactly where the request that produced the
122
+ * reply carried them — and the current step's notes go at the very end. So
123
+ * the conversation a signature covers, and the prefix a cache entry keys on,
124
+ * never change once sent.
125
+ *
126
+ * A signed `ThinkingPart` is echoed only when its endpoint, model and covered
127
+ * non-thinking prefix match. Any mismatch drops the message's whole thinking
128
+ * group while preserving its visible text and tool calls. A redacted block
129
+ * goes back as the `redacted_thinking` it came as.
130
+ */
131
+ const SUMMARY_THINKING_HEADROOM = 8192;
132
+ const DEFAULT_MAX_TOKENS = 8192;
133
+ const TOOL_ID = /^[a-zA-Z0-9_-]+$/;
134
+ /**
135
+ * The id Anthropic is sent for one tool call. A legal id goes as it is; any
136
+ * other — another endpoint's `functions.name:0` — becomes its legal
137
+ * characters plus a hash of the whole, decided by the id alone so a later
138
+ * step adding ids never changes how an earlier one was sent.
139
+ */
140
+ function anthropicToolId(id) {
141
+ if (TOOL_ID.test(id)) return id;
142
+ const hash = createHash("sha256").update(id).digest("hex").slice(0, 12);
143
+ return `${id.replace(/[^a-zA-Z0-9_-]/g, "_")}_${hash}`;
144
+ }
145
+ /** A planned file as blocks: the label and the image, or the line in its place. */
146
+ function fileBlocks(planned, rendering) {
147
+ const label = {
148
+ type: "text",
149
+ text: planned.label
150
+ };
151
+ if (planned.fate !== "send") return [label];
152
+ const data = rendering === "wire" ? planned.data ?? "" : planned.ref.forModel?.id ?? planned.ref.id;
153
+ return [label, {
154
+ type: "image",
155
+ source: {
156
+ type: "base64",
157
+ media_type: planned.mediaType,
158
+ data
159
+ }
160
+ }];
161
+ }
162
+ function toContentBlockParams(part, at, context) {
163
+ switch (part.type) {
164
+ case "text": return [{
165
+ type: "text",
166
+ text: part.text
167
+ }];
168
+ case "thinking": return [part.redacted === true ? {
169
+ type: "redacted_thinking",
170
+ data: part.signature ?? ""
171
+ } : {
172
+ type: "thinking",
173
+ thinking: part.text,
174
+ signature: part.signature ?? ""
175
+ }];
176
+ case "tool-use": return [{
177
+ type: "tool_use",
178
+ id: anthropicToolId(part.id),
179
+ name: part.name,
180
+ input: part.input
181
+ }];
182
+ case "tool-result": {
183
+ const files = part.files ?? [];
184
+ const content = files.length === 0 ? part.content : [...part.content === "" ? [] : [{
185
+ type: "text",
186
+ text: part.content
187
+ }], ...files.flatMap((_, index) => fileBlocks(context.plan.at(at.message, at.part, index), context.rendering))];
188
+ return [{
189
+ type: "tool_result",
190
+ tool_use_id: anthropicToolId(part.toolUseId),
191
+ content,
192
+ ...part.isError !== void 0 ? { is_error: part.isError } : {}
193
+ }];
194
+ }
195
+ case "file": return fileBlocks(context.plan.at(at.message, at.part), context.rendering);
196
+ default: throw new Error(`unhandled content part type: ${String(part.type)}`);
197
+ }
198
+ }
199
+ /**
200
+ * Whether this endpoint can send one message's thinking group back.
201
+ *
202
+ * Two ways it cannot. **No signature**: it was never signed — a transcript
203
+ * resumed from an OpenAI-style endpoint, or from before signatures were
204
+ * carried — and a fabricated one is worse than none, because Anthropic
205
+ * verifies it and answers a modified block with `400 invalid_request_error`,
206
+ * failing every continuation. Endpoint, model and prefix attribution must all
207
+ * match because a change to any covered input can invalidate the signature.
208
+ * One incompatible member drops the whole group so no middle block is removed.
209
+ *
210
+ * Comparing endpoint ids is deliberately coarser than "same signer": two keys
211
+ * against one vendor may share a signer, but replaying a block that cannot be
212
+ * verified would reject the entire request.
213
+ */
214
+ function thinkingGroupIsSendable(message, options, prefix) {
215
+ const thinking = message.content.filter((part) => part.type === "thinking");
216
+ if (thinking.length === 0) return true;
217
+ const model = options.model ?? "";
218
+ return thinking.every((part) => part.signature !== void 0 && part.issuer !== void 0 && part.issuer === options.endpoint && part.originModel === model && part.prefix === prefix);
219
+ }
220
+ /** A text block with nothing in it: Anthropic refuses one. */
221
+ function isEmptyText(part) {
222
+ return part.type === "text" && part.text === "";
223
+ }
224
+ function blocksOf(message, index, sendThinking, context) {
225
+ return message.content.flatMap((part, partIndex) => isEmptyText(part) || part.type === "thinking" && !sendThinking ? [] : toContentBlockParams(part, {
226
+ message: index,
227
+ part: partIndex
228
+ }, context));
229
+ }
230
+ /** The one text block a set of notes renders as, or nothing. */
231
+ function noteBlock(notes) {
232
+ const text = (notes ?? []).map((note) => note.text).join("\n\n");
233
+ return text === "" ? [] : [{
234
+ type: "text",
235
+ text
236
+ }];
237
+ }
238
+ /**
239
+ * Appends blocks to the conversation's last user message, or as a user
240
+ * message of their own after an assistant one. The Messages API combines
241
+ * consecutive messages of one role, so both forms are one user turn.
242
+ */
243
+ function appendUser(messages, blocks) {
244
+ if (blocks.length === 0) return;
245
+ const last = messages.at(-1);
246
+ if (last === void 0 || last.role !== "user") {
247
+ messages.push({
248
+ role: "user",
249
+ content: [...blocks]
250
+ });
251
+ return;
252
+ }
253
+ const content = typeof last.content === "string" ? [] : last.content;
254
+ messages[messages.length - 1] = {
255
+ ...last,
256
+ content: [...content, ...blocks]
257
+ };
258
+ }
259
+ /**
260
+ * Renders messages in Anthropic's shape, each reply preceded by the notes
261
+ * its request appended, then `trailing` at the end. `sendThinking` decides,
262
+ * per message index, whether its thinking group goes out.
263
+ */
264
+ function render(messages, trailing, sendThinking, context) {
265
+ const out = [];
266
+ messages.forEach((message, index) => {
267
+ if (message.role === "assistant") appendUser(out, noteBlock(message.volatile));
268
+ const content = blocksOf(message, index, sendThinking(message, index), context);
269
+ if (content.length === 0) return;
270
+ if (message.role === "user") appendUser(out, content);
271
+ else out.push({
272
+ role: "assistant",
273
+ content
274
+ });
275
+ });
276
+ appendUser(out, noteBlock(trailing));
277
+ return out;
278
+ }
279
+ function toToolParam(tool) {
280
+ return {
281
+ name: tool.name,
282
+ description: tool.description,
283
+ input_schema: tool.inputSchema
284
+ };
285
+ }
286
+ /** A copy without cache marks: where a breakpoint sits says nothing about what
287
+ * the provider signed, so it must not change the fingerprint. */
288
+ function unmarked(value) {
289
+ return JSON.parse(JSON.stringify(value, (key, inner) => key === "cache_control" ? void 0 : inner));
290
+ }
291
+ function systemOf(request) {
292
+ return request.system?.map((text) => ({
293
+ type: "text",
294
+ text
295
+ }));
296
+ }
297
+ function toolsOf(request) {
298
+ return request.tools && request.tools.length > 0 ? request.tools.map(toToolParam) : void 0;
299
+ }
300
+ function prefixOf(system, tools, messages, support) {
301
+ return support.inspectionFingerprint(unmarked({
302
+ ...system === void 0 ? {} : { system },
303
+ ...tools === void 0 ? {} : { tools },
304
+ messages
305
+ }));
306
+ }
307
+ /**
308
+ * Computes the non-thinking prefix covered by a historical assistant
309
+ * signature: everything before that message, its own recorded notes included
310
+ * — they ended the request it answered. `messageIndex` names the message.
311
+ */
312
+ function anthropicPrefixBefore(request, messageIndex, media, support) {
313
+ const before = request.messages.slice(0, messageIndex);
314
+ const notes = request.messages[messageIndex]?.volatile;
315
+ return prefixOf(systemOf(request), toolsOf(request), render(before, notes, () => false, fingerprintContext(request, media, support)), support);
316
+ }
317
+ /** The send plan, from the options' media context or the permissive default. */
318
+ function planOf(request, media, support) {
319
+ return support.planMedia(request, media ?? {
320
+ acceptsImages: true,
321
+ limits: void 0
322
+ });
323
+ }
324
+ function fingerprintContext(request, media, support) {
325
+ return {
326
+ plan: planOf({
327
+ ...request,
328
+ files: void 0
329
+ }, media, support),
330
+ rendering: "fingerprint"
331
+ };
332
+ }
333
+ /**
334
+ * Computes the prefix a new reply is signed under: everything the request
335
+ * carried, its notes included, rendered the way `anthropicPrefixBefore`
336
+ * renders it on the next step and without cache marks.
337
+ */
338
+ function anthropicRequestPrefix(request, media, support) {
339
+ return prefixOf(systemOf(request), toolsOf(request), render(request.messages, request.volatile, () => false, fingerprintContext(request, media, support)), support);
340
+ }
341
+ /** Counts provider-retained thinking state that is actually replayed. */
342
+ function anthropicHiddenInputTokens(request, options) {
343
+ return request.messages.reduce((total, message, index) => {
344
+ if (!thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support))) return total;
345
+ return total + Math.max(0, ...message.content.map((part) => part.type === "thinking" ? part.outputTokens ?? 0 : 0));
346
+ }, 0);
347
+ }
348
+ const EPHEMERAL = { type: "ephemeral" };
349
+ /** Marks the last markable block of one message. */
350
+ function markLast(message) {
351
+ if (typeof message.content === "string") return message;
352
+ const content = [...message.content];
353
+ for (let index = content.length - 1; index >= 0; index -= 1) {
354
+ const block = content[index];
355
+ if (!block || block.type === "thinking" || block.type === "redacted_thinking") continue;
356
+ content[index] = {
357
+ ...block,
358
+ cache_control: EPHEMERAL
359
+ };
360
+ return {
361
+ ...message,
362
+ content
363
+ };
364
+ }
365
+ return message;
366
+ }
367
+ /**
368
+ * Two conversation breakpoints: the end of this request, which the next step
369
+ * repeats, and the end of the previous step's request — the user content
370
+ * just before the last reply — whose cache entry this step reads exactly,
371
+ * however many blocks the step added since.
372
+ */
373
+ function withConversationBreakpoints(messages) {
374
+ const out = [...messages];
375
+ const lastIndex = out.length - 1;
376
+ if (lastIndex < 0) return out;
377
+ out[lastIndex] = markLast(out[lastIndex]);
378
+ const previous = out.findLastIndex((message) => message.role === "assistant") - 1;
379
+ if (previous >= 0 && previous !== lastIndex && out[previous]?.role === "user") out[previous] = markLast(out[previous]);
380
+ return out;
381
+ }
382
+ function toAnthropicRequest(request, options) {
383
+ const summary = request.purpose === "summary";
384
+ if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
385
+ const ordinaryMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
386
+ const thinkingOn = options.thinking !== void 0 && options.thinking.type !== "disabled";
387
+ const maxTokens = summary ? Math.min(request.summaryMaxTokens, Number.isInteger(ordinaryMaxTokens) && ordinaryMaxTokens > 0 ? ordinaryMaxTokens : request.summaryMaxTokens) + (thinkingOn ? SUMMARY_THINKING_HEADROOM : 0) : ordinaryMaxTokens;
388
+ const system = request.system?.map((text, index, all) => index === all.length - 1 ? {
389
+ type: "text",
390
+ text,
391
+ cache_control: EPHEMERAL
392
+ } : {
393
+ type: "text",
394
+ text
395
+ });
396
+ const tools = toolsOf(request);
397
+ const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support)), {
398
+ plan: planOf(request, options.media, options.support),
399
+ rendering: "wire"
400
+ });
401
+ return {
402
+ model: options.model ?? "",
403
+ max_tokens: maxTokens,
404
+ stream: true,
405
+ ...options.effort === void 0 ? {} : { output_config: { effort: options.effort } },
406
+ ...options.thinking === void 0 ? {} : { thinking: options.thinking },
407
+ ...options.temperature === void 0 ? {} : { temperature: options.temperature },
408
+ messages: withConversationBreakpoints(messages),
409
+ ...system === void 0 ? {} : { system },
410
+ ...tools === void 0 ? {} : { tools },
411
+ ...request.toolChoice === "none" && tools !== void 0 ? { tool_choice: { type: "none" } } : {},
412
+ ...summary ? {} : options.extra
413
+ };
414
+ }
415
+ //#endregion
416
+ //#region src/protocol/stream.ts
417
+ function toFinishReason(stopReason) {
418
+ switch (stopReason) {
419
+ case "tool_use": return "tool-calls";
420
+ case "max_tokens":
421
+ case "model_context_window_exceeded": return "max-tokens";
422
+ case "refusal": return "refusal";
423
+ default: return "stop";
424
+ }
425
+ }
426
+ /** The accumulated `input_json_delta` text as JSON, or `undefined` when it
427
+ * will not parse — which is what a tool-use block cut off at `max_tokens`
428
+ * looks like. `JSON.parse` never produces `undefined` itself, so it is free
429
+ * to stand for "no usable input here". */
430
+ function parseToolInput(json) {
431
+ if (json.length === 0) return {};
432
+ try {
433
+ return JSON.parse(json);
434
+ } catch {
435
+ return;
436
+ }
437
+ }
438
+ /**
439
+ * What a reply that was nothing but a cut-off tool call says instead.
440
+ *
441
+ * The call is dropped, and with nothing else in the reply that would leave an
442
+ * assistant message with no content — which reads as a model that had nothing
443
+ * to say and ends the turn as an ordinary completion. This sentence is the
444
+ * adapter's own, not the endpoint's, and it goes where both the person and the
445
+ * next turn read it. The `openai` member carries the same one for the same
446
+ * reason.
447
+ */
448
+ const CUT_OFF_NOTICE = "[The reply was cut off while a tool call was still being written; none of it could be used.]";
449
+ async function* mapAnthropicStream(events, attribution, support) {
450
+ const blocks = /* @__PURE__ */ new Map();
451
+ const finalContent = [];
452
+ let cutOff = false;
453
+ let inputTokens = 0;
454
+ let outputTokens = 0;
455
+ let cache = {};
456
+ let stopped = false;
457
+ let stopReason = null;
458
+ let refusalCategory;
459
+ for await (const event of events) switch (event.type) {
460
+ case "message_start": {
461
+ const usage = event.message.usage;
462
+ inputTokens = usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
463
+ outputTokens = event.message.usage.output_tokens;
464
+ cache = {
465
+ ...typeof usage.cache_read_input_tokens === "number" ? { cacheReadTokens: usage.cache_read_input_tokens } : {},
466
+ ...typeof usage.cache_creation_input_tokens === "number" ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}
467
+ };
468
+ break;
469
+ }
470
+ case "content_block_start": {
471
+ const block = event.content_block;
472
+ if (block.type === "text") blocks.set(event.index, {
473
+ kind: "text",
474
+ text: ""
475
+ });
476
+ else if (block.type === "tool_use") {
477
+ blocks.set(event.index, {
478
+ kind: "tool-use",
479
+ id: block.id,
480
+ name: block.name,
481
+ json: ""
482
+ });
483
+ yield {
484
+ kind: "tool-call-delta",
485
+ id: block.id,
486
+ name: block.name,
487
+ inputDelta: ""
488
+ };
489
+ } else if (block.type === "thinking") blocks.set(event.index, {
490
+ kind: "thinking",
491
+ text: ""
492
+ });
493
+ else if (block.type === "redacted_thinking") blocks.set(event.index, {
494
+ kind: "redacted",
495
+ data: block.data
496
+ });
497
+ else blocks.set(event.index, { kind: "skipped" });
498
+ break;
499
+ }
500
+ case "content_block_delta": {
501
+ const block = blocks.get(event.index);
502
+ const delta = event.delta;
503
+ if (delta.type === "text_delta") {
504
+ if (block?.kind === "text") block.text += delta.text;
505
+ yield {
506
+ kind: "text-delta",
507
+ text: delta.text
508
+ };
509
+ } else if (delta.type === "thinking_delta") {
510
+ if (block?.kind === "thinking") block.text += delta.thinking;
511
+ yield {
512
+ kind: "thinking-delta",
513
+ text: delta.thinking
514
+ };
515
+ } else if (delta.type === "signature_delta") {
516
+ if (block?.kind === "thinking") block.signature = delta.signature;
517
+ } else if (delta.type === "input_json_delta" && block?.kind === "tool-use") {
518
+ block.json += delta.partial_json;
519
+ yield {
520
+ kind: "tool-call-delta",
521
+ id: block.id,
522
+ inputDelta: delta.partial_json
523
+ };
524
+ }
525
+ break;
526
+ }
527
+ case "content_block_stop": {
528
+ const block = blocks.get(event.index);
529
+ if (block?.kind === "text") {
530
+ if (block.text !== "") finalContent.push({
531
+ type: "text",
532
+ text: block.text
533
+ });
534
+ } else if (block?.kind === "redacted") finalContent.push({
535
+ type: "thinking",
536
+ text: "",
537
+ signature: block.data,
538
+ redacted: true
539
+ });
540
+ else if (block?.kind === "tool-use") {
541
+ const input = parseToolInput(block.json);
542
+ if (input === void 0) cutOff = true;
543
+ else finalContent.push({
544
+ type: "tool-use",
545
+ id: block.id,
546
+ name: block.name,
547
+ input
548
+ });
549
+ } else if (block?.kind === "thinking") finalContent.push({
550
+ type: "thinking",
551
+ text: block.text,
552
+ ...block.signature === void 0 ? {} : { signature: block.signature }
553
+ });
554
+ break;
555
+ }
556
+ case "message_delta":
557
+ stopReason = event.delta.stop_reason ?? stopReason;
558
+ if (event.delta.stop_details?.type === "refusal") refusalCategory = event.delta.stop_details.category ?? "unspecified";
559
+ outputTokens = event.usage.output_tokens;
560
+ break;
561
+ case "message_stop": stopped = true;
562
+ }
563
+ if (!stopped) throw support.interruptedFailure();
564
+ if (finalContent.length === 0 && cutOff) finalContent.push({
565
+ type: "text",
566
+ text: CUT_OFF_NOTICE
567
+ });
568
+ const attributedContent = finalContent.map((part) => part.type === "thinking" && part.signature !== void 0 && attribution !== void 0 ? {
569
+ ...part,
570
+ originModel: attribution.originModel,
571
+ prefix: attribution.prefix,
572
+ outputTokens
573
+ } : part);
574
+ yield {
575
+ kind: "final",
576
+ finishReason: toFinishReason(stopReason),
577
+ usage: {
578
+ inputTokens,
579
+ outputTokens,
580
+ ...cache
581
+ },
582
+ ...refusalCategory !== void 0 ? { refusalCategory } : {},
583
+ message: {
584
+ role: "assistant",
585
+ content: attributedContent
586
+ }
587
+ };
588
+ }
589
+ //#endregion
590
+ //#region src/protocol/port.ts
591
+ /**
592
+ * Wires request-building (request.ts), stream-mapping (stream.ts) and the
593
+ * injected host retry loop into the `ModelPort` the
594
+ * kernel's call-model slot dispatches to. Rate limits, overload, server
595
+ * errors, dropped connections and stalls are retried with a
596
+ * `retry-after`-honouring backoff; a retry after output first retracts what
597
+ * streamed. Everything else, and a retryable failure once the budget is
598
+ * spent, becomes the error the driver turns into a failed outcome.
599
+ */
600
+ /** Lets a budget-thinking model think between tool calls. */
601
+ const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
602
+ /** The budget a budget-thinking model gets when a person set none. */
603
+ const DEFAULT_BUDGET = 16e3;
604
+ const BUDGET_FLOOR = 1024;
605
+ /**
606
+ * The neutral plan in Anthropic's own spelling.
607
+ *
608
+ * Thinking on is `adaptive` with a readable summary — current models stream
609
+ * empty thinking without `display: 'summarized'` — and the effort; a model
610
+ * whose thinking is a token budget gets `enabled` with the stored budget or a
611
+ * default one under `max_tokens`, or no thinking at all when `max_tokens`
612
+ * leaves no room for the smallest budget. Thinking off is `disabled`. While
613
+ * thinking is on no temperature goes out: Anthropic refuses one then.
614
+ */
615
+ function anthropicOptions(plan, model, budgetOnly = []) {
616
+ const on = plan.thinking === true;
617
+ const maxTokens = plan.maxTokens;
618
+ const budget = () => {
619
+ const ceiling = (maxTokens ?? Number.POSITIVE_INFINITY) - 1;
620
+ if (ceiling < BUDGET_FLOOR) return void 0;
621
+ const wanted = plan.budgetTokens ?? Math.min(DEFAULT_BUDGET, Math.floor((maxTokens ?? 0) / 2));
622
+ return Math.min(Math.max(wanted, BUDGET_FLOOR), ceiling);
623
+ };
624
+ const byBudget = plan.budgetTokens !== void 0 || budgetOnly.some((one) => model.startsWith(one));
625
+ const tokens = on && byBudget ? budget() : void 0;
626
+ const thinking = !on ? plan.thinking === false ? { type: "disabled" } : void 0 : byBudget ? tokens === void 0 ? void 0 : {
627
+ type: "enabled",
628
+ budget_tokens: tokens
629
+ } : {
630
+ type: "adaptive",
631
+ display: "summarized"
632
+ };
633
+ return {
634
+ ...plan.effort === void 0 || !on ? {} : { effort: plan.effort },
635
+ ...plan.temperature === void 0 || on ? {} : { temperature: plan.temperature },
636
+ ...maxTokens === void 0 ? {} : { maxTokens },
637
+ ...thinking === void 0 ? {} : { thinking },
638
+ ...thinking?.type === "enabled" ? { betas: [INTERLEAVED_THINKING_BETA] } : {}
639
+ };
640
+ }
641
+ /** Creates an Anthropic port with synchronous request inspection and safe stream retries. */
642
+ function createAnthropicModelPort(options) {
643
+ function clientForAttempt(reportProgress) {
644
+ return options.client ?? new Anthropic({
645
+ apiKey: options.apiKey ?? "",
646
+ fetch: async (...args) => options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress),
647
+ baseURL: options.baseURL ?? "",
648
+ maxRetries: 0
649
+ });
650
+ }
651
+ function build(request) {
652
+ const capacity = options.catalogue?.()?.limit;
653
+ const plan = options.params === void 0 ? void 0 : anthropicOptions(options.params(request.params ?? {}), options.model ?? "", options.budgetOnly);
654
+ const { media: mediaOf, ...rest } = options;
655
+ const media = mediaOf?.(request.params ?? {});
656
+ const base = media === void 0 ? rest : {
657
+ ...rest,
658
+ media
659
+ };
660
+ const requestOptions = plan === void 0 ? base : {
661
+ ...base,
662
+ ...plan,
663
+ extra: {
664
+ ...options.extra,
665
+ ...options.support.extraParams(request.params ?? {})
666
+ }
667
+ };
668
+ const betas = plan?.betas;
669
+ return {
670
+ params: toAnthropicRequest(request, requestOptions),
671
+ requestOptions,
672
+ capacity,
673
+ headers: betas === void 0 || betas.length === 0 ? void 0 : { "anthropic-beta": betas.join(",") }
674
+ };
675
+ }
676
+ return {
677
+ inspect(request) {
678
+ const { params, requestOptions, capacity } = build(request);
679
+ const outputReserve = Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? params.max_tokens : capacity?.output ?? 0;
680
+ return options.support.inspect({
681
+ body: params,
682
+ textTokens: countTokens(JSON.stringify(params), { disallowedSpecial: /* @__PURE__ */ new Set() }),
683
+ tokenizer: "o200k_base-json-v1",
684
+ request,
685
+ capacity,
686
+ outputReserve,
687
+ outputReserveSource: Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? "enforced" : "capacity",
688
+ hiddenInputTokens: anthropicHiddenInputTokens(request, requestOptions),
689
+ mediaTokens: options.support.planMedia(request, requestOptions.media ?? {
690
+ acceptsImages: true,
691
+ limits: void 0
692
+ }).tokens,
693
+ fingerprint: {
694
+ rendering: "anthropic-messages-v3",
695
+ endpoint: options.endpoint ?? options.baseURL,
696
+ model: params.model,
697
+ purpose: request.purpose,
698
+ contextWindow: request.params?.contextWindow,
699
+ capacity,
700
+ settings: {
701
+ effort: requestOptions.effort,
702
+ thinking: requestOptions.thinking,
703
+ temperature: requestOptions.temperature,
704
+ maxTokens: params.max_tokens,
705
+ extra: request.purpose === "summary" ? void 0 : requestOptions.extra
706
+ }
707
+ }
708
+ });
709
+ },
710
+ stream(request, signal) {
711
+ const { params, headers, requestOptions } = build(request);
712
+ const prefix = anthropicRequestPrefix(request, requestOptions.media, options.support);
713
+ return options.support.withChatAttempts({
714
+ signal,
715
+ ...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
716
+ ...options.sleep === void 0 ? {} : { sleep: options.sleep },
717
+ ...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
718
+ async *attempt(attemptSignal, reportProgress) {
719
+ const events = await clientForAttempt(reportProgress).messages.create(params, {
720
+ signal: attemptSignal,
721
+ ...headers === void 0 ? {} : { headers }
722
+ });
723
+ yield* mapAnthropicStream((async function* () {
724
+ for await (const event of events) {
725
+ reportProgress();
726
+ yield event;
727
+ }
728
+ })(), {
729
+ originModel: params.model,
730
+ prefix
731
+ }, options.support);
732
+ },
733
+ classify(error) {
734
+ const portError = toPortError(error);
735
+ return {
736
+ error: portError,
737
+ retryable: portError.retryable,
738
+ retryAfterMs: retryAfterMs(error)
739
+ };
740
+ }
741
+ });
742
+ }
743
+ };
744
+ }
745
+ //#endregion
746
+ //#region src/protocol/probe.ts
747
+ const VERSION = "2023-06-01";
748
+ function baseUrlOf(probe) {
749
+ const configured = probe.config.baseUrl;
750
+ return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
751
+ }
752
+ /** Attaches the status so the runtime can tell an authentication failure from
753
+ * an endpoint that answered something else. The body is passed through as
754
+ * the message; whether any of it reaches a person is not this file's call. */
755
+ async function refuse(response) {
756
+ const body = await response.text().catch(() => "");
757
+ throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
758
+ }
759
+ async function get(probe, path, fetcher) {
760
+ return fetcher(`${baseUrlOf(probe)}${path}`, {
761
+ method: "GET",
762
+ headers: {
763
+ "x-api-key": probe.secrets.apiKey ?? "",
764
+ "anthropic-version": VERSION
765
+ },
766
+ signal: probe.signal
767
+ });
768
+ }
769
+ /** Enough pages to carry a catalogue several times the size of the one
770
+ * Anthropic serves, while still ending if an endpoint keeps claiming
771
+ * `has_more` forever. */
772
+ const MAX_PAGES = 20;
773
+ /** The effort levels this endpoint may list, in ascending order. */
774
+ const EFFORT_LEVELS = [
775
+ "minimal",
776
+ "low",
777
+ "medium",
778
+ "high",
779
+ "xhigh",
780
+ "max"
781
+ ];
782
+ function record(value) {
783
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
784
+ }
785
+ function supported(value) {
786
+ return record(value)?.supported === true;
787
+ }
788
+ /** A positive count, or nothing: the endpoint answers `0` or `null` for a
789
+ * limit it does not know. */
790
+ function count(value) {
791
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
792
+ }
793
+ /**
794
+ * One listed model as an offer, reading each field only where the entry
795
+ * carries it. `created_at` may be an epoch value when the release date is
796
+ * unknown, so anything before 2000 is read as absent.
797
+ */
798
+ function offerOf(row, id) {
799
+ const capabilities = record(row.capabilities);
800
+ const effort = record(capabilities?.effort);
801
+ const efforts = effort?.supported === true ? EFFORT_LEVELS.filter((level) => supported(effort[level])) : [];
802
+ const thinking = record(capabilities?.thinking);
803
+ const input = capabilities === void 0 ? void 0 : [
804
+ "text",
805
+ ...supported(capabilities.image_input) ? ["image"] : [],
806
+ ...supported(capabilities.pdf_input) ? ["pdf"] : []
807
+ ];
808
+ const released = typeof row.created_at === "string" && row.created_at >= "2000" ? row.created_at.slice(0, 10) : void 0;
809
+ const contextWindow = count(row.max_input_tokens);
810
+ const maxOutput = count(row.max_tokens);
811
+ return {
812
+ model: id,
813
+ ...typeof row.display_name === "string" ? { name: row.display_name } : {},
814
+ ...contextWindow === void 0 ? {} : { contextWindow },
815
+ ...maxOutput === void 0 ? {} : { maxOutput },
816
+ ...typeof thinking?.supported === "boolean" ? { reasoning: thinking.supported } : {},
817
+ ...efforts.length === 0 ? {} : { efforts },
818
+ ...input === void 0 ? {} : { input },
819
+ ...released === void 0 ? {} : { releaseDate: released }
820
+ };
821
+ }
822
+ const probeAnthropic = {
823
+ /** Every model the endpoint lists. `/v1/models` is paged — it answers with
824
+ * one page plus `has_more`/`last_id` — so this walks the pages with
825
+ * `after_id` until the endpoint says there are no more. A mirror that
826
+ * reports neither field answers in one page, as it always did. */
827
+ async listModels(probe, fetcher = globalThis.fetch) {
828
+ const offers = [];
829
+ let afterId;
830
+ for (let page = 0; page < MAX_PAGES; page += 1) {
831
+ const response = await get(probe, `/v1/models${afterId === void 0 ? "" : `?after_id=${encodeURIComponent(afterId)}`}`, fetcher);
832
+ if (!response.ok) await refuse(response);
833
+ const body = await response.json();
834
+ for (const row of body.data ?? []) {
835
+ if (typeof row.id !== "string") continue;
836
+ offers.push(offerOf(row, row.id));
837
+ }
838
+ if (body.has_more !== true || typeof body.last_id !== "string") break;
839
+ afterId = body.last_id;
840
+ }
841
+ return offers;
842
+ },
843
+ /** Listing models is the cheapest request that needs the credential, so it
844
+ * is also the test: an endpoint that answers it has a working key, and one
845
+ * that refuses says why.
846
+ *
847
+ * An endpoint that serves `/v1/messages` alone answers the listing with
848
+ * 404. The test then sends `/v1/messages` an empty body, which no model
849
+ * runs: an unauthenticated refusal (401, 403) is a wrong key, any other
850
+ * client error means the key got through, and a second 404 is an address
851
+ * that serves neither. */
852
+ async testConnection(probe, fetcher = globalThis.fetch) {
853
+ const listed = await get(probe, "/v1/models?limit=1", fetcher);
854
+ if (listed.ok) return;
855
+ if (listed.status !== 404) await refuse(listed);
856
+ const asked = await fetcher(`${baseUrlOf(probe)}/v1/messages`, {
857
+ method: "POST",
858
+ headers: {
859
+ "x-api-key": probe.secrets.apiKey ?? "",
860
+ "anthropic-version": VERSION,
861
+ "content-type": "application/json"
862
+ },
863
+ body: "{}",
864
+ signal: probe.signal
865
+ });
866
+ if (asked.ok) return;
867
+ if (asked.status === 401 || asked.status === 403 || asked.status === 404 || asked.status >= 500) await refuse(asked);
868
+ }
869
+ };
870
+ //#endregion
871
+ //#region src/protocol.ts
872
+ /** Supplier options interpreted by the Messages implementation. */
873
+ const AnthropicProtocolOptions = z.strictObject({ budgetOnly: z.array(z.string()).optional() });
874
+ /** Registers request mapping, streaming, inspection and probes with host-owned resources. */
875
+ function anthropicProtocolType(support, fetch) {
876
+ return {
877
+ type: "anthropic",
878
+ label: "Anthropic Messages",
879
+ fields: [{
880
+ key: "baseUrl",
881
+ kind: "url",
882
+ label: "Base URL",
883
+ required: true
884
+ }],
885
+ userConfigurable: true,
886
+ optionsSchema: AnthropicProtocolOptions,
887
+ facts,
888
+ prepareParams: (input) => support.prepareParams(input, facts),
889
+ chat: {
890
+ fileKinds: ["image"],
891
+ supportsModel: () => true,
892
+ createPort(call) {
893
+ const options = AnthropicProtocolOptions.parse(call.options);
894
+ return createAnthropicModelPort({
895
+ support,
896
+ fetch,
897
+ model: call.model,
898
+ endpoint: call.providerId,
899
+ apiKey: call.secrets.apiKey ?? "",
900
+ baseURL: String(call.config.baseUrl ?? ""),
901
+ ...options,
902
+ catalogue: () => support.catalogue(call.providerId, call.model),
903
+ media: (stored) => support.mediaContextOf({
904
+ entry: support.catalogue(call.providerId, call.model),
905
+ stored,
906
+ facts,
907
+ endpoint: support.endpoint(call.providerId),
908
+ fileKinds: ["image"]
909
+ }),
910
+ params: (stored) => support.resolveParams({
911
+ entry: support.catalogue(call.providerId, call.model),
912
+ stored,
913
+ facts,
914
+ model: call.model,
915
+ endpoint: support.endpoint(call.providerId)
916
+ })
917
+ });
918
+ }
919
+ },
920
+ normalizeListing: (input) => support.normalizeListing(input),
921
+ listModels: (probe) => probeAnthropic.listModels(probe, fetch),
922
+ testConnection: (probe) => probeAnthropic.testConnection(probe, fetch)
923
+ };
924
+ }
925
+ //#endregion
926
+ //#region src/index.ts
927
+ /** Protocol extensions contribute no tools. */
928
+ const TOOL_NAMES = [];
929
+ const plugin = {
930
+ name: "@eum-agent/llm-protocol-anthropic",
931
+ requires: ["model-support", "network"],
932
+ apply(ctx) {
933
+ const support = ctx.services.get("model-support");
934
+ const network = ctx.services.get("network");
935
+ ctx.models.registerProtocol(anthropicProtocolType(support, network.fetch));
936
+ }
937
+ };
938
+ //#endregion
939
+ export { TOOL_NAMES, plugin as default };
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@eum-agent/llm-protocol-anthropic",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "displayName": {
4
+ "en-US": "Anthropic Model Protocol",
5
+ "zh-CN": "模型协议 · Anthropic"
6
+ },
7
+ "version": "1.0.0",
8
+ "type": "module",
9
+ "description": "Public Anthropic model communication protocol",
10
+ "license": "MIT",
11
+ "exports": {
12
+ ".": {
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "devDependencies": {
20
+ "@eum-agent/plugin": "1.0.0"
21
+ },
22
+ "dependencies": {
23
+ "zod": "^4.4.3",
24
+ "@anthropic-ai/sdk": "^0.122.0",
25
+ "gpt-tokenizer": "4.0.0"
26
+ },
27
+ "yaoguang": {
28
+ "kind": "extension",
29
+ "dependencies": {
30
+ "@eum-agent/llm-management": "1.0.0"
31
+ },
32
+ "foundationDependencies": {
33
+ "@eum-agent/infra-local": "1.0.0"
34
+ },
35
+ "description": {
36
+ "en-US": "Public Anthropic model communication protocol",
37
+ "zh-CN": "Anthropic 公共模型协议"
38
+ }
39
+ },
40
+ "scripts": {
41
+ "build": "tsdown",
42
+ "test": "vitest run",
43
+ "typecheck": "tsc --noEmit"
44
+ }
6
45
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.