@anthropic-ai/sdk 0.125.0 → 0.126.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 (297) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/client.d.mts +2 -2
  3. package/client.d.mts.map +1 -1
  4. package/client.d.ts +2 -2
  5. package/client.d.ts.map +1 -1
  6. package/client.js +846 -840
  7. package/client.js.map +1 -1
  8. package/client.mjs +846 -834
  9. package/client.mjs.map +1 -1
  10. package/core/api-promise.js +71 -68
  11. package/core/api-promise.js.map +1 -1
  12. package/core/api-promise.mjs +71 -64
  13. package/core/api-promise.mjs.map +1 -1
  14. package/core/error.js +5 -2
  15. package/core/error.js.map +1 -1
  16. package/core/error.mjs +5 -2
  17. package/core/error.mjs.map +1 -1
  18. package/core/pagination.js +56 -50
  19. package/core/pagination.js.map +1 -1
  20. package/core/pagination.mjs +56 -41
  21. package/core/pagination.mjs.map +1 -1
  22. package/core/streaming.js +212 -209
  23. package/core/streaming.js.map +1 -1
  24. package/core/streaming.mjs +212 -209
  25. package/core/streaming.mjs.map +1 -1
  26. package/helpers/beta/mcp.js +14 -19
  27. package/helpers/beta/mcp.js.map +1 -1
  28. package/helpers/beta/mcp.mjs +14 -13
  29. package/helpers/beta/mcp.mjs.map +1 -1
  30. package/internal/constants.js +1 -1
  31. package/internal/constants.js.map +1 -1
  32. package/internal/decoders/jsonl.js +27 -24
  33. package/internal/decoders/jsonl.js.map +1 -1
  34. package/internal/decoders/jsonl.mjs +27 -24
  35. package/internal/decoders/jsonl.mjs.map +1 -1
  36. package/internal/decoders/line.js +52 -49
  37. package/internal/decoders/line.js.map +1 -1
  38. package/internal/decoders/line.mjs +52 -43
  39. package/internal/decoders/line.mjs.map +1 -1
  40. package/internal/file-store.js +256 -258
  41. package/internal/file-store.js.map +1 -1
  42. package/internal/file-store.mjs +256 -243
  43. package/internal/file-store.mjs.map +1 -1
  44. package/internal/node.browser.d.mts.map +1 -1
  45. package/internal/node.browser.d.ts.map +1 -1
  46. package/internal/node.browser.js.map +1 -1
  47. package/internal/node.browser.mjs +7 -7
  48. package/internal/node.browser.mjs.map +1 -1
  49. package/internal/shim-types.js +0 -6
  50. package/internal/shim-types.js.map +1 -1
  51. package/internal/shim-types.mjs +0 -6
  52. package/internal/shim-types.mjs.map +1 -1
  53. package/internal/shims.js +0 -6
  54. package/internal/shims.js.map +1 -1
  55. package/internal/shims.mjs +0 -6
  56. package/internal/shims.mjs.map +1 -1
  57. package/internal/stainless-helper-header.js +6 -6
  58. package/internal/stainless-helper-header.js.map +1 -1
  59. package/internal/utils/async-queue.js +66 -63
  60. package/internal/utils/async-queue.js.map +1 -1
  61. package/internal/utils/async-queue.mjs +66 -56
  62. package/internal/utils/async-queue.mjs.map +1 -1
  63. package/internal/utils/bytes.d.mts +1 -1
  64. package/internal/utils/bytes.d.mts.map +1 -1
  65. package/internal/utils/bytes.d.ts +1 -1
  66. package/internal/utils/bytes.d.ts.map +1 -1
  67. package/lib/BetaMessageStream.js +593 -590
  68. package/lib/BetaMessageStream.js.map +1 -1
  69. package/lib/BetaMessageStream.mjs +593 -590
  70. package/lib/BetaMessageStream.mjs.map +1 -1
  71. package/lib/MessageStream.js +544 -541
  72. package/lib/MessageStream.js.map +1 -1
  73. package/lib/MessageStream.mjs +544 -541
  74. package/lib/MessageStream.mjs.map +1 -1
  75. package/lib/environments/poller.js +180 -174
  76. package/lib/environments/poller.js.map +1 -1
  77. package/lib/environments/poller.mjs +180 -153
  78. package/lib/environments/poller.mjs.map +1 -1
  79. package/lib/environments/worker.js +375 -369
  80. package/lib/environments/worker.js.map +1 -1
  81. package/lib/environments/worker.mjs +374 -329
  82. package/lib/environments/worker.mjs.map +1 -1
  83. package/lib/tools/BetaToolRunner.js +316 -313
  84. package/lib/tools/BetaToolRunner.js.map +1 -1
  85. package/lib/tools/BetaToolRunner.mjs +315 -306
  86. package/lib/tools/BetaToolRunner.mjs.map +1 -1
  87. package/lib/tools/SessionToolRunner.js +241 -235
  88. package/lib/tools/SessionToolRunner.js.map +1 -1
  89. package/lib/tools/SessionToolRunner.mjs +241 -192
  90. package/lib/tools/SessionToolRunner.mjs.map +1 -1
  91. package/lib/tools/ToolError.js +39 -36
  92. package/lib/tools/ToolError.js.map +1 -1
  93. package/lib/tools/ToolError.mjs +39 -13
  94. package/lib/tools/ToolError.mjs.map +1 -1
  95. package/package.json +3 -3
  96. package/resources/beta/agents/agents.js +135 -132
  97. package/resources/beta/agents/agents.js.map +1 -1
  98. package/resources/beta/agents/agents.mjs +135 -132
  99. package/resources/beta/agents/agents.mjs.map +1 -1
  100. package/resources/beta/beta.d.mts +5 -5
  101. package/resources/beta/beta.d.mts.map +1 -1
  102. package/resources/beta/beta.d.ts +5 -5
  103. package/resources/beta/beta.d.ts.map +1 -1
  104. package/resources/beta/beta.js +39 -36
  105. package/resources/beta/beta.js.map +1 -1
  106. package/resources/beta/beta.mjs +39 -36
  107. package/resources/beta/beta.mjs.map +1 -1
  108. package/resources/beta/dreams.d.mts +2 -28
  109. package/resources/beta/dreams.d.mts.map +1 -1
  110. package/resources/beta/dreams.d.ts +2 -28
  111. package/resources/beta/dreams.d.ts.map +1 -1
  112. package/resources/beta/environments/environments.js +157 -154
  113. package/resources/beta/environments/environments.js.map +1 -1
  114. package/resources/beta/environments/environments.mjs +157 -154
  115. package/resources/beta/environments/environments.mjs.map +1 -1
  116. package/resources/beta/environments/work.js +255 -252
  117. package/resources/beta/environments/work.js.map +1 -1
  118. package/resources/beta/environments/work.mjs +255 -252
  119. package/resources/beta/environments/work.mjs.map +1 -1
  120. package/resources/beta/index.d.mts +2 -2
  121. package/resources/beta/index.d.mts.map +1 -1
  122. package/resources/beta/index.d.ts +2 -2
  123. package/resources/beta/index.d.ts.map +1 -1
  124. package/resources/beta/index.js.map +1 -1
  125. package/resources/beta/index.mjs.map +1 -1
  126. package/resources/beta/memory-stores/memory-stores.js +150 -147
  127. package/resources/beta/memory-stores/memory-stores.js.map +1 -1
  128. package/resources/beta/memory-stores/memory-stores.mjs +150 -147
  129. package/resources/beta/memory-stores/memory-stores.mjs.map +1 -1
  130. package/resources/beta/messages/batches.d.mts +12 -1
  131. package/resources/beta/messages/batches.d.mts.map +1 -1
  132. package/resources/beta/messages/batches.d.ts +12 -1
  133. package/resources/beta/messages/batches.d.ts.map +1 -1
  134. package/resources/beta/messages/index.d.mts +1 -1
  135. package/resources/beta/messages/index.d.mts.map +1 -1
  136. package/resources/beta/messages/index.d.ts +1 -1
  137. package/resources/beta/messages/index.d.ts.map +1 -1
  138. package/resources/beta/messages/index.js.map +1 -1
  139. package/resources/beta/messages/index.mjs.map +1 -1
  140. package/resources/beta/messages/messages.d.mts +238 -100
  141. package/resources/beta/messages/messages.d.mts.map +1 -1
  142. package/resources/beta/messages/messages.d.ts +238 -100
  143. package/resources/beta/messages/messages.d.ts.map +1 -1
  144. package/resources/beta/messages/messages.js +113 -110
  145. package/resources/beta/messages/messages.js.map +1 -1
  146. package/resources/beta/messages/messages.mjs +113 -110
  147. package/resources/beta/messages/messages.mjs.map +1 -1
  148. package/resources/beta/models.d.mts +22 -1
  149. package/resources/beta/models.d.mts.map +1 -1
  150. package/resources/beta/models.d.ts +22 -1
  151. package/resources/beta/models.d.ts.map +1 -1
  152. package/resources/beta/organization/federation/federation.js +11 -8
  153. package/resources/beta/organization/federation/federation.js.map +1 -1
  154. package/resources/beta/organization/federation/federation.mjs +11 -8
  155. package/resources/beta/organization/federation/federation.mjs.map +1 -1
  156. package/resources/beta/organization/federation/rules/rules.js +187 -184
  157. package/resources/beta/organization/federation/rules/rules.js.map +1 -1
  158. package/resources/beta/organization/federation/rules/rules.mjs +187 -184
  159. package/resources/beta/organization/federation/rules/rules.mjs.map +1 -1
  160. package/resources/beta/organization/organization.js +38 -35
  161. package/resources/beta/organization/organization.js.map +1 -1
  162. package/resources/beta/organization/organization.mjs +38 -35
  163. package/resources/beta/organization/organization.mjs.map +1 -1
  164. package/resources/beta/organization/service-accounts/service-accounts.js +163 -160
  165. package/resources/beta/organization/service-accounts/service-accounts.js.map +1 -1
  166. package/resources/beta/organization/service-accounts/service-accounts.mjs +163 -160
  167. package/resources/beta/organization/service-accounts/service-accounts.mjs.map +1 -1
  168. package/resources/beta/organization/workspaces/workspaces.d.mts +3 -3
  169. package/resources/beta/organization/workspaces/workspaces.d.mts.map +1 -1
  170. package/resources/beta/organization/workspaces/workspaces.d.ts +3 -3
  171. package/resources/beta/organization/workspaces/workspaces.d.ts.map +1 -1
  172. package/resources/beta/organization/workspaces/workspaces.js +97 -94
  173. package/resources/beta/organization/workspaces/workspaces.js.map +1 -1
  174. package/resources/beta/organization/workspaces/workspaces.mjs +97 -94
  175. package/resources/beta/organization/workspaces/workspaces.mjs.map +1 -1
  176. package/resources/beta/sessions/events.d.mts +12 -21
  177. package/resources/beta/sessions/events.d.mts.map +1 -1
  178. package/resources/beta/sessions/events.d.ts +12 -21
  179. package/resources/beta/sessions/events.d.ts.map +1 -1
  180. package/resources/beta/sessions/events.js +118 -115
  181. package/resources/beta/sessions/events.js.map +1 -1
  182. package/resources/beta/sessions/events.mjs +118 -115
  183. package/resources/beta/sessions/events.mjs.map +1 -1
  184. package/resources/beta/sessions/resources.d.mts +0 -3
  185. package/resources/beta/sessions/resources.d.mts.map +1 -1
  186. package/resources/beta/sessions/resources.d.ts +0 -3
  187. package/resources/beta/sessions/resources.d.ts.map +1 -1
  188. package/resources/beta/sessions/sessions.d.mts +2 -2
  189. package/resources/beta/sessions/sessions.d.ts +2 -2
  190. package/resources/beta/sessions/sessions.js +161 -158
  191. package/resources/beta/sessions/sessions.js.map +1 -1
  192. package/resources/beta/sessions/sessions.mjs +161 -158
  193. package/resources/beta/sessions/sessions.mjs.map +1 -1
  194. package/resources/beta/sessions/threads/threads.js +86 -83
  195. package/resources/beta/sessions/threads/threads.js.map +1 -1
  196. package/resources/beta/sessions/threads/threads.mjs +86 -83
  197. package/resources/beta/sessions/threads/threads.mjs.map +1 -1
  198. package/resources/beta/skills/skills.js +104 -101
  199. package/resources/beta/skills/skills.js.map +1 -1
  200. package/resources/beta/skills/skills.mjs +104 -101
  201. package/resources/beta/skills/skills.mjs.map +1 -1
  202. package/resources/beta/tunnels/tunnels.js +188 -185
  203. package/resources/beta/tunnels/tunnels.js.map +1 -1
  204. package/resources/beta/tunnels/tunnels.mjs +188 -185
  205. package/resources/beta/tunnels/tunnels.mjs.map +1 -1
  206. package/resources/beta/user-profiles.d.mts +45 -0
  207. package/resources/beta/user-profiles.d.mts.map +1 -1
  208. package/resources/beta/user-profiles.d.ts +45 -0
  209. package/resources/beta/user-profiles.d.ts.map +1 -1
  210. package/resources/beta/user-profiles.js +25 -10
  211. package/resources/beta/user-profiles.js.map +1 -1
  212. package/resources/beta/user-profiles.mjs +25 -10
  213. package/resources/beta/user-profiles.mjs.map +1 -1
  214. package/resources/beta/vaults/credentials.d.mts +0 -14
  215. package/resources/beta/vaults/credentials.d.mts.map +1 -1
  216. package/resources/beta/vaults/credentials.d.ts +0 -14
  217. package/resources/beta/vaults/credentials.d.ts.map +1 -1
  218. package/resources/beta/vaults/vaults.js +156 -153
  219. package/resources/beta/vaults/vaults.js.map +1 -1
  220. package/resources/beta/vaults/vaults.mjs +156 -153
  221. package/resources/beta/vaults/vaults.mjs.map +1 -1
  222. package/resources/completions.d.mts +1 -1
  223. package/resources/completions.d.ts +1 -1
  224. package/resources/index.d.mts +1 -1
  225. package/resources/index.d.mts.map +1 -1
  226. package/resources/index.d.ts +1 -1
  227. package/resources/index.d.ts.map +1 -1
  228. package/resources/index.js.map +1 -1
  229. package/resources/index.mjs.map +1 -1
  230. package/resources/messages/index.d.mts +1 -1
  231. package/resources/messages/index.d.mts.map +1 -1
  232. package/resources/messages/index.d.ts +1 -1
  233. package/resources/messages/index.d.ts.map +1 -1
  234. package/resources/messages/index.js.map +1 -1
  235. package/resources/messages/index.mjs.map +1 -1
  236. package/resources/messages/messages.d.mts +100 -63
  237. package/resources/messages/messages.d.mts.map +1 -1
  238. package/resources/messages/messages.d.ts +100 -63
  239. package/resources/messages/messages.d.ts.map +1 -1
  240. package/resources/messages/messages.js +115 -112
  241. package/resources/messages/messages.js.map +1 -1
  242. package/resources/messages/messages.mjs +115 -112
  243. package/resources/messages/messages.mjs.map +1 -1
  244. package/resources/skills/skills.js +88 -85
  245. package/resources/skills/skills.js.map +1 -1
  246. package/resources/skills/skills.mjs +88 -85
  247. package/resources/skills/skills.mjs.map +1 -1
  248. package/resources/top-level.js +0 -1
  249. package/resources/top-level.js.map +1 -1
  250. package/resources/top-level.mjs +0 -1
  251. package/resources/top-level.mjs.map +1 -1
  252. package/src/client.ts +13 -1
  253. package/src/internal/node.browser.ts +7 -7
  254. package/src/internal/utils/bytes.ts +1 -1
  255. package/src/resources/beta/beta.ts +24 -1
  256. package/src/resources/beta/dreams.ts +2 -28
  257. package/src/resources/beta/index.ts +11 -0
  258. package/src/resources/beta/messages/batches.ts +13 -1
  259. package/src/resources/beta/messages/index.ts +10 -0
  260. package/src/resources/beta/messages/messages.ts +288 -99
  261. package/src/resources/beta/models.ts +25 -0
  262. package/src/resources/beta/organization/workspaces/workspaces.ts +3 -3
  263. package/src/resources/beta/sessions/events.ts +12 -21
  264. package/src/resources/beta/sessions/resources.ts +0 -3
  265. package/src/resources/beta/sessions/sessions.ts +2 -2
  266. package/src/resources/beta/user-profiles.ts +75 -10
  267. package/src/resources/beta/vaults/credentials.ts +0 -14
  268. package/src/resources/completions.ts +1 -1
  269. package/src/resources/index.ts +6 -0
  270. package/src/resources/messages/index.ts +6 -0
  271. package/src/resources/messages/messages.ts +128 -62
  272. package/src/tsconfig.json +13 -3
  273. package/src/version.ts +1 -1
  274. package/tools/agent-toolset/fs-util.js +0 -6
  275. package/tools/agent-toolset/fs-util.js.map +1 -1
  276. package/tools/agent-toolset/fs-util.mjs +0 -6
  277. package/tools/agent-toolset/fs-util.mjs.map +1 -1
  278. package/tools/agent-toolset/memories.js +4 -4
  279. package/tools/agent-toolset/memories.js.map +1 -1
  280. package/tools/agent-toolset/memories.mjs +2 -2
  281. package/tools/agent-toolset/memories.mjs.map +1 -1
  282. package/tools/agent-toolset/node.browser.js +12 -12
  283. package/tools/agent-toolset/node.browser.js.map +1 -1
  284. package/tools/agent-toolset/node.js +142 -139
  285. package/tools/agent-toolset/node.js.map +1 -1
  286. package/tools/agent-toolset/node.mjs +132 -125
  287. package/tools/agent-toolset/node.mjs.map +1 -1
  288. package/tools/agent-toolset/skills.js +5 -5
  289. package/tools/agent-toolset/skills.js.map +1 -1
  290. package/tools/agent-toolset/sync-interval.js +3 -3
  291. package/tools/agent-toolset/sync-interval.js.map +1 -1
  292. package/tools/memory/node.browser.js +2 -2
  293. package/tools/memory/node.browser.js.map +1 -1
  294. package/version.d.mts +1 -1
  295. package/version.d.ts +1 -1
  296. package/version.js +1 -1
  297. package/version.mjs +1 -1
package/client.js CHANGED
@@ -34,896 +34,902 @@ const log_1 = require("./internal/utils/log.js");
34
34
  const values_2 = require("./internal/utils/values.js");
35
35
  exports.HUMAN_PROMPT = '\\n\\nHuman:';
36
36
  exports.AI_PROMPT = '\\n\\nAssistant:';
37
- /**
38
- * Base class for Anthropic API clients.
39
- */
40
- class BaseAnthropic {
37
+ var BaseAnthropic = /* @__PURE__ */ (() => {
41
38
  /**
42
- * The active credential provider. Default credential resolution runs once
43
- * at construction time. If it fails, the error is surfaced on every
44
- * request and the client must be reconstructed — there is no retry path.
45
- *
46
- * Clones returned by {@link withOptions} share the parent's auth state
47
- * (provider, token cache, pending resolution, and any resolution error)
48
- * unless the caller passes an explicit `apiKey`, `authToken`,
49
- * `credentials`, `config`, or `profile` override.
39
+ * Base class for Anthropic API clients.
50
40
  */
51
- get credentials() {
52
- return this._authState.provider;
53
- }
54
- /**
55
- * API Client for interfacing with the Anthropic API.
56
- *
57
- * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
58
- * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
59
- * @param {string | null | undefined} [opts.webhookKey=process.env['ANTHROPIC_WEBHOOK_SIGNING_KEY'] ?? null]
60
- * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
61
- * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
62
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
63
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
64
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
65
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
66
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
67
- * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
68
- */
69
- constructor({ baseURL = (0, env_1.readEnv)('ANTHROPIC_BASE_URL'), apiKey, authToken, webhookKey = (0, env_1.readEnv)('ANTHROPIC_WEBHOOK_SIGNING_KEY') ?? null, ...opts } = {}) {
70
- _BaseAnthropic_instances.add(this);
71
- this._requestAuthFlags = new WeakMap();
72
- _BaseAnthropic_encoder.set(this, void 0);
73
- // An explicit `profile` is a constructor-level credential choice; when set,
74
- // do not let env ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN shadow it.
75
- if (apiKey === undefined) {
76
- apiKey = opts.profile != null ? null : (0, env_1.readEnv)('ANTHROPIC_API_KEY') ?? null;
77
- }
78
- if (authToken === undefined) {
79
- authToken = opts.profile != null ? null : (0, env_1.readEnv)('ANTHROPIC_AUTH_TOKEN') ?? null;
80
- }
81
- if (opts.profile != null && (opts.credentials != null || opts.config != null)) {
82
- throw new TypeError('Pass at most one of `profile`, `credentials`, or `config`.');
83
- }
84
- const options = {
85
- apiKey,
86
- authToken,
87
- webhookKey,
88
- ...opts,
89
- baseURL: baseURL || `https://api.anthropic.com`,
90
- };
91
- if (!options.dangerouslyAllowBrowser && (0, detect_platform_2.isRunningInBrowser)()) {
92
- throw new Errors.AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
93
- }
94
- this.baseURL = options.baseURL;
95
- // After destructuring, `baseURL` is the constructor arg or
96
- // ANTHROPIC_BASE_URL — both count as an explicit choice that a profile
97
- // base_url must not override. A falsy value means we fell through to the
98
- // hardcoded default above and a profile may supply the host. withOptions()
99
- // propagates the parent's flag via __baseURLIsExplicit so a non-overriding
100
- // clone doesn't mistake the inherited baseURL for a caller-supplied one.
101
- this._baseURLIsExplicit = opts.__baseURLIsExplicit ?? !!baseURL;
102
- this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
103
- this.logger = options.logger ?? console;
104
- // Set default logLevel early so that we can log a warning in parseLogLevel.
105
- this.logLevel = log_1.defaultLogLevel;
106
- this.logLevel =
107
- (0, log_1.parseLogLevel)(options.logLevel, 'ClientOptions.logLevel', (0, log_1.loggerFor)(this)) ??
108
- (0, log_1.parseLogLevel)((0, env_1.readEnv)('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", (0, log_1.loggerFor)(this)) ??
109
- log_1.defaultLogLevel;
110
- this.fetchOptions = options.fetchOptions;
111
- this.maxRetries = (0, values_1.validatePositiveInteger)('maxRetries', options.maxRetries ?? 2);
112
- this.fetch = options.fetch ?? Shims.getDefaultFetch();
113
- tslib_1.__classPrivateFieldSet(this, _BaseAnthropic_encoder, Opts.FallbackEncoder, "f");
114
- this.middleware = [...(options.middleware ?? [])];
115
- const customHeadersEnv = (0, env_1.readEnv)('ANTHROPIC_CUSTOM_HEADERS');
116
- if (customHeadersEnv) {
117
- const parsed = {};
118
- for (const line of customHeadersEnv.split('\n')) {
119
- const colon = line.indexOf(':');
120
- if (colon >= 0) {
121
- parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
41
+ class BaseAnthropic {
42
+ /**
43
+ * The active credential provider. Default credential resolution runs once
44
+ * at construction time. If it fails, the error is surfaced on every
45
+ * request and the client must be reconstructed — there is no retry path.
46
+ *
47
+ * Clones returned by {@link withOptions} share the parent's auth state
48
+ * (provider, token cache, pending resolution, and any resolution error)
49
+ * unless the caller passes an explicit `apiKey`, `authToken`,
50
+ * `credentials`, `config`, or `profile` override.
51
+ */
52
+ get credentials() {
53
+ return this._authState.provider;
54
+ }
55
+ /**
56
+ * API Client for interfacing with the Anthropic API.
57
+ *
58
+ * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
59
+ * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
60
+ * @param {string | null | undefined} [opts.webhookKey=process.env['ANTHROPIC_WEBHOOK_SIGNING_KEY'] ?? null]
61
+ * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
62
+ * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
63
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
64
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
65
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
66
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
67
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
68
+ * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
69
+ */
70
+ constructor({ baseURL = (0, env_1.readEnv)('ANTHROPIC_BASE_URL'), apiKey, authToken, webhookKey = (0, env_1.readEnv)('ANTHROPIC_WEBHOOK_SIGNING_KEY') ?? null, ...opts } = {}) {
71
+ _BaseAnthropic_instances.add(this);
72
+ this._requestAuthFlags = new WeakMap();
73
+ _BaseAnthropic_encoder.set(this, void 0);
74
+ // An explicit `profile` is a constructor-level credential choice; when set,
75
+ // do not let env ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN shadow it.
76
+ if (apiKey === undefined) {
77
+ apiKey = opts.profile != null ? null : (0, env_1.readEnv)('ANTHROPIC_API_KEY') ?? null;
78
+ }
79
+ if (authToken === undefined) {
80
+ authToken = opts.profile != null ? null : (0, env_1.readEnv)('ANTHROPIC_AUTH_TOKEN') ?? null;
81
+ }
82
+ if (opts.profile != null && (opts.credentials != null || opts.config != null)) {
83
+ throw new TypeError('Pass at most one of `profile`, `credentials`, or `config`.');
84
+ }
85
+ const options = {
86
+ apiKey,
87
+ authToken,
88
+ webhookKey,
89
+ ...opts,
90
+ baseURL: baseURL || `https://api.anthropic.com`,
91
+ };
92
+ if (!options.dangerouslyAllowBrowser && (0, detect_platform_2.isRunningInBrowser)()) {
93
+ throw new Errors.AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
94
+ }
95
+ this.baseURL = options.baseURL;
96
+ // After destructuring, `baseURL` is the constructor arg or
97
+ // ANTHROPIC_BASE_URL both count as an explicit choice that a profile
98
+ // base_url must not override. A falsy value means we fell through to the
99
+ // hardcoded default above and a profile may supply the host. withOptions()
100
+ // propagates the parent's flag via __baseURLIsExplicit so a non-overriding
101
+ // clone doesn't mistake the inherited baseURL for a caller-supplied one.
102
+ this._baseURLIsExplicit = opts.__baseURLIsExplicit ?? !!baseURL;
103
+ this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
104
+ this.logger = options.logger ?? console;
105
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
106
+ this.logLevel = log_1.defaultLogLevel;
107
+ this.logLevel =
108
+ (0, log_1.parseLogLevel)(options.logLevel, 'ClientOptions.logLevel', (0, log_1.loggerFor)(this)) ??
109
+ (0, log_1.parseLogLevel)((0, env_1.readEnv)('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", (0, log_1.loggerFor)(this)) ??
110
+ log_1.defaultLogLevel;
111
+ this.fetchOptions = options.fetchOptions;
112
+ this.maxRetries = (0, values_1.validatePositiveInteger)('maxRetries', options.maxRetries ?? 2);
113
+ this.fetch = options.fetch ?? Shims.getDefaultFetch();
114
+ tslib_1.__classPrivateFieldSet(this, _BaseAnthropic_encoder, Opts.FallbackEncoder, "f");
115
+ this.middleware = [...(options.middleware ?? [])];
116
+ const customHeadersEnv = (0, env_1.readEnv)('ANTHROPIC_CUSTOM_HEADERS');
117
+ if (customHeadersEnv) {
118
+ const parsed = {};
119
+ for (const line of customHeadersEnv.split('\n')) {
120
+ const colon = line.indexOf(':');
121
+ if (colon >= 0) {
122
+ parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
123
+ }
124
+ }
125
+ options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
126
+ }
127
+ const inherited = opts.__auth;
128
+ // Never persist the internal __auth handle on _options — it's a
129
+ // one-shot constructor signal, and leaking it through _options would
130
+ // cause withOptions() to spread a stale value into clones.
131
+ delete options.__auth;
132
+ delete options.__baseURLIsExplicit;
133
+ this._options = options;
134
+ this.apiKey = typeof apiKey === 'string' ? apiKey : null;
135
+ this.authToken = authToken;
136
+ this.webhookKey = webhookKey;
137
+ if (inherited) {
138
+ this._authState = inherited;
139
+ if (!this._baseURLIsExplicit && inherited.baseURL) {
140
+ this.baseURL = inherited.baseURL;
122
141
  }
123
142
  }
124
- options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
125
- }
126
- const inherited = opts.__auth;
127
- // Never persist the internal __auth handle on _options it's a
128
- // one-shot constructor signal, and leaking it through _options would
129
- // cause withOptions() to spread a stale value into clones.
130
- delete options.__auth;
131
- delete options.__baseURLIsExplicit;
132
- this._options = options;
133
- this.apiKey = typeof apiKey === 'string' ? apiKey : null;
134
- this.authToken = authToken;
135
- this.webhookKey = webhookKey;
136
- if (inherited) {
137
- this._authState = inherited;
138
- if (!this._baseURLIsExplicit && inherited.baseURL) {
139
- this.baseURL = inherited.baseURL;
140
- }
141
- }
142
- else {
143
- this._authState = { provider: null, tokenCache: null, resolution: null, error: null, extraHeaders: {} };
144
- // apiKey/authToken win over credentials/config/profile; don't build a
145
- // token cache or resolve a config that the request path will then ignore.
146
- if (this.apiKey == null && this.authToken == null) {
147
- const credentials = options.credentials ?? null;
148
- if (credentials) {
149
- this._authState.provider = credentials;
150
- this._authState.tokenCache = this._makeTokenCache(credentials);
143
+ else {
144
+ this._authState = { provider: null, tokenCache: null, resolution: null, error: null, extraHeaders: {} };
145
+ // apiKey/authToken win over credentials/config/profile; don't build a
146
+ // token cache or resolve a config that the request path will then ignore.
147
+ if (this.apiKey == null && this.authToken == null) {
148
+ const credentials = options.credentials ?? null;
149
+ if (credentials) {
150
+ this._authState.provider = credentials;
151
+ this._authState.tokenCache = this._makeTokenCache(credentials);
152
+ }
153
+ else if (options.config != null) {
154
+ const result = (0, credential_chain_1.resolveCredentialsFromConfig)(options.config, this._credentialResolverOptions());
155
+ this._authState.provider = result.provider;
156
+ this._authState.tokenCache = this._makeTokenCache(result.provider);
157
+ this._authState.extraHeaders = result.extraHeaders;
158
+ this._applyCredentialBaseURL(result.baseURL);
159
+ }
160
+ else if (options.profile != null) {
161
+ this._authState.resolution = this._resolveDefaultCredentials(options.profile);
162
+ }
163
+ else if (this._shouldResolveDefaultCredentials()) {
164
+ // No explicit auth provided lazily resolve from the credential
165
+ // chain on first request. Errors are captured into _auth.error and
166
+ // surfaced on first use rather than as an unhandled rejection.
167
+ this._authState.resolution = this._resolveDefaultCredentials();
168
+ }
151
169
  }
152
- else if (options.config != null) {
153
- const result = (0, credential_chain_1.resolveCredentialsFromConfig)(options.config, this._credentialResolverOptions());
170
+ }
171
+ }
172
+ /**
173
+ * Whether to lazily resolve auth from the default credential chain when no
174
+ * explicit auth is configured. Called once from the constructor, so
175
+ * overrides must not depend on subclass instance state. Subclasses that
176
+ * bring their own auth scheme return false so unrelated local credentials
177
+ * are never resolved or allowed to supply a base URL.
178
+ */
179
+ _shouldResolveDefaultCredentials() {
180
+ return true;
181
+ }
182
+ /**
183
+ * Stores a profile/config-supplied base URL on the shared auth state and, if
184
+ * the caller did not pin `baseURL` via constructor option or env, adopts it
185
+ * as this client's outbound API host. Precedence: ctor opt > env > profile >
186
+ * hardcoded default.
187
+ */
188
+ _applyCredentialBaseURL(baseURL) {
189
+ if (!baseURL)
190
+ return;
191
+ const normalized = baseURL.replace(/\/+$/, '');
192
+ this._authState.baseURL = normalized;
193
+ if (!this._baseURLIsExplicit) {
194
+ this.baseURL = normalized;
195
+ }
196
+ }
197
+ /**
198
+ * Options bag passed into the credential chain. `baseURL` here is only the
199
+ * fallback host for the token-exchange POST when the config itself omits
200
+ * `base_url`; the chain returns the config's own `base_url` (if any) on
201
+ * {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL}
202
+ * then adopts for outbound API requests. The two are deliberately decoupled
203
+ * so this fallback never round-trips into precedence.
204
+ */
205
+ _credentialResolverOptions() {
206
+ return {
207
+ baseURL: this.baseURL,
208
+ fetch: this._credentialsFetch(),
209
+ userAgent: this.getUserAgent(),
210
+ onCacheWriteError: (err) => {
211
+ (0, log_1.loggerFor)(this).debug('credential cache write failed (best-effort)', err);
212
+ },
213
+ onSafetyWarning: (msg) => {
214
+ (0, log_1.loggerFor)(this).warn(msg);
215
+ },
216
+ };
217
+ }
218
+ /**
219
+ * A `Fetch` for first-party credential token-exchange requests (OIDC
220
+ * federation jwt-bearer grants, user-OAuth refresh grants) that routes
221
+ * through this client's middleware chain, so middleware observes token
222
+ * traffic like any other request. Only client-level middleware applies:
223
+ * a minted token is shared across requests, so attributing the exchange
224
+ * to any one request's per-request middleware would be arbitrary. For the
225
+ * same reason, `ctx.options` is undefined for these requests.
226
+ */
227
+ _credentialsFetch() {
228
+ return (0, middleware_1.wrapFetchWithMiddleware)(this.fetch, this.middleware, undefined, this);
229
+ }
230
+ _makeTokenCache(provider) {
231
+ return new token_cache_1.TokenCache(provider, (err) => {
232
+ (0, log_1.loggerFor)(this).debug('advisory token refresh failed; serving cached token', err);
233
+ });
234
+ }
235
+ /**
236
+ * Create a new client instance re-using the same options given to the
237
+ * current client with optional overriding.
238
+ */
239
+ withOptions(options) {
240
+ // Share the auth state object unless the caller passes any auth-related
241
+ // key. The `in` check is intentional: even `apiKey: undefined` opts the
242
+ // clone out of sharing (it gets its own _auth and TokenCache, though it
243
+ // may still wrap the parent's provider via the credentials spread below).
244
+ const overridesStructuredAuth = 'credentials' in options || 'config' in options || 'profile' in options;
245
+ const overridesAuth = 'apiKey' in options || 'authToken' in options || overridesStructuredAuth;
246
+ const internal = {
247
+ ...this._options,
248
+ // Only forward baseURL when the caller (or env) explicitly chose it.
249
+ // For a non-explicit parent, this.baseURL may have been mutated to the
250
+ // profile-resolved host; pinning that as the clone's options.baseURL
251
+ // would make _options on the clone misreport caller intent and would
252
+ // leave the clone stuck on the parent's host across an auth override.
253
+ // The clone instead receives the construction-time value via
254
+ // ...this._options above and re-adopts the profile host through the
255
+ // shared _authState.baseURL + __baseURLIsExplicit=false path.
256
+ ...(this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}),
257
+ maxRetries: this.maxRetries,
258
+ timeout: this.timeout,
259
+ logger: this.logger,
260
+ logLevel: this.logLevel,
261
+ fetch: this.fetch,
262
+ fetchOptions: this.fetchOptions,
263
+ middleware: this.middleware,
264
+ apiKey: this.apiKey,
265
+ authToken: this.authToken,
266
+ webhookKey: this.webhookKey,
267
+ // credentials: this.credentials is a no-op when __auth is shared (the
268
+ // ctor takes the inherited path and ignores options.credentials); when
269
+ // overridesAuth is true via apiKey/authToken only, it lets the clone
270
+ // build a fresh TokenCache around the parent's provider.
271
+ credentials: this.credentials,
272
+ // When the caller passes a structured-credential override, drop inherited
273
+ // structured-credential options so only `...options` supplies them —
274
+ // otherwise an inherited `credentials`/`config`/`profile` would trip the
275
+ // mutual-exclusion check or precedence over the override.
276
+ ...(overridesStructuredAuth ? { credentials: undefined, config: undefined, profile: undefined } : {}),
277
+ ...options,
278
+ // Always set __auth so any stale value from ...this._options is
279
+ // overwritten. undefined means "build fresh auth from these options".
280
+ __auth: overridesAuth ? undefined : this._authState,
281
+ __baseURLIsExplicit: 'baseURL' in options ? true : this._baseURLIsExplicit,
282
+ };
283
+ return new this.constructor(internal);
284
+ }
285
+ /**
286
+ * Lazily resolves credentials from config files or environment variables.
287
+ * Called once from the constructor when no explicit auth is provided, or
288
+ * when an explicit `profile` was passed (in which case a missing/unresolved
289
+ * profile is surfaced as an error instead of falling through to "no auth").
290
+ * The returned promise is stored and awaited on the first request.
291
+ */
292
+ async _resolveDefaultCredentials(profile) {
293
+ try {
294
+ const result = await (0, credential_chain_1.defaultCredentials)(this._credentialResolverOptions(), profile);
295
+ if (result) {
154
296
  this._authState.provider = result.provider;
155
297
  this._authState.tokenCache = this._makeTokenCache(result.provider);
156
298
  this._authState.extraHeaders = result.extraHeaders;
157
299
  this._applyCredentialBaseURL(result.baseURL);
158
300
  }
159
- else if (options.profile != null) {
160
- this._authState.resolution = this._resolveDefaultCredentials(options.profile);
161
- }
162
- else if (this._shouldResolveDefaultCredentials()) {
163
- // No explicit auth provided — lazily resolve from the credential
164
- // chain on first request. Errors are captured into _auth.error and
165
- // surfaced on first use rather than as an unhandled rejection.
166
- this._authState.resolution = this._resolveDefaultCredentials();
301
+ else if (profile != null) {
302
+ throw new Errors.AnthropicError(`Profile "${profile}" could not be resolved (no <config_dir>/configs/${profile}.json found).`);
167
303
  }
168
304
  }
169
- }
170
- }
171
- /**
172
- * Whether to lazily resolve auth from the default credential chain when no
173
- * explicit auth is configured. Called once from the constructor, so
174
- * overrides must not depend on subclass instance state. Subclasses that
175
- * bring their own auth scheme return false so unrelated local credentials
176
- * are never resolved or allowed to supply a base URL.
177
- */
178
- _shouldResolveDefaultCredentials() {
179
- return true;
180
- }
181
- /**
182
- * Stores a profile/config-supplied base URL on the shared auth state and, if
183
- * the caller did not pin `baseURL` via constructor option or env, adopts it
184
- * as this client's outbound API host. Precedence: ctor opt > env > profile >
185
- * hardcoded default.
186
- */
187
- _applyCredentialBaseURL(baseURL) {
188
- if (!baseURL)
189
- return;
190
- const normalized = baseURL.replace(/\/+$/, '');
191
- this._authState.baseURL = normalized;
192
- if (!this._baseURLIsExplicit) {
193
- this.baseURL = normalized;
194
- }
195
- }
196
- /**
197
- * Options bag passed into the credential chain. `baseURL` here is only the
198
- * fallback host for the token-exchange POST when the config itself omits
199
- * `base_url`; the chain returns the config's own `base_url` (if any) on
200
- * {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL}
201
- * then adopts for outbound API requests. The two are deliberately decoupled
202
- * so this fallback never round-trips into precedence.
203
- */
204
- _credentialResolverOptions() {
205
- return {
206
- baseURL: this.baseURL,
207
- fetch: this._credentialsFetch(),
208
- userAgent: this.getUserAgent(),
209
- onCacheWriteError: (err) => {
210
- (0, log_1.loggerFor)(this).debug('credential cache write failed (best-effort)', err);
211
- },
212
- onSafetyWarning: (msg) => {
213
- (0, log_1.loggerFor)(this).warn(msg);
214
- },
215
- };
216
- }
217
- /**
218
- * A `Fetch` for first-party credential token-exchange requests (OIDC
219
- * federation jwt-bearer grants, user-OAuth refresh grants) that routes
220
- * through this client's middleware chain, so middleware observes token
221
- * traffic like any other request. Only client-level middleware applies:
222
- * a minted token is shared across requests, so attributing the exchange
223
- * to any one request's per-request middleware would be arbitrary. For the
224
- * same reason, `ctx.options` is undefined for these requests.
225
- */
226
- _credentialsFetch() {
227
- return (0, middleware_1.wrapFetchWithMiddleware)(this.fetch, this.middleware, undefined, this);
228
- }
229
- _makeTokenCache(provider) {
230
- return new token_cache_1.TokenCache(provider, (err) => {
231
- (0, log_1.loggerFor)(this).debug('advisory token refresh failed; serving cached token', err);
232
- });
233
- }
234
- /**
235
- * Create a new client instance re-using the same options given to the
236
- * current client with optional overriding.
237
- */
238
- withOptions(options) {
239
- // Share the auth state object unless the caller passes any auth-related
240
- // key. The `in` check is intentional: even `apiKey: undefined` opts the
241
- // clone out of sharing (it gets its own _auth and TokenCache, though it
242
- // may still wrap the parent's provider via the credentials spread below).
243
- const overridesStructuredAuth = 'credentials' in options || 'config' in options || 'profile' in options;
244
- const overridesAuth = 'apiKey' in options || 'authToken' in options || overridesStructuredAuth;
245
- const internal = {
246
- ...this._options,
247
- // Only forward baseURL when the caller (or env) explicitly chose it.
248
- // For a non-explicit parent, this.baseURL may have been mutated to the
249
- // profile-resolved host; pinning that as the clone's options.baseURL
250
- // would make _options on the clone misreport caller intent and would
251
- // leave the clone stuck on the parent's host across an auth override.
252
- // The clone instead receives the construction-time value via
253
- // ...this._options above and re-adopts the profile host through the
254
- // shared _authState.baseURL + __baseURLIsExplicit=false path.
255
- ...(this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}),
256
- maxRetries: this.maxRetries,
257
- timeout: this.timeout,
258
- logger: this.logger,
259
- logLevel: this.logLevel,
260
- fetch: this.fetch,
261
- fetchOptions: this.fetchOptions,
262
- middleware: this.middleware,
263
- apiKey: this.apiKey,
264
- authToken: this.authToken,
265
- webhookKey: this.webhookKey,
266
- // credentials: this.credentials is a no-op when __auth is shared (the
267
- // ctor takes the inherited path and ignores options.credentials); when
268
- // overridesAuth is true via apiKey/authToken only, it lets the clone
269
- // build a fresh TokenCache around the parent's provider.
270
- credentials: this.credentials,
271
- // When the caller passes a structured-credential override, drop inherited
272
- // structured-credential options so only `...options` supplies them —
273
- // otherwise an inherited `credentials`/`config`/`profile` would trip the
274
- // mutual-exclusion check or precedence over the override.
275
- ...(overridesStructuredAuth ? { credentials: undefined, config: undefined, profile: undefined } : {}),
276
- ...options,
277
- // Always set __auth so any stale value from ...this._options is
278
- // overwritten. undefined means "build fresh auth from these options".
279
- __auth: overridesAuth ? undefined : this._authState,
280
- __baseURLIsExplicit: 'baseURL' in options ? true : this._baseURLIsExplicit,
281
- };
282
- return new this.constructor(internal);
283
- }
284
- /**
285
- * Lazily resolves credentials from config files or environment variables.
286
- * Called once from the constructor when no explicit auth is provided, or
287
- * when an explicit `profile` was passed (in which case a missing/unresolved
288
- * profile is surfaced as an error instead of falling through to "no auth").
289
- * The returned promise is stored and awaited on the first request.
290
- */
291
- async _resolveDefaultCredentials(profile) {
292
- try {
293
- const result = await (0, credential_chain_1.defaultCredentials)(this._credentialResolverOptions(), profile);
294
- if (result) {
295
- this._authState.provider = result.provider;
296
- this._authState.tokenCache = this._makeTokenCache(result.provider);
297
- this._authState.extraHeaders = result.extraHeaders;
298
- this._applyCredentialBaseURL(result.baseURL);
305
+ catch (err) {
306
+ this._authState.error = err;
299
307
  }
300
- else if (profile != null) {
301
- throw new Errors.AnthropicError(`Profile "${profile}" could not be resolved (no <config_dir>/configs/${profile}.json found).`);
308
+ finally {
309
+ this._authState.resolution = null;
302
310
  }
303
311
  }
304
- catch (err) {
305
- this._authState.error = err;
306
- }
307
- finally {
308
- this._authState.resolution = null;
309
- }
310
- }
311
- defaultQuery() {
312
- return this._options.defaultQuery;
313
- }
314
- validateHeaders({ values, nulls }) {
315
- if (values.get('x-api-key') || values.get('authorization')) {
316
- return;
317
- }
318
- if (this._authState.error) {
319
- throw this._authState.error;
320
- }
321
- if (this._authState.tokenCache || this._authState.resolution) {
322
- return; // auth will be injected per-request via authHeaders
323
- }
324
- if (this.apiKey && values.get('x-api-key')) {
325
- return;
326
- }
327
- if (nulls.has('x-api-key')) {
328
- return;
329
- }
330
- if (this.authToken && values.get('authorization')) {
331
- return;
312
+ defaultQuery() {
313
+ return this._options.defaultQuery;
332
314
  }
333
- if (nulls.has('authorization')) {
334
- return;
315
+ validateHeaders({ values, nulls }) {
316
+ if (values.get('x-api-key') || values.get('authorization')) {
317
+ return;
318
+ }
319
+ if (this._authState.error) {
320
+ throw this._authState.error;
321
+ }
322
+ if (this._authState.tokenCache || this._authState.resolution) {
323
+ return; // auth will be injected per-request via authHeaders
324
+ }
325
+ if (this.apiKey && values.get('x-api-key')) {
326
+ return;
327
+ }
328
+ if (nulls.has('x-api-key')) {
329
+ return;
330
+ }
331
+ if (this.authToken && values.get('authorization')) {
332
+ return;
333
+ }
334
+ if (nulls.has('authorization')) {
335
+ return;
336
+ }
337
+ throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
335
338
  }
336
- throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
337
- }
338
- _authFlags(opts) {
339
- let flags = this._requestAuthFlags.get(opts);
340
- if (!flags) {
341
- flags = { usedTokenCache: false, didRefreshFor401: false };
342
- this._requestAuthFlags.set(opts, flags);
339
+ _authFlags(opts) {
340
+ let flags = this._requestAuthFlags.get(opts);
341
+ if (!flags) {
342
+ flags = { usedTokenCache: false, didRefreshFor401: false };
343
+ this._requestAuthFlags.set(opts, flags);
344
+ }
345
+ return flags;
346
+ }
347
+ async authHeaders(opts) {
348
+ // Wait for lazy credential resolution if it's in progress. If it failed,
349
+ // return no auth headers — validateHeaders surfaces the stored error
350
+ // after the explicit-header escape hatch has had a chance to apply.
351
+ if (this._authState.resolution) {
352
+ await this._authState.resolution;
353
+ }
354
+ if (this._authState.error) {
355
+ return undefined;
356
+ }
357
+ // If we have a token cache and no API key is set, use token auth
358
+ if (this._authState.tokenCache && this.apiKey == null) {
359
+ const token = await this._authState.tokenCache.getToken();
360
+ this._authFlags(opts).usedTokenCache = true;
361
+ return (0, headers_1.buildHeaders)([{ Authorization: `Bearer ${token}` }]);
362
+ }
363
+ return (0, headers_1.buildHeaders)([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
343
364
  }
344
- return flags;
345
- }
346
- async authHeaders(opts) {
347
- // Wait for lazy credential resolution if it's in progress. If it failed,
348
- // return no auth headers validateHeaders surfaces the stored error
349
- // after the explicit-header escape hatch has had a chance to apply.
350
- if (this._authState.resolution) {
351
- await this._authState.resolution;
352
- }
353
- if (this._authState.error) {
354
- return undefined;
355
- }
356
- // If we have a token cache and no API key is set, use token auth
357
- if (this._authState.tokenCache && this.apiKey == null) {
358
- const token = await this._authState.tokenCache.getToken();
359
- this._authFlags(opts).usedTokenCache = true;
360
- return (0, headers_1.buildHeaders)([{ Authorization: `Bearer ${token}` }]);
361
- }
362
- return (0, headers_1.buildHeaders)([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
363
- }
364
- async apiKeyAuth(opts) {
365
- if (this.apiKey == null) {
366
- return undefined;
365
+ async apiKeyAuth(opts) {
366
+ if (this.apiKey == null) {
367
+ return undefined;
368
+ }
369
+ return (0, headers_1.buildHeaders)([{ 'X-Api-Key': this.apiKey }]);
367
370
  }
368
- return (0, headers_1.buildHeaders)([{ 'X-Api-Key': this.apiKey }]);
369
- }
370
- async bearerAuth(opts) {
371
- if (this.authToken == null) {
372
- return undefined;
371
+ async bearerAuth(opts) {
372
+ if (this.authToken == null) {
373
+ return undefined;
374
+ }
375
+ return (0, headers_1.buildHeaders)([{ Authorization: `Bearer ${this.authToken}` }]);
376
+ }
377
+ stringifyQuery(query) {
378
+ return (0, query_1.stringifyQuery)(query);
379
+ }
380
+ getUserAgent() {
381
+ return `Anthropic/JS ${version_1.VERSION}`;
382
+ }
383
+ makeStatusError(status, error, message, headers) {
384
+ return Errors.APIError.generate(status, error, message, headers);
385
+ }
386
+ buildURL(path, query, defaultBaseURL) {
387
+ const baseURL = (!tslib_1.__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
388
+ const url = (0, values_1.isAbsoluteURL)(path) ?
389
+ new URL(path)
390
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
391
+ const defaultQuery = this.defaultQuery();
392
+ const pathQuery = Object.fromEntries(url.searchParams);
393
+ if (!(0, values_2.isEmptyObj)(defaultQuery) || !(0, values_2.isEmptyObj)(pathQuery)) {
394
+ query = { ...pathQuery, ...defaultQuery, ...query };
395
+ }
396
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
397
+ url.search = this.stringifyQuery(query);
398
+ }
399
+ return url.toString();
400
+ }
401
+ _calculateNonstreamingTimeout(maxTokens) {
402
+ const defaultTimeout = 10 * 60;
403
+ const expectedTimeout = (60 * 60 * maxTokens) / 128000;
404
+ if (expectedTimeout > defaultTimeout) {
405
+ throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' +
406
+ 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details');
407
+ }
408
+ return defaultTimeout * 1000;
409
+ }
410
+ /**
411
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
412
+ */
413
+ async prepareOptions(options) { }
414
+ /**
415
+ * Used as a callback for mutating the given `RequestInit` object.
416
+ *
417
+ * This is useful for cases where you want to add certain headers based off of
418
+ * the request properties, e.g. `method` or `url`.
419
+ *
420
+ * Runs after all middleware (including {@link backendMiddleware}),
421
+ * immediately before each underlying fetch call, so it sees exactly what
422
+ * goes over the wire. Middleware may replay a request by calling `next()`
423
+ * more than once, so this hook can run multiple times per attempt:
424
+ * overrides must be idempotent and overwrite headers from a previous
425
+ * invocation rather than append to them.
426
+ */
427
+ async prepareRequest(request, { url, options }) {
428
+ // Append auth-derived headers when using token auth. Done here (after all
429
+ // header merging) rather than in authHeaders() so we append to any existing
430
+ // anthropic-beta values instead of being overwritten by later header sources.
431
+ if (this._authState.tokenCache && this.apiKey == null) {
432
+ // Normalize to a Headers instance — custom fetch impls or polyfills can
433
+ // hand back arrays / plain objects, and silently dropping the beta
434
+ // header in that case would surface as a confusing server-side 4xx.
435
+ const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers);
436
+ for (const [k, v] of Object.entries(this._authState.extraHeaders)) {
437
+ if (!headers.has(k))
438
+ headers.set(k, v);
439
+ }
440
+ const existing = headers
441
+ .get('anthropic-beta')
442
+ ?.split(',')
443
+ .map((s) => s.trim());
444
+ if (!existing?.includes(types_1.OAUTH_API_BETA_HEADER)) {
445
+ headers.append('anthropic-beta', types_1.OAUTH_API_BETA_HEADER);
446
+ }
447
+ request.headers = headers;
448
+ }
373
449
  }
374
- return (0, headers_1.buildHeaders)([{ Authorization: `Bearer ${this.authToken}` }]);
375
- }
376
- stringifyQuery(query) {
377
- return (0, query_1.stringifyQuery)(query);
378
- }
379
- getUserAgent() {
380
- return `Anthropic/JS ${version_1.VERSION}`;
381
- }
382
- makeStatusError(status, error, message, headers) {
383
- return Errors.APIError.generate(status, error, message, headers);
384
- }
385
- buildURL(path, query, defaultBaseURL) {
386
- const baseURL = (!tslib_1.__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
387
- const url = (0, values_1.isAbsoluteURL)(path) ?
388
- new URL(path)
389
- : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
390
- const defaultQuery = this.defaultQuery();
391
- const pathQuery = Object.fromEntries(url.searchParams);
392
- if (!(0, values_2.isEmptyObj)(defaultQuery) || !(0, values_2.isEmptyObj)(pathQuery)) {
393
- query = { ...pathQuery, ...defaultQuery, ...query };
394
- }
395
- if (typeof query === 'object' && query && !Array.isArray(query)) {
396
- url.search = this.stringifyQuery(query);
397
- }
398
- return url.toString();
399
- }
400
- _calculateNonstreamingTimeout(maxTokens) {
401
- const defaultTimeout = 10 * 60;
402
- const expectedTimeout = (60 * 60 * maxTokens) / 128000;
403
- if (expectedTimeout > defaultTimeout) {
404
- throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' +
405
- 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details');
406
- }
407
- return defaultTimeout * 1000;
408
- }
409
- /**
410
- * Used as a callback for mutating the given `FinalRequestOptions` object.
411
- */
412
- async prepareOptions(options) { }
413
- /**
414
- * Used as a callback for mutating the given `RequestInit` object.
415
- *
416
- * This is useful for cases where you want to add certain headers based off of
417
- * the request properties, e.g. `method` or `url`.
418
- *
419
- * Runs after all middleware (including {@link backendMiddleware}),
420
- * immediately before each underlying fetch call, so it sees exactly what
421
- * goes over the wire. Middleware may replay a request by calling `next()`
422
- * more than once, so this hook can run multiple times per attempt:
423
- * overrides must be idempotent and overwrite headers from a previous
424
- * invocation rather than append to them.
425
- */
426
- async prepareRequest(request, { url, options }) {
427
- // Append auth-derived headers when using token auth. Done here (after all
428
- // header merging) rather than in authHeaders() so we append to any existing
429
- // anthropic-beta values instead of being overwritten by later header sources.
430
- if (this._authState.tokenCache && this.apiKey == null) {
431
- // Normalize to a Headers instance — custom fetch impls or polyfills can
432
- // hand back arrays / plain objects, and silently dropping the beta
433
- // header in that case would surface as a confusing server-side 4xx.
434
- const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers);
435
- for (const [k, v] of Object.entries(this._authState.extraHeaders)) {
436
- if (!headers.has(k))
437
- headers.set(k, v);
438
- }
439
- const existing = headers
440
- .get('anthropic-beta')
441
- ?.split(',')
442
- .map((s) => s.trim());
443
- if (!existing?.includes(types_1.OAUTH_API_BETA_HEADER)) {
444
- headers.append('anthropic-beta', types_1.OAUTH_API_BETA_HEADER);
445
- }
446
- request.headers = headers;
450
+ /**
451
+ * Internal {@link Middleware} composed innermost in the chain — inside both
452
+ * client-level and per-request middleware, immediately around the underlying
453
+ * `fetch`. Subclasses for third-party backends override this to adapt the
454
+ * canonical Anthropic-shaped request to the backend's wire shape (URL/body
455
+ * rewriting, request signing) and to normalize the wire response back to the
456
+ * canonical shape (e.g. AWS EventStream to SSE).
457
+ *
458
+ * Running inside the user's middleware means user middleware always observes
459
+ * canonical Anthropic-shaped traffic, and the adaptation re-runs (e.g.
460
+ * re-signs) on every `next()` invocation, covering whatever the middleware
461
+ * mutated.
462
+ *
463
+ * Errors thrown here follow the middleware error policy: they propagate to
464
+ * the caller as-is — no retries, no `APIConnectionError` wrapping — unless
465
+ * retryable (see {@link Middleware}); throw a `RetryableError` to opt into
466
+ * the retry path.
467
+ */
468
+ backendMiddleware() {
469
+ return [];
470
+ }
471
+ get(path, opts) {
472
+ return this.methodRequest('get', path, opts);
473
+ }
474
+ post(path, opts) {
475
+ return this.methodRequest('post', path, opts);
476
+ }
477
+ patch(path, opts) {
478
+ return this.methodRequest('patch', path, opts);
479
+ }
480
+ put(path, opts) {
481
+ return this.methodRequest('put', path, opts);
482
+ }
483
+ delete(path, opts) {
484
+ return this.methodRequest('delete', path, opts);
485
+ }
486
+ methodRequest(method, path, opts) {
487
+ return this.request(Promise.resolve(opts).then((opts) => {
488
+ return { method, path, ...opts };
489
+ }));
447
490
  }
448
- }
449
- /**
450
- * Internal {@link Middleware} composed innermost in the chain — inside both
451
- * client-level and per-request middleware, immediately around the underlying
452
- * `fetch`. Subclasses for third-party backends override this to adapt the
453
- * canonical Anthropic-shaped request to the backend's wire shape (URL/body
454
- * rewriting, request signing) and to normalize the wire response back to the
455
- * canonical shape (e.g. AWS EventStream to SSE).
456
- *
457
- * Running inside the user's middleware means user middleware always observes
458
- * canonical Anthropic-shaped traffic, and the adaptation re-runs (e.g.
459
- * re-signs) on every `next()` invocation, covering whatever the middleware
460
- * mutated.
461
- *
462
- * Errors thrown here follow the middleware error policy: they propagate to
463
- * the caller as-is — no retries, no `APIConnectionError` wrapping — unless
464
- * retryable (see {@link Middleware}); throw a `RetryableError` to opt into
465
- * the retry path.
466
- */
467
- backendMiddleware() {
468
- return [];
469
- }
470
- get(path, opts) {
471
- return this.methodRequest('get', path, opts);
472
- }
473
- post(path, opts) {
474
- return this.methodRequest('post', path, opts);
475
- }
476
- patch(path, opts) {
477
- return this.methodRequest('patch', path, opts);
478
- }
479
- put(path, opts) {
480
- return this.methodRequest('put', path, opts);
481
- }
482
- delete(path, opts) {
483
- return this.methodRequest('delete', path, opts);
484
- }
485
- methodRequest(method, path, opts) {
486
- return this.request(Promise.resolve(opts).then((opts) => {
487
- return { method, path, ...opts };
488
- }));
489
- }
490
- request(options, remainingRetries = null) {
491
- return new api_promise_1.APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
492
- }
493
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
494
- const options = await optionsInput;
495
- const maxRetries = (0, values_1.validatePositiveInteger)('maxRetries', options.maxRetries ?? this.maxRetries);
496
- if (retriesRemaining == null) {
497
- retriesRemaining = maxRetries;
498
- // Top-level call: reset per-request auth flags so a reused options object
499
- // (via client.request(opts)) doesn't carry stale 401-refresh state.
500
- this._requestAuthFlags.delete(options);
501
- }
502
- await this.prepareOptions(options);
503
- const { req, url, timeout } = await this.buildRequest(options, {
504
- retryCount: maxRetries - retriesRemaining,
505
- });
506
- /** Not an API request ID, just for correlating local log entries. */
507
- const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
508
- const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
509
- const startTime = Date.now();
510
- if (options.signal?.aborted) {
511
- throw new Errors.APIUserAbortError();
512
- }
513
- const controller = new AbortController();
514
- const response = await this.fetchWithTimeout(url, req, timeout, controller, options, {
515
- requestLogID,
516
- retryOfRequestLogID,
517
- }).catch(errors_1.castToError);
518
- const headersTime = Date.now();
519
- if (response instanceof globalThis.Error) {
520
- (0, request_signal_1.releaseRequestSignal)(controller);
521
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
491
+ request(options, remainingRetries = null) {
492
+ return new api_promise_1.APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
493
+ }
494
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
495
+ const options = await optionsInput;
496
+ const maxRetries = (0, values_1.validatePositiveInteger)('maxRetries', options.maxRetries ?? this.maxRetries);
497
+ if (retriesRemaining == null) {
498
+ retriesRemaining = maxRetries;
499
+ // Top-level call: reset per-request auth flags so a reused options object
500
+ // (via client.request(opts)) doesn't carry stale 401-refresh state.
501
+ this._requestAuthFlags.delete(options);
502
+ }
503
+ await this.prepareOptions(options);
504
+ const { req, url, timeout } = await this.buildRequest(options, {
505
+ retryCount: maxRetries - retriesRemaining,
506
+ });
507
+ /** Not an API request ID, just for correlating local log entries. */
508
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
509
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
510
+ const startTime = Date.now();
522
511
  if (options.signal?.aborted) {
523
512
  throw new Errors.APIUserAbortError();
524
513
  }
525
- // detect native connection timeout errors
526
- // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
527
- // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
528
- // others do not provide enough information to distinguish timeouts from other connection errors
529
- const isTimeout = (0, errors_1.isAbortError)(response) ||
530
- /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
531
- // Errors thrown by middleware (user middleware and the backend adaptation
532
- // alike) propagate to the caller as-is — no retries, no APIConnectionError
533
- // wrapping except retryable errors (timeouts/aborts, APIConnectionErrors,
534
- // and RetryableErrors, directly or in the `cause` chain), which stay on the
535
- // retry path.
536
- const hasMiddleware = this.middleware.length > 0 || !!options.middleware?.length || this.backendMiddleware().length > 0;
537
- if (hasMiddleware && !isTimeout && !(0, middleware_1.isRetryableError)(response)) {
538
- (0, log_1.loggerFor)(this).info(`[${requestLogID}] middleware error (not retryable)`);
539
- (0, log_1.loggerFor)(this).debug(`[${requestLogID}] middleware error (not retryable)`, (0, log_1.formatRequestDetails)({
540
- retryOfRequestLogID,
541
- url,
542
- durationMs: headersTime - startTime,
543
- message: response.message,
544
- }));
545
- throw response;
546
- }
547
- if (retriesRemaining) {
548
- (0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
549
- (0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, (0, log_1.formatRequestDetails)({
514
+ const controller = new AbortController();
515
+ const response = await this.fetchWithTimeout(url, req, timeout, controller, options, {
516
+ requestLogID,
517
+ retryOfRequestLogID,
518
+ }).catch(errors_1.castToError);
519
+ const headersTime = Date.now();
520
+ if (response instanceof globalThis.Error) {
521
+ (0, request_signal_1.releaseRequestSignal)(controller);
522
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
523
+ if (options.signal?.aborted) {
524
+ throw new Errors.APIUserAbortError();
525
+ }
526
+ // detect native connection timeout errors
527
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
528
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
529
+ // others do not provide enough information to distinguish timeouts from other connection errors
530
+ const isTimeout = (0, errors_1.isAbortError)(response) ||
531
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
532
+ // Errors thrown by middleware (user middleware and the backend adaptation
533
+ // alike) propagate to the caller as-is — no retries, no APIConnectionError
534
+ // wrapping — except retryable errors (timeouts/aborts, APIConnectionErrors,
535
+ // and RetryableErrors, directly or in the `cause` chain), which stay on the
536
+ // retry path.
537
+ const hasMiddleware = this.middleware.length > 0 || !!options.middleware?.length || this.backendMiddleware().length > 0;
538
+ if (hasMiddleware && !isTimeout && !(0, middleware_1.isRetryableError)(response)) {
539
+ (0, log_1.loggerFor)(this).info(`[${requestLogID}] middleware error (not retryable)`);
540
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] middleware error (not retryable)`, (0, log_1.formatRequestDetails)({
541
+ retryOfRequestLogID,
542
+ url,
543
+ durationMs: headersTime - startTime,
544
+ message: response.message,
545
+ }));
546
+ throw response;
547
+ }
548
+ if (retriesRemaining) {
549
+ (0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
550
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, (0, log_1.formatRequestDetails)({
551
+ retryOfRequestLogID,
552
+ url,
553
+ durationMs: headersTime - startTime,
554
+ message: response.message,
555
+ }));
556
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
557
+ }
558
+ (0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
559
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, (0, log_1.formatRequestDetails)({
550
560
  retryOfRequestLogID,
551
561
  url,
552
562
  durationMs: headersTime - startTime,
553
563
  message: response.message,
554
564
  }));
555
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
565
+ if (isTimeout) {
566
+ throw new Errors.APIConnectionTimeoutError();
567
+ }
568
+ // a retryable middleware-origin error is still the caller's error: once retries are
569
+ // exhausted it propagates as-is rather than wrapped in APIConnectionError
570
+ if (hasMiddleware && !(0, middleware_1.isFetchOriginError)(response)) {
571
+ throw response;
572
+ }
573
+ throw new Errors.APIConnectionError({ cause: response });
556
574
  }
557
- (0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
558
- (0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, (0, log_1.formatRequestDetails)({
559
- retryOfRequestLogID,
560
- url,
561
- durationMs: headersTime - startTime,
562
- message: response.message,
563
- }));
564
- if (isTimeout) {
565
- throw new Errors.APIConnectionTimeoutError();
566
- }
567
- // a retryable middleware-origin error is still the caller's error: once retries are
568
- // exhausted it propagates as-is rather than wrapped in APIConnectionError
569
- if (hasMiddleware && !(0, middleware_1.isFetchOriginError)(response)) {
570
- throw response;
571
- }
572
- throw new Errors.APIConnectionError({ cause: response });
573
- }
574
- const specialHeaders = [...response.headers.entries()]
575
- .filter(([name]) => name === 'request-id' || name === 'anthropic-workspace-id')
576
- .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
577
- .join('');
578
- const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
579
- if (!response.ok) {
580
- const shouldRetry = await this.shouldRetry(response, options);
581
- if (retriesRemaining && shouldRetry) {
582
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
583
- // We don't need the body of this response.
584
- await Shims.CancelReadableStream(response.body);
585
- (0, request_signal_1.releaseRequestSignal)(controller);
575
+ const specialHeaders = [...response.headers.entries()]
576
+ .filter(([name]) => name === 'request-id' || name === 'anthropic-workspace-id')
577
+ .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
578
+ .join('');
579
+ const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
580
+ if (!response.ok) {
581
+ const shouldRetry = await this.shouldRetry(response, options);
582
+ if (retriesRemaining && shouldRetry) {
583
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
584
+ // We don't need the body of this response.
585
+ await Shims.CancelReadableStream(response.body);
586
+ (0, request_signal_1.releaseRequestSignal)(controller);
587
+ (0, log_1.loggerFor)(this).info(`${responseInfo} - ${retryMessage}`);
588
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response error (${retryMessage})`, (0, log_1.formatRequestDetails)({
589
+ retryOfRequestLogID,
590
+ url: response.url,
591
+ status: response.status,
592
+ headers: response.headers,
593
+ durationMs: headersTime - startTime,
594
+ }));
595
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
596
+ }
597
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
586
598
  (0, log_1.loggerFor)(this).info(`${responseInfo} - ${retryMessage}`);
599
+ const errText = await response.text().catch((err) => (0, errors_1.castToError)(err).message);
600
+ const errJSON = (0, values_1.safeJSON)(errText);
601
+ const errMessage = errJSON ? undefined : errText;
587
602
  (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response error (${retryMessage})`, (0, log_1.formatRequestDetails)({
588
603
  retryOfRequestLogID,
589
604
  url: response.url,
590
605
  status: response.status,
591
606
  headers: response.headers,
592
- durationMs: headersTime - startTime,
607
+ message: errMessage,
608
+ durationMs: Date.now() - startTime,
593
609
  }));
594
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
595
- }
596
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
597
- (0, log_1.loggerFor)(this).info(`${responseInfo} - ${retryMessage}`);
598
- const errText = await response.text().catch((err) => (0, errors_1.castToError)(err).message);
599
- const errJSON = (0, values_1.safeJSON)(errText);
600
- const errMessage = errJSON ? undefined : errText;
601
- (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response error (${retryMessage})`, (0, log_1.formatRequestDetails)({
610
+ (0, request_signal_1.releaseRequestSignal)(controller);
611
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
612
+ throw err;
613
+ }
614
+ (0, log_1.loggerFor)(this).info(responseInfo);
615
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response start`, (0, log_1.formatRequestDetails)({
602
616
  retryOfRequestLogID,
603
617
  url: response.url,
604
618
  status: response.status,
605
619
  headers: response.headers,
606
- message: errMessage,
607
- durationMs: Date.now() - startTime,
620
+ durationMs: headersTime - startTime,
608
621
  }));
609
- (0, request_signal_1.releaseRequestSignal)(controller);
610
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
611
- throw err;
612
- }
613
- (0, log_1.loggerFor)(this).info(responseInfo);
614
- (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response start`, (0, log_1.formatRequestDetails)({
615
- retryOfRequestLogID,
616
- url: response.url,
617
- status: response.status,
618
- headers: response.headers,
619
- durationMs: headersTime - startTime,
620
- }));
621
- (0, request_signal_1.armAbandonmentBackstop)(response.body ?? response, controller);
622
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
623
- }
624
- getAPIList(path, Page, opts) {
625
- return this.requestAPIList(Page, opts && 'then' in opts ?
626
- opts.then((opts) => ({ method: 'get', path, ...opts }))
627
- : { method: 'get', path, ...opts });
628
- }
629
- requestAPIList(Page, options) {
630
- const request = this.makeRequest(options, null, undefined);
631
- return new Pagination.PagePromise(this, request, Page);
632
- }
633
- async fetchWithTimeout(url, init, ms, controller, requestOptions, logCtx) {
634
- const { signal, method, ...options } = init || {};
635
- // Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks.
636
- // An arrow function like `() => controller.abort()` captures the surrounding scope,
637
- // which includes the request body and other large objects. When the user passes a
638
- // long-lived AbortSignal, the listener prevents those objects from being GC'd for
639
- // the lifetime of the signal. Using `.bind()` only retains a reference to the
640
- // controller itself.
641
- const abort = this._makeAbort(controller);
642
- if (signal) {
643
- signal.addEventListener('abort', abort, { once: true });
644
- (0, request_signal_1.registerRequestSignalCleanup)(controller, signal, abort);
645
- }
646
- const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
647
- (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
648
- const fetchOptions = {
649
- signal: controller.signal,
650
- ...(isReadableBody ? { duplex: 'half' } : {}),
651
- method: 'GET',
652
- ...options,
653
- };
654
- if (method) {
655
- // Custom methods like 'patch' need to be uppercased
656
- // See https://github.com/nodejs/undici/issues/2294
657
- fetchOptions.method = method.toUpperCase();
658
- }
659
- // Arm the timeout around the underlying fetch only, not the middleware
660
- // chain — middleware can take arbitrarily long (or call `next` more than
661
- // once), and each inner-fetch invocation gets its own `ms` timer.
662
- const baseFetch = this.fetch;
663
- const timedFetch = async (innerUrl, innerInit) => {
664
- const timeout = setTimeout(abort, ms);
665
- try {
666
- return await baseFetch.call(undefined, innerUrl, innerInit);
622
+ (0, request_signal_1.armAbandonmentBackstop)(response.body ?? response, controller);
623
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
624
+ }
625
+ getAPIList(path, Page, opts) {
626
+ return this.requestAPIList(Page, opts && 'then' in opts ?
627
+ opts.then((opts) => ({ method: 'get', path, ...opts }))
628
+ : { method: 'get', path, ...opts });
629
+ }
630
+ requestAPIList(Page, options) {
631
+ const request = this.makeRequest(options, null, undefined);
632
+ return new Pagination.PagePromise(this, request, Page);
633
+ }
634
+ async fetchWithTimeout(url, init, ms, controller, requestOptions, logCtx) {
635
+ const { signal, method, ...options } = init || {};
636
+ // Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks.
637
+ // An arrow function like `() => controller.abort()` captures the surrounding scope,
638
+ // which includes the request body and other large objects. When the user passes a
639
+ // long-lived AbortSignal, the listener prevents those objects from being GC'd for
640
+ // the lifetime of the signal. Using `.bind()` only retains a reference to the
641
+ // controller itself.
642
+ const abort = this._makeAbort(controller);
643
+ if (signal) {
644
+ signal.addEventListener('abort', abort, { once: true });
645
+ (0, request_signal_1.registerRequestSignalCleanup)(controller, signal, abort);
667
646
  }
668
- finally {
669
- clearTimeout(timeout);
670
- }
671
- };
672
- // Prepare the request (auth signing and other `prepareRequest` hooks) as
673
- // the innermost step, after any middleware — including the backend
674
- // middleware, so it sees exactly what goes over the wire. Runs per
675
- // inner-fetch invocation, so a request middleware rewrote — or replayed
676
- // via a second `next()` call — is prepared fresh each time. Preparation is
677
- // outside the timeout timer, matching its pre-middleware behavior.
678
- const innerFetch = requestOptions === undefined ? timedFetch : (async (innerUrl, innerInit = {}) => {
679
- const innerUrlStr = typeof innerUrl === 'string' ? innerUrl
680
- : innerUrl instanceof URL ? innerUrl.href
681
- : innerUrl.url;
682
- innerInit.headers =
683
- innerInit.headers instanceof Headers ? innerInit.headers : new Headers(innerInit.headers);
684
- await this.prepareRequest(innerInit, { url: innerUrlStr, options: requestOptions });
685
- if (logCtx) {
686
- (0, log_1.loggerFor)(this).debug(`[${logCtx.requestLogID}] sending request`, (0, log_1.formatRequestDetails)({
687
- retryOfRequestLogID: logCtx.retryOfRequestLogID,
688
- method: innerInit.method,
689
- url: innerUrlStr,
690
- options: requestOptions,
691
- headers: innerInit.headers,
692
- }));
647
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
648
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
649
+ const fetchOptions = {
650
+ signal: controller.signal,
651
+ ...(isReadableBody ? { duplex: 'half' } : {}),
652
+ method: 'GET',
653
+ ...options,
654
+ };
655
+ if (method) {
656
+ // Custom methods like 'patch' need to be uppercased
657
+ // See https://github.com/nodejs/undici/issues/2294
658
+ fetchOptions.method = method.toUpperCase();
693
659
  }
694
- return timedFetch(innerUrl, innerInit);
695
- });
696
- const requestMiddleware = requestOptions?.middleware;
697
- const backendMiddleware = this.backendMiddleware();
698
- const allMiddleware = requestMiddleware?.length || backendMiddleware.length ?
699
- [...this.middleware, ...(requestMiddleware ?? []), ...backendMiddleware]
700
- : this.middleware;
701
- return await (0, middleware_1.wrapFetchWithMiddleware)(innerFetch, allMiddleware, requestOptions, this)(url, fetchOptions);
702
- }
703
- async shouldRetry(response, options) {
704
- // Reactive refresh: on a 401 from a request that used the token cache,
705
- // invalidate and retry once. Only fires when this specific request was
706
- // bearer-authenticated (not when an apiKey was used) and only once per
707
- // request a second 401 after refresh falls through to the normal
708
- // retry policy below (which treats 4xx as non-retryable).
709
- const flags = this._authFlags(options);
710
- if (response.status === 401 &&
711
- this._authState.tokenCache &&
712
- flags.usedTokenCache &&
713
- !flags.didRefreshFor401) {
714
- flags.didRefreshFor401 = true;
715
- this._authState.tokenCache.invalidate();
716
- return true;
717
- }
718
- // Note this is not a standard header.
719
- const shouldRetryHeader = response.headers.get('x-should-retry');
720
- // If the server explicitly says whether or not to retry, obey.
721
- if (shouldRetryHeader === 'true')
722
- return true;
723
- if (shouldRetryHeader === 'false')
660
+ // Arm the timeout around the underlying fetch only, not the middleware
661
+ // chain — middleware can take arbitrarily long (or call `next` more than
662
+ // once), and each inner-fetch invocation gets its own `ms` timer.
663
+ const baseFetch = this.fetch;
664
+ const timedFetch = async (innerUrl, innerInit) => {
665
+ const timeout = setTimeout(abort, ms);
666
+ try {
667
+ return await baseFetch.call(undefined, innerUrl, innerInit);
668
+ }
669
+ finally {
670
+ clearTimeout(timeout);
671
+ }
672
+ };
673
+ // Prepare the request (auth signing and other `prepareRequest` hooks) as
674
+ // the innermost step, after any middleware including the backend
675
+ // middleware, so it sees exactly what goes over the wire. Runs per
676
+ // inner-fetch invocation, so a request middleware rewrote — or replayed
677
+ // via a second `next()` call — is prepared fresh each time. Preparation is
678
+ // outside the timeout timer, matching its pre-middleware behavior.
679
+ const innerFetch = requestOptions === undefined ? timedFetch : (async (innerUrl, innerInit = {}) => {
680
+ const innerUrlStr = typeof innerUrl === 'string' ? innerUrl
681
+ : innerUrl instanceof URL ? innerUrl.href
682
+ : innerUrl.url;
683
+ innerInit.headers =
684
+ innerInit.headers instanceof Headers ? innerInit.headers : new Headers(innerInit.headers);
685
+ await this.prepareRequest(innerInit, { url: innerUrlStr, options: requestOptions });
686
+ if (logCtx) {
687
+ (0, log_1.loggerFor)(this).debug(`[${logCtx.requestLogID}] sending request`, (0, log_1.formatRequestDetails)({
688
+ retryOfRequestLogID: logCtx.retryOfRequestLogID,
689
+ method: innerInit.method,
690
+ url: innerUrlStr,
691
+ options: requestOptions,
692
+ headers: innerInit.headers,
693
+ }));
694
+ }
695
+ return timedFetch(innerUrl, innerInit);
696
+ });
697
+ const requestMiddleware = requestOptions?.middleware;
698
+ const backendMiddleware = this.backendMiddleware();
699
+ const allMiddleware = requestMiddleware?.length || backendMiddleware.length ?
700
+ [...this.middleware, ...(requestMiddleware ?? []), ...backendMiddleware]
701
+ : this.middleware;
702
+ return await (0, middleware_1.wrapFetchWithMiddleware)(innerFetch, allMiddleware, requestOptions, this)(url, fetchOptions);
703
+ }
704
+ async shouldRetry(response, options) {
705
+ // Reactive refresh: on a 401 from a request that used the token cache,
706
+ // invalidate and retry once. Only fires when this specific request was
707
+ // bearer-authenticated (not when an apiKey was used) and only once per
708
+ // request — a second 401 after refresh falls through to the normal
709
+ // retry policy below (which treats 4xx as non-retryable).
710
+ const flags = this._authFlags(options);
711
+ if (response.status === 401 &&
712
+ this._authState.tokenCache &&
713
+ flags.usedTokenCache &&
714
+ !flags.didRefreshFor401) {
715
+ flags.didRefreshFor401 = true;
716
+ this._authState.tokenCache.invalidate();
717
+ return true;
718
+ }
719
+ // Note this is not a standard header.
720
+ const shouldRetryHeader = response.headers.get('x-should-retry');
721
+ // If the server explicitly says whether or not to retry, obey.
722
+ if (shouldRetryHeader === 'true')
723
+ return true;
724
+ if (shouldRetryHeader === 'false')
725
+ return false;
726
+ // Retry on request timeouts.
727
+ if (response.status === 408)
728
+ return true;
729
+ // Retry on lock timeouts.
730
+ if (response.status === 409)
731
+ return true;
732
+ // Retry on rate limits.
733
+ if (response.status === 429)
734
+ return true;
735
+ // Retry internal errors.
736
+ if (response.status >= 500)
737
+ return true;
724
738
  return false;
725
- // Retry on request timeouts.
726
- if (response.status === 408)
727
- return true;
728
- // Retry on lock timeouts.
729
- if (response.status === 409)
730
- return true;
731
- // Retry on rate limits.
732
- if (response.status === 429)
733
- return true;
734
- // Retry internal errors.
735
- if (response.status >= 500)
736
- return true;
737
- return false;
738
- }
739
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
740
- let timeoutMillis;
741
- // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
742
- const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
743
- if (retryAfterMillisHeader) {
744
- const timeoutMs = parseFloat(retryAfterMillisHeader);
745
- if (!Number.isNaN(timeoutMs)) {
746
- timeoutMillis = timeoutMs;
747
- }
748
- }
749
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
750
- const retryAfterHeader = responseHeaders?.get('retry-after');
751
- if (retryAfterHeader && !timeoutMillis) {
752
- const timeoutSeconds = parseFloat(retryAfterHeader);
753
- if (!Number.isNaN(timeoutSeconds)) {
754
- timeoutMillis = timeoutSeconds * 1000;
739
+ }
740
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
741
+ let timeoutMillis;
742
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
743
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
744
+ if (retryAfterMillisHeader) {
745
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
746
+ if (!Number.isNaN(timeoutMs)) {
747
+ timeoutMillis = timeoutMs;
748
+ }
755
749
  }
756
- else {
757
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
750
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
751
+ const retryAfterHeader = responseHeaders?.get('retry-after');
752
+ if (retryAfterHeader && !timeoutMillis) {
753
+ const timeoutSeconds = parseFloat(retryAfterHeader);
754
+ if (!Number.isNaN(timeoutSeconds)) {
755
+ timeoutMillis = timeoutSeconds * 1000;
756
+ }
757
+ else {
758
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
759
+ }
758
760
  }
759
- }
760
- // If the API asks us to wait a certain amount of time, do what it says, as long as it's a positive delay that
761
- // one timer can represent (setTimeout fires after 1ms for anything above 2^31 - 1). Otherwise (no header, an
762
- // unparseable value, zero/negative, a date in the past) calculate a default.
763
- if (timeoutMillis === undefined || !(timeoutMillis > 0 && timeoutMillis <= 2 ** 31 - 1)) {
764
- const maxRetries = options.maxRetries ?? this.maxRetries;
765
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
766
- }
767
- await (0, sleep_1.sleep)(timeoutMillis);
768
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
769
- }
770
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
771
- const initialRetryDelay = 0.5;
772
- const maxRetryDelay = 8.0;
773
- const numRetries = maxRetries - retriesRemaining;
774
- // Apply exponential backoff, but not more than the max.
775
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
776
- // Apply some jitter, take up to at most 25 percent of the retry time.
777
- const jitter = 1 - Math.random() * 0.25;
778
- return sleepSeconds * jitter * 1000;
779
- }
780
- calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
781
- const maxTime = 60 * 60 * 1000; // 60 minutes
782
- const defaultTime = 60 * 10 * 1000; // 10 minutes
783
- const expectedTime = (maxTime * maxTokens) / 128000;
784
- if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {
785
- throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details');
786
- }
787
- return defaultTime;
788
- }
789
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
790
- const options = { ...inputOptions };
791
- const { method, path, query, defaultBaseURL } = options;
792
- // Lazy credential resolution may carry a profile-supplied baseURL. Await
793
- // it before building the request URL so the very first request and
794
- // requests on withOptions() clones created before resolution settled
795
- // hit the profile's host rather than the hardcoded default.
796
- if (this._authState.resolution) {
797
- await this._authState.resolution;
798
- }
799
- if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) {
800
- this.baseURL = this._authState.baseURL;
801
- }
802
- const url = this.buildURL(path, query, defaultBaseURL);
803
- if ('timeout' in options)
804
- (0, values_1.validatePositiveInteger)('timeout', options.timeout);
805
- options.timeout = options.timeout ?? this.timeout;
806
- const { bodyHeaders, body } = this.buildBody({ options });
807
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
808
- const req = {
809
- method,
810
- headers: reqHeaders,
811
- ...(options.signal && { signal: options.signal }),
812
- ...(globalThis.ReadableStream &&
813
- body instanceof globalThis.ReadableStream && { duplex: 'half' }),
814
- ...(body && { body }),
815
- ...(this.fetchOptions ?? {}),
816
- ...(options.fetchOptions ?? {}),
817
- };
818
- return { req, url, timeout: options.timeout };
819
- }
820
- async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
821
- const headers = (0, headers_1.buildHeaders)([
822
- {
823
- Accept: 'application/json',
824
- 'User-Agent': this.getUserAgent(),
825
- 'X-Stainless-Retry-Count': String(retryCount),
826
- ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
827
- ...(0, detect_platform_1.getPlatformHeaders)(),
828
- ...(this._options.dangerouslyAllowBrowser ?
829
- { 'anthropic-dangerous-direct-browser-access': 'true' }
830
- : undefined),
831
- 'anthropic-version': '2023-06-01',
832
- },
833
- await this.authHeaders(options),
834
- this._options.defaultHeaders,
835
- bodyHeaders,
836
- options.headers,
837
- ]);
838
- this.validateHeaders(headers);
839
- return headers.values;
840
- }
841
- _makeAbort(controller) {
842
- // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure
843
- // would capture all request options, and cause a memory leak.
844
- return () => controller.abort();
845
- }
846
- buildBody({ options: { body, headers: rawHeaders } }) {
847
- if (!body) {
848
- return { bodyHeaders: undefined, body: undefined };
849
- }
850
- const headers = (0, headers_1.buildHeaders)([rawHeaders]);
851
- if (
852
- // Pass raw type verbatim
853
- ArrayBuffer.isView(body) ||
854
- body instanceof ArrayBuffer ||
855
- body instanceof DataView ||
856
- (typeof body === 'string' &&
857
- // Preserve legacy string encoding behavior for now
858
- headers.values.has('content-type')) ||
859
- // `Blob` is superset of `File`
860
- (globalThis.Blob && body instanceof globalThis.Blob) ||
861
- // `FormData` -> `multipart/form-data`
862
- body instanceof FormData ||
863
- // `URLSearchParams` -> `application/x-www-form-urlencoded`
864
- body instanceof URLSearchParams ||
865
- // Send chunked stream (each chunk has own `length`)
866
- (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
867
- return { bodyHeaders: undefined, body: body };
868
- }
869
- else if (typeof body === 'object' &&
870
- (Symbol.asyncIterator in body ||
871
- (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
872
- return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
873
- }
874
- else if (typeof body === 'object' &&
875
- headers.values.get('content-type') === 'application/x-www-form-urlencoded') {
876
- return {
877
- bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },
878
- body: this.stringifyQuery(body),
761
+ // If the API asks us to wait a certain amount of time, do what it says, as long as it's a positive delay that
762
+ // one timer can represent (setTimeout fires after 1ms for anything above 2^31 - 1). Otherwise (no header, an
763
+ // unparseable value, zero/negative, a date in the past) calculate a default.
764
+ if (timeoutMillis === undefined || !(timeoutMillis > 0 && timeoutMillis <= 2 ** 31 - 1)) {
765
+ const maxRetries = options.maxRetries ?? this.maxRetries;
766
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
767
+ }
768
+ await (0, sleep_1.sleep)(timeoutMillis, options.signal ?? undefined);
769
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
770
+ }
771
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
772
+ const initialRetryDelay = 0.5;
773
+ const maxRetryDelay = 8.0;
774
+ const numRetries = maxRetries - retriesRemaining;
775
+ // Apply exponential backoff, but not more than the max.
776
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
777
+ // Apply some jitter, take up to at most 25 percent of the retry time.
778
+ const jitter = 1 - Math.random() * 0.25;
779
+ return sleepSeconds * jitter * 1000;
780
+ }
781
+ calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
782
+ const maxTime = 60 * 60 * 1000; // 60 minutes
783
+ const defaultTime = 60 * 10 * 1000; // 10 minutes
784
+ const expectedTime = (maxTime * maxTokens) / 128000;
785
+ if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {
786
+ throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details');
787
+ }
788
+ return defaultTime;
789
+ }
790
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
791
+ const options = { ...inputOptions };
792
+ const { method, path, query, defaultBaseURL } = options;
793
+ // Lazy credential resolution may carry a profile-supplied baseURL. Await
794
+ // it before building the request URL so the very first request — and
795
+ // requests on withOptions() clones created before resolution settled
796
+ // hit the profile's host rather than the hardcoded default.
797
+ if (this._authState.resolution) {
798
+ await this._authState.resolution;
799
+ }
800
+ if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) {
801
+ this.baseURL = this._authState.baseURL;
802
+ }
803
+ const url = this.buildURL(path, query, defaultBaseURL);
804
+ if ('timeout' in options)
805
+ (0, values_1.validatePositiveInteger)('timeout', options.timeout);
806
+ options.timeout = options.timeout ?? this.timeout;
807
+ const { bodyHeaders, body } = this.buildBody({ options });
808
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
809
+ const req = {
810
+ method,
811
+ headers: reqHeaders,
812
+ ...(options.signal && { signal: options.signal }),
813
+ ...(globalThis.ReadableStream &&
814
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
815
+ ...(body && { body }),
816
+ ...(this.fetchOptions ?? {}),
817
+ ...(options.fetchOptions ?? {}),
879
818
  };
880
- }
881
- else {
882
- return tslib_1.__classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
819
+ return { req, url, timeout: options.timeout };
820
+ }
821
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
822
+ const headers = (0, headers_1.buildHeaders)([
823
+ {
824
+ Accept: 'application/json',
825
+ 'User-Agent': this.getUserAgent(),
826
+ 'X-Stainless-Retry-Count': String(retryCount),
827
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
828
+ ...(0, detect_platform_1.getPlatformHeaders)(),
829
+ ...(this._options.dangerouslyAllowBrowser ?
830
+ { 'anthropic-dangerous-direct-browser-access': 'true' }
831
+ : undefined),
832
+ 'anthropic-version': '2023-06-01',
833
+ },
834
+ await this.authHeaders(options),
835
+ this._options.defaultHeaders,
836
+ bodyHeaders,
837
+ options.headers,
838
+ ]);
839
+ this.validateHeaders(headers);
840
+ return headers.values;
841
+ }
842
+ _makeAbort(controller) {
843
+ // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure
844
+ // would capture all request options, and cause a memory leak.
845
+ return () => controller.abort();
846
+ }
847
+ buildBody({ options: { body, headers: rawHeaders } }) {
848
+ if (!body) {
849
+ return { bodyHeaders: undefined, body: undefined };
850
+ }
851
+ const headers = (0, headers_1.buildHeaders)([rawHeaders]);
852
+ if (
853
+ // Pass raw type verbatim
854
+ ArrayBuffer.isView(body) ||
855
+ body instanceof ArrayBuffer ||
856
+ body instanceof DataView ||
857
+ (typeof body === 'string' &&
858
+ // Preserve legacy string encoding behavior for now
859
+ headers.values.has('content-type')) ||
860
+ // `Blob` is superset of `File`
861
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
862
+ // `FormData` -> `multipart/form-data`
863
+ body instanceof FormData ||
864
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
865
+ body instanceof URLSearchParams ||
866
+ // Send chunked stream (each chunk has own `length`)
867
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
868
+ return { bodyHeaders: undefined, body: body };
869
+ }
870
+ else if (typeof body === 'object' &&
871
+ (Symbol.asyncIterator in body ||
872
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
873
+ return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
874
+ }
875
+ else if (typeof body === 'object' &&
876
+ headers.values.get('content-type') === 'application/x-www-form-urlencoded') {
877
+ return {
878
+ bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },
879
+ body: this.stringifyQuery(body),
880
+ };
881
+ }
882
+ else {
883
+ return tslib_1.__classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
884
+ }
883
885
  }
884
886
  }
885
- }
887
+ _a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() {
888
+ return this.baseURL !== 'https://api.anthropic.com';
889
+ };
890
+ BaseAnthropic.Anthropic = _a;
891
+ BaseAnthropic.HUMAN_PROMPT = exports.HUMAN_PROMPT;
892
+ BaseAnthropic.AI_PROMPT = exports.AI_PROMPT;
893
+ BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes
894
+ BaseAnthropic.AnthropicError = Errors.AnthropicError;
895
+ BaseAnthropic.APIError = Errors.APIError;
896
+ BaseAnthropic.APIConnectionError = Errors.APIConnectionError;
897
+ BaseAnthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
898
+ BaseAnthropic.APIUserAbortError = Errors.APIUserAbortError;
899
+ BaseAnthropic.NotFoundError = Errors.NotFoundError;
900
+ BaseAnthropic.ConflictError = Errors.ConflictError;
901
+ BaseAnthropic.RateLimitError = Errors.RateLimitError;
902
+ BaseAnthropic.BadRequestError = Errors.BadRequestError;
903
+ BaseAnthropic.AuthenticationError = Errors.AuthenticationError;
904
+ BaseAnthropic.InternalServerError = Errors.InternalServerError;
905
+ BaseAnthropic.PermissionDeniedError = Errors.PermissionDeniedError;
906
+ BaseAnthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
907
+ BaseAnthropic.toFile = Uploads.toFile;
908
+ return BaseAnthropic;
909
+ })();
886
910
  exports.BaseAnthropic = BaseAnthropic;
887
- _a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() {
888
- return this.baseURL !== 'https://api.anthropic.com';
889
- };
890
- BaseAnthropic.Anthropic = _a;
891
- BaseAnthropic.HUMAN_PROMPT = exports.HUMAN_PROMPT;
892
- BaseAnthropic.AI_PROMPT = exports.AI_PROMPT;
893
- BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes
894
- BaseAnthropic.AnthropicError = Errors.AnthropicError;
895
- BaseAnthropic.APIError = Errors.APIError;
896
- BaseAnthropic.APIConnectionError = Errors.APIConnectionError;
897
- BaseAnthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
898
- BaseAnthropic.APIUserAbortError = Errors.APIUserAbortError;
899
- BaseAnthropic.NotFoundError = Errors.NotFoundError;
900
- BaseAnthropic.ConflictError = Errors.ConflictError;
901
- BaseAnthropic.RateLimitError = Errors.RateLimitError;
902
- BaseAnthropic.BadRequestError = Errors.BadRequestError;
903
- BaseAnthropic.AuthenticationError = Errors.AuthenticationError;
904
- BaseAnthropic.InternalServerError = Errors.InternalServerError;
905
- BaseAnthropic.PermissionDeniedError = Errors.PermissionDeniedError;
906
- BaseAnthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
907
- BaseAnthropic.toFile = Uploads.toFile;
908
- /**
909
- * API Client for interfacing with the Anthropic API.
910
- */
911
- class Anthropic extends BaseAnthropic {
912
- constructor() {
913
- super(...arguments);
914
- this.completions = new API.Completions(this);
915
- this.messages = new API.Messages(this);
916
- this.models = new API.Models(this);
917
- this.files = new API.Files(this);
918
- this.skills = new API.Skills(this);
919
- this.beta = new API.Beta(this);
920
- }
921
- }
911
+ var Anthropic = /* @__PURE__ */ (() => {
912
+ /**
913
+ * API Client for interfacing with the Anthropic API.
914
+ */
915
+ class Anthropic extends BaseAnthropic {
916
+ constructor() {
917
+ super(...arguments);
918
+ this.completions = new API.Completions(this);
919
+ this.messages = new API.Messages(this);
920
+ this.models = new API.Models(this);
921
+ this.files = new API.Files(this);
922
+ this.skills = new API.Skills(this);
923
+ this.beta = new API.Beta(this);
924
+ }
925
+ }
926
+ Anthropic.Completions = completions_1.Completions;
927
+ Anthropic.Messages = messages_1.Messages;
928
+ Anthropic.Models = models_1.Models;
929
+ Anthropic.Files = files_1.Files;
930
+ Anthropic.Skills = skills_1.Skills;
931
+ Anthropic.Beta = beta_1.Beta;
932
+ return Anthropic;
933
+ })();
922
934
  exports.Anthropic = Anthropic;
923
- Anthropic.Completions = completions_1.Completions;
924
- Anthropic.Messages = messages_1.Messages;
925
- Anthropic.Models = models_1.Models;
926
- Anthropic.Files = files_1.Files;
927
- Anthropic.Skills = skills_1.Skills;
928
- Anthropic.Beta = beta_1.Beta;
929
935
  //# sourceMappingURL=client.js.map