zidane 7.0.25 → 7.0.26

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 (89) hide show
  1. package/dist/{acp-BhbXWwj_.js → acp-C5O2YBst.js} +21 -3
  2. package/dist/acp-C5O2YBst.js.map +1 -0
  3. package/dist/acp-cli.js +4 -4
  4. package/dist/acp.d.ts +1 -1
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-LC2c1ue-.js → agent-BjI9-PlG.js} +9 -1
  7. package/dist/{agent-LC2c1ue-.js.map → agent-BjI9-PlG.js.map} +1 -1
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/{anthropic-BSbDiW0J.js → anthropic-CUM2CjXS.js} +508 -299
  11. package/dist/anthropic-CUM2CjXS.js.map +1 -0
  12. package/dist/{approvals-Deg8JhMI.js → approvals-xpcwa2UM.js} +35 -4
  13. package/dist/approvals-xpcwa2UM.js.map +1 -0
  14. package/dist/{auth-Nq-tSMb9.js → auth-BhbRmx2I.js} +5 -5
  15. package/dist/{auth-Nq-tSMb9.js.map → auth-BhbRmx2I.js.map} +1 -1
  16. package/dist/chat/pure.d.ts +3 -3
  17. package/dist/chat.d.ts +5 -5
  18. package/dist/chat.js +3 -3
  19. package/dist/contexts/daytona.d.ts +1 -1
  20. package/dist/contexts/e2b.d.ts +1 -1
  21. package/dist/daemon-cli.js +1 -1
  22. package/dist/eval.d.ts +1 -1
  23. package/dist/extensions.d.ts +1 -1
  24. package/dist/extensions.js +1 -1
  25. package/dist/headless.d.ts +1 -1
  26. package/dist/headless.js +1 -1
  27. package/dist/{index-C4mY0oKE.d.ts → index-C0y2tSgk.d.ts} +26 -2
  28. package/dist/index-C0y2tSgk.d.ts.map +1 -0
  29. package/dist/{index-DQn4tuAA.d.ts → index-Co4Fddtj.d.ts} +12 -5
  30. package/dist/index-Co4Fddtj.d.ts.map +1 -0
  31. package/dist/index.d.ts +1 -1
  32. package/dist/index.js +4 -4
  33. package/dist/{ipc-BVqRR-42.js → ipc-BKe8SqXv.js} +2 -2
  34. package/dist/{ipc-BVqRR-42.js.map → ipc-BKe8SqXv.js.map} +1 -1
  35. package/dist/ipc.d.ts +5 -5
  36. package/dist/ipc.js +3 -3
  37. package/dist/mcp.d.ts +1 -1
  38. package/dist/{oauth-CmtlmCzi.js → oauth-B6F43fti.js} +16 -4
  39. package/dist/{oauth-CmtlmCzi.js.map → oauth-B6F43fti.js.map} +1 -1
  40. package/dist/output/stream-json.d.ts +1 -1
  41. package/dist/output/terminal.d.ts +1 -1
  42. package/dist/plugins.d.ts +1 -1
  43. package/dist/presets.d.ts +1 -1
  44. package/dist/presets.js +1 -1
  45. package/dist/providers/anthropic.d.ts +1 -1
  46. package/dist/providers/anthropic.js +1 -1
  47. package/dist/providers/arcee.d.ts +1 -1
  48. package/dist/providers/baseten.d.ts +1 -1
  49. package/dist/providers/cerebras.d.ts +1 -1
  50. package/dist/providers/local.d.ts +1 -1
  51. package/dist/providers/openai-compat.d.ts +1 -1
  52. package/dist/providers/openai.d.ts +1 -1
  53. package/dist/providers/openai.js +1 -1
  54. package/dist/providers/openrouter.d.ts +1 -1
  55. package/dist/providers/xai.d.ts +1 -1
  56. package/dist/providers/xai.js +1 -1
  57. package/dist/{providers-ZucqgwU7.js → providers-DPygcIX3.js} +2 -2
  58. package/dist/{providers-ZucqgwU7.js.map → providers-DPygcIX3.js.map} +1 -1
  59. package/dist/providers.d.ts +1 -1
  60. package/dist/providers.js +3 -3
  61. package/dist/restate.d.ts +1 -1
  62. package/dist/restate.js +1 -1
  63. package/dist/{server-qsKLtfXY.js → server-CGe2GGjg.js} +5 -5
  64. package/dist/{server-qsKLtfXY.js.map → server-CGe2GGjg.js.map} +1 -1
  65. package/dist/session/sqlite.d.ts +1 -1
  66. package/dist/session.d.ts +1 -1
  67. package/dist/skills.d.ts +1 -1
  68. package/dist/{tool-formatters-GZHxP824.d.ts → tool-formatters-bbgUM3zI.d.ts} +2 -2
  69. package/dist/{tool-formatters-GZHxP824.d.ts.map → tool-formatters-bbgUM3zI.d.ts.map} +1 -1
  70. package/dist/tools/fetch-url.d.ts +1 -1
  71. package/dist/tools/web-search.d.ts +1 -1
  72. package/dist/tools.d.ts +1 -1
  73. package/dist/tools.js +1 -1
  74. package/dist/{transcript-anchors-CY50AXdF.d.ts → transcript-anchors-BHyrChoO.d.ts} +3 -2
  75. package/dist/transcript-anchors-BHyrChoO.d.ts.map +1 -0
  76. package/dist/tui.d.ts +3 -3
  77. package/dist/tui.d.ts.map +1 -1
  78. package/dist/tui.js +56 -44
  79. package/dist/tui.js.map +1 -1
  80. package/dist/{turn-operations-CAmNETlu.d.ts → turn-operations-ZP5-2OWi.d.ts} +3 -3
  81. package/dist/{turn-operations-CAmNETlu.d.ts.map → turn-operations-ZP5-2OWi.d.ts.map} +1 -1
  82. package/dist/types.d.ts +1 -1
  83. package/package.json +1 -1
  84. package/dist/acp-BhbXWwj_.js.map +0 -1
  85. package/dist/anthropic-BSbDiW0J.js.map +0 -1
  86. package/dist/approvals-Deg8JhMI.js.map +0 -1
  87. package/dist/index-C4mY0oKE.d.ts.map +0 -1
  88. package/dist/index-DQn4tuAA.d.ts.map +0 -1
  89. package/dist/transcript-anchors-CY50AXdF.d.ts.map +0 -1
@@ -3,7 +3,7 @@ import { t as lazyAsync } from "./lazy-DLOurOC_.js";
3
3
  import { f as isRetryableHttpStatus, h as matchesToolPairingError, l as classifyErrorPrelude, m as matchesContextExceeded, u as errorMessage } from "./errors-DKiMrOKq.js";
4
4
  import { renderSystemForWire, splitSystemPrompt } from "./prompt.js";
5
5
  import { g as toAnthropic, u as fromAnthropic } from "./messages-aORUmIKe.js";
6
- import { a as readOAuthCredentials, r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "./oauth-CmtlmCzi.js";
6
+ import { a as readOAuthCredentials, r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "./oauth-B6F43fti.js";
7
7
  import { Buffer } from "node:buffer";
8
8
  import { arch, homedir, hostname, platform, userInfo } from "node:os";
9
9
  import { createHash, randomUUID } from "node:crypto";
@@ -517,6 +517,172 @@ function anthropicOAuthRefreshError(reason, providerId) {
517
517
  return `${prefix} ${guidance} ${reason}`;
518
518
  }
519
519
  //#endregion
520
+ //#region src/providers/anthropic-rate-limit.ts
521
+ function longAnthropicRetryDelay(headers) {
522
+ const value = headers?.get("retry-after");
523
+ if (!value) return void 0;
524
+ const seconds = Number(value);
525
+ const delay = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(value) - Date.now();
526
+ return Number.isFinite(delay) && delay > 6e4 ? delay : void 0;
527
+ }
528
+ function anthropicRateLimitMessage(delayMs) {
529
+ let seconds = Math.ceil(delayMs / 1e3);
530
+ const parts = [];
531
+ for (const [unit, size] of [
532
+ ["day", 86400],
533
+ ["hour", 3600],
534
+ ["minute", 60],
535
+ ["second", 1]
536
+ ]) {
537
+ const count = Math.floor(seconds / size);
538
+ if (count > 0) {
539
+ parts.push(`${count} ${unit}${count === 1 ? "" : "s"}`);
540
+ seconds %= size;
541
+ }
542
+ if (parts.length === 2) break;
543
+ }
544
+ return `Claude has limited this account. Try again in ${parts.join(", ")}. Check your usage in Claude or contact Anthropic support.`;
545
+ }
546
+ function wrapFetchForAnthropicRateLimit(fetch) {
547
+ return Object.assign(async (...args) => {
548
+ const response = await fetch(...args);
549
+ if (response.status !== 429 || longAnthropicRetryDelay(response.headers) === void 0) return response;
550
+ const headers = new Headers(response.headers);
551
+ headers.set("x-should-retry", "false");
552
+ return new Response(response.body, {
553
+ status: response.status,
554
+ statusText: response.statusText,
555
+ headers
556
+ });
557
+ }, fetch);
558
+ }
559
+ //#endregion
560
+ //#region src/providers/diagnostic.ts
561
+ const NETWORK_CODES = /* @__PURE__ */ new Set([
562
+ "ECONNREFUSED",
563
+ "ECONNRESET",
564
+ "ETIMEDOUT",
565
+ "ENOTFOUND",
566
+ "EAI_AGAIN",
567
+ "ENETUNREACH",
568
+ "EHOSTUNREACH",
569
+ "EPIPE",
570
+ "UND_ERR_CONNECT_TIMEOUT",
571
+ "UND_ERR_HEADERS_TIMEOUT",
572
+ "UND_ERR_SOCKET",
573
+ "CERT_HAS_EXPIRED",
574
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
575
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
576
+ "ERR_TLS_CERT_ALTNAME_INVALID",
577
+ "AbortError",
578
+ "TimeoutError"
579
+ ]);
580
+ function sanitizeProviderDiagnosticMetadata(metadata) {
581
+ const safe = {};
582
+ if (typeof metadata.transportAttempt === "number" && Number.isSafeInteger(metadata.transportAttempt) && metadata.transportAttempt > 0) safe.transportAttempt = metadata.transportAttempt;
583
+ if (typeof metadata.networkCode === "string" && NETWORK_CODES.has(metadata.networkCode)) safe.networkCode = metadata.networkCode;
584
+ if (typeof metadata.httpStatus === "number" && Number.isInteger(metadata.httpStatus) && metadata.httpStatus >= 100 && metadata.httpStatus <= 599) safe.httpStatus = metadata.httpStatus;
585
+ if (typeof metadata.upstreamRequestId === "string" && metadata.upstreamRequestId.length <= 128 && /^req_[\w-]+$/.test(metadata.upstreamRequestId)) safe.upstreamRequestId = metadata.upstreamRequestId;
586
+ const retryAfter = metadata.retryAfter;
587
+ if (typeof retryAfter === "string" && retryAfter.length <= 32 && (/^\d+(?:\.\d+)?$/.test(retryAfter) || retryAfter.length === 29 && new Date(retryAfter).toUTCString() === retryAfter)) safe.retryAfter = retryAfter;
588
+ return safe;
589
+ }
590
+ /** No request or error objects cross this boundary. Diagnostics cannot fail a request. */
591
+ function createProviderDiagnosticTracker(emit, signal) {
592
+ const requestId = crypto.randomUUID();
593
+ const started = performance.now();
594
+ let stageStarted = started;
595
+ let current;
596
+ let attempt = 0;
597
+ let transportAttempt = 0;
598
+ let finished = false;
599
+ let timer;
600
+ let abort = () => {};
601
+ function send(event, metadata = {}) {
602
+ if (!current) return;
603
+ const now = performance.now();
604
+ try {
605
+ emit?.({
606
+ requestId,
607
+ stage: current,
608
+ event,
609
+ elapsedMs: Math.round(now - started),
610
+ stageElapsedMs: Math.round(now - stageStarted),
611
+ attempt,
612
+ ...sanitizeProviderDiagnosticMetadata(metadata)
613
+ });
614
+ } catch {}
615
+ }
616
+ const tracker = {
617
+ wrapFetch(fetch) {
618
+ if (!emit) return fetch;
619
+ return Object.assign(async (...args) => {
620
+ const number = ++transportAttempt;
621
+ const began = performance.now();
622
+ const report = (event, metadata = {}) => {
623
+ try {
624
+ emit({
625
+ requestId,
626
+ stage: "transport",
627
+ event,
628
+ elapsedMs: Math.round(performance.now() - started),
629
+ stageElapsedMs: Math.round(performance.now() - began),
630
+ attempt,
631
+ ...sanitizeProviderDiagnosticMetadata({
632
+ ...metadata,
633
+ transportAttempt: number
634
+ })
635
+ });
636
+ } catch {}
637
+ };
638
+ report("start");
639
+ try {
640
+ const response = await fetch(...args);
641
+ report("end", {
642
+ httpStatus: response.status,
643
+ upstreamRequestId: response.headers.get("request-id"),
644
+ retryAfter: response.headers.get("retry-after")
645
+ });
646
+ return response;
647
+ } catch (error) {
648
+ const err = error;
649
+ report("failure", { networkCode: [
650
+ err?.cause?.code,
651
+ err?.code,
652
+ err?.name
653
+ ].find((value) => typeof value === "string" && NETWORK_CODES.has(value)) });
654
+ throw error;
655
+ }
656
+ }, fetch);
657
+ },
658
+ stage(stage, metadata = {}) {
659
+ if (!emit || finished) return;
660
+ if (current) send("end");
661
+ current = stage;
662
+ stageStarted = performance.now();
663
+ if (stage === "dispatch") attempt++;
664
+ send("start", metadata);
665
+ if (timer) clearInterval(timer);
666
+ timer = setInterval(send, 3e4, "waiting");
667
+ timer.unref?.();
668
+ if (signal?.aborted) abort();
669
+ },
670
+ finish(event, metadata = {}) {
671
+ if (!emit || finished) return;
672
+ finished = true;
673
+ clearInterval(timer);
674
+ signal?.removeEventListener("abort", abort);
675
+ if (current) {
676
+ send("end");
677
+ send(event, metadata);
678
+ }
679
+ }
680
+ };
681
+ abort = () => tracker.finish("abort");
682
+ if (emit) signal?.addEventListener("abort", abort, { once: true });
683
+ return tracker;
684
+ }
685
+ //#endregion
520
686
  //#region src/providers/anthropic.ts
521
687
  const loadAnthropicSdk = lazyAsync(async () => {
522
688
  try {
@@ -701,7 +867,7 @@ function buildAnthropicClientOptions(apiKey, auth, baseURL, extraBetas, extraHea
701
867
  authToken: apiKey,
702
868
  dangerouslyAllowBrowser: true,
703
869
  defaultHeaders,
704
- fetch: wrapFetchForCch(globalThis.fetch),
870
+ fetch: wrapFetchForAnthropicRateLimit(wrapFetchForCch(globalThis.fetch)),
705
871
  ...base
706
872
  };
707
873
  }
@@ -720,8 +886,10 @@ function buildAnthropicClientOptions(apiKey, auth, baseURL, extraBetas, extraHea
720
886
  ...base
721
887
  };
722
888
  }
723
- function createClient(SDK, apiKey, auth, baseURL, extraBetas, extraHeaders) {
724
- return new SDK(buildAnthropicClientOptions(apiKey, auth, baseURL, extraBetas, extraHeaders));
889
+ function createClient(SDK, apiKey, auth, baseURL, extraBetas, extraHeaders, wrapFetch) {
890
+ const options = buildAnthropicClientOptions(apiKey, auth, baseURL, extraBetas, extraHeaders);
891
+ if (wrapFetch) options.fetch = wrapFetch(options.fetch ?? globalThis.fetch);
892
+ return new SDK(options);
725
893
  }
726
894
  /**
727
895
  * Map `ThinkingLevel` budgeted tiers to Anthropic's `output_config.effort`
@@ -1151,6 +1319,13 @@ function classifyAnthropicError(err) {
1151
1319
  if (prelude === "not-object") return null;
1152
1320
  if (prelude === "aborted") return { kind: "aborted" };
1153
1321
  const anyErr = err;
1322
+ const delay = anyErr.status === 429 && anyErr.headers instanceof Headers ? longAnthropicRetryDelay(anyErr.headers) : void 0;
1323
+ if (delay !== void 0) return {
1324
+ kind: "provider_error",
1325
+ providerCode: "rate_limit_error",
1326
+ message: anthropicRateLimitMessage(delay),
1327
+ retryable: false
1328
+ };
1154
1329
  if (!looksLikeAnthropicApiError(err)) {
1155
1330
  const sseError = matchSseErrorEvent(anyErr.message);
1156
1331
  if (sseError) return {
@@ -1606,320 +1781,354 @@ function anthropic(anthropicParams) {
1606
1781
  }
1607
1782
  },
1608
1783
  async stream(options, callbacks) {
1609
- let apiKey = "";
1610
- const resolveCallApiKey = async (forceRefresh = false, rejectedAccess) => {
1611
- const identity = credentialIdentity(anthropicParams);
1612
- return await resolveOAuthApiKey({
1613
- provider: identity.providerId,
1614
- providerId: identity.providerId,
1615
- params: runtimeCredentials ? {
1616
- ...anthropicParams,
1617
- ...runtimeCredentials
1618
- } : anthropicParams,
1619
- envKey: identity.envKey,
1620
- missingError: identity.missingError,
1621
- refreshError: identity.refreshError,
1622
- forceRefresh,
1623
- rejectedAccess
1624
- }, {
1625
- ...callbacks,
1626
- async onOAuthRefresh(ctx) {
1627
- if (ctx.source === "params") runtimeCredentials = {
1628
- access: ctx.credentials.access,
1629
- refresh: ctx.credentials.refresh,
1630
- expires: ctx.credentials.expires
1631
- };
1632
- await callbacks.onOAuthRefresh?.(ctx);
1633
- }
1634
- });
1635
- };
1636
- if (!bedrockConfig) apiKey = await resolveCallApiKey();
1637
- const callAuth = resolveAnthropicAuthShape(apiKey, bedrockConfig ? "api-key" : anthropicParams?.authMode);
1638
- const callIsOAuth = callAuth.claudeCode;
1639
- /**
1640
- * Whether a provider auth rejection on this call is worth ATTEMPTING one
1641
- * forced credential rotation. A bearer-authenticated call MAY resolve its
1642
- * token through the refreshable OAuth store — subscription OAuth and
1643
- * `authMode: 'bearer'` gateways (`extensions/bolt`) both do — so a 401
1644
- * arriving before the local expiry is recoverable for them. Deliberately
1645
- * WIDER than {@link callIsOAuth}, which additionally means "wear the
1646
- * Claude Code persona"; a gateway is not Claude Code but its token still
1647
- * rotates.
1648
- *
1649
- * The ones that cannot rotate stop at the identical-credential guard in
1650
- * the recovery below rather than being excluded here: a static bearer
1651
- * token supplied as `apiKey` short-circuits `resolveOAuthApiKey` and never
1652
- * reaches the store, so the re-resolve returns the same value and costs
1653
- * nothing but a function call. API-key and Bedrock calls never get that
1654
- * far — `callAuth.bearer` is false for both.
1655
- */
1656
- const callCanRotateAuth = callAuth.bearer;
1657
- const effectiveCacheTtl = options.cacheTtl ?? (callIsOAuth ? "1h" : void 0);
1658
- const extendedTtl = options.cache !== false && effectiveCacheTtl === "1h" && !bedrockConfig;
1659
- const conditionalBetas = [...options.modelOptions?.fast && !callIsOAuth ? [FAST_MODE_BETA] : [], ...extendedTtl ? [EXTENDED_CACHE_TTL_BETA] : []];
1660
- const requestBetas = conditionalBetas.length > 0 ? [...anthropicParams?.extraBetas ?? [], ...conditionalBetas] : anthropicParams?.extraBetas;
1661
- const resolvedExtraHeaders = await resolveExtraHeaders(anthropicParams?.extraHeaders);
1662
- let client = bedrockConfig ? await createBedrockClient(bedrockConfig, anthropicParams, resolvedExtraHeaders) : createClient(await loadAnthropicSdk(), apiKey, callAuth, anthropicParams?.baseURL, requestBetas, resolvedExtraHeaders);
1663
- const wireSystem = renderSystemForWire(options.system);
1664
- const system = callIsOAuth ? `You are Claude Code, Anthropic's official CLI for Claude.` : wireSystem;
1665
- const messages = callIsOAuth && options.system ? [
1666
- {
1667
- role: "user",
1668
- content: [{
1669
- type: "text",
1670
- text: wireSystem
1671
- }]
1672
- },
1673
- {
1674
- role: "assistant",
1675
- content: [{
1676
- type: "text",
1677
- text: "Understood. I will proceed with these instructions above the rest of my system prompt."
1678
- }]
1679
- },
1680
- ...options.messages
1681
- ] : [...options.messages];
1682
- const thinking = options.thinking ?? "off";
1683
- const inputTools = options.tools ?? [];
1684
- const nameBoundary = createToolNameBoundary(messages, inputTools.map((t) => t.name), callIsOAuth ? claudeCodeToolAliases : void 0);
1685
- const wireTools = nameBoundary.changed ? inputTools.map((t) => t.name === nameBoundary.toWire(t.name) ? t : {
1686
- ...t,
1687
- name: nameBoundary.toWire(t.name)
1688
- }) : inputTools;
1689
- const modelId = options.model;
1690
- const modelMaxOutput = await resolveAnthropicMaxOutput(modelId, options.maxTokens, options.modelCatalog);
1691
- const params = {
1692
- ...anthropicParams?.extraBodyParams ?? {},
1693
- model: modelId,
1694
- max_tokens: options.maxTokens ?? modelMaxOutput,
1695
- system,
1696
- tools: wireTools,
1697
- messages: nameBoundary.messages.map((m) => toAnthropic(m)),
1698
- stream: true
1699
- };
1700
- if (anthropicParams?.contextManagement && !bedrockConfig) params.context_management = anthropicParams.contextManagement;
1701
- if (options.cache !== false) applyAnthropicCacheBreakpoints(params, callIsOAuth ? void 0 : options.system, extendedTtl ? effectiveCacheTtl : void 0);
1702
- const plan = planAnthropicThinking(thinking, options.thinkingBudget, options.taskBudget, options.effortHint !== false);
1703
- if (plan && bedrockConfig) {
1704
- const budget = plan.kind === "enabled" ? plan.budgetTokens : BEDROCK_THINKING_BUDGETS[plan.effort ?? "medium"];
1705
- params.thinking = {
1706
- type: "enabled",
1707
- budget_tokens: budget
1784
+ const diagnostic = createProviderDiagnosticTracker(callbacks.onDiagnostic, options.signal);
1785
+ let diagnosticActive = false;
1786
+ try {
1787
+ let apiKey = "";
1788
+ const resolveCallApiKey = async (forceRefresh = false, rejectedAccess) => {
1789
+ const identity = credentialIdentity(anthropicParams);
1790
+ return await resolveOAuthApiKey({
1791
+ provider: identity.providerId,
1792
+ providerId: identity.providerId,
1793
+ params: runtimeCredentials ? {
1794
+ ...anthropicParams,
1795
+ ...runtimeCredentials
1796
+ } : anthropicParams,
1797
+ envKey: identity.envKey,
1798
+ missingError: identity.missingError,
1799
+ refreshError: identity.refreshError,
1800
+ forceRefresh,
1801
+ rejectedAccess
1802
+ }, {
1803
+ ...callbacks,
1804
+ onOAuthStage(stage) {
1805
+ if (!callbacks.onDiagnostic || anthropicParams?.authMode === "api-key" || anthropicParams?.authMode === "bearer") return;
1806
+ diagnosticActive = true;
1807
+ diagnostic.stage(stage);
1808
+ },
1809
+ async onOAuthRefresh(ctx) {
1810
+ if (ctx.source === "params") runtimeCredentials = {
1811
+ access: ctx.credentials.access,
1812
+ refresh: ctx.credentials.refresh,
1813
+ expires: ctx.credentials.expires
1814
+ };
1815
+ await callbacks.onOAuthRefresh?.(ctx);
1816
+ }
1817
+ });
1818
+ };
1819
+ if (!bedrockConfig) apiKey = await resolveCallApiKey();
1820
+ const callAuth = resolveAnthropicAuthShape(apiKey, bedrockConfig ? "api-key" : anthropicParams?.authMode);
1821
+ const callIsOAuth = callAuth.claudeCode;
1822
+ if (callIsOAuth && callbacks.onDiagnostic) {
1823
+ diagnosticActive = true;
1824
+ diagnostic.stage("prepare");
1825
+ }
1826
+ /**
1827
+ * Whether a provider auth rejection on this call is worth ATTEMPTING one
1828
+ * forced credential rotation. A bearer-authenticated call MAY resolve its
1829
+ * token through the refreshable OAuth store — subscription OAuth and
1830
+ * `authMode: 'bearer'` gateways (`extensions/bolt`) both do — so a 401
1831
+ * arriving before the local expiry is recoverable for them. Deliberately
1832
+ * WIDER than {@link callIsOAuth}, which additionally means "wear the
1833
+ * Claude Code persona"; a gateway is not Claude Code but its token still
1834
+ * rotates.
1835
+ *
1836
+ * The ones that cannot rotate stop at the identical-credential guard in
1837
+ * the recovery below rather than being excluded here: a static bearer
1838
+ * token supplied as `apiKey` short-circuits `resolveOAuthApiKey` and never
1839
+ * reaches the store, so the re-resolve returns the same value and costs
1840
+ * nothing but a function call. API-key and Bedrock calls never get that
1841
+ * far — `callAuth.bearer` is false for both.
1842
+ */
1843
+ const callCanRotateAuth = callAuth.bearer;
1844
+ const effectiveCacheTtl = options.cacheTtl ?? (callIsOAuth ? "1h" : void 0);
1845
+ const extendedTtl = options.cache !== false && effectiveCacheTtl === "1h" && !bedrockConfig;
1846
+ const conditionalBetas = [...options.modelOptions?.fast && !callIsOAuth ? [FAST_MODE_BETA] : [], ...extendedTtl ? [EXTENDED_CACHE_TTL_BETA] : []];
1847
+ const requestBetas = conditionalBetas.length > 0 ? [...anthropicParams?.extraBetas ?? [], ...conditionalBetas] : anthropicParams?.extraBetas;
1848
+ const resolvedExtraHeaders = await resolveExtraHeaders(anthropicParams?.extraHeaders);
1849
+ let client = bedrockConfig ? await createBedrockClient(bedrockConfig, anthropicParams, resolvedExtraHeaders) : createClient(await loadAnthropicSdk(), apiKey, callAuth, anthropicParams?.baseURL, requestBetas, resolvedExtraHeaders, callIsOAuth ? diagnostic.wrapFetch : void 0);
1850
+ const wireSystem = renderSystemForWire(options.system);
1851
+ const system = callIsOAuth ? `You are Claude Code, Anthropic's official CLI for Claude.` : wireSystem;
1852
+ const messages = callIsOAuth && options.system ? [
1853
+ {
1854
+ role: "user",
1855
+ content: [{
1856
+ type: "text",
1857
+ text: wireSystem
1858
+ }]
1859
+ },
1860
+ {
1861
+ role: "assistant",
1862
+ content: [{
1863
+ type: "text",
1864
+ text: "Understood. I will proceed with these instructions above the rest of my system prompt."
1865
+ }]
1866
+ },
1867
+ ...options.messages
1868
+ ] : [...options.messages];
1869
+ const thinking = options.thinking ?? "off";
1870
+ const inputTools = options.tools ?? [];
1871
+ const nameBoundary = createToolNameBoundary(messages, inputTools.map((t) => t.name), callIsOAuth ? claudeCodeToolAliases : void 0);
1872
+ const wireTools = nameBoundary.changed ? inputTools.map((t) => t.name === nameBoundary.toWire(t.name) ? t : {
1873
+ ...t,
1874
+ name: nameBoundary.toWire(t.name)
1875
+ }) : inputTools;
1876
+ const modelId = options.model;
1877
+ const modelMaxOutput = await resolveAnthropicMaxOutput(modelId, options.maxTokens, options.modelCatalog);
1878
+ const params = {
1879
+ ...anthropicParams?.extraBodyParams ?? {},
1880
+ model: modelId,
1881
+ max_tokens: options.maxTokens ?? modelMaxOutput,
1882
+ system,
1883
+ tools: wireTools,
1884
+ messages: nameBoundary.messages.map((m) => toAnthropic(m)),
1885
+ stream: true
1708
1886
  };
1709
- params.max_tokens = budget + params.max_tokens;
1710
- params.temperature = 1;
1711
- } else if (plan) {
1712
- if (plan.kind === "enabled") {
1887
+ if (anthropicParams?.contextManagement && !bedrockConfig) params.context_management = anthropicParams.contextManagement;
1888
+ if (options.cache !== false) applyAnthropicCacheBreakpoints(params, callIsOAuth ? void 0 : options.system, extendedTtl ? effectiveCacheTtl : void 0);
1889
+ const plan = planAnthropicThinking(thinking, options.thinkingBudget, options.taskBudget, options.effortHint !== false);
1890
+ if (plan && bedrockConfig) {
1891
+ const budget = plan.kind === "enabled" ? plan.budgetTokens : BEDROCK_THINKING_BUDGETS[plan.effort ?? "medium"];
1713
1892
  params.thinking = {
1714
1893
  type: "enabled",
1715
- budget_tokens: plan.budgetTokens,
1716
- display: "summarized"
1717
- };
1718
- params.max_tokens = plan.maxTokensBump + params.max_tokens;
1719
- if (plan.effort) params.output_config = {
1720
- ...params.output_config,
1721
- effort: plan.effort
1722
- };
1723
- } else {
1724
- params.thinking = {
1725
- type: "adaptive",
1726
- display: "summarized"
1894
+ budget_tokens: budget
1727
1895
  };
1728
- const outputConfig = {};
1729
- if (plan.effort) outputConfig.effort = plan.effort;
1730
- if (typeof plan.taskBudgetTokens === "number" && plan.taskBudgetTokens > 0) outputConfig.task_budget = {
1731
- type: "tokens",
1732
- total: plan.taskBudgetTokens
1733
- };
1734
- if (Object.keys(outputConfig).length > 0) params.output_config = {
1735
- ...params.output_config,
1736
- ...outputConfig
1896
+ params.max_tokens = budget + params.max_tokens;
1897
+ params.temperature = 1;
1898
+ } else if (plan) {
1899
+ if (plan.kind === "enabled") {
1900
+ params.thinking = {
1901
+ type: "enabled",
1902
+ budget_tokens: plan.budgetTokens,
1903
+ display: "summarized"
1904
+ };
1905
+ params.max_tokens = plan.maxTokensBump + params.max_tokens;
1906
+ if (plan.effort) params.output_config = {
1907
+ ...params.output_config,
1908
+ effort: plan.effort
1909
+ };
1910
+ } else {
1911
+ params.thinking = {
1912
+ type: "adaptive",
1913
+ display: "summarized"
1914
+ };
1915
+ const outputConfig = {};
1916
+ if (plan.effort) outputConfig.effort = plan.effort;
1917
+ if (typeof plan.taskBudgetTokens === "number" && plan.taskBudgetTokens > 0) outputConfig.task_budget = {
1918
+ type: "tokens",
1919
+ total: plan.taskBudgetTokens
1920
+ };
1921
+ if (Object.keys(outputConfig).length > 0) params.output_config = {
1922
+ ...params.output_config,
1923
+ ...outputConfig
1924
+ };
1925
+ if (typeof plan.maxTokensCap === "number" && plan.maxTokensCap > 0) params.max_tokens = Math.min(params.max_tokens, plan.maxTokensCap);
1926
+ }
1927
+ params.temperature = 1;
1928
+ }
1929
+ params.max_tokens = Math.min(params.max_tokens, modelMaxOutput);
1930
+ if (callIsOAuth) {
1931
+ params.max_tokens = Math.min(params.max_tokens, CLAUDE_CODE_MAX_OUTPUT_TOKENS);
1932
+ if (Array.isArray(params.system)) params.system = [{
1933
+ type: "text",
1934
+ text: claudeCodeBillingText(firstUserMessageText(params.messages))
1935
+ }, ...params.system];
1936
+ if (typeof params.metadata?.user_id !== "string") params.metadata = {
1937
+ ...params.metadata,
1938
+ user_id: claudeCodeUserId()
1737
1939
  };
1738
- if (typeof plan.maxTokensCap === "number" && plan.maxTokensCap > 0) params.max_tokens = Math.min(params.max_tokens, plan.maxTokensCap);
1739
1940
  }
1740
- params.temperature = 1;
1741
- }
1742
- params.max_tokens = Math.min(params.max_tokens, modelMaxOutput);
1743
- if (callIsOAuth) {
1744
- params.max_tokens = Math.min(params.max_tokens, CLAUDE_CODE_MAX_OUTPUT_TOKENS);
1745
- if (Array.isArray(params.system)) params.system = [{
1746
- type: "text",
1747
- text: claudeCodeBillingText(firstUserMessageText(params.messages))
1748
- }, ...params.system];
1749
- if (typeof params.metadata?.user_id !== "string") params.metadata = {
1750
- ...params.metadata,
1751
- user_id: claudeCodeUserId()
1752
- };
1753
- }
1754
- if (params.thinking?.type === "enabled" && params.thinking.budget_tokens >= params.max_tokens) {
1755
- const fitted = params.max_tokens - THINKING_RESPONSE_RESERVE_TOKENS;
1756
- if (fitted >= 1024) params.thinking.budget_tokens = fitted;
1757
- else {
1758
- delete params.thinking;
1759
- delete params.temperature;
1941
+ if (params.thinking?.type === "enabled" && params.thinking.budget_tokens >= params.max_tokens) {
1942
+ const fitted = params.max_tokens - THINKING_RESPONSE_RESERVE_TOKENS;
1943
+ if (fitted >= 1024) params.thinking.budget_tokens = fitted;
1944
+ else {
1945
+ delete params.thinking;
1946
+ delete params.temperature;
1947
+ }
1760
1948
  }
1761
- }
1762
- if (options.modelOptions?.fast && !callIsOAuth) params.speed = "fast";
1763
- if (options.toolChoice) if (options.toolChoice.type === "tool" && options.toolChoice.name) params.tool_choice = {
1764
- type: "tool",
1765
- name: nameBoundary.toWire(options.toolChoice.name)
1766
- };
1767
- else if (options.toolChoice.type === "required") params.tool_choice = { type: "any" };
1768
- else params.tool_choice = { type: "auto" };
1769
- const promptCacheKey = resolvePromptCacheKey(anthropicParams?.promptCacheKey, {
1770
- model: modelId,
1771
- system: options.system,
1772
- messages: options.messages
1773
- });
1774
- if (promptCacheKey !== void 0 && params.metadata?.user_id === void 0) params.metadata = {
1775
- ...params.metadata,
1776
- user_id: promptCacheKey
1777
- };
1778
- const affinityHeaderName = anthropicParams?.promptCacheKeyHeader?.toLowerCase();
1779
- const affinityHeader = anthropicParams?.promptCacheKeyHeader !== void 0 && promptCacheKey !== void 0 && !Object.keys(resolvedExtraHeaders ?? {}).some((k) => k.toLowerCase() === affinityHeaderName) ? { [anthropicParams.promptCacheKeyHeader]: promptCacheKey } : void 0;
1780
- const runStream = async (requestParams, fastRequested, scrubPass = 0, authPass = 0) => {
1781
- const s = client.messages.stream(requestParams, {
1782
- signal: options.signal,
1783
- ...affinityHeader ? { headers: affinityHeader } : {}
1784
- });
1785
- let text = "";
1786
- let observedOutput = false;
1787
- s.on("text", (delta) => {
1788
- observedOutput = true;
1789
- text += delta;
1790
- callbacks.onText(delta);
1791
- });
1792
- if (callbacks.onThinking) s.on("thinking", (delta) => {
1793
- observedOutput = true;
1794
- callbacks.onThinking(delta);
1949
+ if (options.modelOptions?.fast && !callIsOAuth) params.speed = "fast";
1950
+ if (options.toolChoice) if (options.toolChoice.type === "tool" && options.toolChoice.name) params.tool_choice = {
1951
+ type: "tool",
1952
+ name: nameBoundary.toWire(options.toolChoice.name)
1953
+ };
1954
+ else if (options.toolChoice.type === "required") params.tool_choice = { type: "any" };
1955
+ else params.tool_choice = { type: "auto" };
1956
+ const promptCacheKey = resolvePromptCacheKey(anthropicParams?.promptCacheKey, {
1957
+ model: modelId,
1958
+ system: options.system,
1959
+ messages: options.messages
1795
1960
  });
1796
- if (callbacks.onUsage) {
1797
- let live;
1798
- s.on("streamEvent", (event) => {
1799
- if (event.type === "message_start") {
1800
- const u = event.message.usage;
1801
- live = {
1802
- inputTokens: u.input_tokens ?? 0,
1803
- ...u.cache_read_input_tokens != null ? { cacheRead: u.cache_read_input_tokens } : {},
1804
- ...u.cache_creation_input_tokens != null ? { cacheCreation: u.cache_creation_input_tokens } : {},
1805
- ...callIsOAuth ? { billable: false } : {}
1806
- };
1807
- } else if (event.type === "message_delta") live = {
1808
- ...live ?? {
1809
- inputTokens: 0,
1810
- ...callIsOAuth ? { billable: false } : {}
1811
- },
1812
- outputTokens: event.usage.output_tokens
1813
- };
1814
- else return;
1815
- callbacks.onUsage(live);
1961
+ if (promptCacheKey !== void 0 && params.metadata?.user_id === void 0) params.metadata = {
1962
+ ...params.metadata,
1963
+ user_id: promptCacheKey
1964
+ };
1965
+ const affinityHeaderName = anthropicParams?.promptCacheKeyHeader?.toLowerCase();
1966
+ const affinityHeader = anthropicParams?.promptCacheKeyHeader !== void 0 && promptCacheKey !== void 0 && !Object.keys(resolvedExtraHeaders ?? {}).some((k) => k.toLowerCase() === affinityHeaderName) ? { [anthropicParams.promptCacheKeyHeader]: promptCacheKey } : void 0;
1967
+ const runStream = async (requestParams, fastRequested, scrubPass = 0, authPass = 0) => {
1968
+ if (diagnosticActive) diagnostic.stage("dispatch");
1969
+ const s = client.messages.stream(requestParams, {
1970
+ signal: options.signal,
1971
+ ...affinityHeader ? { headers: affinityHeader } : {}
1816
1972
  });
1817
- }
1818
- if (callbacks.onToolCallDelta) s.on("inputJson", () => {
1819
- observedOutput = true;
1820
- callbacks.onToolCallDelta();
1821
- });
1822
- if (callbacks.onServerToolUse || callbacks.onServerToolResult) s.on("contentBlock", (block) => {
1823
- observedOutput = true;
1824
- if (block.type === "server_tool_use") callbacks.onServerToolUse?.({
1825
- id: block.id,
1826
- name: block.name,
1827
- input: block.input ?? {}
1973
+ if (diagnosticActive) {
1974
+ s.on("connect", () => diagnostic.stage("response-headers", {
1975
+ httpStatus: s.response?.status,
1976
+ upstreamRequestId: s.request_id
1977
+ }));
1978
+ let firstActivity = true;
1979
+ s.on("streamEvent", () => {
1980
+ if (!firstActivity) return;
1981
+ firstActivity = false;
1982
+ diagnostic.stage("first-activity");
1983
+ diagnostic.stage("stream");
1984
+ });
1985
+ }
1986
+ let text = "";
1987
+ let observedOutput = false;
1988
+ s.on("text", (delta) => {
1989
+ observedOutput = true;
1990
+ text += delta;
1991
+ callbacks.onText(delta);
1828
1992
  });
1829
- else if (block.type === "web_search_tool_result") callbacks.onServerToolResult?.({
1830
- toolUseId: block.tool_use_id,
1831
- toolName: "web_search",
1832
- content: block.content
1993
+ if (callbacks.onThinking) s.on("thinking", (delta) => {
1994
+ observedOutput = true;
1995
+ callbacks.onThinking(delta);
1833
1996
  });
1834
- });
1835
- let response;
1836
- try {
1837
- response = await s.finalMessage();
1838
- } catch (err) {
1839
- if (!observedOutput && scrubPass < MAX_THINKING_SCRUB_PASSES && isRecoverableThinkingBlockError(err, requestParams.messages)) {
1840
- const failingIndex = parseFailingMessageIndex(err);
1841
- const plan = planThinkingScrub(scrubPass, failingIndex, requestParams.messages);
1842
- const scrubbed = withoutHistoricalThinking(requestParams.messages, plan.upToIndex, plan.alsoMessageIndex);
1843
- if (scrubbed.removed > 0) {
1997
+ if (callbacks.onUsage) {
1998
+ let live;
1999
+ s.on("streamEvent", (event) => {
2000
+ if (event.type === "message_start") {
2001
+ const u = event.message.usage;
2002
+ live = {
2003
+ inputTokens: u.input_tokens ?? 0,
2004
+ ...u.cache_read_input_tokens != null ? { cacheRead: u.cache_read_input_tokens } : {},
2005
+ ...u.cache_creation_input_tokens != null ? { cacheCreation: u.cache_creation_input_tokens } : {},
2006
+ ...callIsOAuth ? { billable: false } : {}
2007
+ };
2008
+ } else if (event.type === "message_delta") live = {
2009
+ ...live ?? {
2010
+ inputTokens: 0,
2011
+ ...callIsOAuth ? { billable: false } : {}
2012
+ },
2013
+ outputTokens: event.usage.output_tokens
2014
+ };
2015
+ else return;
2016
+ callbacks.onUsage(live);
2017
+ });
2018
+ }
2019
+ if (callbacks.onToolCallDelta) s.on("inputJson", () => {
2020
+ observedOutput = true;
2021
+ callbacks.onToolCallDelta();
2022
+ });
2023
+ if (callbacks.onServerToolUse || callbacks.onServerToolResult) s.on("contentBlock", (block) => {
2024
+ observedOutput = true;
2025
+ if (block.type === "server_tool_use") callbacks.onServerToolUse?.({
2026
+ id: block.id,
2027
+ name: block.name,
2028
+ input: block.input ?? {}
2029
+ });
2030
+ else if (block.type === "web_search_tool_result") callbacks.onServerToolResult?.({
2031
+ toolUseId: block.tool_use_id,
2032
+ toolName: "web_search",
2033
+ content: block.content
2034
+ });
2035
+ });
2036
+ let response;
2037
+ try {
2038
+ response = await s.finalMessage();
2039
+ } catch (err) {
2040
+ if (!observedOutput && scrubPass < MAX_THINKING_SCRUB_PASSES && isRecoverableThinkingBlockError(err, requestParams.messages)) {
2041
+ const failingIndex = parseFailingMessageIndex(err);
2042
+ const plan = planThinkingScrub(scrubPass, failingIndex, requestParams.messages);
2043
+ const scrubbed = withoutHistoricalThinking(requestParams.messages, plan.upToIndex, plan.alsoMessageIndex);
2044
+ if (scrubbed.removed > 0) {
2045
+ try {
2046
+ await callbacks.onHistoryRepair?.({
2047
+ type: "invalid-anthropic-thinking-signature",
2048
+ ...failingIndex !== void 0 ? { wireMessageIndex: failingIndex } : {}
2049
+ });
2050
+ } catch (repairErr) {
2051
+ if (process.env.ZIDANE_DEBUG) process.stderr.write(`[zidane/anthropic] history repair callback failed: ${errorMessage(repairErr)}\n`);
2052
+ }
2053
+ return await runStream({
2054
+ ...requestParams,
2055
+ messages: scrubbed.messages
2056
+ }, fastRequested, scrubPass + 1, authPass);
2057
+ }
2058
+ }
2059
+ if (callCanRotateAuth && authPass === 0 && !observedOutput && isAnthropicAuthenticationError(err)) {
2060
+ const rejectedAccess = apiKey;
2061
+ let refreshedApiKey;
1844
2062
  try {
1845
- await callbacks.onHistoryRepair?.({
1846
- type: "invalid-anthropic-thinking-signature",
1847
- ...failingIndex !== void 0 ? { wireMessageIndex: failingIndex } : {}
1848
- });
1849
- } catch (repairErr) {
1850
- if (process.env.ZIDANE_DEBUG) process.stderr.write(`[zidane/anthropic] history repair callback failed: ${errorMessage(repairErr)}\n`);
2063
+ refreshedApiKey = await resolveCallApiKey(true, rejectedAccess);
2064
+ } catch (refreshErr) {
2065
+ if (err !== null && typeof err === "object" && err.cause === void 0) try {
2066
+ err.cause = refreshErr;
2067
+ } catch {}
2068
+ if (process.env.ZIDANE_DEBUG) process.stderr.write(`[zidane/anthropic] forced OAuth refresh after 401 failed: ${errorMessage(refreshErr)}\n`);
2069
+ throw err;
1851
2070
  }
1852
- return await runStream({
1853
- ...requestParams,
1854
- messages: scrubbed.messages
1855
- }, fastRequested, scrubPass + 1, authPass);
2071
+ if (refreshedApiKey === rejectedAccess) throw err;
2072
+ apiKey = refreshedApiKey;
2073
+ client = createClient(await loadAnthropicSdk(), apiKey, callAuth, anthropicParams?.baseURL, requestBetas, resolvedExtraHeaders, callIsOAuth ? diagnostic.wrapFetch : void 0);
2074
+ return await runStream(requestParams, fastRequested, scrubPass, authPass + 1);
1856
2075
  }
1857
- }
1858
- if (callCanRotateAuth && authPass === 0 && !observedOutput && isAnthropicAuthenticationError(err)) {
1859
- const rejectedAccess = apiKey;
1860
- let refreshedApiKey;
1861
- try {
1862
- refreshedApiKey = await resolveCallApiKey(true, rejectedAccess);
1863
- } catch (refreshErr) {
1864
- if (err !== null && typeof err === "object" && err.cause === void 0) try {
1865
- err.cause = refreshErr;
1866
- } catch {}
1867
- if (process.env.ZIDANE_DEBUG) process.stderr.write(`[zidane/anthropic] forced OAuth refresh after 401 failed: ${errorMessage(refreshErr)}\n`);
1868
- throw err;
2076
+ if (fastRequested && !observedOutput && shouldFallbackFromFastMode(err)) {
2077
+ const standardParams = { ...requestParams };
2078
+ delete standardParams.speed;
2079
+ return await runStream(standardParams, false, scrubPass, authPass);
1869
2080
  }
1870
- if (refreshedApiKey === rejectedAccess) throw err;
1871
- apiKey = refreshedApiKey;
1872
- client = createClient(await loadAnthropicSdk(), apiKey, callAuth, anthropicParams?.baseURL, requestBetas, resolvedExtraHeaders);
1873
- return await runStream(requestParams, fastRequested, scrubPass, authPass + 1);
1874
- }
1875
- if (fastRequested && !observedOutput && shouldFallbackFromFastMode(err)) {
1876
- const standardParams = { ...requestParams };
1877
- delete standardParams.speed;
1878
- return await runStream(standardParams, false, scrubPass, authPass);
1879
- }
1880
- if (!observedOutput && isForcedToolChoice(requestParams.tool_choice) && isForcedToolChoiceUnsupportedError(err)) {
1881
- MODELS_REJECTING_FORCED_TOOL_CHOICE.add(modelId);
1882
- return await runStream(withoutForcedToolChoice(requestParams), fastRequested, scrubPass, authPass);
2081
+ if (!observedOutput && isForcedToolChoice(requestParams.tool_choice) && isForcedToolChoiceUnsupportedError(err)) {
2082
+ MODELS_REJECTING_FORCED_TOOL_CHOICE.add(modelId);
2083
+ return await runStream(withoutForcedToolChoice(requestParams), fastRequested, scrubPass, authPass);
2084
+ }
2085
+ throw err;
1883
2086
  }
1884
- throw err;
1885
- }
1886
- const toolCalls = response.content.filter((b) => b.type === "tool_use").map((b) => ({
1887
- id: b.id,
1888
- name: nameBoundary.fromWire(b.name),
1889
- input: b.input
1890
- }));
1891
- const finishReason = mapStopReason(response.stop_reason);
1892
- const isPause = response.stop_reason === "pause_turn";
1893
- const rawUsage = {
1894
- input: response.usage.input_tokens,
1895
- output: response.usage.output_tokens,
1896
- cacheCreation: response.usage.cache_creation_input_tokens ?? void 0,
1897
- cacheRead: response.usage.cache_read_input_tokens ?? void 0,
1898
- ...finishReason ? { finishReason } : {},
1899
- modelId: response.model ?? options.model
1900
- };
1901
- const usage = callIsOAuth ? rawUsage : await priceAnthropicUsage(rawUsage, response, modelId, fastRequested, Boolean(bedrockConfig), options.modelCatalog);
1902
- const assistantMessage = fromAnthropic({
1903
- role: "assistant",
1904
- content: response.content
1905
- });
1906
- if (nameBoundary.changed) assistantMessage.content = assistantMessage.content.map((block) => block.type === "tool_call" ? {
1907
- ...block,
1908
- name: nameBoundary.fromWire(block.name)
1909
- } : block);
1910
- return {
1911
- assistantMessage,
1912
- text,
1913
- toolCalls,
1914
- done: !isPause && (response.stop_reason === "end_turn" || toolCalls.length === 0),
1915
- usage
2087
+ const toolCalls = response.content.filter((b) => b.type === "tool_use").map((b) => ({
2088
+ id: b.id,
2089
+ name: nameBoundary.fromWire(b.name),
2090
+ input: b.input
2091
+ }));
2092
+ const finishReason = mapStopReason(response.stop_reason);
2093
+ const isPause = response.stop_reason === "pause_turn";
2094
+ const rawUsage = {
2095
+ input: response.usage.input_tokens,
2096
+ output: response.usage.output_tokens,
2097
+ cacheCreation: response.usage.cache_creation_input_tokens ?? void 0,
2098
+ cacheRead: response.usage.cache_read_input_tokens ?? void 0,
2099
+ ...finishReason ? { finishReason } : {},
2100
+ modelId: response.model ?? options.model
2101
+ };
2102
+ const usage = callIsOAuth ? rawUsage : await priceAnthropicUsage(rawUsage, response, modelId, fastRequested, Boolean(bedrockConfig), options.modelCatalog);
2103
+ const assistantMessage = fromAnthropic({
2104
+ role: "assistant",
2105
+ content: response.content
2106
+ });
2107
+ if (nameBoundary.changed) assistantMessage.content = assistantMessage.content.map((block) => block.type === "tool_call" ? {
2108
+ ...block,
2109
+ name: nameBoundary.fromWire(block.name)
2110
+ } : block);
2111
+ return {
2112
+ assistantMessage,
2113
+ text,
2114
+ toolCalls,
2115
+ done: !isPause && (response.stop_reason === "end_turn" || toolCalls.length === 0),
2116
+ usage
2117
+ };
1916
2118
  };
1917
- };
1918
- return await runStream(isForcedToolChoice(params.tool_choice) && MODELS_REJECTING_FORCED_TOOL_CHOICE.has(modelId) ? withoutForcedToolChoice(params) : params, options.modelOptions?.fast === true && !callIsOAuth);
2119
+ const result = await runStream(isForcedToolChoice(params.tool_choice) && MODELS_REJECTING_FORCED_TOOL_CHOICE.has(modelId) ? withoutForcedToolChoice(params) : params, options.modelOptions?.fast === true && !callIsOAuth);
2120
+ diagnostic.finish("success");
2121
+ return result;
2122
+ } catch (err) {
2123
+ diagnostic.finish(options.signal?.aborted ? "abort" : "failure", { httpStatus: err && typeof err === "object" && "status" in err ? err.status : void 0 });
2124
+ throw err;
2125
+ } finally {
2126
+ diagnostic.finish("failure");
2127
+ }
1919
2128
  }
1920
2129
  };
1921
2130
  }
1922
2131
  //#endregion
1923
- export { cacheWriteTtlMultiplier as a, defaultAnthropicMaxTokens as c, resolveAnthropicBetas as d, resolveAnthropicMaxOutput as f, buildAnthropicClientOptions as i, planAnthropicThinking as l, FAST_MODE_OPTIONS as m, anthropic as n, classifyAnthropicError as o, ANTHROPIC_EXTRA_MODELS as p, applyAnthropicCacheBreakpoints as r, credentialIdentity as s, EXTENDED_CACHE_TTL_BETA as t, resolveAnthropicAuthShape as u };
2132
+ export { cacheWriteTtlMultiplier as a, defaultAnthropicMaxTokens as c, resolveAnthropicBetas as d, resolveAnthropicMaxOutput as f, FAST_MODE_OPTIONS as h, buildAnthropicClientOptions as i, planAnthropicThinking as l, ANTHROPIC_EXTRA_MODELS as m, anthropic as n, classifyAnthropicError as o, sanitizeProviderDiagnosticMetadata as p, applyAnthropicCacheBreakpoints as r, credentialIdentity as s, EXTENDED_CACHE_TTL_BETA as t, resolveAnthropicAuthShape as u };
1924
2133
 
1925
- //# sourceMappingURL=anthropic-BSbDiW0J.js.map
2134
+ //# sourceMappingURL=anthropic-CUM2CjXS.js.map