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