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