zidane 6.3.8 → 6.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +1 -1
  2. package/dist/{acp-CAX3tOEY.js → acp-DzUgjzNa.js} +5 -5
  3. package/dist/{acp-CAX3tOEY.js.map → acp-DzUgjzNa.js.map} +1 -1
  4. package/dist/acp-cli.js +6 -6
  5. package/dist/acp.d.ts +1 -1
  6. package/dist/acp.js +1 -1
  7. package/dist/{agent-Emjeo5Ad.js → agent-COHX5SpM.js} +52 -21
  8. package/dist/agent-COHX5SpM.js.map +1 -0
  9. package/dist/agent.d.ts +1 -1
  10. package/dist/agent.js +2 -2
  11. package/dist/{anthropic-BN0iPMox.js → anthropic-Bw39RApb.js} +124 -36
  12. package/dist/anthropic-Bw39RApb.js.map +1 -0
  13. package/dist/{auth-Dptb8U5J.js → auth-XS60l6Q5.js} +4 -4
  14. package/dist/{auth-Dptb8U5J.js.map → auth-XS60l6Q5.js.map} +1 -1
  15. package/dist/chat/pure.d.ts +3 -3
  16. package/dist/chat.d.ts +4 -4
  17. package/dist/chat.d.ts.map +1 -1
  18. package/dist/chat.js +3 -3
  19. package/dist/{context-transport-3b0qpM2m.js → context-transport-Nb9CVjLJ.js} +3 -3
  20. package/dist/{context-transport-3b0qpM2m.js.map → context-transport-Nb9CVjLJ.js.map} +1 -1
  21. package/dist/contexts/daytona.d.ts +1 -1
  22. package/dist/contexts/e2b.d.ts +1 -1
  23. package/dist/eval.d.ts +1 -1
  24. package/dist/eval.js +1 -1
  25. package/dist/extensions.d.ts +1 -1
  26. package/dist/extensions.js +1 -1
  27. package/dist/headless.d.ts +1 -1
  28. package/dist/headless.js +3 -3
  29. package/dist/{index-DWXLcGB_.d.ts → index-1Dr4Yqw1.d.ts} +114 -9
  30. package/dist/index-1Dr4Yqw1.d.ts.map +1 -0
  31. package/dist/index.d.ts +1 -1
  32. package/dist/index.js +9 -9
  33. package/dist/{login-Cvx1nSVm.js → login-CPU73khP.js} +5 -2
  34. package/dist/{login-Cvx1nSVm.js.map → login-CPU73khP.js.map} +1 -1
  35. package/dist/{mcp-8bEHU4WB.js → mcp-BNg6hUeX.js} +3 -3
  36. package/dist/{mcp-8bEHU4WB.js.map → mcp-BNg6hUeX.js.map} +1 -1
  37. package/dist/mcp.d.ts +1 -1
  38. package/dist/mcp.js +1 -1
  39. package/dist/{messages-DoHRwMw-.js → messages-DIxD2UCr.js} +2 -2
  40. package/dist/{messages-DoHRwMw-.js.map → messages-DIxD2UCr.js.map} +1 -1
  41. package/dist/{openai-compat-Bf9uMTMa.js → openai-compat-BTbSyQbm.js} +2 -2
  42. package/dist/{openai-compat-Bf9uMTMa.js.map → openai-compat-BTbSyQbm.js.map} +1 -1
  43. package/dist/output/stream-json.d.ts +1 -1
  44. package/dist/output/terminal.d.ts +1 -1
  45. package/dist/presets.d.ts +1 -1
  46. package/dist/presets.js +1 -1
  47. package/dist/providers/anthropic.d.ts +2 -2
  48. package/dist/providers/anthropic.js +1 -1
  49. package/dist/providers/arcee.d.ts +1 -1
  50. package/dist/providers/arcee.js +1 -1
  51. package/dist/providers/baseten.d.ts +1 -1
  52. package/dist/providers/baseten.js +1 -1
  53. package/dist/providers/cerebras.d.ts +1 -1
  54. package/dist/providers/cerebras.js +1 -1
  55. package/dist/providers/local.d.ts +1 -1
  56. package/dist/providers/local.js +1 -1
  57. package/dist/providers/openai-compat.d.ts +1 -1
  58. package/dist/providers/openai-compat.js +1 -1
  59. package/dist/providers/openai.d.ts +1 -1
  60. package/dist/providers/openai.js +3 -3
  61. package/dist/providers/openai.js.map +1 -1
  62. package/dist/providers/openrouter.d.ts +1 -1
  63. package/dist/providers/openrouter.js +1 -1
  64. package/dist/providers/xai.d.ts +1 -1
  65. package/dist/providers/xai.js +1 -1
  66. package/dist/{providers-BlaXBUwd.js → providers-BsH1MnhC.js} +3 -3
  67. package/dist/{providers-BlaXBUwd.js.map → providers-BsH1MnhC.js.map} +1 -1
  68. package/dist/providers.d.ts +1 -1
  69. package/dist/providers.js +4 -4
  70. package/dist/{read-state-CNyeMG7W.js → read-state-Dt7UbVsd.js} +26 -2
  71. package/dist/read-state-Dt7UbVsd.js.map +1 -0
  72. package/dist/restate.d.ts +1 -1
  73. package/dist/restate.js +1 -1
  74. package/dist/session/sqlite.d.ts +1 -1
  75. package/dist/{session-Bdk31kA5.js → session-DY2LWai4.js} +2 -2
  76. package/dist/{session-Bdk31kA5.js.map → session-DY2LWai4.js.map} +1 -1
  77. package/dist/session.d.ts +1 -1
  78. package/dist/session.js +2 -2
  79. package/dist/skills.d.ts +1 -1
  80. package/dist/{stdio-BKFpPNvX.js → stdio-DfWu1rNB.js} +2 -2
  81. package/dist/{stdio-BKFpPNvX.js.map → stdio-DfWu1rNB.js.map} +1 -1
  82. package/dist/{stdio-loader-DFDpBwwI.js → stdio-loader-mfN5JYns.js} +2 -2
  83. package/dist/{stdio-loader-DFDpBwwI.js.map → stdio-loader-mfN5JYns.js.map} +1 -1
  84. package/dist/{tool-formatters-Co5gl_7R.d.ts → tool-formatters-BaHq343O.d.ts} +2 -2
  85. package/dist/{tool-formatters-Co5gl_7R.d.ts.map → tool-formatters-BaHq343O.d.ts.map} +1 -1
  86. package/dist/tools/fetch-url.d.ts +1 -1
  87. package/dist/tools/web-search.d.ts +1 -1
  88. package/dist/tools.d.ts +1 -1
  89. package/dist/tools.js +2 -2
  90. package/dist/{transcript-anchors-DBPJr5Ks.d.ts → transcript-anchors-BquAWoGN.d.ts} +2 -2
  91. package/dist/{transcript-anchors-DBPJr5Ks.d.ts.map → transcript-anchors-BquAWoGN.d.ts.map} +1 -1
  92. package/dist/{transcript-anchors-DhBTqTyc.js → transcript-anchors-CWzlwIOr.js} +13 -7
  93. package/dist/{transcript-anchors-DhBTqTyc.js.map → transcript-anchors-CWzlwIOr.js.map} +1 -1
  94. package/dist/tui.d.ts +3 -3
  95. package/dist/tui.js +8 -7
  96. package/dist/tui.js.map +1 -1
  97. package/dist/{turn-operations-DokFalMC.d.ts → turn-operations-OQlIx13T.d.ts} +3 -3
  98. package/dist/{turn-operations-DokFalMC.d.ts.map → turn-operations-OQlIx13T.d.ts.map} +1 -1
  99. package/dist/types-BIarq1qE.js.map +1 -1
  100. package/dist/types.d.ts +1 -1
  101. package/dist/{xai-BI4KgCGS.js → xai-DnZfHvTz.js} +2 -2
  102. package/dist/{xai-BI4KgCGS.js.map → xai-DnZfHvTz.js.map} +1 -1
  103. package/docs/ARCHITECTURE.md +2 -1
  104. package/docs/CHAT.md +1 -1
  105. package/package.json +7 -2
  106. package/dist/agent-Emjeo5Ad.js.map +0 -1
  107. package/dist/anthropic-BN0iPMox.js.map +0 -1
  108. package/dist/index-DWXLcGB_.d.ts.map +0 -1
  109. package/dist/read-state-CNyeMG7W.js.map +0 -1
package/dist/agent.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { $d as hashMessages, $m as hydrateReadStateFromSession, $r as createRunSummaryCollector, Gd as CacheBreakInfo, Gi as AgentHookMap, Gr as RunSummaryBudget, Jd as CacheDimensionName, Ji as McpConnector, Jm as HydrateReadStateOptions, Jr as RunSummaryCollectorOptions, Kd as CacheBreakLoggerOptions, Ki as AgentHooks, Kr as RunSummaryByModel, Qd as fnv1a32, Qr as RunSummaryValidation, Ur as RunSummary, Wi as Agent, Wr as RunSummaryBlock, Xd as CacheDriftInfo, Xi as McpToolWrap, Xm as ReadStateMap, Xr as RunSummaryRepeatGuard, Yd as CacheDimensionSnapshot, Yi as McpToolMeta, Ym as ReadStateEntry, Yr as RunSummaryError, Zd as diffCacheDimensions, Zi as createAgent, Zm as getReadState, Zr as RunSummaryTokens, ef as installCacheBreakLogger, eh as hydrateReadStateFromSessionAsync, nh as resolveReadStateMap, qd as CacheDimensionDiff, qi as AgentOptions, qr as RunSummaryCollector, tf as snapshotCacheDimensions, th as readStateKey } from "./index-DWXLcGB_.js";
1
+ import { $d as hashMessages, $r as createRunSummaryCollector, Gd as CacheBreakInfo, Gi as AgentHookMap, Gr as RunSummaryBudget, Jd as CacheDimensionName, Ji as McpConnector, Jr as RunSummaryCollectorOptions, Kd as CacheBreakLoggerOptions, Ki as AgentHooks, Kr as RunSummaryByModel, Qd as fnv1a32, Qm as getReadState, Qr as RunSummaryValidation, Ur as RunSummary, Wi as Agent, Wr as RunSummaryBlock, Xd as CacheDriftInfo, Xi as McpToolWrap, Xm as ReadStateEntry, Xr as RunSummaryRepeatGuard, Yd as CacheDimensionSnapshot, Yi as McpToolMeta, Ym as HydrateReadStateOptions, Yr as RunSummaryError, Zd as diffCacheDimensions, Zi as createAgent, Zm as ReadStateMap, Zr as RunSummaryTokens, ef as installCacheBreakLogger, eh as hydrateReadStateFromSession, nh as readStateKey, qd as CacheDimensionDiff, qi as AgentOptions, qr as RunSummaryCollector, rh as resolveReadStateMap, tf as snapshotCacheDimensions, th as hydrateReadStateFromSessionAsync } from "./index-1Dr4Yqw1.js";
2
2
  export { type Agent, type AgentHookMap, type AgentHooks, type AgentOptions, type CacheBreakInfo, type CacheBreakLoggerOptions, type CacheDimensionDiff, type CacheDimensionName, type CacheDimensionSnapshot, type CacheDriftInfo, type HydrateReadStateOptions, type McpConnector, type McpToolMeta, type McpToolWrap, type ReadStateEntry, type ReadStateMap, type RunSummary, type RunSummaryBlock, type RunSummaryBudget, type RunSummaryByModel, type RunSummaryCollector, type RunSummaryCollectorOptions, type RunSummaryError, type RunSummaryRepeatGuard, type RunSummaryTokens, type RunSummaryValidation, createAgent, createRunSummaryCollector, diffCacheDimensions, fnv1a32, getReadState, hashMessages, hydrateReadStateFromSession, hydrateReadStateFromSessionAsync, installCacheBreakLogger, readStateKey, resolveReadStateMap, snapshotCacheDimensions };
package/dist/agent.js CHANGED
@@ -1,5 +1,5 @@
1
- import { a as hydrateReadStateFromSessionAsync, c as resolveReadStateMap, i as hydrateReadStateFromSession, s as readStateKey, t as getReadState } from "./read-state-CNyeMG7W.js";
2
- import { t as createAgent } from "./agent-Emjeo5Ad.js";
1
+ import { a as hydrateReadStateFromSessionAsync, c as readStateKey, i as hydrateReadStateFromSession, l as resolveReadStateMap, t as getReadState } from "./read-state-Dt7UbVsd.js";
2
+ import { t as createAgent } from "./agent-COHX5SpM.js";
3
3
  import { a as snapshotCacheDimensions, i as installCacheBreakLogger, n as fnv1a32, r as hashMessages, t as diffCacheDimensions } from "./cache-telemetry-ehVdWsg2.js";
4
4
  import { t as createRunSummaryCollector } from "./run-summary-BU_NgwUT.js";
5
5
  export { createAgent, createRunSummaryCollector, diffCacheDimensions, fnv1a32, getReadState, hashMessages, hydrateReadStateFromSession, hydrateReadStateFromSessionAsync, installCacheBreakLogger, readStateKey, resolveReadStateMap, snapshotCacheDimensions };
@@ -1,8 +1,8 @@
1
1
  import { t as lazyAsync } from "./lazy-DLOurOC_.js";
2
2
  import { c as classifyErrorPrelude, d as isRetryableHttpStatus, f as matchesContextExceeded, l as errorMessage, p as matchesToolPairingError } from "./errors-DJUxZg9b.js";
3
- import { O as unsupportedMediaError, S as resolvePromptCacheKey, b as sanitizeToolSpecs, v as createToolNameBoundary, w as fillEstimatedCost } from "./openai-compat-Bf9uMTMa.js";
3
+ import { O as unsupportedMediaError, S as resolvePromptCacheKey, b as sanitizeToolSpecs, v as createToolNameBoundary, w as fillEstimatedCost } from "./openai-compat-BTbSyQbm.js";
4
4
  import { renderSystemForWire, splitSystemPrompt } from "./prompt.js";
5
- import { g as toAnthropic, u as fromAnthropic } from "./messages-DoHRwMw-.js";
5
+ import { g as toAnthropic, u as fromAnthropic } from "./messages-DIxD2UCr.js";
6
6
  import { a as readOAuthCredentials, r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "./oauth-CuFPhsHY.js";
7
7
  //#region src/chat/anthropic-models.ts
8
8
  /**
@@ -131,6 +131,31 @@ const loadAnthropicSdk = lazyAsync(async () => {
131
131
  throw new Error("The `anthropic` provider requires the `@anthropic-ai/sdk` package, which is an optional peer dependency. Install it with your package manager (e.g. `bun add @anthropic-ai/sdk`).", err instanceof Error ? { cause: err } : void 0);
132
132
  }
133
133
  });
134
+ const loadBedrockSdk = lazyAsync(async () => {
135
+ try {
136
+ return (await import("@anthropic-ai/bedrock-sdk")).AnthropicBedrock;
137
+ } catch (err) {
138
+ throw new Error("The `anthropic` provider in Bedrock mode requires the `@anthropic-ai/bedrock-sdk` package, which is an optional peer dependency. Install it with your package manager (e.g. `bun add @anthropic-ai/bedrock-sdk`).", err instanceof Error ? { cause: err } : void 0);
139
+ }
140
+ });
141
+ /**
142
+ * Build the Bedrock client for one call. Auth is SigV4 via the AWS credential
143
+ * chain — the Anthropic key/OAuth machinery is intentionally bypassed. Betas
144
+ * are NOT forwarded: Bedrock's translation layer rejects unknown beta flags,
145
+ * and the persona/fast-mode features they gate don't exist there.
146
+ */
147
+ async function createBedrockClient(config, anthropicParams, extraHeaders) {
148
+ return new (config.sdk ?? await (loadBedrockSdk()))({
149
+ awsRegion: config.region ?? process.env.AWS_REGION ?? "us-west-2",
150
+ ...anthropicParams?.baseURL ? { baseURL: anthropicParams.baseURL } : {},
151
+ ...extraHeaders && Object.keys(extraHeaders).length > 0 ? { defaultHeaders: extraHeaders } : {}
152
+ });
153
+ }
154
+ /** Normalize the `bedrock` param: `true` → empty config, absent → undefined. */
155
+ function normalizeBedrock(value) {
156
+ if (!value) return void 0;
157
+ return value === true ? {} : value;
158
+ }
134
159
  /** Beta flags sent unconditionally on the OAuth path (Claude Code parity). */
135
160
  const OAUTH_DEFAULT_BETAS = ["claude-code-20250219", "oauth-2025-04-20"];
136
161
  /**
@@ -291,6 +316,28 @@ function createClient(SDK, apiKey, auth, baseURL, extraBetas, extraHeaders) {
291
316
  * enum. `minimal` collapses to `low` (the closest equivalent — Anthropic does
292
317
  * not have a sub-`low` tier).
293
318
  */
319
+ /**
320
+ * Explicit thinking budgets for Bedrock, per effort tier. Bedrock's
321
+ * anthropic-native path only accepts the legacy
322
+ * `thinking: { type: 'enabled', budget_tokens }` shape (the 4.6 surface —
323
+ * `output_config.effort`, adaptive, `display` — is rejected by its
324
+ * translation layer), so effort tiers degrade to token budgets. Floor is
325
+ * Anthropic's 1024 minimum; ceilings stay well under haiku/sonnet output
326
+ * caps — the request builder clamps against the model ceiling regardless.
327
+ */
328
+ /**
329
+ * Output tokens reserved for the visible response when an explicit thinking
330
+ * budget must be shrunk to fit under the model's `max_tokens` ceiling — see
331
+ * the budget clamp in `stream()`.
332
+ */
333
+ const THINKING_RESPONSE_RESERVE_TOKENS = 1024;
334
+ const BEDROCK_THINKING_BUDGETS = {
335
+ low: 4096,
336
+ medium: 12288,
337
+ high: 24576,
338
+ xhigh: 32768,
339
+ max: 32768
340
+ };
294
341
  const EFFORT_FOR_LEVEL = {
295
342
  minimal: "low",
296
343
  low: "low",
@@ -403,10 +450,31 @@ const loadPiModelGetter = lazyAsync(async () => {
403
450
  * back to {@link defaultAnthropicMaxTokens} only when the registry lacks the
404
451
  * model. Used as BOTH the default (when the caller leaves `maxTokens` unset)
405
452
  * and a hard clamp, since a `max_tokens` above the model's max would 400.
453
+ *
454
+ * The clamp is only as good as the ceiling's provenance, so an explicit caller
455
+ * `maxTokens` can RAISE the fallback: models the registry doesn't know are
456
+ * mostly ids that never appear in pi-ai's anthropic registry — Bedrock ids
457
+ * (`global.anthropic.claude-*`) and non-Anthropic models served over the
458
+ * Anthropic wire (`openai.gpt-*` on Bedrock, gateway aliases). For the
459
+ * latter the fallback degrades to the 32000 catch-all; for the former the
460
+ * family match yields a deliberately conservative non-beta floor. Clamping a
461
+ * caller who knows the real ceiling down to either silently truncates long
462
+ * generations mid-write (observed as turns pinned at exactly 32000 tokens).
463
+ *
464
+ * It can only raise, never lower: the caller's `maxTokens` is a cap on the
465
+ * VISIBLE response, already enforced as `max_tokens` itself, whereas this
466
+ * value is the model's physical ceiling. Letting it lower the ceiling would
467
+ * break the `enabled` thinking path's invariant that the budget sits ON TOP
468
+ * of the response cap — the budget would be shrunk to share the caller's cap,
469
+ * or dropped entirely once no satisfiable budget fits.
470
+ *
471
+ * A registry-backed max always wins — above it the provider 400s.
406
472
  */
407
- async function resolveAnthropicMaxOutput(modelId) {
473
+ async function resolveAnthropicMaxOutput(modelId, explicitMaxTokens) {
408
474
  const registryMax = (await loadPiModelGetter())?.("anthropic", modelId)?.maxTokens;
409
- return typeof registryMax === "number" && registryMax > 0 ? registryMax : defaultAnthropicMaxTokens(modelId);
475
+ if (typeof registryMax === "number" && registryMax > 0) return registryMax;
476
+ const fallback = defaultAnthropicMaxTokens(modelId);
477
+ return typeof explicitMaxTokens === "number" && explicitMaxTokens > 0 ? Math.max(fallback, explicitMaxTokens) : fallback;
410
478
  }
411
479
  const EPHEMERAL = { type: "ephemeral" };
412
480
  /**
@@ -880,7 +948,8 @@ function anthropicPromptMessage(parts) {
880
948
  };
881
949
  }
882
950
  function anthropic(anthropicParams) {
883
- const isOAuth = resolveAnthropicAuthShape(getConfiguredApiKey(anthropicParams), anthropicParams?.authMode).bearer;
951
+ const bedrockConfig = normalizeBedrock(anthropicParams?.bedrock);
952
+ const isOAuth = resolveAnthropicAuthShape(bedrockConfig ? "" : getConfiguredApiKey(anthropicParams), anthropicParams?.authMode).bearer;
884
953
  const defaultModel = anthropicParams?.defaultModel || "claude-opus-4-8";
885
954
  let runtimeCredentials = extractRuntimeCredentials(anthropicParams);
886
955
  return {
@@ -895,7 +964,7 @@ function anthropic(anthropicParams) {
895
964
  documents: true,
896
965
  audio: false,
897
966
  video: false,
898
- nativeWebSearch: { maxUses: 5 },
967
+ ...bedrockConfig ? {} : { nativeWebSearch: { maxUses: 5 } },
899
968
  adaptiveBudgetIsEnvelope: true,
900
969
  ...anthropicParams?.capabilities
901
970
  }
@@ -905,7 +974,7 @@ function anthropic(anthropicParams) {
905
974
  const hasWebSearch = !!nativeWebSearch && tools.some((t) => t.name === "web_search");
906
975
  const out = sanitizeToolSpecs(hasWebSearch ? tools.filter((t) => t.name !== "web_search") : tools, { profile: "anthropic" }).map((t) => ({
907
976
  name: t.name,
908
- description: t.description,
977
+ description: t.description ?? "",
909
978
  input_schema: t.inputSchema
910
979
  }));
911
980
  if (hasWebSearch && nativeWebSearch) {
@@ -951,6 +1020,7 @@ function anthropic(anthropicParams) {
951
1020
  promptMessage: anthropicPromptMessage,
952
1021
  classifyError: classifyAnthropicError,
953
1022
  async countTokens(payload, signal) {
1023
+ if (bedrockConfig) return null;
954
1024
  try {
955
1025
  const SDK = await loadAnthropicSdk();
956
1026
  const identity = credentialIdentity(anthropicParams);
@@ -1004,36 +1074,38 @@ function anthropic(anthropicParams) {
1004
1074
  }
1005
1075
  },
1006
1076
  async stream(options, callbacks) {
1007
- const SDK = await loadAnthropicSdk();
1008
- const identity = credentialIdentity(anthropicParams);
1009
- const apiKey = await resolveOAuthApiKey({
1010
- provider: identity.providerId,
1011
- providerId: identity.providerId,
1012
- params: runtimeCredentials ? {
1013
- ...anthropicParams,
1014
- ...runtimeCredentials
1015
- } : anthropicParams,
1016
- envKey: identity.envKey,
1017
- missingError: identity.missingError,
1018
- refreshError: identity.refreshError
1019
- }, {
1020
- ...callbacks,
1021
- async onOAuthRefresh(ctx) {
1022
- if (ctx.source === "params") runtimeCredentials = {
1023
- access: ctx.credentials.access,
1024
- refresh: ctx.credentials.refresh,
1025
- expires: ctx.credentials.expires
1026
- };
1027
- await callbacks.onOAuthRefresh?.(ctx);
1028
- }
1029
- });
1030
- const callAuth = resolveAnthropicAuthShape(apiKey, anthropicParams?.authMode);
1077
+ let apiKey = "";
1078
+ if (!bedrockConfig) {
1079
+ const identity = credentialIdentity(anthropicParams);
1080
+ apiKey = await resolveOAuthApiKey({
1081
+ provider: identity.providerId,
1082
+ providerId: identity.providerId,
1083
+ params: runtimeCredentials ? {
1084
+ ...anthropicParams,
1085
+ ...runtimeCredentials
1086
+ } : anthropicParams,
1087
+ envKey: identity.envKey,
1088
+ missingError: identity.missingError,
1089
+ refreshError: identity.refreshError
1090
+ }, {
1091
+ ...callbacks,
1092
+ async onOAuthRefresh(ctx) {
1093
+ if (ctx.source === "params") runtimeCredentials = {
1094
+ access: ctx.credentials.access,
1095
+ refresh: ctx.credentials.refresh,
1096
+ expires: ctx.credentials.expires
1097
+ };
1098
+ await callbacks.onOAuthRefresh?.(ctx);
1099
+ }
1100
+ });
1101
+ }
1102
+ const callAuth = resolveAnthropicAuthShape(apiKey, bedrockConfig ? "api-key" : anthropicParams?.authMode);
1031
1103
  const callIsOAuth = callAuth.claudeCode;
1032
- const extendedTtl = options.cache !== false && options.cacheTtl === "1h" && !callIsOAuth;
1104
+ const extendedTtl = options.cache !== false && options.cacheTtl === "1h" && !callIsOAuth && !bedrockConfig;
1033
1105
  const conditionalBetas = [...options.modelOptions?.fast ? [FAST_MODE_BETA] : [], ...extendedTtl ? [EXTENDED_CACHE_TTL_BETA] : []];
1034
1106
  const requestBetas = conditionalBetas.length > 0 ? [...anthropicParams?.extraBetas ?? [], ...conditionalBetas] : anthropicParams?.extraBetas;
1035
1107
  const resolvedExtraHeaders = await resolveExtraHeaders(anthropicParams?.extraHeaders);
1036
- const client = createClient(SDK, apiKey, callAuth, anthropicParams?.baseURL, requestBetas, resolvedExtraHeaders);
1108
+ const client = bedrockConfig ? await createBedrockClient(bedrockConfig, anthropicParams, resolvedExtraHeaders) : createClient(await loadAnthropicSdk(), apiKey, callAuth, anthropicParams?.baseURL, requestBetas, resolvedExtraHeaders);
1037
1109
  const wireSystem = renderSystemForWire(options.system);
1038
1110
  const system = callIsOAuth ? `You are Claude Code, Anthropic's official CLI for Claude.` : wireSystem;
1039
1111
  const messages = callIsOAuth && options.system ? [
@@ -1061,7 +1133,7 @@ function anthropic(anthropicParams) {
1061
1133
  name: nameBoundary.toWire(t.name)
1062
1134
  }) : inputTools;
1063
1135
  const modelId = options.model;
1064
- const modelMaxOutput = await resolveAnthropicMaxOutput(modelId);
1136
+ const modelMaxOutput = await resolveAnthropicMaxOutput(modelId, options.maxTokens);
1065
1137
  const params = {
1066
1138
  ...anthropicParams?.extraBodyParams ?? {},
1067
1139
  model: modelId,
@@ -1074,7 +1146,15 @@ function anthropic(anthropicParams) {
1074
1146
  if (anthropicParams?.contextManagement) params.context_management = anthropicParams.contextManagement;
1075
1147
  if (options.cache !== false) applyAnthropicCacheBreakpoints(params, callIsOAuth ? void 0 : options.system, extendedTtl ? options.cacheTtl : void 0);
1076
1148
  const plan = planAnthropicThinking(thinking, options.thinkingBudget, options.taskBudget, options.effortHint !== false);
1077
- if (plan) {
1149
+ if (plan && bedrockConfig) {
1150
+ const budget = plan.kind === "enabled" ? plan.budgetTokens : BEDROCK_THINKING_BUDGETS[plan.effort ?? "medium"];
1151
+ params.thinking = {
1152
+ type: "enabled",
1153
+ budget_tokens: budget
1154
+ };
1155
+ params.max_tokens = budget + params.max_tokens;
1156
+ params.temperature = 1;
1157
+ } else if (plan) {
1078
1158
  if (plan.kind === "enabled") {
1079
1159
  params.thinking = {
1080
1160
  type: "enabled",
@@ -1106,6 +1186,14 @@ function anthropic(anthropicParams) {
1106
1186
  params.temperature = 1;
1107
1187
  }
1108
1188
  params.max_tokens = Math.min(params.max_tokens, modelMaxOutput);
1189
+ if (params.thinking?.type === "enabled" && params.thinking.budget_tokens >= params.max_tokens) {
1190
+ const fitted = params.max_tokens - THINKING_RESPONSE_RESERVE_TOKENS;
1191
+ if (fitted >= 1024) params.thinking.budget_tokens = fitted;
1192
+ else {
1193
+ delete params.thinking;
1194
+ delete params.temperature;
1195
+ }
1196
+ }
1109
1197
  if (options.modelOptions?.fast) params.speed = "fast";
1110
1198
  if (options.toolChoice) if (options.toolChoice.type === "tool" && options.toolChoice.name) params.tool_choice = {
1111
1199
  type: "tool",
@@ -1226,4 +1314,4 @@ function anthropic(anthropicParams) {
1226
1314
  //#endregion
1227
1315
  export { classifyAnthropicError as a, planAnthropicThinking as c, resolveAnthropicMaxOutput as d, ANTHROPIC_EXTRA_MODELS as f, buildAnthropicClientOptions as i, resolveAnthropicAuthShape as l, anthropic as n, credentialIdentity as o, FAST_MODE_OPTIONS as p, applyAnthropicCacheBreakpoints as r, defaultAnthropicMaxTokens as s, EXTENDED_CACHE_TTL_BETA as t, resolveAnthropicBetas as u };
1228
1316
 
1229
- //# sourceMappingURL=anthropic-BN0iPMox.js.map
1317
+ //# sourceMappingURL=anthropic-Bw39RApb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-Bw39RApb.js","names":[],"sources":["../src/chat/anthropic-models.ts","../src/providers/anthropic.ts"],"sourcesContent":["/**\n * Anthropic models not (yet) bundled in `@earendil-works/pi-ai`'s registry.\n *\n * pi-ai ships a static price/metadata registry that lags new Anthropic\n * releases by a dep bump. Until the bump lands, list freshly-shipped models\n * here so they show in the picker, expose the reasoning knob, and get an\n * accurate cost estimate. Entries are merged ahead of pi-ai's list in\n * {@link modelsForDescriptor} and de-duped by id, so once pi-ai catches up\n * the bundled entry simply wins.\n */\n\nimport type { ModelInfo, ModelOption } from './providers'\n\n/**\n * Anthropic \"fast mode\" — `speed: \"fast\"` on the Messages API. ~2.5× output\n * tokens/sec at a per-model price multiplier. Supported on Opus 4.6 / 4.7 /\n * 4.8 / 5 only; the API errors if sent on any other model, so it's attached\n * just to those entries (see {@link FAST_MODE_OPTIONS}).\n *\n * The multiplier scales ALL rate components (input, output, and both cache\n * rates) uniformly: per Anthropic, \"prompt caching multipliers apply on top of\n * fast mode pricing\" across the full context window. Opus 5 and 4.8 are 2×\n * ($5/$25 → $10/$50); Opus 4.6 / 4.7 are a steeper 6× ($5/$25 → $30/$150).\n * See https://platform.claude.com/docs/en/build-with-claude/fast-mode.\n */\nexport const FAST_MODE_OPTION: ModelOption = {\n id: 'fast',\n label: 'Fast mode',\n description: '~2.5× faster output at premium pricing',\n costMultiplier: { input: 2, output: 2, cacheRead: 2, cacheWrite: 2 },\n}\n\nconst FAST_MODE_OPTION_LEGACY: ModelOption = {\n ...FAST_MODE_OPTION,\n description: '~2.5× faster output at 6× pricing',\n costMultiplier: { input: 6, output: 6, cacheRead: 6, cacheWrite: 6 },\n}\n\n/** Model ids that accept `speed: \"fast\"`, mapped to their fast-mode option. */\nexport const FAST_MODE_OPTIONS: Readonly<Record<string, ModelOption>> = {\n 'claude-opus-5': FAST_MODE_OPTION,\n 'claude-opus-4-8': FAST_MODE_OPTION,\n 'claude-opus-4-7': FAST_MODE_OPTION_LEGACY,\n 'claude-opus-4-6': FAST_MODE_OPTION_LEGACY,\n}\n\n/**\n * The price multiplier to apply to a model's base rates when fast mode is\n * active, or `undefined` when the model has no fast-mode pricing (i.e. doesn't\n * support it). Mirrors {@link FAST_MODE_OPTIONS} — kept as a separate accessor\n * so the cost layer can stay decoupled from the picker-facing option objects.\n */\nexport function fastModeCostMultiplier(modelId: string): ModelOption['costMultiplier'] {\n return FAST_MODE_OPTIONS[modelId]?.costMultiplier\n}\n\n/**\n * Claude Opus 5 — GA 2026-07-24. The announcement confirms $5/$25 per MTok\n * (same as Opus 4.8) and fast mode at 2×; the 1M context, 128k output, and\n * cache rates are ASSUMED from Opus 4.8 — verify against the model docs once\n * they're up. See https://www.anthropic.com/news/claude-opus-5.\n *\n * Claude Fable 5 — GA 2026-06-09. Anthropic's most capable widely released\n * model: $10/$50 per MTok, 1M context, 128k output, adaptive thinking\n * (always on), vision. No fast-mode support (Opus 4.6/4.7/4.8/5 only).\n *\n * Claude Opus 4.8 — shipped 2026-05-28. Same price/context/output as Opus 4.7\n * ($5/$25 per MTok, 1M context, 128k output), adaptive thinking, vision.\n * See https://www.anthropic.com/news/claude-opus-4-8.\n *\n * Claude Mythos 5 is deliberately absent: it's invitation-only (Project\n * Glasswing), so it would be a dead picker entry for virtually all users.\n *\n * See https://platform.claude.com/docs/en/about-claude/models/overview.\n */\nexport const ANTHROPIC_EXTRA_MODELS: readonly ModelInfo[] = [\n {\n id: 'claude-opus-5',\n name: 'Claude Opus 5',\n reasoning: true,\n input: ['text', 'image'],\n cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n provider: 'anthropic',\n options: [FAST_MODE_OPTION],\n },\n {\n id: 'claude-fable-5',\n name: 'Claude Fable 5',\n reasoning: true,\n input: ['text', 'image'],\n cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n provider: 'anthropic',\n },\n {\n id: 'claude-opus-4-8',\n name: 'Claude Opus 4.8',\n reasoning: true,\n input: ['text', 'image'],\n cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n provider: 'anthropic',\n options: [FAST_MODE_OPTION],\n },\n]\n","// Type-only imports — erased at build time. Safe when the peer dep is not installed\n// at consume time; the types only need to resolve during Zidane's own build\n// (where `@anthropic-ai/sdk` is present as a devDependency).\nimport type Anthropic from '@anthropic-ai/sdk'\nimport type { Model } from '@anthropic-ai/sdk/resources'\nimport type { Provider, ProviderCapabilities, StreamCallbacks, ToolResult, ToolSpec, TurnResult } from '.'\nimport type { ClassifiedError } from '../errors'\nimport type { CacheTtl, PromptPart, SessionContentBlock, SessionMessage, ThinkingLevel, TurnFinishReason, TurnUsage } from '../types'\nimport type { OAuthParams } from './oauth'\nimport type { PromptCacheKeyOption } from './prompt-cache-key'\nimport { fastModeCostMultiplier } from '../chat/anthropic-models'\nimport { classifyErrorPrelude, errorMessage, isRetryableHttpStatus, matchesContextExceeded, matchesToolPairingError } from '../errors'\nimport { lazyAsync } from '../lazy'\nimport { unsupportedMediaError } from '../prompt'\nimport { fromAnthropic, toAnthropic } from '../session/messages'\nimport { renderSystemForWire, splitSystemPrompt } from '../system-prompt'\nimport { fillEstimatedCost } from './cost'\nimport { extractRuntimeCredentials, readOAuthCredentials, resolveOAuthApiKey } from './oauth'\nimport { resolvePromptCacheKey } from './prompt-cache-key'\nimport { sanitizeToolSpecs } from './schema-sanitize'\nimport { createToolNameBoundary } from './tool-name-boundary'\n\ntype AnthropicCtor = typeof Anthropic\ntype AnthropicInstance = InstanceType<AnthropicCtor>\n\n// Lazy-loaded SDK class. `@anthropic-ai/sdk` is an OPTIONAL peer dependency: the\n// module is imported only when the anthropic provider opens a connection.\nconst loadAnthropicSdk = lazyAsync(async (): Promise<AnthropicCtor> => {\n try {\n const mod = await import('@anthropic-ai/sdk')\n return mod.default as unknown as AnthropicCtor\n }\n catch (err) {\n throw new Error(\n 'The `anthropic` provider requires the `@anthropic-ai/sdk` package, which is an optional peer dependency. '\n + 'Install it with your package manager (e.g. `bun add @anthropic-ai/sdk`).',\n err instanceof Error ? { cause: err } : undefined,\n )\n }\n})\n\n// Same optional-peer treatment for the Bedrock flavor. `AnthropicBedrock`\n// subclasses the same client core (`BaseAnthropic`) and exposes the identical\n// `messages` surface (minus `countTokens` / `batches`), so downstream stream\n// handling is byte-identical — only construction and auth differ (SigV4).\nconst loadBedrockSdk = lazyAsync(async (): Promise<AnthropicCtor> => {\n try {\n const mod = await import('@anthropic-ai/bedrock-sdk')\n return mod.AnthropicBedrock as unknown as AnthropicCtor\n }\n catch (err) {\n throw new Error(\n 'The `anthropic` provider in Bedrock mode requires the `@anthropic-ai/bedrock-sdk` package, which is an optional peer dependency. '\n + 'Install it with your package manager (e.g. `bun add @anthropic-ai/bedrock-sdk`).',\n err instanceof Error ? { cause: err } : undefined,\n )\n }\n})\n\n/**\n * Build the Bedrock client for one call. Auth is SigV4 via the AWS credential\n * chain — the Anthropic key/OAuth machinery is intentionally bypassed. Betas\n * are NOT forwarded: Bedrock's translation layer rejects unknown beta flags,\n * and the persona/fast-mode features they gate don't exist there.\n */\nasync function createBedrockClient(\n config: AnthropicBedrockConfig,\n anthropicParams: AnthropicParams | undefined,\n extraHeaders: Record<string, string> | undefined,\n): Promise<AnthropicInstance> {\n const Ctor = (config.sdk ?? await loadBedrockSdk()) as AnthropicCtor\n const options: Record<string, unknown> = {\n awsRegion: config.region ?? process.env.AWS_REGION ?? 'us-west-2',\n ...(anthropicParams?.baseURL ? { baseURL: anthropicParams.baseURL } : {}),\n ...(extraHeaders && Object.keys(extraHeaders).length > 0 ? { defaultHeaders: extraHeaders } : {}),\n }\n return new (Ctor as unknown as new (o: Record<string, unknown>) => AnthropicInstance)(options)\n}\n\n/** Normalize the `bedrock` param: `true` → empty config, absent → undefined. */\nfunction normalizeBedrock(value: AnthropicParams['bedrock']): AnthropicBedrockConfig | undefined {\n if (!value)\n return undefined\n return value === true ? {} : value\n}\n\n/**\n * Server-side context-management config — the body of `context_management` on\n * the Messages API. Typed loosely (Record-of-unknown) so we don't pin a specific\n * SDK schema version: the v0.90 SDK does not yet type this field, but the wire\n * format is stable behind the `context-management-2025-06-27` beta.\n *\n * See: https://docs.anthropic.com/en/docs/build-with-claude/context-management\n */\nexport interface AnthropicContextManagement {\n edits?: Array<Record<string, unknown>>\n [key: string]: unknown\n}\n\n/**\n * Amazon Bedrock mode for the anthropic provider.\n *\n * Routes the identical Messages wire shape through `@anthropic-ai/bedrock-sdk`\n * (`AnthropicBedrock`), which signs requests with SigV4 instead of an\n * Anthropic API key. Credentials resolve through the standard AWS chain —\n * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (+ `AWS_SESSION_TOKEN`) env\n * vars, shared config, instance roles — so no `ANTHROPIC_API_KEY` is needed\n * or consulted.\n *\n * Model ids are Bedrock-shaped (e.g.\n * `global.anthropic.claude-haiku-4-5-20251001-v1:0`); pass one as\n * `defaultModel` or per run.\n */\nexport interface AnthropicBedrockConfig {\n /**\n * AWS region for the Bedrock runtime endpoint. Resolution order:\n * this field → `AWS_REGION` env → `us-west-2`.\n */\n region?: string\n /**\n * Bring-your-own client constructor. The default lazily imports\n * `@anthropic-ai/bedrock-sdk` (an optional peer dependency); override for\n * runtimes where that default cannot work — edge workers needing a custom\n * `providerChainResolver`, pre-configured credentials objects — or to\n * inject a fake in tests without module-level mocking (Bun's\n * `mock.module` leaks across test files).\n *\n * Receives the resolved client options (`awsRegion`, plus `baseURL` /\n * `defaultHeaders` passthrough) and must return an object exposing the\n * Anthropic `messages` surface.\n */\n sdk?: new (options: Record<string, unknown>) => unknown\n}\n\nexport interface AnthropicParams extends OAuthParams {\n defaultModel?: string\n /**\n * Run against Amazon Bedrock instead of the Anthropic API. `true` uses\n * env-resolved AWS credentials and region defaults; pass an\n * {@link AnthropicBedrockConfig} to set the region or inject a client\n * constructor. See the config type for credential resolution and model-id\n * shape.\n *\n * Bedrock has no `count_tokens` endpoint (the provider's `countTokens`\n * returns `null` and callers fall back to the heuristic) and no Claude\n * Code persona; beta headers are not sent. Thinking degrades to the\n * legacy explicit-budget shape — Bedrock rejects the 4.6 surface\n * (`output_config.effort`, adaptive) — with per-effort budgets from\n * `BEDROCK_THINKING_BUDGETS` clamped under the model's output ceiling;\n * an explicit `thinkingBudget` wins. Server-side web search\n * (`nativeWebSearch`) is not advertised: AWS doesn't host Anthropic's\n * search tool, so the canonical `web_search` ToolDef runs client-side\n * like on other non-Anthropic routes.\n *\n * Caveats: {@link AnthropicParams.contextManagement} (and any\n * `extraBodyParams` from the 4.6+ API surface) is rejected by Bedrock's\n * translation layer — don't combine it with bedrock mode. `baseURL` is\n * honored but must point at a genuine Bedrock endpoint (e.g. a VPC\n * endpoint): SigV4 signs the request for that host, so a rewriting proxy\n * breaks the signature.\n */\n bedrock?: boolean | AnthropicBedrockConfig\n /**\n * Optional override for the Anthropic SDK base URL. Honored end-to-end — headers and\n * routing pass through to the forwarded host. Useful for proxies (e.g. corporate\n * gateways, internal router).\n */\n baseURL?: string\n /**\n * Additional `anthropic-beta` flags to opt into. Merged with the OAuth-path\n * defaults (`claude-code-20250219`, `oauth-2025-04-20`); duplicates are\n * de-duped. Examples:\n *\n * - `'context-management-2025-06-27'` — server-side context compaction\n * (token-accurate; pair with {@link AnthropicParams.contextManagement}).\n * - `'token-efficient-tools-2026-03-28'` — terser tool_use wire format.\n * - `'interleaved-thinking-2025-05-14'` — think between tool calls within\n * one turn.\n * - `'redact-thinking-2026-02-12'` — replace large thinking blocks with\n * stubs server-side.\n * - `'prompt-caching-scope-2026-01-05'` — extended prompt-cache scope.\n *\n * Honored on both the OAuth and API-key paths.\n */\n extraBetas?: readonly string[]\n /**\n * Server-side context-management directive. Sent on the request body as\n * `context_management`. Requires the `context-management-2025-06-27` beta —\n * add it to {@link AnthropicParams.extraBetas}.\n *\n * Typed loosely so future Anthropic schema additions land without an SDK\n * bump. A typical compaction edit:\n *\n * ```ts\n * contextManagement: {\n * edits: [{\n * type: 'clear_tool_uses_20250919',\n * trigger: { type: 'input_tokens', value: 180_000 },\n * clear_at_least: { type: 'input_tokens', value: 140_000 },\n * clear_tool_inputs: ['Read', 'Bash', 'Grep'],\n * }],\n * }\n * ```\n */\n contextManagement?: AnthropicContextManagement\n /**\n * Generic pass-through for fields on the Messages API request body that the\n * SDK does not yet type. Spread into the request before the typed fields,\n * so explicit options ({@link AnthropicParams.contextManagement} and the\n * built-in fields like `model` / `tools` / `messages`) win on collision.\n *\n * Forward-compat escape hatch for new Anthropic betas — when a future flag\n * ships before zidane has a dedicated typed knob, set it here without\n * waiting on a release. Most fields will still need the matching beta in\n * {@link AnthropicParams.extraBetas}.\n */\n extraBodyParams?: Record<string, unknown>\n /**\n * Prompt-cache affinity key — an opt-in routing hint carried on the request as\n * `metadata.user_id`. See {@link PromptCacheKeyOption} for the shapes and\n * `./prompt-cache-key.ts` for which routes honor it.\n *\n * On 1P Anthropic this is effectively a no-op: cache entries are scoped per\n * organization/workspace and matched purely by prefix, with no client-side\n * routing knob, and `metadata.user_id`'s documented purpose is abuse\n * detection. It is plumbed here for the case {@link AnthropicParams.baseURL}\n * already serves — a proxy or AI gateway in front of the Messages API, which\n * CAN route on a stable session key — and so a host sets one flag regardless\n * of which provider is behind it.\n *\n * The derived default is a hash, which also satisfies Anthropic's guidance\n * that this field not carry PII.\n *\n * Default: unset — no `metadata` is added and requests stay byte-identical.\n */\n promptCacheKey?: PromptCacheKeyOption\n /**\n * Additionally send the affinity key as this HTTP header, for gateways that\n * route on a header rather than a body field. Defers to any same-named entry\n * in {@link AnthropicParams.extraHeaders}.\n *\n * Default: unset — no header is added.\n */\n promptCacheKeyHeader?: string\n /**\n * Extra HTTP headers sent on every request, merged into the SDK's\n * `defaultHeaders`. Honored on both the OAuth and API-key paths.\n *\n * Use for routing/attribution headers a proxy or gateway in front of the\n * `baseURL` consumes (e.g. a target-provider selector). Reserved zidane\n * headers (`anthropic-beta`, `user-agent`, `x-app`, and the OAuth browser\n * flag) take precedence on collision.\n *\n * May be a **function** resolved per request (awaited) instead of a static\n * map — the seam for gateways minting short-lived/signed auth tokens that a\n * long, suspended, or replayed durable run outlives. The resolver runs on\n * every `stream()` / `countTokens()` call, so it can return a freshly-minted\n * token each turn (e.g. `{ authorization: \\`Bearer ${await mintWorkToken()}\\` }`)\n * without rebuilding the provider.\n */\n extraHeaders?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>)\n /**\n * How the resolved credential reaches the wire.\n *\n * - `'auto'` (default) — bearer iff the token is an Anthropic OAuth access\n * token (`sk-ant-oat…`), which also turns on the **Claude Code persona**\n * (`claude-code-*` betas, `x-app: cli`, the canonical Claude Code system\n * block). Otherwise `x-api-key`.\n * - `'bearer'` — always `Authorization: Bearer <token>`, WITHOUT the Claude\n * Code persona. This is the mode for an Anthropic-Messages-compatible\n * gateway behind {@link AnthropicParams.baseURL} that authenticates with\n * its own bearer token (Bolt's `bex_…`, an internal router, …).\n * - `'api-key'` — always `x-api-key`, no persona. Forces a proxy that\n * expects Anthropic's native header even when the token happens to look\n * like an OAuth one.\n *\n * Only `'auto'` can enable the persona: an explicit mode means \"this is not\n * Anthropic's own OAuth\", and sending Claude Code's betas / system block to\n * a third-party gateway is at best noise and at worst a 400.\n */\n authMode?: 'auto' | 'bearer' | 'api-key'\n /**\n * Override advertised capabilities (merged over the Anthropic defaults).\n * For gateways behind {@link AnthropicParams.baseURL} that don't implement\n * a native affordance — e.g. `{ nativeWebSearch: undefined }` to fall back\n * to the client-side `web_search` tool when the proxy rejects Anthropic's\n * `web_search_20250305` server tool.\n */\n capabilities?: Partial<ProviderCapabilities>\n /**\n * Override the credential identity used to resolve (and lazily refresh) the\n * token on every call. Defaults to Anthropic's own\n * (`providerId: 'anthropic'`, env `ANTHROPIC_API_KEY`).\n *\n * Set this when {@link AnthropicParams.baseURL} points at a gateway that\n * issues its own OAuth credentials under a different key in\n * `credentials.json`. The whole shared machinery — refresh-on-expiry,\n * cross-process lock, atomic persist, the `onOAuthRefresh` callback — then\n * applies to that provider instead, with no reimplementation. Pair with\n * `authMode: 'bearer'` for a bearer-token gateway.\n *\n * `providerId` must be registered in pi-ai's OAuth registry\n * (`registerOAuthProvider`) for refresh to resolve.\n */\n credentialSource?: {\n /** OAuth provider id — also the credentials-file key. */\n providerId: string\n /** Env var consulted before the credentials file. Omit for OAuth-only. */\n envKey?: string\n /** Message thrown when no credential is configured. */\n missingError?: string\n /** Message thrown when refresh fails, given the underlying reason. */\n refreshError?: (reason: string) => string\n }\n}\n\n/** Beta flags sent unconditionally on the OAuth path (Claude Code parity). */\nconst OAUTH_DEFAULT_BETAS = ['claude-code-20250219', 'oauth-2025-04-20'] as const\n\n/**\n * Beta flag that enables the `speed: \"fast\"` request field (fast mode — up to\n * 2.5× output tokens/sec at premium pricing; supported models are enumerated\n * in `FAST_MODE_OPTIONS` in chat/anthropic-models.ts). Sent as an\n * `anthropic-beta` header only on requests that opt into fast mode; absent\n * otherwise so standard requests keep a byte-stable header for prompt caching.\n *\n * See: https://platform.claude.com/docs/en/build-with-claude/fast-mode\n */\nconst FAST_MODE_BETA = 'fast-mode-2026-02-01'\nconst API_KEY_RESERVED_EXTRA_HEADER_NAMES = new Set(['anthropic-beta'])\nconst OAUTH_RESERVED_EXTRA_HEADER_NAMES = new Set([\n 'anthropic-beta',\n 'anthropic-dangerous-direct-browser-access',\n 'user-agent',\n 'x-app',\n])\n\nfunction filterReservedExtraHeaders(\n extraHeaders: Record<string, string> | undefined,\n reservedNames: ReadonlySet<string>,\n): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [name, value] of Object.entries(extraHeaders ?? {})) {\n if (!reservedNames.has(name.toLowerCase()))\n out[name] = value\n }\n return out\n}\n\n/**\n * Build the `anthropic-beta` header value — OAuth defaults plus caller-supplied\n * extras, de-duped while preserving order. Returns `undefined` when no betas\n * apply (non-OAuth, no extras).\n */\nexport function resolveAnthropicBetas(\n isOAuth: boolean,\n extraBetas?: readonly string[],\n): string | undefined {\n const seen = new Set<string>()\n const out: string[] = []\n if (isOAuth) {\n for (const b of OAUTH_DEFAULT_BETAS) {\n if (!seen.has(b)) { seen.add(b); out.push(b) }\n }\n }\n if (extraBetas) {\n for (const b of extraBetas) {\n if (typeof b === 'string' && b.length > 0 && !seen.has(b)) {\n seen.add(b)\n out.push(b)\n }\n }\n }\n return out.length > 0 ? out.join(',') : undefined\n}\n\n/**\n * Credential-resolution identity for {@link resolveOAuthApiKey}. Anthropic's\n * own unless the caller pointed the provider at a gateway with its own\n * credentials via {@link AnthropicParams.credentialSource}.\n */\nexport function credentialIdentity(anthropicParams?: AnthropicParams): {\n providerId: string\n envKey?: string\n missingError: string\n refreshError: (reason: string) => string\n} {\n const source = anthropicParams?.credentialSource\n if (!source) {\n return {\n providerId: 'anthropic',\n envKey: 'ANTHROPIC_API_KEY',\n missingError: 'No API key found. Run `bun run auth` first.',\n refreshError: reason => `Anthropic OAuth token refresh failed. Run \\`bun run auth --anthropic\\` again. ${reason}`,\n }\n }\n return {\n providerId: source.providerId,\n envKey: source.envKey,\n missingError: source.missingError ?? `No credentials found for \"${source.providerId}\". Sign in first.`,\n refreshError: source.refreshError ?? (reason => `OAuth token refresh failed for \"${source.providerId}\". Sign in again. ${reason}`),\n }\n}\n\n/**\n * Whether the wire auth is a bearer token, and whether the Claude Code\n * persona (betas + `x-app` headers + system-prompt folding) applies. Only the\n * default `'auto'` mode infers both from the token shape — see\n * {@link AnthropicParams.authMode}.\n */\nexport function resolveAnthropicAuthShape(\n apiKey: string,\n authMode: AnthropicParams['authMode'],\n): { bearer: boolean, claudeCode: boolean } {\n if (authMode === 'bearer')\n return { bearer: true, claudeCode: false }\n if (authMode === 'api-key')\n return { bearer: false, claudeCode: false }\n const isOAuth = apiKey.includes('sk-ant-oat')\n return { bearer: isOAuth, claudeCode: isOAuth }\n}\n\nfunction getConfiguredApiKey(anthropicParams?: AnthropicParams): string {\n if (anthropicParams?.apiKey)\n return anthropicParams.apiKey\n\n if (anthropicParams?.access)\n return anthropicParams.access\n\n // Gateway credentials live under their own key — resolve the factory-time\n // snapshot from there and never fall back to Anthropic's own key/creds\n // (a `bex_` gateway must not silently stream on the user's Anthropic key).\n // An empty snapshot is fine: the real error surfaces per call from\n // `resolveOAuthApiKey` with this source's `missingError`.\n const source = anthropicParams?.credentialSource\n if (source) {\n const fromEnv = source.envKey ? process.env[source.envKey] : undefined\n if (fromEnv)\n return fromEnv\n return readOAuthCredentials()[source.providerId]?.access ?? ''\n }\n\n if (process.env.ANTHROPIC_API_KEY)\n return process.env.ANTHROPIC_API_KEY\n\n // `readOAuthCredentials` tolerates a missing or corrupted file and returns `{}`\n // in both cases, so stale/half-written creds never crash agent construction.\n const access = readOAuthCredentials().anthropic?.access\n if (typeof access === 'string' && access.length > 0)\n return access\n\n throw new Error('No API key found. Run `bun run auth` first.')\n}\n\n/**\n * Resolve {@link AnthropicParams.extraHeaders} to a concrete map. A function\n * form is invoked (and awaited) per call so gateway auth tokens can refresh\n * each turn; a static map passes through.\n */\nasync function resolveExtraHeaders(\n value: AnthropicParams['extraHeaders'],\n): Promise<Record<string, string> | undefined> {\n return typeof value === 'function' ? value() : value\n}\n\n/**\n * SDK constructor options for a resolved credential — the single place that\n * decides which auth header goes on the wire.\n *\n * Exported (and pure) so the header shape is test-pinned without a network\n * round-trip: `authToken` → `Authorization: Bearer …`, `apiKey` → `x-api-key`,\n * and `apiKey: null` alongside `authToken` is what suppresses `x-api-key` so a\n * gateway sees exactly one credential.\n */\nexport function buildAnthropicClientOptions(\n apiKey: string,\n auth: { bearer: boolean, claudeCode: boolean },\n baseURL?: string,\n extraBetas?: readonly string[],\n extraHeaders?: Record<string, string>,\n): Record<string, unknown> {\n const base = baseURL ? { baseURL } : {}\n const betaHeader = resolveAnthropicBetas(auth.claudeCode, extraBetas)\n if (auth.claudeCode) {\n const callerHeaders = filterReservedExtraHeaders(extraHeaders, OAUTH_RESERVED_EXTRA_HEADER_NAMES)\n const defaultHeaders: Record<string, string> = {\n ...callerHeaders,\n 'anthropic-dangerous-direct-browser-access': 'true',\n 'user-agent': 'zidane/2.0.0',\n 'x-app': 'cli',\n }\n if (betaHeader)\n defaultHeaders['anthropic-beta'] = betaHeader\n return {\n apiKey: null,\n authToken: apiKey,\n dangerouslyAllowBrowser: true,\n defaultHeaders,\n ...base,\n }\n }\n // Non-persona paths — only emit the beta header when the caller opted in,\n // and let caller headers through except `anthropic-beta` (reserved so the\n // fast-mode / opt-in beta computation stays authoritative).\n const defaultHeaders = filterReservedExtraHeaders(extraHeaders, API_KEY_RESERVED_EXTRA_HEADER_NAMES)\n if (betaHeader)\n defaultHeaders['anthropic-beta'] = betaHeader\n const headers = Object.keys(defaultHeaders).length > 0 ? { defaultHeaders } : {}\n // Bearer without the persona: a gateway token (`bex_…`, an internal router\n // key) in front of `baseURL`.\n if (auth.bearer)\n return { apiKey: null, authToken: apiKey, ...headers, ...base }\n return { apiKey, ...headers, ...base }\n}\n\nfunction createClient(\n SDK: AnthropicCtor,\n apiKey: string,\n auth: { bearer: boolean, claudeCode: boolean },\n baseURL?: string,\n extraBetas?: readonly string[],\n extraHeaders?: Record<string, string>,\n): AnthropicInstance {\n return new SDK(\n buildAnthropicClientOptions(apiKey, auth, baseURL, extraBetas, extraHeaders) as ConstructorParameters<AnthropicCtor>[0],\n )\n}\n\ntype BudgetedThinkingLevel = Exclude<ThinkingLevel, 'off' | 'adaptive'>\n\n/**\n * Map `ThinkingLevel` budgeted tiers to Anthropic's `output_config.effort`\n * enum. `minimal` collapses to `low` (the closest equivalent — Anthropic does\n * not have a sub-`low` tier).\n */\n/**\n * Explicit thinking budgets for Bedrock, per effort tier. Bedrock's\n * anthropic-native path only accepts the legacy\n * `thinking: { type: 'enabled', budget_tokens }` shape (the 4.6 surface —\n * `output_config.effort`, adaptive, `display` — is rejected by its\n * translation layer), so effort tiers degrade to token budgets. Floor is\n * Anthropic's 1024 minimum; ceilings stay well under haiku/sonnet output\n * caps — the request builder clamps against the model ceiling regardless.\n */\n/**\n * Output tokens reserved for the visible response when an explicit thinking\n * budget must be shrunk to fit under the model's `max_tokens` ceiling — see\n * the budget clamp in `stream()`.\n */\nconst THINKING_RESPONSE_RESERVE_TOKENS = 1024\n\nconst BEDROCK_THINKING_BUDGETS: Record<'low' | 'medium' | 'high' | 'xhigh' | 'max', number> = {\n low: 4096,\n medium: 12288,\n high: 24576,\n xhigh: 32768,\n max: 32768,\n}\n\nconst EFFORT_FOR_LEVEL: Record<BudgetedThinkingLevel, 'low' | 'medium' | 'high' | 'xhigh' | 'max'> = {\n minimal: 'low',\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n max: 'max',\n}\n\n/**\n * Description of the Anthropic-side thinking configuration derived from a\n * ThinkingLevel. `null` means no thinking-related field should be set on the\n * request.\n *\n * Two shapes:\n * - `adaptive` — `thinking.type='adaptive'`. The model self-budgets per turn.\n * When `effort` is set, also emits `output_config.effort` to hint at the\n * level of reasoning the caller wants. This is the post-Claude-4.6 default\n * for level-based control and avoids the `thinking.type='enabled'`\n * deprecation warning. When `maxTokensCap` is set, the request builder\n * reduces `max_tokens` to `min(max_tokens, maxTokensCap)` — adaptive thinks\n * and replies inside one envelope, so capping the envelope soft-bounds the\n * thinking too.\n * - `enabled` — explicit-budget path: `thinking.type='enabled'` with an\n * explicit `budget_tokens`. `maxTokensBump` is added to the request's\n * `max_tokens` so the budget sits on top of the response cap. When the\n * caller's level maps to an effort tier, `effort` is carried too and\n * emitted as `output_config.effort` alongside the explicit budget —\n * both fields are valid together on 4.6+ models. The only way to pin a\n * precise token budget; Anthropic emits a deprecation warning for this\n * shape on opus 4.6+, so we only route here when the caller explicitly\n * sets `behavior.thinkingBudget`.\n *\n * In both shapes Anthropic requires `temperature` to be `1`.\n */\nexport type AnthropicThinkingPlan\n = | { kind: 'enabled', budgetTokens: number, maxTokensBump: number, effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' }\n | { kind: 'adaptive', effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max', maxTokensCap?: number, taskBudgetTokens?: number }\n\n/**\n * Decide how to translate a `ThinkingLevel` into Anthropic's request shape.\n * Pure / synchronous — exported so tests can assert routing without standing\n * up the SDK.\n *\n * Routing rules:\n * - `'off'` → `null` (no thinking field, no effort hint).\n * - `'adaptive'` → adaptive thinking with no effort hint (model decides\n * everything). When `taskBudget` is set, it is carried as\n * `taskBudgetTokens` and emitted as `output_config.task_budget` — the\n * native whole-task thinking cap. LEGACY: when `customBudget` is set, it\n * is carried as `maxTokensCap` so the request builder caps `max_tokens`\n * accordingly — this clamps the whole response envelope (text and\n * tool-call JSON included), which is the wrong knob for bounding thinking\n * now that `taskBudget` exists; kept only for callers who already depend\n * on it. Prefer `taskBudget`.\n * - Budgeted levels → adaptive thinking with an `effort` hint (plus\n * `taskBudgetTokens` when `taskBudget` is set), unless `customBudget` is\n * provided.\n * - Any level + `customBudget` → explicit-budget `enabled` path, carrying\n * the level's `effort` hint alongside the budget. The caller has opted\n * into precise budget control and accepts the Anthropic deprecation\n * warning that comes with it on opus 4.6+. `'adaptive'` is the sole\n * exception: it never falls back to enabled, since adaptive is the\n * current Anthropic API surface for self-budgeted thinking. `taskBudget`\n * is adaptive-only and ignored on this path.\n * - `effortHint: false` (default `true`) strips the `effort` hint from\n * every shape — budgeted levels plan plain adaptive and the\n * `customBudget` path plans `enabled` with no `output_config.effort` —\n * for Anthropic models that reject the effort field.\n */\nexport function planAnthropicThinking(\n level: ThinkingLevel,\n customBudget?: number,\n taskBudget?: number,\n effortHint = true,\n): AnthropicThinkingPlan | null {\n if (level === 'off')\n return null\n const taskBudgetTokens = typeof taskBudget === 'number' && taskBudget > 0 ? taskBudget : undefined\n if (level === 'adaptive') {\n return {\n kind: 'adaptive',\n ...(typeof customBudget === 'number' && customBudget > 0 ? { maxTokensCap: customBudget } : {}),\n ...(taskBudgetTokens !== undefined ? { taskBudgetTokens } : {}),\n }\n }\n if (customBudget !== undefined) {\n return {\n kind: 'enabled',\n budgetTokens: customBudget,\n maxTokensBump: customBudget,\n ...(effortHint ? { effort: EFFORT_FOR_LEVEL[level] } : {}),\n }\n }\n return {\n kind: 'adaptive',\n ...(effortHint ? { effort: EFFORT_FOR_LEVEL[level] } : {}),\n ...(taskBudgetTokens !== undefined ? { taskBudgetTokens } : {}),\n }\n}\n\n/**\n * Map Anthropic's native `stop_reason` to the zidane `TurnFinishReason` union.\n *\n * `pause_turn` and `model_context_window_exceeded` are 4.6+ stop reasons that\n * pre-Z21 collapsed to `'other'` and silently terminated the run. They now\n * map to `'pause'` and `'length'` respectively, and the surrounding caller\n * adjusts the `done` flag so the loop can recover.\n */\nfunction mapStopReason(stopReason: string | null | undefined): TurnFinishReason | undefined {\n if (!stopReason)\n return undefined\n switch (stopReason) {\n case 'end_turn':\n case 'stop_sequence':\n return 'stop'\n case 'tool_use':\n return 'tool-calls'\n case 'max_tokens':\n case 'model_context_window_exceeded':\n // 4.6+: response bumped against the model's context window mid-stream.\n // Treat as a length-class stop so consumers can prune + retry; the\n // partial assistant response is preserved.\n return 'length'\n case 'refusal':\n return 'content-filter'\n // 4.6+: server-side mid-turn pause for long thinking. The loop\n // continues with a synthetic continue message rather than terminating.\n case 'pause_turn':\n return 'pause'\n default:\n return 'other'\n }\n}\n\n/**\n * Conservative per-family output ceiling, used ONLY as a fallback when pi-ai's\n * model registry doesn't know the model (or pi-ai is externalized) — see\n * {@link resolveAnthropicMaxOutput}, which is the primary path. These are\n * non-beta floors we can always send without a 400; the registry reports the\n * real (often much higher, e.g. Opus 4.x = 128K native) max when available.\n */\nexport function defaultAnthropicMaxTokens(modelId: string): number {\n const id = modelId.toLowerCase()\n if (id.includes('haiku'))\n return 8192\n if (id.includes('sonnet'))\n return 64000\n // opus + anything unrecognized → 32000: a safe floor when the registry is\n // unavailable. The registry lifts this to the model's true max when present.\n return 32000\n}\n\n/**\n * Lazily-loaded pi-ai model-registry getter (cached; keeps the multi-MB\n * registry out of the static bundle, mirroring `cost.ts`). Returns `null` when\n * pi-ai is externalized, in which case callers fall back to the family map.\n */\nconst loadPiModelGetter = lazyAsync(\n async (): Promise<((provider: string, model: string) => { maxTokens?: number } | undefined) | null> => {\n try {\n const mod = await import('@earendil-works/pi-ai/providers/all')\n return mod.getBuiltinModel as unknown as (provider: string, model: string) => { maxTokens?: number } | undefined\n }\n catch {\n return null\n }\n },\n)\n\n/**\n * Resolve a model's max output tokens. Prefers pi-ai's bundled registry — the\n * authoritative source the SDK itself uses to build requests, so e.g. Opus 4.x\n * reports its full native 128K (no extended-output beta required) — and falls\n * back to {@link defaultAnthropicMaxTokens} only when the registry lacks the\n * model. Used as BOTH the default (when the caller leaves `maxTokens` unset)\n * and a hard clamp, since a `max_tokens` above the model's max would 400.\n *\n * The clamp is only as good as the ceiling's provenance, so an explicit caller\n * `maxTokens` can RAISE the fallback: models the registry doesn't know are\n * mostly ids that never appear in pi-ai's anthropic registry — Bedrock ids\n * (`global.anthropic.claude-*`) and non-Anthropic models served over the\n * Anthropic wire (`openai.gpt-*` on Bedrock, gateway aliases). For the\n * latter the fallback degrades to the 32000 catch-all; for the former the\n * family match yields a deliberately conservative non-beta floor. Clamping a\n * caller who knows the real ceiling down to either silently truncates long\n * generations mid-write (observed as turns pinned at exactly 32000 tokens).\n *\n * It can only raise, never lower: the caller's `maxTokens` is a cap on the\n * VISIBLE response, already enforced as `max_tokens` itself, whereas this\n * value is the model's physical ceiling. Letting it lower the ceiling would\n * break the `enabled` thinking path's invariant that the budget sits ON TOP\n * of the response cap — the budget would be shrunk to share the caller's cap,\n * or dropped entirely once no satisfiable budget fits.\n *\n * A registry-backed max always wins — above it the provider 400s.\n */\nexport async function resolveAnthropicMaxOutput(modelId: string, explicitMaxTokens?: number): Promise<number> {\n const getModel = await loadPiModelGetter()\n const registryMax = getModel?.('anthropic', modelId)?.maxTokens\n if (typeof registryMax === 'number' && registryMax > 0)\n return registryMax\n const fallback = defaultAnthropicMaxTokens(modelId)\n return typeof explicitMaxTokens === 'number' && explicitMaxTokens > 0\n ? Math.max(fallback, explicitMaxTokens)\n : fallback\n}\n\nconst EPHEMERAL: Anthropic.CacheControlEphemeral = { type: 'ephemeral' }\n\n/**\n * `cache_control` for the requested TTL. `'5m'` stays the bare ephemeral shape\n * (no `ttl` field) so default-TTL requests are byte-identical to what every\n * zidane version has ever sent — adding `ttl: '5m'` would be semantically\n * equal but is gratuitous churn against proxies that pattern-match the body.\n * `'1h'` also requires the `extended-cache-ttl-2025-04-11` beta header, which\n * the request path adds — see {@link EXTENDED_CACHE_TTL_BETA}.\n */\nfunction cacheControlFor(ttl: CacheTtl | undefined): Anthropic.CacheControlEphemeral {\n return ttl === '1h' ? { type: 'ephemeral', ttl: '1h' } : EPHEMERAL\n}\n\n/** Beta flag Anthropic requires before it honors `ttl: '1h'` on `cache_control`. */\nexport const EXTENDED_CACHE_TTL_BETA = 'extended-cache-ttl-2025-04-11'\n\n/**\n * Mutate an Anthropic request in place to add cache breakpoints on the three\n * stable prefixes:\n * 1. System prompt — `cache_control` on the static prefix only (see below).\n * 2. Tool definitions — last tool.\n * 3. Conversation — last content block of the last message.\n *\n * Each breakpoint tells Anthropic to cache the prefix ending at that block;\n * subsequent turns reuse the cached prefix and pay only for the delta. Safe\n * no-op when any prefix is empty (no tools, empty system, etc.).\n *\n * System-prompt boundary handling (`SYSTEM_PROMPT_BOUNDARY`):\n *\n * - When `originalSystem` is provided AND carries the marker, the system\n * block is rewritten as a 2-block array: static (cached) then dynamic\n * (uncached). The caller is expected to have already stripped the marker\n * from `params.system` via {@link renderSystemForWire} — this helper\n * only re-splits to apply `cache_control` cleanly.\n * - When `originalSystem` is omitted or marker-free, the existing single-\n * block treatment applies: `cache_control` on the whole system string.\n * - Array system prompts: existing semantics — `cache_control` lands on the\n * last block. Callers building their own multi-block layout own the\n * breakpoint placement.\n */\nexport function applyAnthropicCacheBreakpoints(\n params: Anthropic.MessageCreateParamsStreaming,\n originalSystem?: string,\n ttl?: CacheTtl,\n): void {\n const cacheControl = cacheControlFor(ttl)\n if (typeof params.system === 'string') {\n if (params.system.length > 0) {\n // `originalSystem` is the authoritative source for the boundary split\n // — `params.system` may have been pre-rendered by `renderSystemForWire`.\n // Fall back to `params.system` itself when no original was supplied\n // (or an empty original) so an external caller that embedded a marker\n // directly doesn't leak it into the cached block on the wire.\n const splitSource = originalSystem && originalSystem.length > 0\n ? originalSystem\n : params.system\n const parts = splitSystemPrompt(splitSource)\n if (parts.dynamic.length > 0) {\n const blocks: Anthropic.TextBlockParam[] = []\n if (parts.static.length > 0)\n blocks.push({ type: 'text', text: parts.static, cache_control: cacheControl })\n blocks.push({ type: 'text', text: parts.dynamic })\n params.system = blocks\n }\n else {\n // No marker — wrap the (already marker-free) string in a single\n // cached block. `parts.static` equals `splitSource` in this branch.\n params.system = [{ type: 'text', text: parts.static, cache_control: cacheControl }]\n }\n }\n }\n else if (Array.isArray(params.system) && params.system.length > 0) {\n const lastIdx = params.system.length - 1\n params.system = params.system.map((block, i) =>\n i === lastIdx ? { ...block, cache_control: cacheControl } : block,\n )\n }\n\n if (params.tools && params.tools.length > 0) {\n const lastIdx = params.tools.length - 1\n params.tools = params.tools.map((tool, i) =>\n i === lastIdx ? { ...tool, cache_control: cacheControl } : tool,\n ) as Anthropic.ToolUnion[]\n }\n\n if (params.messages.length === 0)\n return\n const lastMsgIdx = params.messages.length - 1\n const lastMsg = params.messages[lastMsgIdx]\n if (typeof lastMsg.content === 'string') {\n if (lastMsg.content.length === 0)\n return\n params.messages[lastMsgIdx] = {\n ...lastMsg,\n content: [{ type: 'text', text: lastMsg.content, cache_control: cacheControl }],\n }\n return\n }\n if (!Array.isArray(lastMsg.content) || lastMsg.content.length === 0)\n return\n const blocks = lastMsg.content\n // `ThinkingBlockParam` and `RedactedThinkingBlockParam` do not accept `cache_control`\n // in the SDK types — walk backward past any trailing thinking blocks to find the\n // nearest cache-eligible block. Returns -1 when every block is a thinking variant,\n // which skips this breakpoint; system + tools still carry the cache prefix.\n let targetIdx = blocks.length - 1\n while (targetIdx >= 0 && isThinkingBlock(blocks[targetIdx]))\n targetIdx -= 1\n if (targetIdx < 0)\n return\n const nextBlocks = blocks.slice()\n nextBlocks[targetIdx] = { ...nextBlocks[targetIdx], cache_control: cacheControl } as typeof nextBlocks[number]\n params.messages[lastMsgIdx] = { ...lastMsg, content: nextBlocks }\n}\n\nfunction isThinkingBlock(block: { type: string }): boolean {\n return block.type === 'thinking' || block.type === 'redacted_thinking'\n}\n\n/**\n * Duck-type check for an Anthropic SDK `APIError` — avoids a runtime dependency\n * on `@anthropic-ai/sdk` so `classifyError` stays usable even when the optional\n * peer dep isn't loaded (e.g. host code calling it on an unrelated provider's\n * error).\n *\n * Anthropic's APIError shape: `.status: number` + `.error` (parsed body, object\n * or null). Plain `Error`s don't have `.status` + `.error`.\n */\nfunction looksLikeAnthropicApiError(err: unknown): boolean {\n if (!err || typeof err !== 'object')\n return false\n const e = err as { status?: unknown, error?: unknown }\n return typeof e.status === 'number' && 'error' in e\n}\n\n/**\n * Anthropic SSE `error` event types that warrant a retry. `overloaded_error`\n * is the headline case (capacity event mid-stream); `api_error` and\n * `timeout_error` are both server-side transient failures. `invalid_request_error`,\n * `authentication_error`, `permission_error`, `not_found_error`, `billing_error`\n * are terminal — retrying them would just hammer a bad request.\n *\n * `rate_limit_error` here would be redundant: the SDK's pre-stream retry\n * handles 429, and a mid-stream `rate_limit_error` is exceedingly rare. We\n * include it anyway for symmetry with the HTTP-level retry policy.\n */\nconst SSE_RETRYABLE_ERROR_TYPES = new Set<string>([\n 'overloaded_error',\n 'api_error',\n 'timeout_error',\n 'rate_limit_error',\n])\n\n/**\n * Try to parse an Anthropic SSE `error` event payload out of a thrown error's\n * message. The SDK's `MessageStream` surfaces mid-stream error events by\n * throwing an `AnthropicError` whose `.message` contains the raw JSON shape:\n *\n * {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"},\"request_id\":\"req_...\"}\n *\n * Returns the inner `{ type, message }` or `null` when the message isn't\n * the canonical SSE error shape. Tolerant: silently returns `null` for\n * non-string input, non-JSON content, or any shape mismatch.\n */\nfunction matchSseErrorEvent(message: unknown): { type: string, message: string } | null {\n if (typeof message !== 'string' || message.length === 0)\n return null\n // Cheap pre-check to avoid JSON.parse on every error message.\n if (!message.includes('\"type\":\"error\"') && !message.includes('\"type\": \"error\"'))\n return null\n // The message may be the JSON itself or have it embedded (some SDK paths\n // prefix a human prelude). Scan for the first `{` and try from there.\n const start = message.indexOf('{')\n if (start < 0)\n return null\n try {\n const parsed = JSON.parse(message.slice(start)) as unknown\n if (!parsed || typeof parsed !== 'object')\n return null\n const outer = parsed as { type?: unknown, error?: unknown }\n if (outer.type !== 'error' || !outer.error || typeof outer.error !== 'object')\n return null\n const inner = outer.error as { type?: unknown, message?: unknown }\n if (typeof inner.type !== 'string')\n return null\n return {\n type: inner.type,\n message: typeof inner.message === 'string' ? inner.message : inner.type,\n }\n }\n catch {\n return null\n }\n}\n\n/**\n * Classify an Anthropic SDK / HTTP error for typed-error wrapping.\n *\n * - `prompt is too long` (400 invalid_request_error) → `context_exceeded`.\n * - `'tool_use' ids were found without 'tool_result' blocks` /\n * `'tool_result must be preceded by a tool_call'` (400) →\n * `tool_pairing_corruption`. The local repair pass should have caught\n * this — the typed error tells consumers their pre-send pipeline is\n * shipping orphaned blocks somehow (custom `context:transform` hook,\n * bypassed loop, mid-stream session edit) so they can patch the root\n * cause instead of chasing 400s.\n * - Any other Anthropic `APIError`-shaped value → `provider_error` with the\n * native status/type code.\n * - Unknown errors → `null` (loop wraps in `AgentProviderError` generically).\n *\n * Anthropic's wire error shape is `{ type: 'error', error: { type, message } }` — the\n * SDK stores the parsed body on `err.error`. We walk both levels so callers see the\n * most specific `providerCode` we can find.\n */\nexport function classifyAnthropicError(err: unknown): ClassifiedError | null {\n const prelude = classifyErrorPrelude(err)\n if (prelude === 'not-object')\n return null\n if (prelude === 'aborted')\n return { kind: 'aborted' }\n\n interface InnerError { type?: string, message?: string }\n interface AnthError {\n name?: string\n message?: string\n status?: number\n error?: InnerError & { error?: InnerError }\n }\n const anyErr = err as AnthError\n\n // Mid-stream SSE error event — the SDK's `MessageStream` surfaces these by\n // throwing an `AnthropicError` (plain Error subclass, no `.status`) whose\n // `.message` carries the raw SSE error JSON, e.g.\n // `{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"},\"request_id\":\"...\"}`.\n // The pre-stream HTTP retry inside the SDK can't help here — the response\n // already opened with a 200, then the server emitted `event: error`\n // mid-stream. Classify these so the loop-level retry kicks in.\n //\n // Guarded on `!looksLikeAnthropicApiError(err)` so we don't shadow the\n // structured `APIError` branch below (which also stringifies its body into\n // `.message` and would otherwise match this same pattern).\n if (!looksLikeAnthropicApiError(err)) {\n const sseError = matchSseErrorEvent(anyErr.message)\n if (sseError) {\n return {\n kind: 'provider_error',\n providerCode: sseError.type,\n message: sseError.message,\n retryable: SSE_RETRYABLE_ERROR_TYPES.has(sseError.type),\n }\n }\n return null\n }\n\n // Prefer the inner error when present (Anthropic's nested shape).\n const innerType = anyErr.error?.error?.type\n const outerType = anyErr.error?.type\n const nativeType = innerType && innerType !== 'error' ? innerType : outerType\n const message = anyErr.error?.error?.message\n ?? anyErr.error?.message\n ?? anyErr.message\n ?? ''\n\n if (matchesContextExceeded(message)) {\n return {\n kind: 'context_exceeded',\n providerCode: nativeType ?? 'invalid_request_error',\n message,\n }\n }\n\n if (matchesToolPairingError(message)) {\n return {\n kind: 'tool_pairing_corruption',\n providerCode: nativeType ?? 'invalid_request_error',\n message,\n }\n }\n\n const status = anyErr.status\n const retryable = typeof status === 'number'\n ? isRetryableHttpStatus(status)\n : undefined\n\n return {\n kind: 'provider_error',\n providerCode: nativeType ?? (status ? String(status) : undefined),\n message,\n ...(retryable !== undefined ? { retryable } : {}),\n }\n}\n\nfunction shouldFallbackFromFastMode(err: unknown): boolean {\n const classified = classifyAnthropicError(err)\n if (classified?.kind === 'provider_error' && classified.retryable === true)\n return true\n\n const message = err instanceof Error ? err.message : String(err)\n return /\\b(?:fast|speed)\\b/i.test(message)\n && /capacity|overload|rate|unavailable|unsupported|not supported|not permitted|extra inputs|invalid/i.test(message)\n}\n\n/**\n * Anthropic signs thinking blocks so they can be echoed through tool-use\n * chains without exposing raw reasoning. A signature can become\n * unverifiable after a model/route/account switch, a legacy session edit,\n * or a provider-side signing-key rotation. We cannot validate the opaque\n * signature locally; Anthropic reports this as a request-validation 400\n * (`invalid_request_error`) with no machine-readable subcode — the message\n * string is the only signal.\n *\n * Detection is layered, most-stable signal first:\n *\n * 1. Structural: the validation 400 pinpoints a wire location\n * (`messages.N.content.M: …`) and OUR OWN request payload has a\n * thinking/redacted_thinking block at that exact position. The locator\n * format is API-stable; the prose around it is not (Anthropic has\n * already reworded it once, from \"Invalid signature in thinking block\"\n * to \"Invalid `signature` in `thinking` block\", which silently\n * disabled a wording-only matcher). This deliberately classifies ANY\n * validation complaint targeting one of our opaque thinking blocks as\n * recoverable — dropping the block is the correct remedy for the whole\n * class (bad signature, corrupt data, ordering), and if the scrubbed\n * retry still 400s the error propagates unchanged.\n * 2. Wording fallback: some error shapes omit the locator; match the\n * known prose variants, tolerating backticks and minor rewording.\n *\n * Match narrowly: retrying any broader 400 could hide a real bad request.\n */\nfunction isRecoverableThinkingBlockError(err: unknown, messages?: Anthropic.MessageParam[]): boolean {\n if (!isRequestValidationError(err))\n return false\n\n if (messages !== undefined) {\n const path = parseFailingBlockPath(err)\n if (path !== undefined) {\n const content = messages[path.message]?.content\n const block = Array.isArray(content) ? content[path.content] : undefined\n if (block !== undefined && (block.type === 'thinking' || block.type === 'redacted_thinking'))\n return true\n }\n }\n\n return /invalid\\s+`?signature`?\\s+in\\s+(?:the\\s+)?`?thinking`?\\s+block/i.test(errorText(err))\n}\n\n/**\n * True when the error looks like an Anthropic request-validation failure:\n * status 400 and, when the nested API body carries a type, that type is\n * `invalid_request_error`. Both fields are optional on SDK-wrapped or\n * gateway shapes, so each is enforced only when present — but a present,\n * different value (e.g. 429, `authentication_error`) disqualifies: the\n * recovery permanently scrubs session history, so it must never fire on a\n * non-validation failure that coincidentally mentions a locator.\n */\nfunction isRequestValidationError(err: unknown): boolean {\n // Field probes only — a non-object error (string throw from a custom\n // stream factory) has neither status nor type and falls through to the\n // caller's prose match, same as the pre-structural matcher.\n const status = typeof err === 'object' && err !== null && 'status' in err\n ? (err as { status?: unknown }).status\n : undefined\n if (status !== undefined && status !== 400)\n return false\n const nestedType = typeof err === 'object' && err !== null ? nestedErrorType(err) : undefined\n return nestedType === undefined || nestedType === 'invalid_request_error'\n}\n\n/** The `error.error.type` of a nested Anthropic API error body, when present. */\nfunction nestedErrorType(err: object): string | undefined {\n const outer = 'error' in err ? (err as { error?: unknown }).error : undefined\n if (typeof outer !== 'object' || outer === null)\n return undefined\n const inner = 'error' in outer ? (outer as { error?: unknown }).error : outer\n if (typeof inner !== 'object' || inner === null)\n return undefined\n const type = 'type' in inner ? (inner as { type?: unknown }).type : undefined\n return typeof type === 'string' ? type : undefined\n}\n\n/** Error message + nested API error body, flattened for pattern matching. */\nfunction errorText(err: unknown): string {\n const nested = typeof err === 'object' && err !== null && 'error' in err\n ? JSON.stringify((err as { error?: unknown }).error)\n : ''\n return `${err instanceof Error ? err.message : String(err)} ${nested}`\n}\n\n/**\n * Full wire locator of the block the 400 pinpointed (`messages.5.content.0:\n * …`), or `undefined` when the shape doesn't carry one. Unlike the prose,\n * this locator prefix is a stable part of Anthropic's validation-error\n * format — it lets {@link isRecoverableThinkingBlockError} verify against\n * the actual request payload instead of trusting wording.\n */\nfunction parseFailingBlockPath(err: unknown): { message: number, content: number } | undefined {\n const match = /\\bmessages\\.(\\d+)\\.content\\.(\\d+)\\b/.exec(errorText(err))\n if (!match)\n return undefined\n const message = Number(match[1])\n const content = Number(match[2])\n return Number.isSafeInteger(message) && Number.isSafeInteger(content)\n ? { message, content }\n : undefined\n}\n\n/**\n * Wire index of the message the 400 pinpointed (`messages.5.content.0:\n * Invalid signature…`), or `undefined` when the shape doesn't carry one.\n * Lets the retry scrub only blocks at/before the failing message — later\n * messages can hold STILL-VALID thinking (e.g. minted this run after a\n * mid-session account switch) that the active tool-use chain requires.\n */\nfunction parseFailingMessageIndex(err: unknown): number | undefined {\n const match = /\\bmessages\\.(\\d+)\\./.exec(errorText(err))\n if (!match)\n return undefined\n const index = Number(match[1])\n return Number.isSafeInteger(index) ? index : undefined\n}\n\n/**\n * Hard cap on signature-400 scrub retries within one `stream()` call. Two\n * passes resolve every real-world shape (bounded pass, then the\n * everything-but-active-chain pass); the third is margin. Beyond that the\n * error is not signature poisoning and must surface.\n */\nconst MAX_THINKING_SCRUB_PASSES = 3\n\n/**\n * Wire index where the ACTIVE chain begins: the last user message that\n * carries real user content (string content, or any non-tool_result\n * block). Everything from there onward is the current prompt plus the\n * in-flight assistant/tool exchange — its thinking blocks were minted by\n * this very call chain and Anthropic requires them to be echoed back, so\n * escalated scrubs must never cross this boundary. `undefined` when no\n * such message exists (degenerate resume shapes) — callers treat that as\n * \"no protected region\".\n */\nfunction activeChainScrubBoundary(messages: Anthropic.MessageParam[]): number | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]\n if (message?.role !== 'user')\n continue\n if (typeof message.content === 'string')\n return i\n if (message.content.some(block => block.type !== 'tool_result'))\n return i\n }\n return undefined\n}\n\n/**\n * Decide what a scrub pass may touch. The bound NEVER crosses into the\n * active chain wholesale — not even on pass 0 with no parseable locator\n * (an unbounded first pass would strip the in-flight chain's thinking and\n * trade a recoverable 400 for an \"expected thinking block\" one). When the\n * API-reported failing index lies INSIDE the chain, only that single\n * message is scrubbed on top of the pre-chain region: the block the API\n * itself rejected fails whether or not it is echoed, but sibling chain\n * messages below it may hold still-valid thinking the exchange requires.\n *\n * - pass 0 with a pre-chain locator → bounded at the locator (preserves\n * later, still-valid historical thinking).\n * - pass 0 without a locator, and every escalated pass → the full\n * pre-chain history.\n * - no active chain at all (degenerate resume shapes) → locator bound on\n * pass 0, full history afterwards.\n */\nfunction planThinkingScrub(\n scrubPass: number,\n failingIndex: number | undefined,\n messages: Anthropic.MessageParam[],\n): { upToIndex?: number, alsoMessageIndex?: number } {\n const chainStart = activeChainScrubBoundary(messages)\n if (chainStart === undefined) {\n return scrubPass === 0 && failingIndex !== undefined\n ? { upToIndex: failingIndex }\n : {} // no protected region — scrub the full history\n }\n const beforeChain = chainStart - 1\n const inChain = failingIndex !== undefined && failingIndex >= chainStart\n const upToIndex = scrubPass === 0 && failingIndex !== undefined && !inChain\n ? failingIndex\n : beforeChain\n return inChain ? { upToIndex, alsoMessageIndex: failingIndex } : { upToIndex }\n}\n\n/**\n * Remove opaque historical Anthropic reasoning from a retry payload. Text,\n * tool calls/results, images, and every other block are preserved exactly.\n * If a message consisted only of reasoning, leave a neutral text marker so\n * the wire never receives an empty content array and conversation role\n * boundaries stay intact.\n *\n * `upToIndex` bounds the scrub to messages at/before the API-reported\n * failing index (see {@link parseFailingMessageIndex}); `undefined` strips\n * everywhere. `alsoMessageIndex` additionally scrubs that single message\n * beyond the bound (see {@link planThinkingScrub}). A later stale block\n * simply triggers the same recovery again — each pass removes at least\n * one block, so the recursion is bounded.\n */\nfunction withoutHistoricalThinking(\n messages: Anthropic.MessageParam[],\n upToIndex?: number,\n alsoMessageIndex?: number,\n): {\n messages: Anthropic.MessageParam[]\n removed: number\n} {\n let removed = 0\n const scrubbed = messages.map((message, index) => {\n if (upToIndex !== undefined && index > upToIndex && index !== alsoMessageIndex)\n return message\n if (!Array.isArray(message.content))\n return message\n const content = message.content.filter((block) => {\n if (block.type === 'thinking' || block.type === 'redacted_thinking') {\n removed += 1\n return false\n }\n return true\n })\n return {\n ...message,\n content: content.length > 0\n ? content\n : [{ type: 'text' as const, text: '[historical reasoning omitted]' }],\n }\n })\n return { messages: scrubbed, removed }\n}\n\n/**\n * Build a user `SessionMessage` from multimodal prompt parts.\n *\n * - Text parts → text blocks.\n * - Image parts → base64 image blocks.\n * - Document parts → canonical document blocks. `toAnthropic` emits native\n * document blocks only for base64 PDFs; text/non-PDF documents fall back to\n * attachment-tagged text to avoid invalid Anthropic source media types.\n *\n * The format mirrors `defaultPromptMessage`'s output on shape — Anthropic-specific\n * handling differs only in that `promptMessage` being present tells the agent loop\n * to route PromptPart[] through this function rather than throwing on base64 docs.\n */\nfunction anthropicPromptMessage(parts: PromptPart[]): SessionMessage {\n const content: SessionContentBlock[] = []\n\n for (const part of parts) {\n if (part.type === 'text') {\n if (part.text.length > 0)\n content.push({ type: 'text', text: part.text })\n continue\n }\n\n if (part.type === 'image') {\n content.push({ type: 'image', mediaType: part.mediaType, data: part.data })\n continue\n }\n\n if (part.type === 'audio')\n throw unsupportedMediaError('audio', 'anthropic')\n if (part.type === 'video')\n throw unsupportedMediaError('video', 'anthropic')\n\n // document\n content.push({\n type: 'document',\n mediaType: part.mediaType,\n data: part.data,\n encoding: part.encoding,\n ...(part.name ? { name: part.name } : {}),\n })\n }\n\n return { role: 'user', content }\n}\n\nexport function anthropic(\n anthropicParams?: AnthropicParams,\n): Provider {\n const bedrockConfig = normalizeBedrock(anthropicParams?.bedrock)\n // Bedrock mode authenticates through the AWS credential chain — resolving\n // an Anthropic key here would throw for users who (correctly) have none.\n const configuredApiKey = bedrockConfig ? '' : getConfiguredApiKey(anthropicParams)\n // Factory-time snapshot — used only for the static `meta.isOAuth` flag.\n // Keys resolve per call (env / file creds can change between construction\n // and a turn), so `countTokens` / `stream` re-derive the auth shape from the\n // freshly resolved key instead of trusting this.\n const isOAuth = resolveAnthropicAuthShape(configuredApiKey, anthropicParams?.authMode).bearer\n const defaultModel = anthropicParams?.defaultModel || 'claude-opus-4-8'\n let runtimeCredentials = extractRuntimeCredentials(anthropicParams)\n\n return {\n name: 'anthropic',\n meta: {\n defaultModel,\n isOAuth,\n // True when server-side context management is configured: the API may\n // clear old tool results mid-conversation without the client knowing.\n // The loop reads this to disable the read_file dedup, whose client-side\n // hash can't tell that a server-cleared body left the wire — otherwise\n // the \"unchanged\" replay stub would strand the model on missing content.\n clearsContextServerSide: Boolean(anthropicParams?.contextManagement),\n capabilities: {\n vision: true,\n imageInToolResult: true,\n documents: true,\n // Anthropic Messages API has no audio/video input content block.\n audio: false,\n video: false,\n // Anthropic Messages API supports `web_search_20250305` as a\n // server-side tool — the model issues searches and consumes\n // results without a client-visible tool_use round-trip. The\n // canonical `web_search` `ToolDef` ships as a cross-provider\n // fallback; when this capability is set, `formatTools` rewrites\n // it to the server-tool wire shape and drops the function-tool\n // version so the model uses the native path.\n //\n // NOT on Bedrock: AWS doesn't host Anthropic's server-side search\n // (live-verified 400, \"The provided request is not valid\"), and\n // because `formatTools` rewrites the TOOLS ARRAY, advertising it\n // would fail every request from any agent whose toolset merely\n // CONTAINS a `web_search` tool — zidane's default set does. With\n // the capability absent, that ToolDef passes through as a regular\n // function tool and executes client-side like on every other\n // non-Anthropic route. Callers can re-enable via `capabilities`\n // below if AWS ever ships it.\n ...(bedrockConfig ? {} : { nativeWebSearch: { maxUses: 5 } }),\n // Anthropic adaptive has no native per-turn thinking budget knob, so\n // `thinkingBudget` caps the whole response envelope (`max_tokens`).\n // The loop skips `thinkingDecay` for adaptive here — see the flag docs.\n adaptiveBudgetIsEnvelope: true,\n // Caller overrides last — a gateway in front of `baseURL` may not\n // implement every native affordance (server-side web search is the\n // usual casualty), and advertising one it lacks 400s every turn.\n ...anthropicParams?.capabilities,\n },\n },\n\n formatTools(tools: ToolSpec[]): Anthropic.ToolUnion[] {\n // Sanitize before forwarding — Anthropic 400s on the strict shapes\n // (root `$ref`, root `oneOf|anyOf|allOf`, `type: ['object', 'null']`,\n // missing `properties`, `nullable: true`) that show up in MCP-server\n // schemas. The strict `anthropic` profile coerces those without\n // changing semantics for valid schemas. Warnings are de-duped to\n // `console.warn` so the same bad schema doesn't spam the log every\n // turn.\n //\n // `web_search` is special-cased: when present, it's emitted as the\n // server-tool `web_search_20250305` block and removed from the\n // function-tools list. The model invokes it without a client-side\n // round-trip; Anthropic injects the search results into the\n // assistant message directly. See the `nativeWebSearch` capability\n // declared above.\n const nativeWebSearch = this.meta.capabilities?.nativeWebSearch\n // `hasWebSearch` is the existence check; `fnTools` is the filtered\n // list. Computing existence via `tools.some` (rather than comparing\n // pre/post-filter lengths) makes the rewrite intent obvious at a\n // glance.\n const hasWebSearch = !!nativeWebSearch && tools.some(t => t.name === 'web_search')\n const fnTools = hasWebSearch ? tools.filter(t => t.name !== 'web_search') : tools\n const sanitized = sanitizeToolSpecs(fnTools, { profile: 'anthropic' })\n // `?? ''`: MCP servers routinely omit descriptions, and while the\n // Anthropic API tolerates the field's absence, anthropic-format\n // GATEWAYS in front of it often validate `description` as a required\n // string — one description-less tool then 400s the whole request\n // before any model sees it. An empty string is valid everywhere.\n const out: Anthropic.ToolUnion[] = sanitized.map(t => ({\n name: t.name,\n description: t.description ?? '',\n input_schema: t.inputSchema as Anthropic.Tool['input_schema'],\n }))\n if (hasWebSearch && nativeWebSearch) {\n // `max_uses` is optional — omit when the capability doesn't pin a value\n // so Anthropic's server-side default applies.\n const block: Anthropic.WebSearchTool20250305 = {\n type: 'web_search_20250305',\n name: 'web_search',\n }\n if (typeof nativeWebSearch.maxUses === 'number')\n block.max_uses = nativeWebSearch.maxUses\n out.push(block)\n }\n return out\n },\n\n userMessage(content: string): SessionMessage {\n return { role: 'user', content: [{ type: 'text', text: content }] }\n },\n\n assistantMessage(content: string): SessionMessage {\n return { role: 'assistant', content: [{ type: 'text', text: content }] }\n },\n\n toolResultsMessage(results: ToolResult[]): SessionMessage {\n return {\n role: 'user',\n content: results.map(r => ({\n type: 'tool_result' as const,\n callId: r.id,\n output: r.content,\n ...(r.isError ? { isError: true as const } : {}),\n ...(r.metadata ? { metadata: r.metadata } : {}),\n })),\n }\n },\n\n promptMessage: anthropicPromptMessage,\n\n classifyError: classifyAnthropicError,\n\n async countTokens(payload, signal): Promise<number | null> {\n // Bedrock has no `count_tokens` endpoint (the SDK omits the method) —\n // return null immediately so the caller's heuristic takes over without\n // paying a doomed request or logging an error every turn.\n if (bedrockConfig)\n return null\n try {\n const SDK = await loadAnthropicSdk()\n const identity = credentialIdentity(anthropicParams)\n const apiKey = await resolveOAuthApiKey(\n {\n provider: identity.providerId,\n providerId: identity.providerId,\n params: runtimeCredentials ? { ...anthropicParams, ...runtimeCredentials } : anthropicParams,\n envKey: identity.envKey,\n missingError: identity.missingError,\n refreshError: identity.refreshError,\n },\n )\n // Derive OAuth-ness from the freshly resolved key — auth mode can\n // change between factory construction and this call (env var set,\n // creds file rotated), and a stale flag would skew the count's\n // system-prompt folding relative to what `stream()` actually sends.\n const callAuth = resolveAnthropicAuthShape(apiKey, anthropicParams?.authMode)\n const callIsOAuth = callAuth.claudeCode\n const client = createClient(\n SDK,\n apiKey,\n callAuth,\n anthropicParams?.baseURL,\n anthropicParams?.extraBetas,\n await resolveExtraHeaders(anthropicParams?.extraHeaders),\n )\n\n // Mirror `stream()`'s wire-payload build so the count matches what is\n // actually sent: OAuth folds the real system prompt into a synthetic\n // user/assistant pair and sends the canonical Claude Code prompt as\n // the system block.\n const wireSystem = renderSystemForWire(payload.system)\n const system = callIsOAuth\n ? `You are Claude Code, Anthropic's official CLI for Claude.`\n : wireSystem\n const messages: SessionMessage[] = callIsOAuth && payload.system\n ? [\n { role: 'user', content: [{ type: 'text' as const, text: wireSystem }] },\n { role: 'assistant', content: [{ type: 'text' as const, text: 'Understood. I will proceed with these instructions above the rest of my system prompt.' }] },\n ...payload.messages,\n ]\n : [...payload.messages]\n\n // Same request-local name boundary as `stream()` — a foreign/legacy\n // tool name in replayed history would 400 the count exactly like the\n // real request.\n const countTools = payload.tools as Anthropic.Tool[]\n const countBoundary = createToolNameBoundary(messages, countTools.map(t => t.name))\n const res = await client.messages.countTokens(\n {\n model: payload.model as Model,\n system,\n tools: countBoundary.changed\n ? countTools.map(t => ({ ...t, name: countBoundary.toWire(t.name) }))\n : countTools,\n messages: countBoundary.messages.map(m => toAnthropic(m)) as Anthropic.MessageParam[],\n },\n signal ? { signal } : undefined,\n )\n return res.input_tokens\n }\n catch (err) {\n // Unreachable under the active auth / network — caller falls back to\n // the heuristic. Surface the cause when debugging so a silent auth /\n // scope rejection (e.g. OAuth lacking the count endpoint) is visible.\n if (process.env.ZIDANE_DEBUG_COUNT)\n console.error('[anthropic.countTokens] failed:', err)\n return null\n }\n },\n\n async stream(options, callbacks: StreamCallbacks): Promise<TurnResult> {\n // Bedrock mode: SigV4 auth via the AWS credential chain — the Anthropic\n // key/OAuth resolution below must not run (it throws for users who,\n // correctly, have no Anthropic key). No persona, no betas: the wire\n // shape past client construction is identical, so everything from the\n // system block on flows through the same code.\n let apiKey = ''\n if (!bedrockConfig) {\n const identity = credentialIdentity(anthropicParams)\n apiKey = await resolveOAuthApiKey(\n {\n provider: identity.providerId,\n providerId: identity.providerId,\n params: runtimeCredentials ? { ...anthropicParams, ...runtimeCredentials } : anthropicParams,\n envKey: identity.envKey,\n missingError: identity.missingError,\n refreshError: identity.refreshError,\n },\n {\n ...callbacks,\n async onOAuthRefresh(ctx) {\n if (ctx.source === 'params') {\n runtimeCredentials = {\n access: ctx.credentials.access,\n refresh: ctx.credentials.refresh,\n expires: ctx.credentials.expires,\n }\n }\n await callbacks.onOAuthRefresh?.(ctx)\n },\n },\n )\n }\n // Per-call OAuth detection — see the matching note in `countTokens`.\n // Resolved before the conditional betas: the extended-TTL gate below\n // branches on it. Bedrock is never OAuth (empty key → bearer: false).\n const callAuth = resolveAnthropicAuthShape(apiKey, bedrockConfig ? 'api-key' : anthropicParams?.authMode)\n const callIsOAuth = callAuth.claudeCode\n // Fast mode (`speed: \"fast\"`) is gated behind the `fast-mode-2026-02-01`\n // beta — without the header Anthropic rejects the body field with\n // `speed: Extra inputs are not permitted`. Inject it here (not in the\n // static default betas) so the header is present exactly when the request\n // will carry `speed: \"fast\"`, keeping non-fast requests byte-stable for\n // the prompt cache.\n //\n // Same conditional-injection contract for the extended cache TTL: the\n // `ttl: '1h'` field on `cache_control` is rejected without its beta, so\n // the header rides exactly the requests whose breakpoints carry the ttl\n // (cache on + cacheTtl '1h') and every other request stays byte-stable.\n //\n // OAuth (Claude Code persona) is excluded: only api-key auth has been\n // verified against `extended-cache-ttl-2025-04-11`, and the CC endpoint\n // already carries its own beta set — an unaccepted beta or `ttl` field\n // would 400 EVERY request for that host. `cacheTtl` therefore degrades\n // to the default 5m TTL on OAuth (the ttl argument is withheld at the\n // `applyAnthropicCacheBreakpoints` call below, matching this gate).\n // Bedrock is excluded like OAuth: beta headers are not sent there (the\n // SigV4 client drops them), so a `ttl` field on the breakpoints would\n // arrive without its gating beta and 400. `cacheTtl` degrades to the\n // default TTL on Bedrock.\n const extendedTtl = options.cache !== false && options.cacheTtl === '1h' && !callIsOAuth && !bedrockConfig\n const conditionalBetas = [\n ...(options.modelOptions?.fast ? [FAST_MODE_BETA] : []),\n ...(extendedTtl ? [EXTENDED_CACHE_TTL_BETA] : []),\n ]\n const requestBetas = conditionalBetas.length > 0\n ? [...(anthropicParams?.extraBetas ?? []), ...conditionalBetas]\n : anthropicParams?.extraBetas\n // Bound rather than inlined into `createClient`: the affinity-header\n // no-clobber check below needs the resolved map, and a function resolver\n // must not be called twice per request (it may mint a token).\n const resolvedExtraHeaders = await resolveExtraHeaders(anthropicParams?.extraHeaders)\n const client = bedrockConfig\n ? await createBedrockClient(bedrockConfig, anthropicParams, resolvedExtraHeaders)\n : createClient(\n await loadAnthropicSdk(),\n apiKey,\n callAuth,\n anthropicParams?.baseURL,\n requestBetas,\n resolvedExtraHeaders,\n )\n\n // System prompt injection is handled by agent.ts — we just pass it through.\n // For OAuth, the Claude Code API requires the system block to start with\n // the canonical Claude Code prompt — we prepend it to the real system prompt.\n // For OAuth, the CC API requires the system block to start with the canonical\n // Claude Code prompt. The real system prompt is injected as user+assistant messages.\n //\n // The boundary marker (`SYSTEM_PROMPT_BOUNDARY`) is structural metadata\n // for `applyAnthropicCacheBreakpoints`; strip it before the bytes hit\n // the wire so it never reaches the model. The original (un-rendered)\n // string is preserved as `options.system` and forwarded to the cache\n // helper below for an accurate static/dynamic split.\n const wireSystem = renderSystemForWire(options.system)\n const system = callIsOAuth\n ? `You are Claude Code, Anthropic's official CLI for Claude.`\n : wireSystem\n const messages: SessionMessage[] = callIsOAuth && options.system\n ? [\n { role: 'user', content: [{ type: 'text' as const, text: wireSystem }] },\n { role: 'assistant', content: [{ type: 'text' as const, text: 'Understood. I will proceed with these instructions above the rest of my system prompt.' }] },\n ...options.messages,\n ]\n : [...options.messages]\n const thinking = options.thinking ?? 'off'\n\n // Request-local tool-name boundary. The tools array is normally clean\n // (agent aliasing + `sanitizeToolSpecs` ran upstream), but REPLAYED\n // HISTORY can carry names the current alias maps never saw — sessions\n // imported from other clients, renamed MCP servers, removed tools. The\n // Anthropic-family endpoints (direct API, Bedrock Converse, compatible\n // gateways) validate historical `toolUse.name` against\n // `[a-zA-Z0-9_-]{1,64}` as strictly as the tools array, so one stale\n // name 400s the whole request. Offender-only: clean requests are\n // byte-identical and the prompt cache is unaffected.\n const inputTools = (options.tools ?? []) as Anthropic.ToolUnion[]\n const nameBoundary = createToolNameBoundary(messages, inputTools.map(t => t.name))\n // Renaming only touches genuine offenders — always plain custom tools\n // (server-tool names like `web_search` are wire-legal by construction),\n // so widening the spread back to the union member is safe.\n const wireTools = nameBoundary.changed\n ? inputTools.map(t => (t.name === nameBoundary.toWire(t.name) ? t : { ...t, name: nameBoundary.toWire(t.name) } as Anthropic.ToolUnion))\n : inputTools\n\n const modelId = options.model as Model\n // The model's max output, sourced from pi-ai's registry (Opus 4.x = 128K\n // native; conservative family fallback when the registry misses). Used as\n // BOTH the default (when `maxTokens` is unset — the field is required) AND\n // a hard clamp, since a value above the model's max would 400. An explicit\n // caller maxTokens RAISES the fallback for registry-unknown models (never\n // lowers it — see the resolver's docblock: the thinking budget sits on top\n // of the caller's cap, so the cap can't double as the ceiling).\n const modelMaxOutput = await resolveAnthropicMaxOutput(modelId, options.maxTokens)\n\n // `context_management` is an untyped beta in SDK v0.90; widen `params` with\n // an optional field so we don't have to double-cast through `unknown` to\n // attach it below.\n const params: Anthropic.MessageCreateParamsStreaming & {\n context_management?: AnthropicContextManagement\n speed?: 'fast' | 'standard'\n // `task_budget` shipped after the pinned SDK's `OutputConfig` type;\n // widen until the SDK catches up.\n output_config?: { task_budget?: { type: 'tokens', total: number } }\n } = {\n // Forward-compat escape hatch for un-typed beta fields. Spread first so\n // the typed core (model / max_tokens / system / tools / messages /\n // stream) and the explicit `context_management` below override on\n // collision — explicit always wins.\n ...((anthropicParams?.extraBodyParams ?? {}) as Record<string, unknown>),\n model: modelId,\n // Required field — default to the model's full max output when unset.\n // The ceiling (incl. a caller cap above the model max) is enforced once,\n // after the thinking plan, since the `enabled` path adds budget on top.\n max_tokens: options.maxTokens ?? modelMaxOutput,\n system,\n tools: wireTools,\n messages: nameBoundary.messages.map(m => toAnthropic(m)) as Anthropic.MessageParam[],\n stream: true,\n }\n\n // Server-side context management (beta `context-management-2025-06-27`).\n // Skipped when the caller didn't pass a config — leaving the field off\n // the wire keeps requests valid on accounts that don't have the beta enabled.\n if (anthropicParams?.contextManagement)\n params.context_management = anthropicParams.contextManagement\n\n // Prompt caching — inject `cache_control: { type: 'ephemeral' }` breakpoints\n // on the three largest stable prefixes: system prompt, tool definitions, and\n // the last message's final content block. Three of Anthropic's four allowed\n // breakpoints; leaves headroom for a future thinking-block breakpoint.\n //\n // On the API-key path, `params.system` was derived from\n // `renderSystemForWire(options.system)` so the cache helper can split\n // the original on the `SYSTEM_PROMPT_BOUNDARY` marker and apply\n // `cache_control` to the static prefix only — per-turn churn in the\n // dynamic suffix no longer invalidates the cached doctrine above.\n //\n // On the OAuth path, `params.system` is the canonical Claude Code\n // prompt (`\"You are Claude Code...\"`) — `options.system` lives in the\n // injected user message instead, so we do NOT forward it here. Passing\n // it would replace the CC prompt with the user's doctrine. The user\n // message is still naturally cached via the last-message breakpoint\n // applied below; per-turn churn there bypasses the boundary feature on\n // OAuth, but parity with the pre-feature behavior is preserved.\n //\n // Skipped when `options.cache === false` (opt-out) or on any shape that would\n // produce an invalid request (empty system string, zero tools, empty message list).\n if (options.cache !== false)\n applyAnthropicCacheBreakpoints(params, callIsOAuth ? undefined : options.system, extendedTtl ? options.cacheTtl : undefined)\n\n // Enable thinking / extended thinking when requested. The default path\n // for level-based control is `thinking.type='adaptive'` plus an\n // `output_config.effort` hint — Anthropic deprecated the explicit\n // `thinking.type='enabled' + budget_tokens` shape on opus 4.6+ and\n // recommends adaptive instead. Callers who need a precise token budget\n // can opt into the explicit-budget path by setting\n // `behavior.thinkingBudget`, accepting Anthropic's deprecation\n // warning in exchange. Either shape requires `temperature=1`.\n //\n // `display: 'summarized'` is set explicitly on both shapes — Opus 4.7\n // and Claude Mythos Preview silently flipped the default to\n // `'omitted'` (signature-only, no text), which makes the SDK fire\n // `thinking` deltas with empty `thinking` content and breaks every\n // host that surfaces traces live. Older models still default to\n // `'summarized'` so this is a no-op there.\n const plan = planAnthropicThinking(thinking, options.thinkingBudget, options.taskBudget, options.effortHint !== false)\n if (plan && bedrockConfig) {\n // Bedrock's translation layer predates the 4.6 thinking surface:\n // `output_config.effort` is rejected with \"Extra inputs are not\n // permitted\" (live-verified), and `thinking.type='adaptive'` /\n // `display` are the same API generation — so every level routes\n // through the legacy explicit-budget shape Bedrock documents. The\n // effort tier picks the budget; an explicit `thinkingBudget` wins.\n const budget = plan.kind === 'enabled'\n ? plan.budgetTokens\n : BEDROCK_THINKING_BUDGETS[plan.effort ?? 'medium']\n params.thinking = { type: 'enabled', budget_tokens: budget }\n // Budget rides on top of the response cap, clamped to the model\n // ceiling below like the standard `enabled` path.\n params.max_tokens = budget + params.max_tokens\n params.temperature = 1\n }\n else if (plan) {\n if (plan.kind === 'enabled') {\n params.thinking = { type: 'enabled', budget_tokens: plan.budgetTokens, display: 'summarized' }\n params.max_tokens = plan.maxTokensBump + params.max_tokens\n // The explicit budget pins tokens; the effort hint still shapes HOW\n // the model spends them. Both fields are valid together on 4.6+.\n // Merge onto any `output_config` the caller passed via\n // `extraBodyParams` (spread first above) rather than clobbering it.\n if (plan.effort)\n params.output_config = { ...params.output_config, effort: plan.effort }\n }\n else {\n params.thinking = { type: 'adaptive', display: 'summarized' }\n const outputConfig: NonNullable<typeof params.output_config> = {}\n if (plan.effort)\n outputConfig.effort = plan.effort\n // Native whole-task thinking cap — adaptive-only. Coexists with the\n // effort hint.\n if (typeof plan.taskBudgetTokens === 'number' && plan.taskBudgetTokens > 0)\n outputConfig.task_budget = { type: 'tokens', total: plan.taskBudgetTokens }\n // Merge onto any caller-supplied `output_config` from\n // `extraBodyParams`; don't drop their fields.\n if (Object.keys(outputConfig).length > 0)\n params.output_config = { ...params.output_config, ...outputConfig }\n // LEGACY (`thinkingBudget` on adaptive): soft-cap the response\n // envelope (`max_tokens`). This clamps text and tool-call JSON too —\n // prefer `taskBudget` above. Reduce only; never raise above the\n // caller's request.\n if (typeof plan.maxTokensCap === 'number' && plan.maxTokensCap > 0)\n params.max_tokens = Math.min(params.max_tokens, plan.maxTokensCap)\n }\n params.temperature = 1\n }\n\n // The `enabled` thinking path adds the budget ON TOP of `max_tokens`,\n // which — now that the base defaults to the model's full max — can push\n // the envelope past the model's hard ceiling → 400. Clamp the final value\n // so the budget shares the envelope rather than overflowing it.\n params.max_tokens = Math.min(params.max_tokens, modelMaxOutput)\n\n // Anthropic requires `thinking.budget_tokens` STRICTLY below\n // `max_tokens` (400 otherwise — live-verified on Bedrock, where every\n // level routes through the explicit-budget shape and a mid-tier budget\n // already exceeds a haiku-class 8K ceiling; the direct API has the\n // same failure with a caller `thinkingBudget` above the ceiling).\n // After the envelope clamp above, shrink the budget to fit, reserving\n // room for the visible response. When even Anthropic's documented\n // 1024-token budget minimum can't fit under the envelope, no\n // satisfiable budget exists — degrade to a non-thinking request\n // (dropping the temperature pin the thinking branch set; nothing else\n // sets it) rather than shipping a 400 we can predict locally.\n if (params.thinking?.type === 'enabled' && params.thinking.budget_tokens >= params.max_tokens) {\n const fitted = params.max_tokens - THINKING_RESPONSE_RESERVE_TOKENS\n if (fitted >= 1024) {\n params.thinking.budget_tokens = fitted\n }\n else {\n delete params.thinking\n delete params.temperature\n }\n }\n\n // Fast mode (`speed: \"fast\"`) — ~2.5× output throughput at premium\n // pricing. Supported only on the models in `FAST_MODE_OPTIONS`\n // (chat/anthropic-models.ts); the model-options surface only offers it\n // on those, and Anthropic 400s a request with\n // `speed` on an unsupported model. `speed` is an untyped beta field in\n // SDK v0.90 (widened on `params` above).\n if (options.modelOptions?.fast)\n params.speed = 'fast'\n\n // Tool choice forcing. The forced name must match the (possibly\n // boundary-renamed) name in the tools array, mirroring openai-compat.\n if (options.toolChoice) {\n if (options.toolChoice.type === 'tool' && options.toolChoice.name)\n params.tool_choice = { type: 'tool', name: nameBoundary.toWire(options.toolChoice.name) }\n else if (options.toolChoice.type === 'required')\n params.tool_choice = { type: 'any' }\n else\n params.tool_choice = { type: 'auto' }\n }\n\n // Prompt-cache affinity key, carried as `metadata.user_id`. Derived from\n // the session's stable prefix, so it is byte-identical across a session's\n // turns and cannot itself break a cache. Merged onto any `metadata` the\n // caller passed via `extraBodyParams` (spread first above) rather than\n // clobbering it, and a caller- or gateway-supplied `user_id` always wins:\n // an intermediary that sets this itself must not be second-guessed.\n //\n // `options.system` is used for the derivation on BOTH auth paths, not\n // `params.system` — on OAuth the latter is the canonical Claude Code\n // prompt, identical across every session, which would collapse all\n // sessions onto one key.\n const promptCacheKey = resolvePromptCacheKey(anthropicParams?.promptCacheKey, {\n model: modelId,\n system: options.system,\n messages: options.messages,\n })\n if (promptCacheKey !== undefined && params.metadata?.user_id === undefined)\n params.metadata = { ...params.metadata, user_id: promptCacheKey }\n\n // HTTP header names are case-insensitive (and the SDK merges per-request\n // headers over `defaultHeaders` case-insensitively), so the no-clobber\n // probe must be too — an exact-key check would let the affinity header\n // silently beat a differently-cased caller header from `extraHeaders`.\n const affinityHeaderName = anthropicParams?.promptCacheKeyHeader?.toLowerCase()\n const affinityHeader = anthropicParams?.promptCacheKeyHeader !== undefined && promptCacheKey !== undefined\n && !Object.keys(resolvedExtraHeaders ?? {}).some(k => k.toLowerCase() === affinityHeaderName)\n ? { [anthropicParams.promptCacheKeyHeader]: promptCacheKey }\n : undefined\n\n const runStream = async (\n requestParams: typeof params,\n fastRequested: boolean,\n scrubPass = 0,\n ): Promise<TurnResult> => {\n const s = client.messages.stream(requestParams, {\n signal: options.signal,\n ...(affinityHeader ? { headers: affinityHeader } : {}),\n })\n\n let text = ''\n let observedOutput = false\n\n s.on('text', (delta) => {\n observedOutput = true\n text += delta\n callbacks.onText(delta)\n })\n\n if (callbacks.onThinking) {\n s.on('thinking', (delta) => {\n observedOutput = true\n callbacks.onThinking!(delta)\n })\n }\n\n // Liveness signal for tool-only turns: `inputJson` fires as a\n // `tool_use` block's arguments stream in. Without it, a turn that\n // emits only tool calls (no text/thinking) never trips the loop's\n // \"first response observed\" gate and the first-response watchdog can\n // abort an actively-progressing stream. (B2)\n if (callbacks.onToolCallDelta) {\n s.on('inputJson', () => {\n observedOutput = true\n callbacks.onToolCallDelta!()\n })\n }\n\n // Server-tool blocks (e.g. `web_search_20250305`) execute on Anthropic's\n // side and arrive in the assistant content stream — not via our tool\n // loop. The SDK fires `contentBlock` once per block as it closes, so\n // listen for the two we care about and dispatch generic callbacks.\n // Other block types (text, thinking, tool_use, …) have their own paths\n // above / in `finalMessage()` — ignored here to avoid double-emission.\n if (callbacks.onServerToolUse || callbacks.onServerToolResult) {\n s.on('contentBlock', (block) => {\n observedOutput = true\n if (block.type === 'server_tool_use') {\n callbacks.onServerToolUse?.({\n id: block.id,\n name: block.name,\n input: (block.input as Record<string, unknown> | undefined) ?? {},\n })\n }\n else if (block.type === 'web_search_tool_result') {\n callbacks.onServerToolResult?.({\n toolUseId: block.tool_use_id,\n toolName: 'web_search',\n content: block.content,\n })\n }\n })\n }\n\n let response: Anthropic.Message\n try {\n response = await s.finalMessage()\n }\n catch (err) {\n if (!observedOutput && scrubPass < MAX_THINKING_SCRUB_PASSES && isRecoverableThinkingBlockError(err, requestParams.messages)) {\n const failingIndex = parseFailingMessageIndex(err)\n // Escalation ladder: the first pass scrubs only at/before the\n // API-reported failing index (preserving still-valid thinking\n // later in the wire). If the retry hits ANOTHER signature 400 —\n // the API reports one bad locator at a time, so scattered stale\n // blocks surface index-by-index — stop chasing locators and\n // scrub the full history EXCEPT the active chain. See\n // {@link planThinkingScrub} for the chain-protection rules\n // (never strip the in-flight exchange's thinking wholesale;\n // Anthropic requires it echoed back).\n const plan = planThinkingScrub(scrubPass, failingIndex, requestParams.messages)\n const scrubbed = withoutHistoricalThinking(requestParams.messages, plan.upToIndex, plan.alsoMessageIndex)\n // Guard against an infinite retry if Anthropic reports the same\n // error despite there being nothing left to strip (or if this is\n // already the scrubbed retry).\n if (scrubbed.removed > 0) {\n // Ask the loop to repair + persist its canonical history before\n // retrying. Direct provider consumers may omit the callback;\n // the scrubbed wire retry still succeeds for this turn.\n try {\n await callbacks.onHistoryRepair?.({\n type: 'invalid-anthropic-thinking-signature',\n ...(failingIndex !== undefined ? { wireMessageIndex: failingIndex } : {}),\n })\n }\n catch (repairErr) {\n // Canonical persistence is best-effort; never let a host\n // callback block the safe wire-level recovery for this turn.\n if (process.env.ZIDANE_DEBUG)\n process.stderr.write(`[zidane/anthropic] history repair callback failed: ${errorMessage(repairErr)}\\n`)\n }\n return await runStream(\n { ...requestParams, messages: scrubbed.messages },\n fastRequested,\n scrubPass + 1,\n )\n }\n }\n if (fastRequested && !observedOutput && shouldFallbackFromFastMode(err)) {\n const standardParams = { ...requestParams }\n delete standardParams.speed\n return await runStream(standardParams, false)\n }\n throw err\n }\n\n const toolCalls = response.content\n .filter((b): b is Anthropic.ToolUseBlock => b.type === 'tool_use')\n .map(b => ({ id: b.id, name: nameBoundary.fromWire(b.name), input: b.input as Record<string, unknown> }))\n\n const finishReason = mapStopReason(response.stop_reason)\n\n // `pause_turn` is *not* terminal — the loop has to inject a continue\n // message and run another turn. Without this branch, the previous\n // `toolCalls.length === 0` shortcut would mark the run done at the\n // pause and silently drop the work in flight.\n const isPause = response.stop_reason === 'pause_turn'\n\n const rawUsage: TurnUsage = {\n input: response.usage.input_tokens,\n output: response.usage.output_tokens,\n cacheCreation: response.usage.cache_creation_input_tokens ?? undefined,\n cacheRead: response.usage.cache_read_input_tokens ?? undefined,\n ...(finishReason ? { finishReason } : {}),\n modelId: response.model ?? (options.model as string),\n }\n // OAuth = subscription traffic (Claude Pro/Max via a Claude Code\n // account): usage is included in the flat plan, not billed per\n // token. Estimating API-list prices for it produces large dollar\n // figures the user never pays — so `cost` stays absent and cost\n // surfaces (footer counter, usage-by-model rows) show tokens\n // without a price, matching Claude Code's own /cost behavior.\n // API-key turns estimate as before; a mixed session (OAuth primary\n // with an API-key fallback, or vice versa) prices each turn by how\n // it was actually served.\n const usage = callIsOAuth\n ? rawUsage\n : await fillEstimatedCost(rawUsage, 'anthropic', fastRequested\n ? fastModeCostMultiplier(response.model ?? (options.model as string))\n : undefined)\n const assistantMessage = fromAnthropic({ role: 'assistant', content: response.content })\n // Restore caller-side names on persisted content so the outer loop's\n // own wire→canonical aliasing applies normally (mirrors openai.ts).\n if (nameBoundary.changed) {\n assistantMessage.content = assistantMessage.content.map(block =>\n block.type === 'tool_call' ? { ...block, name: nameBoundary.fromWire(block.name) } : block,\n )\n }\n return {\n assistantMessage,\n text,\n toolCalls,\n done: !isPause && (response.stop_reason === 'end_turn' || toolCalls.length === 0),\n usage,\n }\n }\n\n return await runStream(params, options.modelOptions?.fast === true)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,MAAa,mBAAgC;CAC3C,IAAI;CACJ,OAAO;CACP,aAAa;CACb,gBAAgB;EAAE,OAAO;EAAG,QAAQ;EAAG,WAAW;EAAG,YAAY;CAAE;AACr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AAO,MAAM,UAAU,QAAQ,QAAQ,cAAc,SAAS,IAAI;EACpE;CACF;AACF"}
@@ -1,11 +1,11 @@
1
1
  import { t as writeFileAtomic } from "./atomic-write-B7zr1ddF.js";
2
- import { f as ANTHROPIC_EXTRA_MODELS, n as anthropic, p as FAST_MODE_OPTIONS } from "./anthropic-BN0iPMox.js";
2
+ import { f as ANTHROPIC_EXTRA_MODELS, n as anthropic, p as FAST_MODE_OPTIONS } from "./anthropic-Bw39RApb.js";
3
3
  import { d as registerOAuthProvider, l as refreshAnthropicToken, u as refreshOpenAICodexToken } from "./oauth-CuFPhsHY.js";
4
4
  import { arcee } from "./providers/arcee.js";
5
5
  import { baseten } from "./providers/baseten.js";
6
6
  import { cerebras } from "./providers/cerebras.js";
7
- import { n as createXaiOAuthProvider, r as generatePkce, t as xai } from "./xai-BI4KgCGS.js";
8
- import { n as createCursorOAuthProvider } from "./providers-BlaXBUwd.js";
7
+ import { n as createXaiOAuthProvider, r as generatePkce, t as xai } from "./xai-DnZfHvTz.js";
8
+ import { n as createCursorOAuthProvider } from "./providers-BsH1MnhC.js";
9
9
  import { local } from "./providers/local.js";
10
10
  import { openai } from "./providers/openai.js";
11
11
  import { openrouter } from "./providers/openrouter.js";
@@ -1439,4 +1439,4 @@ function detectAuth(dataDir, registry, env = process.env) {
1439
1439
  //#endregion
1440
1440
  export { restoreModelOptions as C, piIdOf as S, modelOptionsFor as _, readProviderCredential as a, openaiDescriptor as b, writeCredentials as c, cerebrasDescriptor as d, credKeyOf as f, localDescriptor as g, getModelInfo as h, readCredentials as i, BUILTIN_PROVIDERS as l, getContextWindow as m, applyApiKeyEnv as n, removeProviderCredential as o, enabledModelOptions as p, credentialsPath as r, setProviderCredential as s, detectAuth as t, anthropicDescriptor as u, modelSupportsReasoning as v, renderDefaultCallbackPage as w, openrouterDescriptor as x, modelsForDescriptor as y };
1441
1441
 
1442
- //# sourceMappingURL=auth-Dptb8U5J.js.map
1442
+ //# sourceMappingURL=auth-XS60l6Q5.js.map