@anthropic-ai/sdk 0.125.0 → 0.127.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 (417) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/client.d.mts +12 -11
  3. package/client.d.mts.map +1 -1
  4. package/client.d.ts +12 -11
  5. package/client.d.ts.map +1 -1
  6. package/client.js +865 -845
  7. package/client.js.map +1 -1
  8. package/client.mjs +866 -840
  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/parse.d.mts.map +1 -1
  50. package/internal/parse.d.ts.map +1 -1
  51. package/internal/parse.js +2 -2
  52. package/internal/parse.js.map +1 -1
  53. package/internal/parse.mjs +3 -3
  54. package/internal/parse.mjs.map +1 -1
  55. package/internal/shim-types.js +0 -6
  56. package/internal/shim-types.js.map +1 -1
  57. package/internal/shim-types.mjs +0 -6
  58. package/internal/shim-types.mjs.map +1 -1
  59. package/internal/shims.d.mts +3 -3
  60. package/internal/shims.d.mts.map +1 -1
  61. package/internal/shims.d.ts +3 -3
  62. package/internal/shims.d.ts.map +1 -1
  63. package/internal/shims.js +0 -6
  64. package/internal/shims.js.map +1 -1
  65. package/internal/shims.mjs +0 -6
  66. package/internal/shims.mjs.map +1 -1
  67. package/internal/stainless-helper-header.js +6 -6
  68. package/internal/stainless-helper-header.js.map +1 -1
  69. package/internal/utils/async-queue.js +66 -63
  70. package/internal/utils/async-queue.js.map +1 -1
  71. package/internal/utils/async-queue.mjs +66 -56
  72. package/internal/utils/async-queue.mjs.map +1 -1
  73. package/internal/utils/bytes.d.mts +1 -1
  74. package/internal/utils/bytes.d.mts.map +1 -1
  75. package/internal/utils/bytes.d.ts +1 -1
  76. package/internal/utils/bytes.d.ts.map +1 -1
  77. package/internal/utils/log.d.mts +7 -12
  78. package/internal/utils/log.d.mts.map +1 -1
  79. package/internal/utils/log.d.ts +7 -12
  80. package/internal/utils/log.d.ts.map +1 -1
  81. package/internal/utils/log.js +12 -0
  82. package/internal/utils/log.js.map +1 -1
  83. package/internal/utils/log.mjs +11 -0
  84. package/internal/utils/log.mjs.map +1 -1
  85. package/lib/BetaMessageStream.d.mts.map +1 -1
  86. package/lib/BetaMessageStream.d.ts.map +1 -1
  87. package/lib/BetaMessageStream.js +595 -590
  88. package/lib/BetaMessageStream.js.map +1 -1
  89. package/lib/BetaMessageStream.mjs +595 -590
  90. package/lib/BetaMessageStream.mjs.map +1 -1
  91. package/lib/MessageStream.js +544 -541
  92. package/lib/MessageStream.js.map +1 -1
  93. package/lib/MessageStream.mjs +544 -541
  94. package/lib/MessageStream.mjs.map +1 -1
  95. package/lib/beta-parser.d.mts +1 -3
  96. package/lib/beta-parser.d.mts.map +1 -1
  97. package/lib/beta-parser.d.ts +1 -3
  98. package/lib/beta-parser.d.ts.map +1 -1
  99. package/lib/beta-parser.js.map +1 -1
  100. package/lib/beta-parser.mjs.map +1 -1
  101. package/lib/environments/poller.js +180 -174
  102. package/lib/environments/poller.js.map +1 -1
  103. package/lib/environments/poller.mjs +180 -153
  104. package/lib/environments/poller.mjs.map +1 -1
  105. package/lib/environments/worker.js +375 -369
  106. package/lib/environments/worker.js.map +1 -1
  107. package/lib/environments/worker.mjs +374 -329
  108. package/lib/environments/worker.mjs.map +1 -1
  109. package/lib/internal/stub.d.mts +2 -0
  110. package/lib/internal/stub.d.mts.map +1 -0
  111. package/lib/internal/stub.d.ts +2 -0
  112. package/lib/internal/stub.d.ts.map +1 -0
  113. package/lib/internal/stub.js +6 -0
  114. package/lib/internal/stub.js.map +1 -0
  115. package/lib/internal/stub.mjs +3 -0
  116. package/lib/internal/stub.mjs.map +1 -0
  117. package/lib/internal/types.d.mts +5 -0
  118. package/lib/internal/types.d.mts.map +1 -0
  119. package/lib/internal/types.d.ts +5 -0
  120. package/lib/internal/types.d.ts.map +1 -0
  121. package/lib/internal/types.js +3 -0
  122. package/lib/internal/types.js.map +1 -0
  123. package/lib/internal/types.mjs +2 -0
  124. package/lib/internal/types.mjs.map +1 -0
  125. package/lib/middleware.js +6 -1
  126. package/lib/middleware.js.map +1 -1
  127. package/lib/middleware.mjs +6 -1
  128. package/lib/middleware.mjs.map +1 -1
  129. package/lib/parser.d.mts +1 -3
  130. package/lib/parser.d.mts.map +1 -1
  131. package/lib/parser.d.ts +1 -3
  132. package/lib/parser.d.ts.map +1 -1
  133. package/lib/parser.js.map +1 -1
  134. package/lib/parser.mjs.map +1 -1
  135. package/lib/tools/BetaToolRunner.d.mts +21 -6
  136. package/lib/tools/BetaToolRunner.d.mts.map +1 -1
  137. package/lib/tools/BetaToolRunner.d.ts +21 -6
  138. package/lib/tools/BetaToolRunner.d.ts.map +1 -1
  139. package/lib/tools/BetaToolRunner.js +415 -310
  140. package/lib/tools/BetaToolRunner.js.map +1 -1
  141. package/lib/tools/BetaToolRunner.mjs +414 -303
  142. package/lib/tools/BetaToolRunner.mjs.map +1 -1
  143. package/lib/tools/SessionToolRunner.js +241 -235
  144. package/lib/tools/SessionToolRunner.js.map +1 -1
  145. package/lib/tools/SessionToolRunner.mjs +241 -192
  146. package/lib/tools/SessionToolRunner.mjs.map +1 -1
  147. package/lib/tools/ToolError.js +39 -36
  148. package/lib/tools/ToolError.js.map +1 -1
  149. package/lib/tools/ToolError.mjs +39 -13
  150. package/lib/tools/ToolError.mjs.map +1 -1
  151. package/lib/transform-json-schema.js +7 -5
  152. package/lib/transform-json-schema.js.map +1 -1
  153. package/lib/transform-json-schema.mjs +7 -5
  154. package/lib/transform-json-schema.mjs.map +1 -1
  155. package/package.json +4 -3
  156. package/resources/beta/agents/agents.js +135 -132
  157. package/resources/beta/agents/agents.js.map +1 -1
  158. package/resources/beta/agents/agents.mjs +135 -132
  159. package/resources/beta/agents/agents.mjs.map +1 -1
  160. package/resources/beta/beta.d.mts +5 -5
  161. package/resources/beta/beta.d.mts.map +1 -1
  162. package/resources/beta/beta.d.ts +5 -5
  163. package/resources/beta/beta.d.ts.map +1 -1
  164. package/resources/beta/beta.js +39 -36
  165. package/resources/beta/beta.js.map +1 -1
  166. package/resources/beta/beta.mjs +39 -36
  167. package/resources/beta/beta.mjs.map +1 -1
  168. package/resources/beta/deployment-runs.d.mts +4 -0
  169. package/resources/beta/deployment-runs.d.mts.map +1 -1
  170. package/resources/beta/deployment-runs.d.ts +4 -0
  171. package/resources/beta/deployment-runs.d.ts.map +1 -1
  172. package/resources/beta/deployments.d.mts +5 -0
  173. package/resources/beta/deployments.d.mts.map +1 -1
  174. package/resources/beta/deployments.d.ts +5 -0
  175. package/resources/beta/deployments.d.ts.map +1 -1
  176. package/resources/beta/dreams.d.mts +19 -28
  177. package/resources/beta/dreams.d.mts.map +1 -1
  178. package/resources/beta/dreams.d.ts +19 -28
  179. package/resources/beta/dreams.d.ts.map +1 -1
  180. package/resources/beta/environments/environments.js +157 -154
  181. package/resources/beta/environments/environments.js.map +1 -1
  182. package/resources/beta/environments/environments.mjs +157 -154
  183. package/resources/beta/environments/environments.mjs.map +1 -1
  184. package/resources/beta/environments/work.js +255 -252
  185. package/resources/beta/environments/work.js.map +1 -1
  186. package/resources/beta/environments/work.mjs +255 -252
  187. package/resources/beta/environments/work.mjs.map +1 -1
  188. package/resources/beta/index.d.mts +2 -2
  189. package/resources/beta/index.d.mts.map +1 -1
  190. package/resources/beta/index.d.ts +2 -2
  191. package/resources/beta/index.d.ts.map +1 -1
  192. package/resources/beta/index.js.map +1 -1
  193. package/resources/beta/index.mjs.map +1 -1
  194. package/resources/beta/memory-stores/memories.d.mts +6 -0
  195. package/resources/beta/memory-stores/memories.d.mts.map +1 -1
  196. package/resources/beta/memory-stores/memories.d.ts +6 -0
  197. package/resources/beta/memory-stores/memories.d.ts.map +1 -1
  198. package/resources/beta/memory-stores/memory-stores.js +150 -147
  199. package/resources/beta/memory-stores/memory-stores.js.map +1 -1
  200. package/resources/beta/memory-stores/memory-stores.mjs +150 -147
  201. package/resources/beta/memory-stores/memory-stores.mjs.map +1 -1
  202. package/resources/beta/memory-stores/memory-versions.d.mts +7 -0
  203. package/resources/beta/memory-stores/memory-versions.d.mts.map +1 -1
  204. package/resources/beta/memory-stores/memory-versions.d.ts +7 -0
  205. package/resources/beta/memory-stores/memory-versions.d.ts.map +1 -1
  206. package/resources/beta/messages/batches.d.mts +12 -1
  207. package/resources/beta/messages/batches.d.mts.map +1 -1
  208. package/resources/beta/messages/batches.d.ts +12 -1
  209. package/resources/beta/messages/batches.d.ts.map +1 -1
  210. package/resources/beta/messages/index.d.mts +1 -1
  211. package/resources/beta/messages/index.d.mts.map +1 -1
  212. package/resources/beta/messages/index.d.ts +1 -1
  213. package/resources/beta/messages/index.d.ts.map +1 -1
  214. package/resources/beta/messages/index.js.map +1 -1
  215. package/resources/beta/messages/index.mjs.map +1 -1
  216. package/resources/beta/messages/messages.d.mts +239 -101
  217. package/resources/beta/messages/messages.d.mts.map +1 -1
  218. package/resources/beta/messages/messages.d.ts +239 -101
  219. package/resources/beta/messages/messages.d.ts.map +1 -1
  220. package/resources/beta/messages/messages.js +113 -110
  221. package/resources/beta/messages/messages.js.map +1 -1
  222. package/resources/beta/messages/messages.mjs +113 -110
  223. package/resources/beta/messages/messages.mjs.map +1 -1
  224. package/resources/beta/models.d.mts +22 -1
  225. package/resources/beta/models.d.mts.map +1 -1
  226. package/resources/beta/models.d.ts +22 -1
  227. package/resources/beta/models.d.ts.map +1 -1
  228. package/resources/beta/organization/federation/federation.js +11 -8
  229. package/resources/beta/organization/federation/federation.js.map +1 -1
  230. package/resources/beta/organization/federation/federation.mjs +11 -8
  231. package/resources/beta/organization/federation/federation.mjs.map +1 -1
  232. package/resources/beta/organization/federation/rules/rules.js +187 -184
  233. package/resources/beta/organization/federation/rules/rules.js.map +1 -1
  234. package/resources/beta/organization/federation/rules/rules.mjs +187 -184
  235. package/resources/beta/organization/federation/rules/rules.mjs.map +1 -1
  236. package/resources/beta/organization/index.d.mts +1 -1
  237. package/resources/beta/organization/index.d.mts.map +1 -1
  238. package/resources/beta/organization/index.d.ts +1 -1
  239. package/resources/beta/organization/index.d.ts.map +1 -1
  240. package/resources/beta/organization/index.js.map +1 -1
  241. package/resources/beta/organization/index.mjs.map +1 -1
  242. package/resources/beta/organization/organization.d.mts +2 -2
  243. package/resources/beta/organization/organization.d.mts.map +1 -1
  244. package/resources/beta/organization/organization.d.ts +2 -2
  245. package/resources/beta/organization/organization.d.ts.map +1 -1
  246. package/resources/beta/organization/organization.js +38 -35
  247. package/resources/beta/organization/organization.js.map +1 -1
  248. package/resources/beta/organization/organization.mjs +38 -35
  249. package/resources/beta/organization/organization.mjs.map +1 -1
  250. package/resources/beta/organization/rate-limits.d.mts +87 -5
  251. package/resources/beta/organization/rate-limits.d.mts.map +1 -1
  252. package/resources/beta/organization/rate-limits.d.ts +87 -5
  253. package/resources/beta/organization/rate-limits.d.ts.map +1 -1
  254. package/resources/beta/organization/service-accounts/service-accounts.js +163 -160
  255. package/resources/beta/organization/service-accounts/service-accounts.js.map +1 -1
  256. package/resources/beta/organization/service-accounts/service-accounts.mjs +163 -160
  257. package/resources/beta/organization/service-accounts/service-accounts.mjs.map +1 -1
  258. package/resources/beta/organization/workspaces/rate-limits.d.mts +9 -4
  259. package/resources/beta/organization/workspaces/rate-limits.d.mts.map +1 -1
  260. package/resources/beta/organization/workspaces/rate-limits.d.ts +9 -4
  261. package/resources/beta/organization/workspaces/rate-limits.d.ts.map +1 -1
  262. package/resources/beta/organization/workspaces/rate-limits.js.map +1 -1
  263. package/resources/beta/organization/workspaces/rate-limits.mjs.map +1 -1
  264. package/resources/beta/organization/workspaces/workspaces.d.mts +3 -3
  265. package/resources/beta/organization/workspaces/workspaces.d.mts.map +1 -1
  266. package/resources/beta/organization/workspaces/workspaces.d.ts +3 -3
  267. package/resources/beta/organization/workspaces/workspaces.d.ts.map +1 -1
  268. package/resources/beta/organization/workspaces/workspaces.js +97 -94
  269. package/resources/beta/organization/workspaces/workspaces.js.map +1 -1
  270. package/resources/beta/organization/workspaces/workspaces.mjs +97 -94
  271. package/resources/beta/organization/workspaces/workspaces.mjs.map +1 -1
  272. package/resources/beta/sessions/events.d.mts +12 -21
  273. package/resources/beta/sessions/events.d.mts.map +1 -1
  274. package/resources/beta/sessions/events.d.ts +12 -21
  275. package/resources/beta/sessions/events.d.ts.map +1 -1
  276. package/resources/beta/sessions/events.js +118 -115
  277. package/resources/beta/sessions/events.js.map +1 -1
  278. package/resources/beta/sessions/events.mjs +118 -115
  279. package/resources/beta/sessions/events.mjs.map +1 -1
  280. package/resources/beta/sessions/resources.d.mts +0 -3
  281. package/resources/beta/sessions/resources.d.mts.map +1 -1
  282. package/resources/beta/sessions/resources.d.ts +0 -3
  283. package/resources/beta/sessions/resources.d.ts.map +1 -1
  284. package/resources/beta/sessions/sessions.d.mts +8 -2
  285. package/resources/beta/sessions/sessions.d.mts.map +1 -1
  286. package/resources/beta/sessions/sessions.d.ts +8 -2
  287. package/resources/beta/sessions/sessions.d.ts.map +1 -1
  288. package/resources/beta/sessions/sessions.js +161 -158
  289. package/resources/beta/sessions/sessions.js.map +1 -1
  290. package/resources/beta/sessions/sessions.mjs +161 -158
  291. package/resources/beta/sessions/sessions.mjs.map +1 -1
  292. package/resources/beta/sessions/threads/threads.js +86 -83
  293. package/resources/beta/sessions/threads/threads.js.map +1 -1
  294. package/resources/beta/sessions/threads/threads.mjs +86 -83
  295. package/resources/beta/sessions/threads/threads.mjs.map +1 -1
  296. package/resources/beta/skills/skills.js +104 -101
  297. package/resources/beta/skills/skills.js.map +1 -1
  298. package/resources/beta/skills/skills.mjs +104 -101
  299. package/resources/beta/skills/skills.mjs.map +1 -1
  300. package/resources/beta/tunnels/certificates.d.mts +2 -2
  301. package/resources/beta/tunnels/certificates.d.ts +2 -2
  302. package/resources/beta/tunnels/tunnels.js +188 -185
  303. package/resources/beta/tunnels/tunnels.js.map +1 -1
  304. package/resources/beta/tunnels/tunnels.mjs +188 -185
  305. package/resources/beta/tunnels/tunnels.mjs.map +1 -1
  306. package/resources/beta/user-profiles.d.mts +45 -0
  307. package/resources/beta/user-profiles.d.mts.map +1 -1
  308. package/resources/beta/user-profiles.d.ts +45 -0
  309. package/resources/beta/user-profiles.d.ts.map +1 -1
  310. package/resources/beta/user-profiles.js +25 -10
  311. package/resources/beta/user-profiles.js.map +1 -1
  312. package/resources/beta/user-profiles.mjs +25 -10
  313. package/resources/beta/user-profiles.mjs.map +1 -1
  314. package/resources/beta/vaults/credentials.d.mts +19 -19
  315. package/resources/beta/vaults/credentials.d.mts.map +1 -1
  316. package/resources/beta/vaults/credentials.d.ts +19 -19
  317. package/resources/beta/vaults/credentials.d.ts.map +1 -1
  318. package/resources/beta/vaults/vaults.js +156 -153
  319. package/resources/beta/vaults/vaults.js.map +1 -1
  320. package/resources/beta/vaults/vaults.mjs +156 -153
  321. package/resources/beta/vaults/vaults.mjs.map +1 -1
  322. package/resources/completions.d.mts +1 -1
  323. package/resources/completions.d.ts +1 -1
  324. package/resources/index.d.mts +1 -1
  325. package/resources/index.d.mts.map +1 -1
  326. package/resources/index.d.ts +1 -1
  327. package/resources/index.d.ts.map +1 -1
  328. package/resources/index.js.map +1 -1
  329. package/resources/index.mjs.map +1 -1
  330. package/resources/messages/index.d.mts +1 -1
  331. package/resources/messages/index.d.mts.map +1 -1
  332. package/resources/messages/index.d.ts +1 -1
  333. package/resources/messages/index.d.ts.map +1 -1
  334. package/resources/messages/index.js.map +1 -1
  335. package/resources/messages/index.mjs.map +1 -1
  336. package/resources/messages/messages.d.mts +100 -63
  337. package/resources/messages/messages.d.mts.map +1 -1
  338. package/resources/messages/messages.d.ts +100 -63
  339. package/resources/messages/messages.d.ts.map +1 -1
  340. package/resources/messages/messages.js +115 -112
  341. package/resources/messages/messages.js.map +1 -1
  342. package/resources/messages/messages.mjs +115 -112
  343. package/resources/messages/messages.mjs.map +1 -1
  344. package/resources/skills/skills.js +88 -85
  345. package/resources/skills/skills.js.map +1 -1
  346. package/resources/skills/skills.mjs +88 -85
  347. package/resources/skills/skills.mjs.map +1 -1
  348. package/resources/top-level.js +0 -1
  349. package/resources/top-level.js.map +1 -1
  350. package/resources/top-level.mjs +0 -1
  351. package/resources/top-level.mjs.map +1 -1
  352. package/src/client.ts +95 -72
  353. package/src/internal/node.browser.ts +7 -7
  354. package/src/internal/parse.ts +8 -11
  355. package/src/internal/shims.ts +4 -3
  356. package/src/internal/utils/bytes.ts +1 -1
  357. package/src/internal/utils/log.ts +16 -2
  358. package/src/lib/BetaMessageStream.ts +7 -5
  359. package/src/lib/beta-parser.ts +1 -3
  360. package/src/lib/internal/stub.ts +2 -0
  361. package/src/lib/internal/types.ts +2 -0
  362. package/src/lib/middleware.ts +6 -1
  363. package/src/lib/parser.ts +1 -3
  364. package/src/lib/tools/BetaToolRunner.ts +157 -24
  365. package/src/lib/transform-json-schema.ts +8 -6
  366. package/src/resources/beta/beta.ts +24 -1
  367. package/src/resources/beta/deployment-runs.ts +4 -0
  368. package/src/resources/beta/deployments.ts +5 -0
  369. package/src/resources/beta/dreams.ts +19 -28
  370. package/src/resources/beta/index.ts +11 -0
  371. package/src/resources/beta/memory-stores/memories.ts +6 -0
  372. package/src/resources/beta/memory-stores/memory-versions.ts +7 -0
  373. package/src/resources/beta/messages/batches.ts +13 -1
  374. package/src/resources/beta/messages/index.ts +10 -0
  375. package/src/resources/beta/messages/messages.ts +289 -100
  376. package/src/resources/beta/models.ts +25 -0
  377. package/src/resources/beta/organization/index.ts +6 -0
  378. package/src/resources/beta/organization/organization.ts +12 -0
  379. package/src/resources/beta/organization/rate-limits.ts +112 -4
  380. package/src/resources/beta/organization/workspaces/rate-limits.ts +16 -4
  381. package/src/resources/beta/organization/workspaces/workspaces.ts +3 -3
  382. package/src/resources/beta/sessions/events.ts +12 -21
  383. package/src/resources/beta/sessions/resources.ts +0 -3
  384. package/src/resources/beta/sessions/sessions.ts +8 -2
  385. package/src/resources/beta/tunnels/certificates.ts +2 -2
  386. package/src/resources/beta/user-profiles.ts +75 -10
  387. package/src/resources/beta/vaults/credentials.ts +19 -19
  388. package/src/resources/completions.ts +1 -1
  389. package/src/resources/index.ts +6 -0
  390. package/src/resources/messages/index.ts +6 -0
  391. package/src/resources/messages/messages.ts +128 -62
  392. package/src/tsconfig.json +13 -3
  393. package/src/version.ts +1 -1
  394. package/tools/agent-toolset/fs-util.js +0 -6
  395. package/tools/agent-toolset/fs-util.js.map +1 -1
  396. package/tools/agent-toolset/fs-util.mjs +0 -6
  397. package/tools/agent-toolset/fs-util.mjs.map +1 -1
  398. package/tools/agent-toolset/memories.js +4 -4
  399. package/tools/agent-toolset/memories.js.map +1 -1
  400. package/tools/agent-toolset/memories.mjs +2 -2
  401. package/tools/agent-toolset/memories.mjs.map +1 -1
  402. package/tools/agent-toolset/node.browser.js +12 -12
  403. package/tools/agent-toolset/node.browser.js.map +1 -1
  404. package/tools/agent-toolset/node.js +142 -139
  405. package/tools/agent-toolset/node.js.map +1 -1
  406. package/tools/agent-toolset/node.mjs +132 -125
  407. package/tools/agent-toolset/node.mjs.map +1 -1
  408. package/tools/agent-toolset/skills.js +5 -5
  409. package/tools/agent-toolset/skills.js.map +1 -1
  410. package/tools/agent-toolset/sync-interval.js +3 -3
  411. package/tools/agent-toolset/sync-interval.js.map +1 -1
  412. package/tools/memory/node.browser.js +2 -2
  413. package/tools/memory/node.browser.js.map +1 -1
  414. package/version.d.mts +1 -1
  415. package/version.d.ts +1 -1
  416. package/version.js +1 -1
  417. package/version.mjs +1 -1
package/client.mjs CHANGED
@@ -27,898 +27,924 @@ import { Skills, } from "./resources/skills/skills.mjs";
27
27
  import { isRunningInBrowser } from "./internal/detect-platform.mjs";
28
28
  import { buildHeaders } from "./internal/headers.mjs";
29
29
  import { readEnv } from "./internal/utils/env.mjs";
30
- import { defaultLogLevel, formatRequestDetails, loggerFor, parseLogLevel, } from "./internal/utils/log.mjs";
30
+ import { debugLogRequestDetails, defaultLogLevel, loggerFor, parseLogLevel, } from "./internal/utils/log.mjs";
31
31
  import { isEmptyObj } from "./internal/utils/values.mjs";
32
32
  export const HUMAN_PROMPT = '\\n\\nHuman:';
33
33
  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
+ }
119
124
  }
125
+ options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
120
126
  }
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);
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;
141
+ }
142
+ }
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;
312
+ defaultQuery() {
313
+ return this._options.defaultQuery;
317
314
  }
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;
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');
329
338
  }
330
- if (nulls.has('authorization')) {
331
- return;
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)]);
332
364
  }
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);
365
+ async apiKeyAuth(opts) {
366
+ if (this.apiKey == null) {
367
+ return undefined;
368
+ }
369
+ return buildHeaders([{ 'X-Api-Key': this.apiKey }]);
340
370
  }
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;
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.set('anthropic-beta', [...(existing ?? []), OAUTH_API_BETA_HEADER].join(','));
446
+ }
447
+ request.headers = headers;
448
+ }
364
449
  }
365
- return buildHeaders([{ 'X-Api-Key': this.apiKey }]);
366
- }
367
- async bearerAuth(opts) {
368
- if (this.authToken == null) {
369
- return undefined;
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
+ }));
370
490
  }
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;
491
+ request(options, remainingRetries = null) {
492
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
444
493
  }
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`;
494
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
495
+ const options = await optionsInput;
496
+ let maxRetries = validatePositiveInteger('maxRetries', options.maxRetries ?? this.maxRetries);
497
+ if (this.isStreamBody(options.body)) {
498
+ maxRetries = 0;
499
+ }
500
+ if (retriesRemaining == null) {
501
+ retriesRemaining = maxRetries;
502
+ // Top-level call: reset per-request auth flags so a reused options object
503
+ // (via client.request(opts)) doesn't carry stale 401-refresh state.
504
+ this._requestAuthFlags.delete(options);
505
+ }
506
+ await this.prepareOptions(options);
507
+ const { req, url, timeout } = await this.buildRequest(options, {
508
+ retryCount: maxRetries - retriesRemaining,
509
+ });
510
+ /** Not an API request ID, just for correlating local log entries. */
511
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
512
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
513
+ const startTime = Date.now();
519
514
  if (options.signal?.aborted) {
520
515
  throw new Errors.APIUserAbortError();
521
516
  }
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({
517
+ const controller = new AbortController();
518
+ const response = await this.fetchWithTimeout(url, req, timeout, controller, options, {
519
+ requestLogID,
520
+ retryOfRequestLogID,
521
+ }).catch(castToError);
522
+ const headersTime = Date.now();
523
+ if (response instanceof globalThis.Error) {
524
+ releaseRequestSignal(controller);
525
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
526
+ if (options.signal?.aborted) {
527
+ throw new Errors.APIUserAbortError();
528
+ }
529
+ // detect native connection timeout errors
530
+ // 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)"
531
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
532
+ // others do not provide enough information to distinguish timeouts from other connection errors
533
+ const isTimeout = isAbortError(response) ||
534
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
535
+ // Errors thrown by middleware (user middleware and the backend adaptation
536
+ // alike) propagate to the caller as-is — no retries, no APIConnectionError
537
+ // wrapping — except retryable errors (timeouts/aborts, APIConnectionErrors,
538
+ // and RetryableErrors, directly or in the `cause` chain), which stay on the
539
+ // retry path.
540
+ const hasMiddleware = this.middleware.length > 0 || !!options.middleware?.length || this.backendMiddleware().length > 0;
541
+ if (hasMiddleware && !isTimeout && !isRetryableError(response)) {
542
+ loggerFor(this).info(`[${requestLogID}] middleware error (not retryable)`);
543
+ debugLogRequestDetails(loggerFor(this), `[${requestLogID}] middleware error (not retryable)`, {
544
+ retryOfRequestLogID,
545
+ url,
546
+ durationMs: headersTime - startTime,
547
+ message: response.message,
548
+ });
549
+ throw response;
550
+ }
551
+ if (retriesRemaining) {
552
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
553
+ debugLogRequestDetails(loggerFor(this), `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, {
554
+ retryOfRequestLogID,
555
+ url,
556
+ durationMs: headersTime - startTime,
557
+ message: response.message,
558
+ });
559
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
560
+ }
561
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
562
+ debugLogRequestDetails(loggerFor(this), `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, {
547
563
  retryOfRequestLogID,
548
564
  url,
549
565
  durationMs: headersTime - startTime,
550
566
  message: response.message,
551
- }));
552
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
567
+ });
568
+ if (isTimeout) {
569
+ throw new Errors.APIConnectionTimeoutError();
570
+ }
571
+ // a retryable middleware-origin error is still the caller's error: once retries are
572
+ // exhausted it propagates as-is rather than wrapped in APIConnectionError
573
+ if (hasMiddleware && !isFetchOriginError(response)) {
574
+ throw response;
575
+ }
576
+ throw new Errors.APIConnectionError({ cause: response });
553
577
  }
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);
578
+ const specialHeaders = [...response.headers.entries()]
579
+ .filter(([name]) => name === 'request-id' || name === 'anthropic-workspace-id')
580
+ .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
581
+ .join('');
582
+ const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
583
+ if (!response.ok) {
584
+ const shouldRetry = await this.shouldRetry(response, options);
585
+ if (retriesRemaining && shouldRetry) {
586
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
587
+ // We don't need the body of this response.
588
+ await Shims.CancelReadableStream(response.body);
589
+ releaseRequestSignal(controller);
590
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
591
+ debugLogRequestDetails(loggerFor(this), `[${requestLogID}] response error (${retryMessage})`, {
592
+ retryOfRequestLogID,
593
+ url: response.url,
594
+ status: response.status,
595
+ headers: response.headers,
596
+ durationMs: headersTime - startTime,
597
+ });
598
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
599
+ }
600
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
583
601
  loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
584
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
602
+ const errText = await response.text().catch((err) => castToError(err).message);
603
+ const errJSON = safeJSON(errText);
604
+ const errMessage = errJSON ? undefined : errText;
605
+ debugLogRequestDetails(loggerFor(this), `[${requestLogID}] response error (${retryMessage})`, {
585
606
  retryOfRequestLogID,
586
607
  url: response.url,
587
608
  status: response.status,
588
609
  headers: response.headers,
589
- durationMs: headersTime - startTime,
590
- }));
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
+ message: errMessage,
611
+ durationMs: Date.now() - startTime,
612
+ });
613
+ releaseRequestSignal(controller);
614
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
615
+ throw err;
616
+ }
617
+ loggerFor(this).info(responseInfo);
618
+ debugLogRequestDetails(loggerFor(this), `[${requestLogID}] response start`, {
599
619
  retryOfRequestLogID,
600
620
  url: response.url,
601
621
  status: response.status,
602
622
  headers: response.headers,
603
- message: errMessage,
604
- durationMs: Date.now() - startTime,
605
- }));
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);
623
+ durationMs: headersTime - startTime,
624
+ });
625
+ armAbandonmentBackstop(response.body ?? response, controller);
626
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
627
+ }
628
+ getAPIList(path, Page, opts) {
629
+ return this.requestAPIList(Page, opts && 'then' in opts ?
630
+ opts.then((opts) => ({ method: 'get', path, ...opts }))
631
+ : { method: 'get', path, ...opts });
632
+ }
633
+ requestAPIList(Page, options) {
634
+ const request = this.makeRequest(options, null, undefined);
635
+ return new Pagination.PagePromise(this, request, Page);
636
+ }
637
+ async fetchWithTimeout(url, init, ms, controller, requestOptions, logCtx) {
638
+ const { signal, method, ...options } = init || {};
639
+ // Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks.
640
+ // An arrow function like `() => controller.abort()` captures the surrounding scope,
641
+ // which includes the request body and other large objects. When the user passes a
642
+ // long-lived AbortSignal, the listener prevents those objects from being GC'd for
643
+ // the lifetime of the signal. Using `.bind()` only retains a reference to the
644
+ // controller itself.
645
+ const abort = this._makeAbort(controller);
646
+ if (signal) {
647
+ signal.addEventListener('abort', abort, { once: true });
648
+ registerRequestSignalCleanup(controller, signal, abort);
664
649
  }
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
- }));
690
- }
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')
721
- 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;
650
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
651
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
652
+ const fetchOptions = {
653
+ signal: controller.signal,
654
+ ...(isReadableBody ? { duplex: 'half' } : {}),
655
+ method: 'GET',
656
+ ...options,
657
+ };
658
+ if (method) {
659
+ // Custom methods like 'patch' need to be uppercased
660
+ // See https://github.com/nodejs/undici/issues/2294
661
+ fetchOptions.method = method.toUpperCase();
752
662
  }
753
- else {
754
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
663
+ // Arm the timeout around the underlying fetch only, not the middleware
664
+ // chain — middleware can take arbitrarily long (or call `next` more than
665
+ // once), and each inner-fetch invocation gets its own `ms` timer.
666
+ const baseFetch = this.fetch;
667
+ const timedFetch = async (innerUrl, innerInit) => {
668
+ const timeout = setTimeout(abort, ms);
669
+ try {
670
+ return await baseFetch.call(undefined, innerUrl, innerInit);
671
+ }
672
+ finally {
673
+ clearTimeout(timeout);
674
+ }
675
+ };
676
+ // Prepare the request (auth signing and other `prepareRequest` hooks) as
677
+ // the innermost step, after any middleware — including the backend
678
+ // middleware, so it sees exactly what goes over the wire. Runs per
679
+ // inner-fetch invocation, so a request middleware rewrote — or replayed
680
+ // via a second `next()` call — is prepared fresh each time. Preparation is
681
+ // outside the timeout timer, matching its pre-middleware behavior.
682
+ const innerFetch = requestOptions === undefined ? timedFetch : (async (innerUrl, innerInit = {}) => {
683
+ const innerUrlStr = typeof innerUrl === 'string' ? innerUrl
684
+ : innerUrl instanceof URL ? innerUrl.href
685
+ : innerUrl.url;
686
+ innerInit.headers =
687
+ innerInit.headers instanceof Headers ? innerInit.headers : new Headers(innerInit.headers);
688
+ await this.prepareRequest(innerInit, { url: innerUrlStr, options: requestOptions });
689
+ if (logCtx) {
690
+ debugLogRequestDetails(loggerFor(this), `[${logCtx.requestLogID}] sending request`, {
691
+ retryOfRequestLogID: logCtx.retryOfRequestLogID,
692
+ method: innerInit.method,
693
+ url: innerUrlStr,
694
+ options: requestOptions,
695
+ headers: innerInit.headers,
696
+ });
697
+ }
698
+ return timedFetch(innerUrl, innerInit);
699
+ });
700
+ const requestMiddleware = requestOptions?.middleware;
701
+ const backendMiddleware = this.backendMiddleware();
702
+ const allMiddleware = requestMiddleware?.length || backendMiddleware.length ?
703
+ [...this.middleware, ...(requestMiddleware ?? []), ...backendMiddleware]
704
+ : this.middleware;
705
+ return await wrapFetchWithMiddleware(innerFetch, allMiddleware, requestOptions, this)(url, fetchOptions);
706
+ }
707
+ async shouldRetry(response, options) {
708
+ // Reactive refresh: on a 401 from a request that used the token cache,
709
+ // invalidate and retry once. Only fires when this specific request was
710
+ // bearer-authenticated (not when an apiKey was used) and only once per
711
+ // request — a second 401 after refresh falls through to the normal
712
+ // retry policy below (which treats 4xx as non-retryable).
713
+ const flags = this._authFlags(options);
714
+ if (response.status === 401 &&
715
+ this._authState.tokenCache &&
716
+ flags.usedTokenCache &&
717
+ !flags.didRefreshFor401) {
718
+ flags.didRefreshFor401 = true;
719
+ this._authState.tokenCache.invalidate();
720
+ return true;
755
721
  }
722
+ // Note this is not a standard header.
723
+ const shouldRetryHeader = response.headers.get('x-should-retry');
724
+ // If the server explicitly says whether or not to retry, obey.
725
+ if (shouldRetryHeader === 'true')
726
+ return true;
727
+ if (shouldRetryHeader === 'false')
728
+ return false;
729
+ // Retry on request timeouts.
730
+ if (response.status === 408)
731
+ return true;
732
+ // Retry on lock timeouts.
733
+ if (response.status === 409)
734
+ return true;
735
+ // Retry on rate limits.
736
+ if (response.status === 429)
737
+ return true;
738
+ // Retry internal errors.
739
+ if (response.status >= 500)
740
+ return true;
741
+ return false;
756
742
  }
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),
743
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
744
+ let timeoutMillis;
745
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
746
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
747
+ if (retryAfterMillisHeader) {
748
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
749
+ if (!Number.isNaN(timeoutMs)) {
750
+ timeoutMillis = timeoutMs;
751
+ }
752
+ }
753
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
754
+ const retryAfterHeader = responseHeaders?.get('retry-after');
755
+ if (retryAfterHeader && !timeoutMillis) {
756
+ const timeoutSeconds = parseFloat(retryAfterHeader);
757
+ if (!Number.isNaN(timeoutSeconds)) {
758
+ timeoutMillis = timeoutSeconds * 1000;
759
+ }
760
+ else {
761
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
762
+ }
763
+ }
764
+ // 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
765
+ // one timer can represent (setTimeout fires after 1ms for anything above 2^31 - 1). Otherwise (no header, an
766
+ // unparseable value, zero/negative, a date in the past) calculate a default.
767
+ if (timeoutMillis === undefined || !(timeoutMillis > 0 && timeoutMillis <= 2 ** 31 - 1)) {
768
+ const maxRetries = options.maxRetries ?? this.maxRetries;
769
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
770
+ }
771
+ await sleep(timeoutMillis, options.signal ?? undefined);
772
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
773
+ }
774
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
775
+ const initialRetryDelay = 0.5;
776
+ const maxRetryDelay = 8.0;
777
+ const numRetries = maxRetries - retriesRemaining;
778
+ // Apply exponential backoff, but not more than the max.
779
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
780
+ // Apply some jitter, take up to at most 25 percent of the retry time.
781
+ const jitter = 1 - Math.random() * 0.25;
782
+ return sleepSeconds * jitter * 1000;
783
+ }
784
+ calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
785
+ const maxTime = 60 * 60 * 1000; // 60 minutes
786
+ const defaultTime = 60 * 10 * 1000; // 10 minutes
787
+ const expectedTime = (maxTime * maxTokens) / 128000;
788
+ if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {
789
+ 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');
790
+ }
791
+ return defaultTime;
792
+ }
793
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
794
+ const options = { ...inputOptions };
795
+ const { method, path, query, defaultBaseURL } = options;
796
+ // Lazy credential resolution may carry a profile-supplied baseURL. Await
797
+ // it before building the request URL so the very first request — and
798
+ // requests on withOptions() clones created before resolution settled —
799
+ // hit the profile's host rather than the hardcoded default.
800
+ if (this._authState.resolution) {
801
+ await this._authState.resolution;
802
+ }
803
+ if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) {
804
+ this.baseURL = this._authState.baseURL;
805
+ }
806
+ const url = this.buildURL(path, query, defaultBaseURL);
807
+ if ('timeout' in options)
808
+ validatePositiveInteger('timeout', options.timeout);
809
+ options.timeout = options.timeout ?? this.timeout;
810
+ const { bodyHeaders, body } = this.buildBody({ options });
811
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
812
+ const req = {
813
+ method,
814
+ headers: reqHeaders,
815
+ ...(options.signal && { signal: options.signal }),
816
+ ...(globalThis.ReadableStream &&
817
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
818
+ ...(body && { body }),
819
+ ...(this.fetchOptions ?? {}),
820
+ ...(options.fetchOptions ?? {}),
876
821
  };
822
+ return { req, url, timeout: options.timeout };
823
+ }
824
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
825
+ const headers = buildHeaders([
826
+ {
827
+ Accept: 'application/json',
828
+ 'User-Agent': this.getUserAgent(),
829
+ 'X-Stainless-Retry-Count': String(retryCount),
830
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
831
+ ...getPlatformHeaders(),
832
+ ...(this._options.dangerouslyAllowBrowser ?
833
+ { 'anthropic-dangerous-direct-browser-access': 'true' }
834
+ : undefined),
835
+ 'anthropic-version': '2023-06-01',
836
+ },
837
+ await this.authHeaders(options),
838
+ this._options.defaultHeaders,
839
+ bodyHeaders,
840
+ options.headers,
841
+ ]);
842
+ this.validateHeaders(headers);
843
+ return headers.values;
844
+ }
845
+ _makeAbort(controller) {
846
+ // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure
847
+ // would capture all request options, and cause a memory leak.
848
+ return () => controller.abort();
849
+ }
850
+ buildBody({ options: { body, headers: rawHeaders } }) {
851
+ if (!body) {
852
+ return { bodyHeaders: undefined, body: undefined };
853
+ }
854
+ const headers = buildHeaders([rawHeaders]);
855
+ if (
856
+ // Pass raw type verbatim
857
+ ArrayBuffer.isView(body) ||
858
+ body instanceof ArrayBuffer ||
859
+ body instanceof DataView ||
860
+ (typeof body === 'string' &&
861
+ // Preserve legacy string encoding behavior for now
862
+ headers.values.has('content-type')) ||
863
+ // `Blob` is superset of `File`
864
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
865
+ // `FormData` -> `multipart/form-data`
866
+ body instanceof FormData ||
867
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
868
+ body instanceof URLSearchParams ||
869
+ // Send chunked stream (each chunk has own `length`)
870
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
871
+ return { bodyHeaders: undefined, body: body };
872
+ }
873
+ else if (this.isStreamBody(body)) {
874
+ return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
875
+ }
876
+ else if (typeof body === 'object' &&
877
+ headers.values.get('content-type') === 'application/x-www-form-urlencoded') {
878
+ return {
879
+ bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },
880
+ body: this.stringifyQuery(body),
881
+ };
882
+ }
883
+ else {
884
+ return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
885
+ }
877
886
  }
878
- else {
879
- return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
880
- }
881
- }
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
+ /**
888
+ * Whether `body` is sent as a stream, which can be read only once:
889
+ * a `ReadableStream`, an async iterable or an iterator.
890
+ */
891
+ isStreamBody(body) {
892
+ if (globalThis.ReadableStream && body instanceof globalThis.ReadableStream) {
893
+ return true;
894
+ }
895
+ return (typeof body === 'object' &&
896
+ body !== null &&
897
+ (Symbol.asyncIterator in body ||
898
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function')));
899
+ }
900
+ }
901
+ _a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() {
902
+ return this.baseURL !== 'https://api.anthropic.com';
903
+ };
904
+ BaseAnthropic.Anthropic = _a;
905
+ BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT;
906
+ BaseAnthropic.AI_PROMPT = AI_PROMPT;
907
+ BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes
908
+ BaseAnthropic.AnthropicError = Errors.AnthropicError;
909
+ BaseAnthropic.APIError = Errors.APIError;
910
+ BaseAnthropic.APIConnectionError = Errors.APIConnectionError;
911
+ BaseAnthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
912
+ BaseAnthropic.APIUserAbortError = Errors.APIUserAbortError;
913
+ BaseAnthropic.NotFoundError = Errors.NotFoundError;
914
+ BaseAnthropic.ConflictError = Errors.ConflictError;
915
+ BaseAnthropic.RateLimitError = Errors.RateLimitError;
916
+ BaseAnthropic.BadRequestError = Errors.BadRequestError;
917
+ BaseAnthropic.AuthenticationError = Errors.AuthenticationError;
918
+ BaseAnthropic.InternalServerError = Errors.InternalServerError;
919
+ BaseAnthropic.PermissionDeniedError = Errors.PermissionDeniedError;
920
+ BaseAnthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
921
+ BaseAnthropic.toFile = Uploads.toFile;
922
+ return BaseAnthropic;
923
+ })();
904
924
  /**
905
925
  * API Client for interfacing with the Anthropic API.
906
926
  */
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;
927
+ export var Anthropic = /* @__PURE__ */ (() => {
928
+ /**
929
+ * API Client for interfacing with the Anthropic API.
930
+ */
931
+ class Anthropic extends BaseAnthropic {
932
+ constructor() {
933
+ super(...arguments);
934
+ this.completions = new API.Completions(this);
935
+ this.messages = new API.Messages(this);
936
+ this.models = new API.Models(this);
937
+ this.files = new API.Files(this);
938
+ this.skills = new API.Skills(this);
939
+ this.beta = new API.Beta(this);
940
+ }
941
+ }
942
+ Anthropic.Completions = Completions;
943
+ Anthropic.Messages = Messages;
944
+ Anthropic.Models = Models;
945
+ Anthropic.Files = Files;
946
+ Anthropic.Skills = Skills;
947
+ Anthropic.Beta = Beta;
948
+ return Anthropic;
949
+ })();
924
950
  //# sourceMappingURL=client.mjs.map