@eum-agent/llm-protocol-anthropic 0.0.0-stage → 1.0.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.
Files changed (3) hide show
  1. package/dist/index.js +1214 -0
  2. package/package.json +42 -3
  3. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,1214 @@
1
+ import { z } from "zod";
2
+ import Anthropic, { APIConnectionError, APIError } from "@anthropic-ai/sdk";
3
+ import { createHash } from "node:crypto";
4
+ import { setImmediate } from "node:timers/promises";
5
+ //#region src/protocol/facts.ts
6
+ /** Parameter ranges and request limits for this provider wire. */
7
+ const facts = {
8
+ outputLimit: {
9
+ support: "required",
10
+ ordinary: 16e3
11
+ },
12
+ temperature: {
13
+ min: 0,
14
+ max: 1,
15
+ step: .05,
16
+ default: 1
17
+ },
18
+ thinkingSwitch: true,
19
+ limits: {
20
+ requestBytes: 33554432,
21
+ images: 100
22
+ }
23
+ };
24
+ //#endregion
25
+ //#region src/protocol/errors.ts
26
+ /**
27
+ * SDK exceptions have two consumers: explicit probes retain provider text for
28
+ * their credential-redaction boundary, while Agent calls accept only fixed
29
+ * templates and allowlisted facts through the host factory.
30
+ */
31
+ /** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
32
+ * every other status is not — retrying a bad request or an authentication
33
+ * failure only spends the backoff budget on a call that will never succeed. */
34
+ function isRetryableStatus(status) {
35
+ return status === 408 || status === 409 || status === 429 || status !== void 0 && status >= 500;
36
+ }
37
+ /** The provider's own `retry-after` header, in milliseconds — read for the
38
+ * backoff delay only; the header value itself carries no credential. */
39
+ function retryAfterMs(error) {
40
+ if (!(error instanceof APIError)) return void 0;
41
+ const header = error.headers?.get("retry-after");
42
+ if (!header) return void 0;
43
+ const seconds = Number(header);
44
+ if (!Number.isFinite(seconds) || seconds < 0) return void 0;
45
+ const milliseconds = seconds * 1e3;
46
+ return Number.isFinite(milliseconds) ? milliseconds : void 0;
47
+ }
48
+ /** Converts any exception the SDK call can throw into a `ModelCallError`.
49
+ * Never reads `error.headers` into the result; the body goes to
50
+ * `providerText` alone. */
51
+ /** Error types an event stream reports mid-reply that a second attempt can
52
+ * get past: the stream carries no status, only this. */
53
+ const RETRYABLE_TYPES = /* @__PURE__ */ new Set([
54
+ "overloaded_error",
55
+ "api_error",
56
+ "rate_limit_error"
57
+ ]);
58
+ function streamErrorType(error) {
59
+ const body = error.error;
60
+ const inner = body?.error?.type ?? body?.type;
61
+ return typeof inner === "string" ? inner : void 0;
62
+ }
63
+ /** Maps verified SDK classes and factory identities to bounded Agent failure candidates. */
64
+ function toModelFailure(error, failures) {
65
+ if (failures.owns(error)) return error;
66
+ if (!(error instanceof APIError)) return failures.create({
67
+ code: "unknown",
68
+ stage: "unknown",
69
+ category: "unknown",
70
+ source: "unknown",
71
+ retryable: false
72
+ });
73
+ const rawCode = streamErrorType(error) ?? error.type;
74
+ const providerCode = typeof rawCode === "string" && (/* @__PURE__ */ new Set([
75
+ "usage_not_included",
76
+ "usage_limit_reached",
77
+ "insufficient_quota",
78
+ "context_length_exceeded",
79
+ "rate_limit_exceeded",
80
+ "overloaded_error",
81
+ "api_error",
82
+ "rate_limit_error",
83
+ "cyber_policy",
84
+ "invalid_prompt",
85
+ "bio_policy",
86
+ "misalignment_policy_violation"
87
+ ])).has(rawCode) ? rawCode : void 0;
88
+ const connection = error instanceof APIConnectionError;
89
+ const status = Number.isInteger(error.status) && Number(error.status) >= 100 && Number(error.status) <= 599 ? error.status : void 0;
90
+ return failures.create({
91
+ code: connection ? "stream-interrupted" : status === 413 ? "request-too-large" : status === void 0 ? "provider-error" : "http-error",
92
+ stage: connection ? "transport" : status === 413 ? "request" : status === void 0 ? "stream" : "transport",
93
+ category: connection ? "network" : status === 413 ? "request-too-large" : "provider",
94
+ source: connection ? "transport" : "protocol",
95
+ ...status === void 0 ? {} : { status },
96
+ retryable: connection || isRetryableStatus(status) || status === void 0 && RETRYABLE_TYPES.has(streamErrorType(error) ?? ""),
97
+ ...providerCode === void 0 ? {} : { providerCode }
98
+ });
99
+ }
100
+ //#endregion
101
+ //#region src/protocol/request.ts
102
+ /**
103
+ * `ModelRequest` (kernel's vocabulary, provider-neutral) → Anthropic's
104
+ * `MessageCreateParamsStreaming`. Everything this side must fix for the
105
+ * outbound request lands here: `system` as the top-level parameter (not a
106
+ * message), tool results kept as one message with several `tool_result`
107
+ * blocks (the transcript shape, already Anthropic's own), and the thinking
108
+ * configuration the port decided. Always streamed — 128K of output without
109
+ * streaming risks an HTTP timeout.
110
+ *
111
+ * **Every request extends the previous one.** A reply's recorded volatile
112
+ * notes are rendered just before it, as a text block at the end of the user
113
+ * content that precedes it — exactly where the request that produced the
114
+ * reply carried them — and the current step's notes go at the very end. So
115
+ * the conversation a signature covers, and the prefix a cache entry keys on,
116
+ * never change once sent.
117
+ *
118
+ * A signed `ThinkingPart` is echoed only when its endpoint, model and covered
119
+ * non-thinking prefix match. Any mismatch drops the message's whole thinking
120
+ * group while preserving its visible text and tool calls. A redacted block
121
+ * goes back as the `redacted_thinking` it came as.
122
+ */
123
+ const SUMMARY_THINKING_HEADROOM = 8192;
124
+ const DEFAULT_MAX_TOKENS = 16e3;
125
+ const TOOL_ID = /^[a-zA-Z0-9_-]+$/;
126
+ /**
127
+ * The id Anthropic is sent for one tool call. A legal id goes as it is; any
128
+ * other — another endpoint's `functions.name:0` — becomes its legal
129
+ * characters plus a hash of the whole, decided by the id alone so a later
130
+ * step adding ids never changes how an earlier one was sent.
131
+ */
132
+ function anthropicToolId(id) {
133
+ if (TOOL_ID.test(id)) return id;
134
+ const hash = createHash("sha256").update(id).digest("hex").slice(0, 12);
135
+ return `${id.replace(/[^a-zA-Z0-9_-]/g, "_")}_${hash}`;
136
+ }
137
+ /** A planned file as blocks: the label and the image, or the line in its place. */
138
+ function fileBlocks(planned, rendering) {
139
+ const label = {
140
+ type: "text",
141
+ text: planned.label
142
+ };
143
+ if (planned.fate !== "send") return [label];
144
+ const data = rendering === "wire" ? planned.data ?? "" : planned.ref.forModel?.id ?? planned.ref.id;
145
+ return [label, {
146
+ type: "image",
147
+ source: {
148
+ type: "base64",
149
+ media_type: planned.mediaType,
150
+ data
151
+ }
152
+ }];
153
+ }
154
+ function toContentBlockParams(part, at, context) {
155
+ switch (part.type) {
156
+ case "text": return [{
157
+ type: "text",
158
+ text: part.text
159
+ }];
160
+ case "thinking": return [part.redacted === true ? {
161
+ type: "redacted_thinking",
162
+ data: part.signature ?? ""
163
+ } : {
164
+ type: "thinking",
165
+ thinking: part.text,
166
+ ...context.unsignedThinking ? part.signature === void 0 ? {} : { signature: part.signature } : { signature: part.signature ?? "" }
167
+ }];
168
+ case "tool-use": return [{
169
+ type: "tool_use",
170
+ id: anthropicToolId(part.id),
171
+ name: part.name,
172
+ input: part.input
173
+ }];
174
+ case "tool-result": {
175
+ const files = part.files ?? [];
176
+ const content = files.length === 0 ? part.content : [...part.content === "" ? [] : [{
177
+ type: "text",
178
+ text: part.content
179
+ }], ...files.flatMap((_, index) => fileBlocks(context.plan.at(at.message, at.part, index), context.rendering))];
180
+ return [{
181
+ type: "tool_result",
182
+ tool_use_id: anthropicToolId(part.toolUseId),
183
+ content,
184
+ ...part.isError !== void 0 ? { is_error: part.isError } : {}
185
+ }];
186
+ }
187
+ case "file": return fileBlocks(context.plan.at(at.message, at.part), context.rendering);
188
+ default: throw new Error(`unhandled content part type: ${String(part.type)}`);
189
+ }
190
+ }
191
+ /**
192
+ * Whether this endpoint can send one message's thinking group back.
193
+ *
194
+ * Two ways it cannot. **No signature**: it was never signed — a transcript
195
+ * resumed from an OpenAI-style endpoint, or from before signatures were
196
+ * carried — and a fabricated one is worse than none, because Anthropic
197
+ * verifies it and answers a modified block with `400 invalid_request_error`,
198
+ * failing every continuation. Endpoint, model and prefix attribution must all
199
+ * match because a change to any covered input can invalidate the signature.
200
+ * One incompatible member drops the whole group so no middle block is removed.
201
+ *
202
+ * Comparing endpoint ids is deliberately coarser than "same signer": two keys
203
+ * against one vendor may share a signer, but replaying a block that cannot be
204
+ * verified would reject the entire request.
205
+ */
206
+ function thinkingGroupIsSendable(message, options, prefix) {
207
+ if (!message.content.some((part) => part.type === "text" && part.text !== "" || part.type === "tool-use")) return false;
208
+ if (options.reasoningReplay === "omit" || message.outputTruncation?.incompleteThinking) return false;
209
+ if (options.reasoningReplay === "unsigned-thinking") return true;
210
+ const thinking = message.content.filter((part) => part.type === "thinking");
211
+ if (thinking.length === 0) return true;
212
+ 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);
214
+ }
215
+ /** A text block with nothing in it: Anthropic refuses one. */
216
+ function isEmptyText(part) {
217
+ return part.type === "text" && part.text === "";
218
+ }
219
+ function blocksOf(message, index, sendThinking, context) {
220
+ return message.content.flatMap((part, partIndex) => isEmptyText(part) || part.type === "thinking" && !sendThinking ? [] : toContentBlockParams(part, {
221
+ message: index,
222
+ part: partIndex
223
+ }, context));
224
+ }
225
+ /** The one text block a set of notes renders as, or nothing. */
226
+ function noteBlock(notes) {
227
+ const text = (notes ?? []).map((note) => note.text).join("\n\n");
228
+ return text === "" ? [] : [{
229
+ type: "text",
230
+ text
231
+ }];
232
+ }
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
+ function appendUser(messages, blocks) {
239
+ if (blocks.length === 0) return;
240
+ const last = messages.at(-1);
241
+ if (last === void 0 || last.role !== "user") {
242
+ messages.push({
243
+ role: "user",
244
+ content: [...blocks]
245
+ });
246
+ return;
247
+ }
248
+ const content = typeof last.content === "string" ? [] : last.content;
249
+ messages[messages.length - 1] = {
250
+ ...last,
251
+ content: [...content, ...blocks]
252
+ };
253
+ }
254
+ /**
255
+ * Renders messages in Anthropic's shape, each reply preceded by the notes
256
+ * its request appended, then `trailing` at the end. `sendThinking` decides,
257
+ * per message index, whether its thinking group goes out.
258
+ */
259
+ function render(messages, trailing, sendThinking, context) {
260
+ const out = [];
261
+ messages.forEach((message, index) => {
262
+ if (message.role === "assistant") appendUser(out, noteBlock(message.volatile));
263
+ const content = blocksOf(message, index, sendThinking(message, index), context);
264
+ if (content.length === 0) return;
265
+ if (message.role === "user") appendUser(out, content);
266
+ else out.push({
267
+ role: "assistant",
268
+ content
269
+ });
270
+ });
271
+ appendUser(out, noteBlock(trailing));
272
+ return out;
273
+ }
274
+ function toToolParam(tool) {
275
+ return {
276
+ name: tool.name,
277
+ description: tool.description,
278
+ input_schema: tool.inputSchema
279
+ };
280
+ }
281
+ /** A copy without cache marks: where a breakpoint sits says nothing about what
282
+ * the provider signed, so it must not change the fingerprint. */
283
+ function unmarked(value) {
284
+ return JSON.parse(JSON.stringify(value, (key, inner) => key === "cache_control" ? void 0 : inner));
285
+ }
286
+ function systemOf(request) {
287
+ return request.system?.map((text) => ({
288
+ type: "text",
289
+ text
290
+ }));
291
+ }
292
+ function toolsOf(request) {
293
+ return request.tools && request.tools.length > 0 ? request.tools.map(toToolParam) : void 0;
294
+ }
295
+ function prefixOf(system, tools, messages, support) {
296
+ return support.inspectionFingerprint(unmarked({
297
+ ...system === void 0 ? {} : { system },
298
+ ...tools === void 0 ? {} : { tools },
299
+ messages
300
+ }));
301
+ }
302
+ /**
303
+ * Computes the non-thinking prefix covered by a historical assistant
304
+ * signature: everything before that message, its own recorded notes included
305
+ * — they ended the request it answered. `messageIndex` names the message.
306
+ */
307
+ function anthropicPrefixBefore(request, messageIndex, media, support) {
308
+ const before = request.messages.slice(0, messageIndex);
309
+ const notes = request.messages[messageIndex]?.volatile;
310
+ return prefixOf(systemOf(request), toolsOf(request), render(before, notes, () => false, fingerprintContext(request, media, support)), support);
311
+ }
312
+ /** The send plan, from the options' media context or the permissive default. */
313
+ function planOf(request, media, support) {
314
+ return support.planMedia(request, media ?? {
315
+ acceptsImages: true,
316
+ limits: void 0
317
+ });
318
+ }
319
+ function fingerprintContext(request, media, support) {
320
+ return {
321
+ plan: planOf({
322
+ ...request,
323
+ files: void 0
324
+ }, media, support),
325
+ rendering: "fingerprint"
326
+ };
327
+ }
328
+ /**
329
+ * Computes the prefix a new reply is signed under: everything the request
330
+ * carried, its notes included, rendered the way `anthropicPrefixBefore`
331
+ * renders it on the next step and without cache marks.
332
+ */
333
+ function anthropicRequestPrefix(request, media, support) {
334
+ return prefixOf(systemOf(request), toolsOf(request), render(request.messages, request.volatile, () => false, fingerprintContext(request, media, support)), support);
335
+ }
336
+ /** Counts provider-retained thinking state that is actually replayed. */
337
+ function anthropicHiddenInputTokens(request, options) {
338
+ return request.messages.reduce((total, message, index) => {
339
+ if (!thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support))) return total;
340
+ return total + Math.max(0, ...message.content.map((part) => part.type === "thinking" ? part.outputTokens ?? 0 : 0));
341
+ }, 0);
342
+ }
343
+ const EPHEMERAL = { type: "ephemeral" };
344
+ /** Marks the last markable block of one message. */
345
+ function markLast(message) {
346
+ if (typeof message.content === "string") return message;
347
+ const content = [...message.content];
348
+ for (let index = content.length - 1; index >= 0; index -= 1) {
349
+ const block = content[index];
350
+ if (!block || block.type === "thinking" || block.type === "redacted_thinking") continue;
351
+ content[index] = {
352
+ ...block,
353
+ cache_control: EPHEMERAL
354
+ };
355
+ return {
356
+ ...message,
357
+ content
358
+ };
359
+ }
360
+ return message;
361
+ }
362
+ /**
363
+ * Two conversation breakpoints: the end of this request, which the next step
364
+ * repeats, and the end of the previous step's request — the user content
365
+ * just before the last reply — whose cache entry this step reads exactly,
366
+ * however many blocks the step added since.
367
+ */
368
+ function withConversationBreakpoints(messages) {
369
+ const out = [...messages];
370
+ const lastIndex = out.length - 1;
371
+ if (lastIndex < 0) return out;
372
+ out[lastIndex] = markLast(out[lastIndex]);
373
+ const previous = out.findLastIndex((message) => message.role === "assistant") - 1;
374
+ if (previous >= 0 && previous !== lastIndex && out[previous]?.role === "user") out[previous] = markLast(out[previous]);
375
+ return out;
376
+ }
377
+ function toAnthropicRequest(request, options) {
378
+ const summary = request.purpose === "summary";
379
+ if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
380
+ const ordinaryMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
381
+ const thinkingOn = options.thinking !== void 0 && options.thinking.type !== "disabled";
382
+ 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 ? {
384
+ type: "text",
385
+ text,
386
+ cache_control: EPHEMERAL
387
+ } : {
388
+ type: "text",
389
+ text
390
+ });
391
+ const tools = toolsOf(request);
392
+ const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support)), {
393
+ plan: planOf(request, options.media, options.support),
394
+ rendering: "wire",
395
+ unsignedThinking: options.reasoningReplay === "unsigned-thinking"
396
+ });
397
+ return {
398
+ model: options.model ?? "",
399
+ max_tokens: maxTokens,
400
+ stream: true,
401
+ ...options.effort === void 0 ? {} : { output_config: { effort: options.effort } },
402
+ ...options.thinking === void 0 ? {} : { thinking: options.thinking },
403
+ ...options.temperature === void 0 ? {} : { temperature: options.temperature },
404
+ messages: withConversationBreakpoints(messages),
405
+ ...system === void 0 ? {} : { system },
406
+ ...tools === void 0 ? {} : { tools },
407
+ ...request.toolChoice === "none" && tools !== void 0 ? { tool_choice: { type: "none" } } : {},
408
+ ...summary ? {} : options.extra
409
+ };
410
+ }
411
+ //#endregion
412
+ //#region src/protocol/sse-response.ts
413
+ const MAX_FRAME_BYTES = 8388608;
414
+ const WORK_PER_TURN = 65536;
415
+ /**
416
+ * Supplies one complete SSE frame per SDK read at the known messages streaming entrance.
417
+ * Every successful body is framed, including suppliers with missing or incorrect MIME headers.
418
+ * LF, CRLF and CR line endings are normalized to LF without decoding field bytes.
419
+ * Incomplete EOF bytes are retained for the SDK's ordinary final-line handling.
420
+ * A normalized frame exceeding 8 MiB is refused before further allocation.
421
+ * Buffered input yields to timers and cancellation after at most 64 KiB of work.
422
+ * Cancellation and read failure join original-body cancellation before releasing its reader.
423
+ * Response metadata and HTTP error bodies are preserved.
424
+ */
425
+ function frameSseResponse(response, signal) {
426
+ if (!response.ok || response.body === null) return response;
427
+ const reader = response.body.getReader();
428
+ let buffer = /* @__PURE__ */ new Uint8Array(1024);
429
+ let length = 0;
430
+ let lineLength = 0;
431
+ let skipLf = false;
432
+ let chunk;
433
+ let offset = 0;
434
+ let work = 0;
435
+ let stopped = false;
436
+ let cancellation;
437
+ let abort;
438
+ function release() {
439
+ buffer = /* @__PURE__ */ new Uint8Array();
440
+ chunk = void 0;
441
+ if (abort !== void 0) signal?.removeEventListener("abort", abort);
442
+ reader.releaseLock();
443
+ }
444
+ function cancel(reason) {
445
+ if (cancellation !== void 0) return cancellation;
446
+ if (stopped) return Promise.resolve();
447
+ stopped = true;
448
+ cancellation = (async () => {
449
+ try {
450
+ await reader.cancel(reason);
451
+ } finally {
452
+ release();
453
+ }
454
+ })();
455
+ return cancellation;
456
+ }
457
+ function append(byte) {
458
+ if (length === MAX_FRAME_BYTES) throw new RangeError("SSE frame exceeds 8 MiB");
459
+ if (length === buffer.length) {
460
+ const grown = new Uint8Array(Math.min(MAX_FRAME_BYTES, Math.max(1024, buffer.length * 2)));
461
+ grown.set(buffer);
462
+ buffer = grown;
463
+ }
464
+ buffer[length++] = byte;
465
+ }
466
+ const body = new ReadableStream({
467
+ start(controller) {
468
+ abort = () => {
469
+ const reason = signal?.reason ?? new DOMException("The request was aborted", "AbortError");
470
+ cancel(reason).then(() => controller.error(reason), (cleanup) => controller.error(new AggregateError([reason, cleanup], "SSE cancellation failed")));
471
+ };
472
+ signal?.addEventListener("abort", abort, { once: true });
473
+ if (signal?.aborted) abort();
474
+ },
475
+ async pull(controller) {
476
+ try {
477
+ while (!stopped) {
478
+ if (chunk === void 0 || offset === chunk.length) {
479
+ work += 1;
480
+ if (work >= WORK_PER_TURN) {
481
+ work = 0;
482
+ await setImmediate();
483
+ if (stopped) return;
484
+ }
485
+ const next = await reader.read();
486
+ if (stopped) return;
487
+ if (next.done) {
488
+ if (length > 0) controller.enqueue(buffer.slice(0, length));
489
+ stopped = true;
490
+ release();
491
+ controller.close();
492
+ return;
493
+ }
494
+ chunk = next.value;
495
+ offset = 0;
496
+ }
497
+ const current = chunk;
498
+ if (current === void 0) continue;
499
+ while (offset < current.length) {
500
+ work += 1;
501
+ if (work >= WORK_PER_TURN) {
502
+ work = 0;
503
+ await setImmediate();
504
+ if (stopped) return;
505
+ }
506
+ const byte = current[offset++];
507
+ if (skipLf) {
508
+ skipLf = false;
509
+ if (byte === 10) continue;
510
+ }
511
+ if (byte === 13 || byte === 10) {
512
+ append(10);
513
+ skipLf = byte === 13;
514
+ if (lineLength === 0) {
515
+ controller.enqueue(buffer.slice(0, length));
516
+ length = 0;
517
+ return;
518
+ }
519
+ lineLength = 0;
520
+ } else {
521
+ append(byte);
522
+ lineLength += 1;
523
+ }
524
+ }
525
+ }
526
+ } catch (error) {
527
+ if (stopped) return;
528
+ try {
529
+ await cancel(error);
530
+ } catch (cleanup) {
531
+ controller.error(cleanup === error ? error : new AggregateError([error, cleanup], "SSE read cleanup failed"));
532
+ return;
533
+ }
534
+ controller.error(error);
535
+ }
536
+ },
537
+ cancel
538
+ }, { highWaterMark: 0 });
539
+ const framed = new Response(body, {
540
+ status: response.status,
541
+ statusText: response.statusText,
542
+ headers: response.headers
543
+ });
544
+ for (const key of [
545
+ "url",
546
+ "redirected",
547
+ "type"
548
+ ]) Object.defineProperty(framed, key, { value: response[key] });
549
+ return framed;
550
+ }
551
+ //#endregion
552
+ //#region src/protocol/stream.ts
553
+ function toFinishReason(stopReason, support) {
554
+ switch (stopReason) {
555
+ case "tool_use": return "tool-calls";
556
+ case "max_tokens":
557
+ case "model_context_window_exceeded": return "max-tokens";
558
+ case "refusal": return "refusal";
559
+ case "end_turn":
560
+ case "stop_sequence":
561
+ case "pause_turn": return "stop";
562
+ default: throw support.failures.create({
563
+ code: stopReason === null ? "finish-reason-missing" : "finish-reason-unsupported",
564
+ stage: "response-validation",
565
+ category: "protocol",
566
+ source: "protocol",
567
+ retryable: false
568
+ });
569
+ }
570
+ }
571
+ /** The accumulated `input_json_delta` text as JSON, or `undefined` when it
572
+ * will not parse — which is what a tool-use block cut off at `max_tokens`
573
+ * looks like. `JSON.parse` never produces `undefined` itself, so it is free
574
+ * to stand for "no usable input here". */
575
+ function parseToolInput(json) {
576
+ if (json.length === 0) return {};
577
+ try {
578
+ return JSON.parse(json);
579
+ } catch {
580
+ return;
581
+ }
582
+ }
583
+ /**
584
+ * Streams provider deltas and a completed, usable reply with signed reasoning.
585
+ * Unknown terminal reasons and replies containing only reasoning fail without retry;
586
+ * a stream without message_stop retains interruption semantics.
587
+ */
588
+ async function* mapAnthropicStream(events, attribution, support) {
589
+ const blocks = /* @__PURE__ */ new Map();
590
+ const finalContent = [];
591
+ const incompleteToolCalls = [];
592
+ let incompleteThinking = false;
593
+ let inputTokens = 0;
594
+ let outputTokens = 0;
595
+ let cache = {};
596
+ let stopped = false;
597
+ let stopReason = null;
598
+ let refusalCategory;
599
+ for await (const event of events) switch (event.type) {
600
+ case "message_start": {
601
+ const usage = event.message.usage;
602
+ inputTokens = usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
603
+ outputTokens = event.message.usage.output_tokens;
604
+ cache = {
605
+ ...typeof usage.cache_read_input_tokens === "number" ? { cacheReadTokens: usage.cache_read_input_tokens } : {},
606
+ ...typeof usage.cache_creation_input_tokens === "number" ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {}
607
+ };
608
+ break;
609
+ }
610
+ case "content_block_start": {
611
+ const block = event.content_block;
612
+ if (block.type === "text") blocks.set(event.index, {
613
+ kind: "text",
614
+ text: block.text
615
+ });
616
+ else if (block.type === "tool_use") {
617
+ blocks.set(event.index, {
618
+ kind: "tool-use",
619
+ id: block.id,
620
+ name: block.name,
621
+ json: ""
622
+ });
623
+ yield {
624
+ kind: "tool-call-delta",
625
+ id: block.id,
626
+ name: block.name,
627
+ inputDelta: ""
628
+ };
629
+ } else if (block.type === "thinking") blocks.set(event.index, {
630
+ kind: "thinking",
631
+ text: ""
632
+ });
633
+ else if (block.type === "redacted_thinking") blocks.set(event.index, {
634
+ kind: "redacted",
635
+ data: block.data
636
+ });
637
+ else blocks.set(event.index, { kind: "skipped" });
638
+ break;
639
+ }
640
+ case "content_block_delta": {
641
+ const block = blocks.get(event.index);
642
+ const delta = event.delta;
643
+ if (delta.type === "text_delta") {
644
+ if (block?.kind === "text") block.text += delta.text;
645
+ yield {
646
+ kind: "text-delta",
647
+ text: delta.text
648
+ };
649
+ } else if (delta.type === "thinking_delta") {
650
+ if (block?.kind === "thinking") block.text += delta.thinking;
651
+ yield {
652
+ kind: "thinking-delta",
653
+ text: delta.thinking
654
+ };
655
+ } else if (delta.type === "signature_delta") {
656
+ if (block?.kind === "thinking") block.signature = delta.signature;
657
+ } else if (delta.type === "input_json_delta" && block?.kind === "tool-use") {
658
+ block.json += delta.partial_json;
659
+ yield {
660
+ kind: "tool-call-delta",
661
+ id: block.id,
662
+ inputDelta: delta.partial_json
663
+ };
664
+ }
665
+ break;
666
+ }
667
+ case "content_block_stop": {
668
+ const block = blocks.get(event.index);
669
+ if (block?.kind === "text") {
670
+ if (block.text !== "") finalContent.push({
671
+ type: "text",
672
+ text: block.text
673
+ });
674
+ } else if (block?.kind === "redacted") finalContent.push({
675
+ type: "thinking",
676
+ text: "",
677
+ signature: block.data,
678
+ redacted: true
679
+ });
680
+ else if (block?.kind === "tool-use") {
681
+ const input = parseToolInput(block.json);
682
+ if (input === void 0) incompleteToolCalls.push({
683
+ id: block.id,
684
+ name: block.name
685
+ });
686
+ else finalContent.push({
687
+ type: "tool-use",
688
+ id: block.id,
689
+ name: block.name,
690
+ input
691
+ });
692
+ } else if (block?.kind === "thinking") finalContent.push({
693
+ type: "thinking",
694
+ text: block.text,
695
+ ...block.signature === void 0 ? {} : { signature: block.signature }
696
+ });
697
+ blocks.delete(event.index);
698
+ break;
699
+ }
700
+ case "message_delta":
701
+ stopReason = event.delta.stop_reason ?? stopReason;
702
+ if (event.delta.stop_details?.type === "refusal") refusalCategory = event.delta.stop_details.category ?? "unspecified";
703
+ outputTokens = event.usage.output_tokens;
704
+ break;
705
+ case "message_stop": stopped = true;
706
+ }
707
+ if (!stopped) throw support.interruptedFailure();
708
+ const finishReason = toFinishReason(stopReason, support);
709
+ if (finishReason === "max-tokens") {
710
+ for (const block of blocks.values()) if (block.kind === "text" && block.text !== "") finalContent.push({
711
+ type: "text",
712
+ text: block.text
713
+ });
714
+ else if (block.kind === "thinking") {
715
+ finalContent.push({
716
+ type: "thinking",
717
+ text: block.text
718
+ });
719
+ incompleteThinking = true;
720
+ } else if (block.kind === "tool-use") incompleteToolCalls.push({
721
+ id: block.id,
722
+ name: block.name
723
+ });
724
+ else if (block.kind === "redacted") incompleteThinking = true;
725
+ } else if (incompleteToolCalls.length > 0 || blocks.size > 0) throw support.failures.create({
726
+ code: "response-invalid",
727
+ stage: "response-validation",
728
+ category: "protocol",
729
+ source: "protocol",
730
+ retryable: false,
731
+ finishReason
732
+ });
733
+ if (finishReason !== "refusal" && finishReason !== "max-tokens" && !finalContent.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
734
+ code: "response-empty",
735
+ stage: "response-validation",
736
+ category: "protocol",
737
+ source: "protocol",
738
+ retryable: false,
739
+ finishReason
740
+ });
741
+ const attributedContent = finalContent.map((part) => part.type === "thinking" && part.signature !== void 0 && attribution !== void 0 ? {
742
+ ...part,
743
+ originModel: attribution.originModel,
744
+ prefix: attribution.prefix,
745
+ outputTokens
746
+ } : part);
747
+ yield {
748
+ kind: "final",
749
+ finishReason,
750
+ ...finishReason === "max-tokens" ? { outputTruncation: {
751
+ incompleteToolCalls,
752
+ ...incompleteThinking ? { incompleteThinking: true } : {}
753
+ } } : {},
754
+ usage: {
755
+ inputTokens,
756
+ outputTokens,
757
+ ...cache
758
+ },
759
+ ...refusalCategory !== void 0 ? { refusalCategory } : {},
760
+ message: {
761
+ role: "assistant",
762
+ content: attributedContent
763
+ }
764
+ };
765
+ }
766
+ //#endregion
767
+ //#region src/protocol/port.ts
768
+ /**
769
+ * Wires request-building (request.ts), stream-mapping (stream.ts) and the
770
+ * injected host retry loop into the `ModelPort` the
771
+ * kernel's call-model slot dispatches to. Rate limits, overload, server
772
+ * errors, dropped connections and stalls are retried with a
773
+ * `retry-after`-honouring backoff; a retry after output first retracts what
774
+ * streamed. Everything else, and a retryable failure once the budget is
775
+ * spent, becomes the error the driver turns into a failed outcome.
776
+ */
777
+ /** Lets a budget-thinking model think between tool calls. */
778
+ const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
779
+ /** The budget a budget-thinking model gets when a person set none. */
780
+ const DEFAULT_BUDGET = 16e3;
781
+ const BUDGET_FLOOR = 1024;
782
+ /**
783
+ * The neutral plan in Anthropic's own spelling.
784
+ *
785
+ * Thinking on is `adaptive` with a readable summary — current models stream
786
+ * empty thinking without `display: 'summarized'` — and the effort; a model
787
+ * whose thinking is a token budget gets `enabled` with the stored budget or a
788
+ * default one under `max_tokens`, or no thinking at all when `max_tokens`
789
+ * leaves no room for the smallest budget. Thinking off is `disabled`. While
790
+ * thinking is on no temperature goes out: Anthropic refuses one then.
791
+ */
792
+ function anthropicOptions(plan, model, budgetOnly = []) {
793
+ const on = plan.thinking === true;
794
+ const maxTokens = plan.maxTokens;
795
+ const budget = () => {
796
+ const ceiling = (maxTokens ?? Number.POSITIVE_INFINITY) - 1;
797
+ if (ceiling < BUDGET_FLOOR) return void 0;
798
+ const wanted = plan.budgetTokens ?? Math.min(DEFAULT_BUDGET, Math.floor((maxTokens ?? 0) / 2));
799
+ return Math.min(Math.max(wanted, BUDGET_FLOOR), ceiling);
800
+ };
801
+ const byBudget = plan.budgetTokens !== void 0 || budgetOnly.some((one) => model.startsWith(one));
802
+ const tokens = on && byBudget ? budget() : void 0;
803
+ const thinking = !on ? plan.thinking === false ? { type: "disabled" } : void 0 : byBudget ? tokens === void 0 ? void 0 : {
804
+ type: "enabled",
805
+ budget_tokens: tokens
806
+ } : {
807
+ type: "adaptive",
808
+ display: "summarized"
809
+ };
810
+ return {
811
+ ...plan.effort === void 0 || !on ? {} : { effort: plan.effort },
812
+ ...plan.temperature === void 0 || on ? {} : { temperature: plan.temperature },
813
+ ...maxTokens === void 0 ? {} : { maxTokens },
814
+ ...thinking === void 0 ? {} : { thinking },
815
+ ...thinking?.type === "enabled" ? { betas: [INTERLEAVED_THINKING_BETA] } : {}
816
+ };
817
+ }
818
+ /** Creates an Anthropic port with synchronous request inspection and safe stream retries. */
819
+ function createAnthropicModelPort(options) {
820
+ function clientForAttempt(reportProgress) {
821
+ return options.client ?? new Anthropic({
822
+ apiKey: options.apiKey ?? "",
823
+ fetch: async (...args) => frameSseResponse(options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress), args[1]?.signal),
824
+ baseURL: options.baseURL ?? "",
825
+ maxRetries: 0
826
+ });
827
+ }
828
+ function build(request) {
829
+ const capacity = options.catalogue?.()?.limit;
830
+ const plan = options.params === void 0 ? void 0 : anthropicOptions(options.params(request.params ?? {}), options.model ?? "", options.budgetOnly);
831
+ const { media: mediaOf, ...rest } = options;
832
+ const media = mediaOf?.(request.params ?? {});
833
+ const base = media === void 0 ? rest : {
834
+ ...rest,
835
+ media
836
+ };
837
+ const requestOptions = plan === void 0 ? base : {
838
+ ...base,
839
+ ...plan,
840
+ extra: {
841
+ ...options.extra,
842
+ ...options.support.extraParams(request.params ?? {})
843
+ }
844
+ };
845
+ const betas = plan?.betas;
846
+ return {
847
+ params: toAnthropicRequest(request, requestOptions),
848
+ requestOptions,
849
+ capacity,
850
+ headers: betas === void 0 || betas.length === 0 ? void 0 : { "anthropic-beta": betas.join(",") }
851
+ };
852
+ }
853
+ return {
854
+ inspect(request) {
855
+ const { params, requestOptions, capacity } = build(request);
856
+ const outputReserve = Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? params.max_tokens : capacity?.output ?? 0;
857
+ return options.support.inspect({
858
+ body: params,
859
+ textTokens: options.support.measureText(options.support.requestText("messages", params)),
860
+ tokenizer: "o200k_base-protocol-text-v2",
861
+ request,
862
+ capacity,
863
+ outputReserve,
864
+ outputReserveSource: Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? "enforced" : "capacity",
865
+ hiddenInputTokens: anthropicHiddenInputTokens(request, requestOptions),
866
+ mediaTokens: options.support.planMedia(request, requestOptions.media ?? {
867
+ acceptsImages: true,
868
+ limits: void 0
869
+ }).tokens,
870
+ fingerprint: {
871
+ rendering: "anthropic-messages-v3",
872
+ endpoint: options.endpoint ?? options.baseURL,
873
+ model: params.model,
874
+ purpose: request.purpose,
875
+ contextWindow: request.params?.contextWindow,
876
+ capacity,
877
+ settings: {
878
+ effort: requestOptions.effort,
879
+ thinking: requestOptions.thinking,
880
+ temperature: requestOptions.temperature,
881
+ maxTokens: params.max_tokens,
882
+ extra: request.purpose === "summary" ? void 0 : requestOptions.extra
883
+ }
884
+ }
885
+ });
886
+ },
887
+ stream(request, signal, observer) {
888
+ signal.throwIfAborted();
889
+ const { params, headers, requestOptions } = build(request);
890
+ const prefix = anthropicRequestPrefix(request, requestOptions.media, options.support);
891
+ return options.support.withChatAttempts({
892
+ signal,
893
+ ...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
894
+ ...options.sleep === void 0 ? {} : { sleep: options.sleep },
895
+ ...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
896
+ async *attempt(attemptSignal, reportProgress, attempt) {
897
+ const observe = (event) => {
898
+ try {
899
+ observer?.observe?.(event);
900
+ } catch {}
901
+ };
902
+ const attemptCount = attempt + 1;
903
+ let outcome = "unknown";
904
+ let firstResponseFinished = false;
905
+ observe({
906
+ stage: "attempt",
907
+ phase: "start",
908
+ attempt: attemptCount
909
+ });
910
+ observe({
911
+ stage: "first-response",
912
+ phase: "start",
913
+ attempt: attemptCount
914
+ });
915
+ try {
916
+ attemptSignal.throwIfAborted();
917
+ const events = await clientForAttempt(reportProgress).messages.create(params, {
918
+ signal: attemptSignal,
919
+ ...headers === void 0 ? {} : { headers }
920
+ });
921
+ firstResponseFinished = true;
922
+ observe({
923
+ stage: "first-response",
924
+ phase: "end",
925
+ attempt: attemptCount,
926
+ outcome: "ok"
927
+ });
928
+ attemptSignal.throwIfAborted();
929
+ try {
930
+ observer?.dispatched({ attempt });
931
+ } catch {}
932
+ attemptSignal.throwIfAborted();
933
+ const observed = (async function* () {
934
+ for await (const event of events) {
935
+ reportProgress();
936
+ yield event;
937
+ }
938
+ })();
939
+ for await (const chunk of mapAnthropicStream(observed, {
940
+ originModel: params.model,
941
+ prefix
942
+ }, options.support)) {
943
+ if (chunk.kind === "final") outcome = "ok";
944
+ yield chunk;
945
+ }
946
+ } catch (error) {
947
+ outcome = attemptSignal.aborted ? "cancelled" : "error";
948
+ throw error;
949
+ } finally {
950
+ if (!firstResponseFinished) observe({
951
+ stage: "first-response",
952
+ phase: "end",
953
+ attempt: attemptCount,
954
+ outcome
955
+ });
956
+ observe({
957
+ stage: "attempt",
958
+ phase: "end",
959
+ attempt: attemptCount,
960
+ outcome
961
+ });
962
+ }
963
+ },
964
+ classify(error) {
965
+ const portError = toModelFailure(error, options.support.failures);
966
+ return {
967
+ error: portError,
968
+ retryable: portError.retryable === true,
969
+ retryAfterMs: retryAfterMs(error)
970
+ };
971
+ }
972
+ });
973
+ }
974
+ };
975
+ }
976
+ //#endregion
977
+ //#region src/protocol/probe.ts
978
+ const VERSION = "2023-06-01";
979
+ async function readBody(response, maxBytes) {
980
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error("invalid response budget");
981
+ const declared = response.headers.get("content-length");
982
+ if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
983
+ await response.body?.cancel();
984
+ throw new Error("read-limit: provider response exceeds its member budget");
985
+ }
986
+ if (!response.body) return {
987
+ text: "",
988
+ bytes: 0
989
+ };
990
+ const reader = response.body.getReader();
991
+ const decoder = new TextDecoder();
992
+ let bytes = 0, text = "";
993
+ try {
994
+ for (;;) {
995
+ const next = await reader.read();
996
+ if (next.done) break;
997
+ bytes += next.value.byteLength;
998
+ if (bytes > maxBytes) {
999
+ await reader.cancel();
1000
+ throw new Error("read-limit: provider response exceeds its member budget");
1001
+ }
1002
+ text += decoder.decode(next.value, { stream: true });
1003
+ }
1004
+ return {
1005
+ text: text + decoder.decode(),
1006
+ bytes
1007
+ };
1008
+ } finally {
1009
+ reader.releaseLock();
1010
+ }
1011
+ }
1012
+ function baseUrlOf(probe) {
1013
+ const configured = probe.config.baseUrl;
1014
+ return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
1015
+ }
1016
+ /** Attaches the status so the runtime can tell an authentication failure from
1017
+ * an endpoint that answered something else. The body is passed through as
1018
+ * the message; whether any of it reaches a person is not this file's call. */
1019
+ async function refuse(response, maxBytes = 8388608) {
1020
+ const body = (await readBody(response, maxBytes)).text;
1021
+ throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
1022
+ }
1023
+ async function get(probe, path, fetcher) {
1024
+ return fetcher(`${baseUrlOf(probe)}${path}`, {
1025
+ method: "GET",
1026
+ headers: {
1027
+ "x-api-key": probe.secrets.apiKey ?? "",
1028
+ "anthropic-version": VERSION
1029
+ },
1030
+ signal: probe.signal
1031
+ });
1032
+ }
1033
+ /** Enough pages to carry a catalogue several times the size of the one
1034
+ * Anthropic serves, while still ending if an endpoint keeps claiming
1035
+ * `has_more` forever. */
1036
+ const MAX_PAGES = 20;
1037
+ /** The effort levels this endpoint may list, in ascending order. */
1038
+ const EFFORT_LEVELS = [
1039
+ "minimal",
1040
+ "low",
1041
+ "medium",
1042
+ "high",
1043
+ "xhigh",
1044
+ "max"
1045
+ ];
1046
+ function record(value) {
1047
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1048
+ }
1049
+ function supported(value) {
1050
+ return record(value)?.supported === true;
1051
+ }
1052
+ /** A positive count, or nothing: the endpoint answers `0` or `null` for a
1053
+ * limit it does not know. */
1054
+ function count(value) {
1055
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
1056
+ }
1057
+ /**
1058
+ * One listed model as an offer, reading each field only where the entry
1059
+ * carries it. `created_at` may be an epoch value when the release date is
1060
+ * unknown, so anything before 2000 is read as absent.
1061
+ */
1062
+ function offerOf(row, id) {
1063
+ const capabilities = record(row.capabilities);
1064
+ const effort = record(capabilities?.effort);
1065
+ const efforts = effort?.supported === true ? EFFORT_LEVELS.filter((level) => supported(effort[level])) : [];
1066
+ const thinking = record(capabilities?.thinking);
1067
+ const input = capabilities === void 0 ? void 0 : [
1068
+ "text",
1069
+ ...supported(capabilities.image_input) ? ["image"] : [],
1070
+ ...supported(capabilities.pdf_input) ? ["pdf"] : []
1071
+ ];
1072
+ const released = typeof row.created_at === "string" && row.created_at >= "2000" ? row.created_at.slice(0, 10) : void 0;
1073
+ const contextWindow = count(row.max_input_tokens);
1074
+ const maxOutput = count(row.max_tokens);
1075
+ return {
1076
+ model: id,
1077
+ ...typeof row.display_name === "string" ? { name: row.display_name } : {},
1078
+ ...contextWindow === void 0 ? {} : { contextWindow },
1079
+ ...maxOutput === void 0 ? {} : { maxOutput },
1080
+ ...typeof thinking?.supported === "boolean" ? { reasoning: thinking.supported } : {},
1081
+ ...efforts.length === 0 ? {} : { efforts },
1082
+ ...input === void 0 ? {} : { input },
1083
+ ...released === void 0 ? {} : { releaseDate: released }
1084
+ };
1085
+ }
1086
+ const probeAnthropic = {
1087
+ /** Every model the endpoint lists. `/v1/models` is paged — it answers with
1088
+ * one page plus `has_more`/`last_id` — so this walks the pages with
1089
+ * `after_id` until the endpoint says there are no more. A mirror that
1090
+ * reports neither field answers in one page, as it always did. */
1091
+ async listModels(probe, fetcher = globalThis.fetch) {
1092
+ const offers = [];
1093
+ let afterId;
1094
+ let remaining = probe.maxResponseBytes ?? 8388608;
1095
+ for (let page = 0; page < MAX_PAGES; page += 1) {
1096
+ const response = await get(probe, `/v1/models${afterId === void 0 ? "" : `?after_id=${encodeURIComponent(afterId)}`}`, fetcher);
1097
+ if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
1098
+ const received = await readBody(response, remaining);
1099
+ remaining -= received.bytes;
1100
+ const body = JSON.parse(received.text);
1101
+ for (const row of body.data ?? []) {
1102
+ if (typeof row.id !== "string") continue;
1103
+ offers.push(offerOf(row, row.id));
1104
+ }
1105
+ if (body.has_more !== true || typeof body.last_id !== "string") break;
1106
+ if (remaining < 1) throw new Error("read-limit: provider listing exhausted its member budget");
1107
+ afterId = body.last_id;
1108
+ }
1109
+ return offers;
1110
+ },
1111
+ /** Listing models is the cheapest request that needs the credential, so it
1112
+ * is also the test: an endpoint that answers it has a working key, and one
1113
+ * that refuses says why.
1114
+ *
1115
+ * An endpoint that serves `/v1/messages` alone answers the listing with
1116
+ * 404. The test then sends `/v1/messages` an empty body, which no model
1117
+ * runs: an unauthenticated refusal (401, 403) is a wrong key, any other
1118
+ * client error means the key got through, and a second 404 is an address
1119
+ * that serves neither. */
1120
+ async testConnection(probe, fetcher = globalThis.fetch) {
1121
+ const listed = await get(probe, "/v1/models?limit=1", fetcher);
1122
+ if (listed.ok) return;
1123
+ if (listed.status !== 404) await refuse(listed);
1124
+ const asked = await fetcher(`${baseUrlOf(probe)}/v1/messages`, {
1125
+ method: "POST",
1126
+ headers: {
1127
+ "x-api-key": probe.secrets.apiKey ?? "",
1128
+ "anthropic-version": VERSION,
1129
+ "content-type": "application/json"
1130
+ },
1131
+ body: "{}",
1132
+ signal: probe.signal
1133
+ });
1134
+ if (asked.ok) return;
1135
+ if (asked.status === 401 || asked.status === 403 || asked.status === 404 || asked.status >= 500) await refuse(asked);
1136
+ }
1137
+ };
1138
+ //#endregion
1139
+ //#region src/protocol.ts
1140
+ /** Supplier options interpreted by the Messages implementation. */
1141
+ const AnthropicProtocolOptions = z.strictObject({
1142
+ reasoningReplay: z.enum([
1143
+ "omit",
1144
+ "signed-thinking",
1145
+ "unsigned-thinking"
1146
+ ]).optional(),
1147
+ budgetOnly: z.array(z.string()).optional()
1148
+ });
1149
+ /** Registers request mapping, streaming, inspection and probes with host-owned resources. */
1150
+ function anthropicProtocolType(support, fetch) {
1151
+ return {
1152
+ type: "anthropic",
1153
+ label: "Anthropic Messages",
1154
+ fields: [{
1155
+ key: "baseUrl",
1156
+ kind: "url",
1157
+ label: "Base URL",
1158
+ required: true
1159
+ }],
1160
+ userConfigurable: true,
1161
+ optionsSchema: AnthropicProtocolOptions,
1162
+ facts,
1163
+ prepareParams: (input) => support.prepareParams(input, facts),
1164
+ chat: {
1165
+ fileKinds: ["image"],
1166
+ supportsModel: () => true,
1167
+ createPort(call) {
1168
+ const options = AnthropicProtocolOptions.parse(call.options);
1169
+ return createAnthropicModelPort({
1170
+ support,
1171
+ fetch,
1172
+ model: call.model,
1173
+ endpoint: call.providerId,
1174
+ apiKey: call.secrets.apiKey ?? "",
1175
+ baseURL: String(call.config.baseUrl ?? ""),
1176
+ ...options,
1177
+ catalogue: () => support.catalogue(call.providerId, call.model),
1178
+ media: (stored) => support.mediaContextOf({
1179
+ entry: support.catalogue(call.providerId, call.model),
1180
+ stored,
1181
+ facts,
1182
+ endpoint: support.endpoint(call.providerId),
1183
+ fileKinds: ["image"]
1184
+ }),
1185
+ params: (stored) => support.resolveParams({
1186
+ entry: support.catalogue(call.providerId, call.model),
1187
+ stored,
1188
+ facts,
1189
+ model: call.model,
1190
+ endpoint: support.endpoint(call.providerId)
1191
+ })
1192
+ });
1193
+ }
1194
+ },
1195
+ normalizeListing: (input) => support.normalizeListing(input),
1196
+ listModels: (probe) => probeAnthropic.listModels(probe, fetch),
1197
+ testConnection: (probe) => probeAnthropic.testConnection(probe, fetch)
1198
+ };
1199
+ }
1200
+ //#endregion
1201
+ //#region src/index.ts
1202
+ /** Protocol extensions contribute no tools. */
1203
+ const TOOL_NAMES = [];
1204
+ const plugin = {
1205
+ name: "@eum-agent/llm-protocol-anthropic",
1206
+ requires: ["model-support", "network"],
1207
+ apply(ctx) {
1208
+ const support = ctx.services.get("model-support");
1209
+ const network = ctx.services.get("network");
1210
+ ctx.models.registerProtocol(anthropicProtocolType(support, network.fetch));
1211
+ }
1212
+ };
1213
+ //#endregion
1214
+ 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.1",
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.1"
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.1"
31
+ },
32
+ "foundationDependencies": {
33
+ "@eum-agent/infra-local": "1.0.1"
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.