@eum-agent/llm-protocol-anthropic 1.0.0 → 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 (2) hide show
  1. package/dist/index.js +374 -99
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,12 +1,14 @@
1
1
  import { z } from "zod";
2
2
  import Anthropic, { APIConnectionError, APIError } from "@anthropic-ai/sdk";
3
- import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
4
3
  import { createHash } from "node:crypto";
4
+ import { setImmediate } from "node:timers/promises";
5
5
  //#region src/protocol/facts.ts
6
6
  /** Parameter ranges and request limits for this provider wire. */
7
7
  const facts = {
8
- maxTokensRequired: true,
9
- maxTokensFallback: 8192,
8
+ outputLimit: {
9
+ support: "required",
10
+ ordinary: 16e3
11
+ },
10
12
  temperature: {
11
13
  min: 0,
12
14
  max: 1,
@@ -22,39 +24,10 @@ const facts = {
22
24
  //#endregion
23
25
  //#region src/protocol/errors.ts
24
26
  /**
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.
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.
34
30
  */
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
31
  /** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
59
32
  * every other status is not — retrying a bad request or an authentication
60
33
  * failure only spends the backoff budget on a call that will never succeed. */
@@ -68,8 +41,9 @@ function retryAfterMs(error) {
68
41
  const header = error.headers?.get("retry-after");
69
42
  if (!header) return void 0;
70
43
  const seconds = Number(header);
71
- if (!Number.isFinite(seconds)) return void 0;
72
- return seconds * 1e3;
44
+ if (!Number.isFinite(seconds) || seconds < 0) return void 0;
45
+ const milliseconds = seconds * 1e3;
46
+ return Number.isFinite(milliseconds) ? milliseconds : void 0;
73
47
  }
74
48
  /** Converts any exception the SDK call can throw into a `ModelCallError`.
75
49
  * Never reads `error.headers` into the result; the body goes to
@@ -86,24 +60,42 @@ function streamErrorType(error) {
86
60
  const inner = body?.error?.type ?? body?.type;
87
61
  return typeof inner === "string" ? inner : void 0;
88
62
  }
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;
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
+ });
107
99
  }
108
100
  //#endregion
109
101
  //#region src/protocol/request.ts
@@ -129,7 +121,7 @@ function providerTextOf(error) {
129
121
  * goes back as the `redacted_thinking` it came as.
130
122
  */
131
123
  const SUMMARY_THINKING_HEADROOM = 8192;
132
- const DEFAULT_MAX_TOKENS = 8192;
124
+ const DEFAULT_MAX_TOKENS = 16e3;
133
125
  const TOOL_ID = /^[a-zA-Z0-9_-]+$/;
134
126
  /**
135
127
  * The id Anthropic is sent for one tool call. A legal id goes as it is; any
@@ -171,7 +163,7 @@ function toContentBlockParams(part, at, context) {
171
163
  } : {
172
164
  type: "thinking",
173
165
  thinking: part.text,
174
- signature: part.signature ?? ""
166
+ ...context.unsignedThinking ? part.signature === void 0 ? {} : { signature: part.signature } : { signature: part.signature ?? "" }
175
167
  }];
176
168
  case "tool-use": return [{
177
169
  type: "tool_use",
@@ -212,6 +204,9 @@ function toContentBlockParams(part, at, context) {
212
204
  * verified would reject the entire request.
213
205
  */
214
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;
215
210
  const thinking = message.content.filter((part) => part.type === "thinking");
216
211
  if (thinking.length === 0) return true;
217
212
  const model = options.model ?? "";
@@ -396,7 +391,8 @@ function toAnthropicRequest(request, options) {
396
391
  const tools = toolsOf(request);
397
392
  const messages = render(request.messages, request.volatile, (message, index) => thinkingGroupIsSendable(message, options, anthropicPrefixBefore(request, index, options.media, options.support)), {
398
393
  plan: planOf(request, options.media, options.support),
399
- rendering: "wire"
394
+ rendering: "wire",
395
+ unsignedThinking: options.reasoningReplay === "unsigned-thinking"
400
396
  });
401
397
  return {
402
398
  model: options.model ?? "",
@@ -413,14 +409,163 @@ function toAnthropicRequest(request, options) {
413
409
  };
414
410
  }
415
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
416
552
  //#region src/protocol/stream.ts
417
- function toFinishReason(stopReason) {
553
+ function toFinishReason(stopReason, support) {
418
554
  switch (stopReason) {
419
555
  case "tool_use": return "tool-calls";
420
556
  case "max_tokens":
421
557
  case "model_context_window_exceeded": return "max-tokens";
422
558
  case "refusal": return "refusal";
423
- default: return "stop";
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
+ });
424
569
  }
425
570
  }
426
571
  /** The accumulated `input_json_delta` text as JSON, or `undefined` when it
@@ -436,20 +581,15 @@ function parseToolInput(json) {
436
581
  }
437
582
  }
438
583
  /**
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.
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.
447
587
  */
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
588
  async function* mapAnthropicStream(events, attribution, support) {
450
589
  const blocks = /* @__PURE__ */ new Map();
451
590
  const finalContent = [];
452
- let cutOff = false;
591
+ const incompleteToolCalls = [];
592
+ let incompleteThinking = false;
453
593
  let inputTokens = 0;
454
594
  let outputTokens = 0;
455
595
  let cache = {};
@@ -471,7 +611,7 @@ async function* mapAnthropicStream(events, attribution, support) {
471
611
  const block = event.content_block;
472
612
  if (block.type === "text") blocks.set(event.index, {
473
613
  kind: "text",
474
- text: ""
614
+ text: block.text
475
615
  });
476
616
  else if (block.type === "tool_use") {
477
617
  blocks.set(event.index, {
@@ -539,7 +679,10 @@ async function* mapAnthropicStream(events, attribution, support) {
539
679
  });
540
680
  else if (block?.kind === "tool-use") {
541
681
  const input = parseToolInput(block.json);
542
- if (input === void 0) cutOff = true;
682
+ if (input === void 0) incompleteToolCalls.push({
683
+ id: block.id,
684
+ name: block.name
685
+ });
543
686
  else finalContent.push({
544
687
  type: "tool-use",
545
688
  id: block.id,
@@ -551,6 +694,7 @@ async function* mapAnthropicStream(events, attribution, support) {
551
694
  text: block.text,
552
695
  ...block.signature === void 0 ? {} : { signature: block.signature }
553
696
  });
697
+ blocks.delete(event.index);
554
698
  break;
555
699
  }
556
700
  case "message_delta":
@@ -561,9 +705,38 @@ async function* mapAnthropicStream(events, attribution, support) {
561
705
  case "message_stop": stopped = true;
562
706
  }
563
707
  if (!stopped) throw support.interruptedFailure();
564
- if (finalContent.length === 0 && cutOff) finalContent.push({
565
- type: "text",
566
- text: CUT_OFF_NOTICE
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
567
740
  });
568
741
  const attributedContent = finalContent.map((part) => part.type === "thinking" && part.signature !== void 0 && attribution !== void 0 ? {
569
742
  ...part,
@@ -573,7 +746,11 @@ async function* mapAnthropicStream(events, attribution, support) {
573
746
  } : part);
574
747
  yield {
575
748
  kind: "final",
576
- finishReason: toFinishReason(stopReason),
749
+ finishReason,
750
+ ...finishReason === "max-tokens" ? { outputTruncation: {
751
+ incompleteToolCalls,
752
+ ...incompleteThinking ? { incompleteThinking: true } : {}
753
+ } } : {},
577
754
  usage: {
578
755
  inputTokens,
579
756
  outputTokens,
@@ -643,7 +820,7 @@ function createAnthropicModelPort(options) {
643
820
  function clientForAttempt(reportProgress) {
644
821
  return options.client ?? new Anthropic({
645
822
  apiKey: options.apiKey ?? "",
646
- fetch: async (...args) => options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress),
823
+ fetch: async (...args) => frameSseResponse(options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress), args[1]?.signal),
647
824
  baseURL: options.baseURL ?? "",
648
825
  maxRetries: 0
649
826
  });
@@ -679,8 +856,8 @@ function createAnthropicModelPort(options) {
679
856
  const outputReserve = Number.isInteger(params.max_tokens) && params.max_tokens > 0 ? params.max_tokens : capacity?.output ?? 0;
680
857
  return options.support.inspect({
681
858
  body: params,
682
- textTokens: countTokens(JSON.stringify(params), { disallowedSpecial: /* @__PURE__ */ new Set() }),
683
- tokenizer: "o200k_base-json-v1",
859
+ textTokens: options.support.measureText(options.support.requestText("messages", params)),
860
+ tokenizer: "o200k_base-protocol-text-v2",
684
861
  request,
685
862
  capacity,
686
863
  outputReserve,
@@ -707,7 +884,8 @@ function createAnthropicModelPort(options) {
707
884
  }
708
885
  });
709
886
  },
710
- stream(request, signal) {
887
+ stream(request, signal, observer) {
888
+ signal.throwIfAborted();
711
889
  const { params, headers, requestOptions } = build(request);
712
890
  const prefix = anthropicRequestPrefix(request, requestOptions.media, options.support);
713
891
  return options.support.withChatAttempts({
@@ -715,26 +893,79 @@ function createAnthropicModelPort(options) {
715
893
  ...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
716
894
  ...options.sleep === void 0 ? {} : { sleep: options.sleep },
717
895
  ...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 }
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
722
914
  });
723
- yield* mapAnthropicStream((async function* () {
724
- for await (const event of events) {
725
- reportProgress();
726
- yield event;
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;
727
945
  }
728
- })(), {
729
- originModel: params.model,
730
- prefix
731
- }, options.support);
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
+ }
732
963
  },
733
964
  classify(error) {
734
- const portError = toPortError(error);
965
+ const portError = toModelFailure(error, options.support.failures);
735
966
  return {
736
967
  error: portError,
737
- retryable: portError.retryable,
968
+ retryable: portError.retryable === true,
738
969
  retryAfterMs: retryAfterMs(error)
739
970
  };
740
971
  }
@@ -745,6 +976,39 @@ function createAnthropicModelPort(options) {
745
976
  //#endregion
746
977
  //#region src/protocol/probe.ts
747
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
+ }
748
1012
  function baseUrlOf(probe) {
749
1013
  const configured = probe.config.baseUrl;
750
1014
  return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
@@ -752,8 +1016,8 @@ function baseUrlOf(probe) {
752
1016
  /** Attaches the status so the runtime can tell an authentication failure from
753
1017
  * an endpoint that answered something else. The body is passed through as
754
1018
  * 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(() => "");
1019
+ async function refuse(response, maxBytes = 8388608) {
1020
+ const body = (await readBody(response, maxBytes)).text;
757
1021
  throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
758
1022
  }
759
1023
  async function get(probe, path, fetcher) {
@@ -827,15 +1091,19 @@ const probeAnthropic = {
827
1091
  async listModels(probe, fetcher = globalThis.fetch) {
828
1092
  const offers = [];
829
1093
  let afterId;
1094
+ let remaining = probe.maxResponseBytes ?? 8388608;
830
1095
  for (let page = 0; page < MAX_PAGES; page += 1) {
831
1096
  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();
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);
834
1101
  for (const row of body.data ?? []) {
835
1102
  if (typeof row.id !== "string") continue;
836
1103
  offers.push(offerOf(row, row.id));
837
1104
  }
838
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");
839
1107
  afterId = body.last_id;
840
1108
  }
841
1109
  return offers;
@@ -870,7 +1138,14 @@ const probeAnthropic = {
870
1138
  //#endregion
871
1139
  //#region src/protocol.ts
872
1140
  /** Supplier options interpreted by the Messages implementation. */
873
- const AnthropicProtocolOptions = z.strictObject({ budgetOnly: z.array(z.string()).optional() });
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
+ });
874
1149
  /** Registers request mapping, streaming, inspection and probes with host-owned resources. */
875
1150
  function anthropicProtocolType(support, fetch) {
876
1151
  return {
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.0",
7
+ "version": "1.0.1",
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.0"
20
+ "@eum-agent/plugin": "1.0.1"
21
21
  },
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
@@ -27,10 +27,10 @@
27
27
  "yaoguang": {
28
28
  "kind": "extension",
29
29
  "dependencies": {
30
- "@eum-agent/llm-management": "1.0.0"
30
+ "@eum-agent/llm-management": "1.0.1"
31
31
  },
32
32
  "foundationDependencies": {
33
- "@eum-agent/infra-local": "1.0.0"
33
+ "@eum-agent/infra-local": "1.0.1"
34
34
  },
35
35
  "description": {
36
36
  "en-US": "Public Anthropic model communication protocol",