sliccy 5.67.1 → 5.68.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 (200) hide show
  1. package/dist/ui/assets/__vite-browser-external-CtuZSfo7.js +1 -0
  2. package/dist/ui/assets/{account-store-D7kMPjMl.js → account-store-CoA-EjrR.js} +1 -1
  3. package/dist/ui/assets/account-store-Cw-Kdlic.js +94 -0
  4. package/dist/ui/assets/adobe-B4gTTma2.js +1 -0
  5. package/dist/ui/assets/adobe-CqST5E4B.js +2 -0
  6. package/dist/ui/assets/amazon-bedrock-Cg62P8pR.json +1 -0
  7. package/dist/ui/assets/anthropic-4_qTN2Mu.json +1 -0
  8. package/dist/ui/assets/anthropic-messages-6XWFkWWy.js +39 -0
  9. package/dist/ui/assets/anthropic-messages-D42B1WVl.js +39 -0
  10. package/dist/ui/assets/{apps-BoOkGG9c.js → apps-BtS9MYxU.js} +1 -1
  11. package/dist/ui/assets/azure-openai-CKRM23oV.js +1 -0
  12. package/dist/ui/assets/azure-openai-CcIDDU6v.js +1 -0
  13. package/dist/ui/assets/azure-openai-responses-BvEv9lZE.js +1 -0
  14. package/dist/ui/assets/azure-openai-responses-DE9sINqp.json +1 -0
  15. package/dist/ui/assets/azure-openai-responses-DRSA640t.js +1 -0
  16. package/dist/ui/assets/bedrock-camp-D_7EbOFH.js +1 -0
  17. package/dist/ui/assets/bedrock-camp-PMQ4Iu6f.js +1 -0
  18. package/dist/ui/assets/cerebras-Cjamhn6S.js +1 -0
  19. package/dist/ui/assets/cerebras-DsAtsb2V.js +1 -0
  20. package/dist/ui/assets/cloudflare-ai-gateway-DDb7hKDm.json +1 -0
  21. package/dist/ui/assets/cloudflare-workers-ai-hYVOS3es.json +1 -0
  22. package/dist/ui/assets/compat-Spvv5tCW.js +2 -0
  23. package/dist/ui/assets/{composer-speech-CWgEvzia.js → composer-speech-BSy_wbJC.js} +1 -1
  24. package/dist/ui/assets/{connect-surface-C-7W435s.js → connect-surface-C6I8TboO.js} +1 -1
  25. package/dist/ui/assets/{context-compaction-dcYYajWb.js → context-compaction-CW5AQ9bv.js} +1 -1
  26. package/dist/ui/assets/deferred-tools-C1IEsG5C.js +1 -0
  27. package/dist/ui/assets/deferred-tools-DNuoafg8.js +1 -0
  28. package/dist/ui/assets/diagnostics-BsVbaNHR.js +1 -0
  29. package/dist/ui/assets/{dip-CxC1oNbs.js → dip-D3QakWLH.js} +1 -1
  30. package/dist/ui/assets/{ensure-speech-assets-Wr0NmhbD.js → ensure-speech-assets-8cWrra0n.js} +1 -1
  31. package/dist/ui/assets/event-stream-qbAZIAKV.js +1 -0
  32. package/dist/ui/assets/fireworks-B7kEGNCU.json +1 -0
  33. package/dist/ui/assets/{fs-D5H4qV90.js → fs-Bmq507Od.js} +1 -1
  34. package/dist/ui/assets/{fs-D_yANcgX.js → fs-WTyVMSI7.js} +2 -2
  35. package/dist/ui/assets/{github-BpqJV3zd.js → github-B6i7fX-k.js} +1 -1
  36. package/dist/ui/assets/{github-O8AoJ7u2.js → github-D7xWsi2X.js} +2 -2
  37. package/dist/ui/assets/github-copilot-Bo5sSGEf.js +2 -0
  38. package/dist/ui/assets/github-copilot-DgH4lVlG.js +1 -0
  39. package/dist/ui/assets/github-copilot-K9C_HNHm.json +1 -0
  40. package/dist/ui/assets/google-F4XgvJ1y.json +1 -0
  41. package/dist/ui/assets/google-generative-ai-BqEHWDKc.js +1 -0
  42. package/dist/ui/assets/google-generative-ai-DOAY2Bef.js +1 -0
  43. package/dist/ui/assets/{google-shared-CCJkdw81.js → google-shared-2WQG4pNx.js} +1 -1
  44. package/dist/ui/assets/{google-shared-p5XdfI6c.js → google-shared-CGD-JGZx.js} +1 -1
  45. package/dist/ui/assets/google-vertex-C-dQj0iH.js +1 -0
  46. package/dist/ui/assets/google-vertex-CiTExP0E.js +1 -0
  47. package/dist/ui/assets/{hear-C1RTIY9q.js → hear-B5lURJtR.js} +1 -1
  48. package/dist/ui/assets/{hear-BxiGt0Ct.js → hear-DI5vlKdf.js} +1 -1
  49. package/dist/ui/assets/huggingface-BjNadu0v.json +1 -0
  50. package/dist/ui/assets/{installer-FOVSBgCf.js → installer-kDSMsl2T.js} +1 -1
  51. package/dist/ui/assets/{js-realm-worker-DFnuhv4z.js → js-realm-worker-d_SDr24a.js} +7 -7
  52. package/dist/ui/assets/{kernel-worker-uWACBBhV.js → kernel-worker-DNk5pbO8.js} +592 -588
  53. package/dist/ui/assets/{kokoro-engine-8rE8HqhM.js → kokoro-engine-DX7VicqD.js} +1 -1
  54. package/dist/ui/assets/{legacy-api-aliases-BQSsmFIS.js → legacy-api-aliases-CRTuRAqQ.js} +1 -1
  55. package/dist/ui/assets/{legacy-api-aliases-BEwZmDvB.js → legacy-api-aliases-CdGTJw-r.js} +1 -1
  56. package/dist/ui/assets/{lick-ws-bridge-TTCR56gq.js → lick-ws-bridge-BVIYLuDJ.js} +1 -1
  57. package/dist/ui/assets/{local-llm-DuSay7Zm.js → local-llm-4lJSiK5z.js} +1 -1
  58. package/dist/ui/assets/{local-llm-DtdiuuN-.js → local-llm-BHmd5Fd7.js} +2 -2
  59. package/dist/ui/assets/{magick-wasm-BiCoSTdr.js → magick-wasm-Daq1kpb4.js} +1 -1
  60. package/dist/ui/assets/{main-DXAgi47H.js → main-CrR9ucLa.js} +3 -3
  61. package/dist/ui/assets/mistral-CLEcIOtP.json +1 -0
  62. package/dist/ui/assets/{mistral-conversations-DbKikZnf.js → mistral-conversations-BIHTMTfL.js} +1 -1
  63. package/dist/ui/assets/{mistral-conversations-CLDzxp2F.js → mistral-conversations-CFKNSaPt.js} +2 -2
  64. package/dist/ui/assets/models-Bnh9VDA1.js +1 -0
  65. package/dist/ui/assets/moonshotai-8QShYhhE.json +1 -0
  66. package/dist/ui/assets/moonshotai-cn-7hHZff5z.json +1 -0
  67. package/dist/ui/assets/{mount-B6AQ9wuU.js → mount-Bt1UFWjP.js} +2 -2
  68. package/dist/ui/assets/{mount-C5cBuZIQ.js → mount-Cvxu87k0.js} +1 -1
  69. package/dist/ui/assets/{mount-recovery-DUunzxUB.js → mount-recovery-2ElXrqlr.js} +1 -1
  70. package/dist/ui/assets/new-session-CiuddhGl.js +2 -0
  71. package/dist/ui/assets/nvidia-dA6GzUPm.json +1 -0
  72. package/dist/ui/assets/oauth-bootstrap-BKh-w2bl.js +2 -0
  73. package/dist/ui/assets/openai-BehvdaXx.json +1 -0
  74. package/dist/ui/assets/openai-codex-BTjoLqTw.js +1 -0
  75. package/dist/ui/assets/openai-codex-ChonaqJh.js +1 -0
  76. package/dist/ui/assets/openai-codex-responses-B7cFMjWk.js +7 -0
  77. package/dist/ui/assets/openai-codex-responses-DqxoDEwc.js +7 -0
  78. package/dist/ui/assets/openai-completions-Z1aRkqWe.js +5 -0
  79. package/dist/ui/assets/openai-completions-o78dOizF.js +5 -0
  80. package/dist/ui/assets/openai-responses-SPfzkTJm.js +1 -0
  81. package/dist/ui/assets/openai-responses-shared-BHsJFKuB.js +10 -0
  82. package/dist/ui/assets/openai-responses-shared-Dg5Ojqlw.js +10 -0
  83. package/dist/ui/assets/openai-responses-xSdsW9lw.js +1 -0
  84. package/dist/ui/assets/opencode-4chvZrBR.json +1 -0
  85. package/dist/ui/assets/opencode-go-Chp1OOUx.json +1 -0
  86. package/dist/ui/assets/openrouter-BG0ZjAOt.js +1 -0
  87. package/dist/ui/assets/openrouter-DuD25f7F.js +1 -0
  88. package/dist/ui/assets/openrouter-ZLTwKIjA.json +1 -0
  89. package/dist/ui/assets/openrouter-models-B8MWxzTa.js +1 -0
  90. package/dist/ui/assets/openrouter-models-DM9v24kQ.js +1 -0
  91. package/dist/ui/assets/openrouter-oauth-CK60lvKj.js +1 -0
  92. package/dist/ui/assets/openrouter-oauth-COmvA0Z1.js +1 -0
  93. package/dist/ui/assets/openrouter.models-Bi9GV7Zn.js +1 -0
  94. package/dist/ui/assets/openrouter.models-D41M1z_D.js +1 -0
  95. package/dist/ui/assets/{page-follower-tray-BblmGsa_.js → page-follower-tray-9fFxBm3_.js} +1 -1
  96. package/dist/ui/assets/{panel-rpc-handlers-C7cI_wpd.js → panel-rpc-handlers-CFg5NA3F.js} +2 -2
  97. package/dist/ui/assets/pi-messages-DRdk3sMN.js +7 -0
  98. package/dist/ui/assets/pi-messages-fKU_b1SK.js +7 -0
  99. package/dist/ui/assets/{provider-mNJ81Nmf.js → provider-4BBnXotd.js} +2 -2
  100. package/dist/ui/assets/{provider-B_beyvZ1.js → provider-DXnAAcyy.js} +1 -1
  101. package/dist/ui/assets/{provider-settings-Br12uT6y.js → provider-settings-Bv01tMmE.js} +1 -1
  102. package/dist/ui/assets/{provider-settings-Bynyth1-.js → provider-settings-DsZhN2JS.js} +1 -1
  103. package/dist/ui/assets/{provider-store-access-DPdIt2P7.js → provider-store-access-JTv_TUOb.js} +2 -2
  104. package/dist/ui/assets/provider-store-access-saWse80P.js +1 -0
  105. package/dist/ui/assets/providers-BoV1YFxZ.js +1 -0
  106. package/dist/ui/assets/providers-u1yhVbk3.js +2 -0
  107. package/dist/ui/assets/py-realm-worker-C9yzXwPb.js +244 -0
  108. package/dist/ui/assets/{pyodide-BahZNzwn.js → pyodide-B9hoVXZ4.js} +2 -2
  109. package/dist/ui/assets/{quick-llm-DAjUwXji.js → quick-llm-CXqHh13i.js} +1 -1
  110. package/dist/ui/assets/qwen-token-plan-BpxmzamU.json +1 -0
  111. package/dist/ui/assets/qwen-token-plan-cn-CPhDR0u_.json +1 -0
  112. package/dist/ui/assets/{session-freezer-ByN74MO5.js → session-freezer-Dd9Vda0R.js} +3 -3
  113. package/dist/ui/assets/setup-sudo-CDu03XrJ.js +2 -0
  114. package/dist/ui/assets/shared-BYVJAPbn.js +1 -0
  115. package/dist/ui/assets/shared-pjIf7b3g.js +4 -0
  116. package/dist/ui/assets/{skills-BMDzPReO.js → skills-CW8kM1BJ.js} +1 -1
  117. package/dist/ui/assets/{speak-BeDix5EH.js → speak-B4wyr-p6.js} +1 -1
  118. package/dist/ui/assets/{speak-CkvZB0fq.js → speak-aEIq7SEP.js} +1 -1
  119. package/dist/ui/assets/{sprinkle-bridge-YYPWJ55I.js → sprinkle-bridge-DziYRsuS.js} +1 -1
  120. package/dist/ui/assets/{sprinkle-manager-CK0eo6zp.js → sprinkle-manager-354rS3Fe.js} +1 -1
  121. package/dist/ui/assets/{store-Bo-VXhKX.js → store-J9T9BcgY.js} +1 -1
  122. package/dist/ui/assets/{sudo-CIRZ-EUo.js → sudo-DzRD7NyW.js} +1 -1
  123. package/dist/ui/assets/together-CYZ-lBBF.json +1 -0
  124. package/dist/ui/assets/transform-messages-Bp94o3FD.js +1 -0
  125. package/dist/ui/assets/transform-messages-wECJwtH0.js +1 -0
  126. package/dist/ui/assets/{transformers-env-C77NUYNM.js → transformers-env-CeJN6XlP.js} +1 -1
  127. package/dist/ui/assets/{transformers-env-RUMoBRzi.js → transformers-env-DZtq7i0I.js} +1 -1
  128. package/dist/ui/assets/{upgrade-detection-BGS7lBbj.js → upgrade-detection-BIhXOe-Q.js} +1 -1
  129. package/dist/ui/assets/vercel-ai-gateway-ZtkcQH_C.json +1 -0
  130. package/dist/ui/assets/{voice-reply-RJ5RbAjY.js → voice-reply-6cMxpz9H.js} +1 -1
  131. package/dist/ui/assets/{wc-extension-BS1GKkBY.js → wc-extension-DrjbYKDl.js} +2 -2
  132. package/dist/ui/assets/wc-follower-Ss6qgVMU.js +17 -0
  133. package/dist/ui/assets/{wc-live-BU8bhGYQ.js → wc-live-DALR9RxO.js} +3 -3
  134. package/dist/ui/assets/wc-nav-rD7F67u7.js +2 -0
  135. package/dist/ui/assets/{wc-onboarding-oXM_3rWS.js → wc-onboarding-D3EwB9c1.js} +2 -2
  136. package/dist/ui/assets/wc-placeholder-BEIr39eF.js +4 -0
  137. package/dist/ui/assets/{wc-settings-CwYBG83C.js → wc-settings-CZc7gWTY.js} +2 -2
  138. package/dist/ui/assets/{wc-shell-APVSI6kq.js → wc-shell-BgYP6QNP.js} +2 -2
  139. package/dist/ui/assets/{wc-sprinkles-XTLYtBLP.js → wc-sprinkles-DtnXjTrx.js} +2 -2
  140. package/dist/ui/assets/wc-tray-DDa-t_xi.js +2 -0
  141. package/dist/ui/assets/{whisper-engine-6Ks_tvV1.js → whisper-engine-G1YfvaDM.js} +1 -1
  142. package/dist/ui/assets/{whisper-session-36PZh-9m.js → whisper-session-Ds5v74N9.js} +2 -2
  143. package/dist/ui/assets/xai-grok-Co4pMrel.js +1 -0
  144. package/dist/ui/assets/xai-grok-HbxyqvtP.js +1 -0
  145. package/dist/ui/index.html +12 -10
  146. package/dist/ui/packages/webapp/index.html +12 -10
  147. package/package.json +3 -2
  148. package/dist/ui/assets/__vite-browser-external-DZX1xHt-.js +0 -1
  149. package/dist/ui/assets/account-store-DpZitlUY.js +0 -98
  150. package/dist/ui/assets/adobe-Bmh-_khT.js +0 -2
  151. package/dist/ui/assets/adobe-DyH_9qJK.js +0 -1
  152. package/dist/ui/assets/anthropic-messages-CIsUSIzG.js +0 -39
  153. package/dist/ui/assets/anthropic-messages-_fPAePlR.js +0 -39
  154. package/dist/ui/assets/azure-openai-Dm2kMacy.js +0 -1
  155. package/dist/ui/assets/azure-openai-rcs4Z0Nm.js +0 -1
  156. package/dist/ui/assets/azure-openai-responses-DhzbC_tL.js +0 -1
  157. package/dist/ui/assets/azure-openai-responses-bHfWNMbx.js +0 -1
  158. package/dist/ui/assets/bedrock-camp-BqDUcxBp.js +0 -1
  159. package/dist/ui/assets/bedrock-camp-DdoLg8ey.js +0 -1
  160. package/dist/ui/assets/cerebras-Bb96dS8U.js +0 -1
  161. package/dist/ui/assets/cerebras-Ih70UTEx.js +0 -1
  162. package/dist/ui/assets/compat-DyT25qXb.js +0 -2
  163. package/dist/ui/assets/github-copilot-Bf-iW8mK.js +0 -2
  164. package/dist/ui/assets/github-copilot-C_R0Ma0E.js +0 -1
  165. package/dist/ui/assets/google-generative-ai-CyS9qbzb.js +0 -1
  166. package/dist/ui/assets/google-generative-ai-DkRyuoBH.js +0 -1
  167. package/dist/ui/assets/google-vertex-Cp9ldPyE.js +0 -1
  168. package/dist/ui/assets/google-vertex-D7VRnbrL.js +0 -1
  169. package/dist/ui/assets/models-CzSI8IsT.js +0 -1
  170. package/dist/ui/assets/new-session-CgnPWa_k.js +0 -2
  171. package/dist/ui/assets/oauth-bootstrap-CmurjaMI.js +0 -2
  172. package/dist/ui/assets/openai-codex-D-gmV2fj.js +0 -1
  173. package/dist/ui/assets/openai-codex-Dv3Zo1Dx.js +0 -1
  174. package/dist/ui/assets/openai-codex-responses-B_k2rCqO.js +0 -7
  175. package/dist/ui/assets/openai-codex-responses-RviMslSH.js +0 -7
  176. package/dist/ui/assets/openai-completions-CGLtJfv2.js +0 -5
  177. package/dist/ui/assets/openai-completions-COYKlBqA.js +0 -5
  178. package/dist/ui/assets/openai-responses-C4mUX6jK.js +0 -1
  179. package/dist/ui/assets/openai-responses-D02gU0ey.js +0 -1
  180. package/dist/ui/assets/openai-responses-shared-CCTyKL6A.js +0 -10
  181. package/dist/ui/assets/openai-responses-shared-bVKJbQt9.js +0 -10
  182. package/dist/ui/assets/provider-store-access-CeFzxjQ9.js +0 -1
  183. package/dist/ui/assets/providers-DiQPQy2w.js +0 -2
  184. package/dist/ui/assets/providers-t50k54fw.js +0 -1
  185. package/dist/ui/assets/py-realm-worker-VuYxvTG9.js +0 -244
  186. package/dist/ui/assets/setup-sudo-PBmKBl1V.js +0 -2
  187. package/dist/ui/assets/shared-Bs3KpKjW.js +0 -4
  188. package/dist/ui/assets/shared-CR9p6ivA.js +0 -1
  189. package/dist/ui/assets/transform-messages-CVIV-EgO.js +0 -1
  190. package/dist/ui/assets/transform-messages-fFaW-DLG.js +0 -1
  191. package/dist/ui/assets/wc-follower-BWvESj7q.js +0 -17
  192. package/dist/ui/assets/wc-nav-CPVp8Fk2.js +0 -2
  193. package/dist/ui/assets/wc-placeholder-BvLEsaiK.js +0 -4
  194. package/dist/ui/assets/wc-tray-CUbKbp0U.js +0 -2
  195. package/dist/ui/assets/xai-grok-B5CWbUwl.js +0 -1
  196. package/dist/ui/assets/xai-grok-models-B0Tf--xf.js +0 -1
  197. package/dist/ui/assets/xai-grok-models-CeEBaUMC.js +0 -1
  198. package/dist/ui/assets/xai-grok-qyS7ZUXU.js +0 -1
  199. package/dist/ui/assets/xai-grok-sanitize-CR2JoOJd.js +0 -5
  200. package/dist/ui/assets/xai-grok-sanitize-CV6qvaEF.js +0 -5
@@ -1 +0,0 @@
1
- import{n as e}from"./panel-rpc-CjFVE0nK.js";import{O as t,i as n,u as r}from"./account-store-DpZitlUY.js";import{p as i}from"./transform-messages-CVIV-EgO.js";import{a,c as o,d as s,f as c,i as l,o as u,p as d,s as f}from"./bedrock-camp-BqDUcxBp.js";import{a as p,r as m,s as h,t as g}from"./legacy-api-aliases-BEwZmDvB.js";import{n as _}from"./llm-session-id-ZObKEXzb.js";import{t as v}from"./adobe-oauth-state-Vbbfo7gR.js";import{getOAuthPageOrigin as ee}from"./oauth-service-foejPYvF.js";import"./provider-settings-Br12uT6y.js";var te={proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`};function ne(e,t){return a(e,t)}function y(e,t,n){return e!==`xhigh`||!t?e:f(t,n)?`xhigh`:u(t,n)?`max`:`high`}function re(e,t){let n=e?t?.thinkingLevelMap?.[e]:void 0;return y((()=>{if(typeof n==`string`)return n;switch(e){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`xhigh`:return`xhigh`;default:return`high`}})(),t?.id,t?.name)}function ie(e,t){return async(n,r)=>{let i=t?await t(n,r)??n:n,a=i.thinking;return a&&a.type===`enabled`&&(i.thinking={type:`adaptive`,...a.display===void 0?{}:{display:a.display}},i.output_config={...i.output_config??{},effort:e}),i}}function b(e,t){if(!ne(e.id,e.name))return t;let n=t,r=y(n.effort??re(n.reasoning,e),e.id,e.name);return{...t,onPayload:ie(r,n.onPayload)}}function ae(e,t){let n={id:e.id,name:e.name??e.id},r=t?.api??e.api,i=t?.context_window??e.context_window,a=t?.max_tokens??e.max_tokens,o=t?.reasoning??e.reasoning,s=t?.input??e.input;r&&(n.api=r),i!==void 0&&(n.context_window=i),a!==void 0&&(n.max_tokens=a),o!==void 0&&(n.reasoning=o),s&&(n.input=s);let c=t?.cost??e.cost;return c&&(n.cost=c),/haiku/i.test(e.id)&&(n.compat={supportsEagerToolInputStreaming:!1}),/sonnet-5\b/i.test(e.id)&&!n.thinkingLevelMap&&(n.thinkingLevelMap={xhigh:`xhigh`}),n}function oe(e=3e5){let t=0;return{async run(n,r=Date.now()){if(r<t)return null;let i=null;try{i=await n()}catch(e){console.debug(`[silent-renew-backoff] renew threw:`,e instanceof Error?e.message:String(e)),i=null}return t=i?0:r+e,i},inCooldown(e=Date.now()){return e<t}}}const x=Object.assign({"/packages/webapp/providers/adobe-config.json":te})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function S(){let e=r(`adobe`);if(e)return e.replace(/\/$/,``);if(x.proxyEndpoint)return x.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}const C=new Map,w=new Map,T=`slicc-adobe-models`;function E(e){try{localStorage.setItem(T,JSON.stringify(e))}catch{}}async function D(e){let t=C.get(e);if(t)return t;try{let t=await fetch(`${e}/v1/config`,{headers:{[W]:`5.67.1`}});if(t.ok){let n=await t.json();return C.set(e,n),n}console.warn(`[adobe] Proxy /v1/config returned ${t.status}, falling back to build-time config`)}catch(e){console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e))}return{}}function O(e){let t=e.clientId||x.clientId;if(!t)throw Error(`Could not determine IMS client ID — proxy /v1/config did not return one and adobe-config.json is empty`);return t}function k(e){return e.scopes||x.scopes}function A(e){return e.imsEnvironment||x.imsEnvironment||`prod`}const j={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function M(e){return j[e??x.imsEnvironment??`prod`]??j.prod}const N=typeof chrome<`u`&&!!chrome?.runtime?.id;function P(){return n().find(e=>e.providerId===`adobe`)}async function se(e,t){try{let n=await fetch(`${M(t)}/ims/userinfo/v2`,{headers:{Authorization:`Bearer ${e}`}});if(n.ok){let e=await n.json();return{name:e.displayName||e.name||e.email,avatar:e.picture||e.avatar_url}}console.warn(`[adobe] User profile fetch returned ${n.status}, account will have no display name`)}catch(e){console.warn(`[adobe] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function F(e){let t=e.indexOf(`#`);if(t<0)return null;let n=new URLSearchParams(e.slice(t+1)),r=n.get(`access_token`);return r?{accessToken:r,expiresIn:parseInt(n.get(`expires_in`)??`86400`,10)}:null}const I={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!x.proxyEndpoint,baseUrlPlaceholder:`https://your-proxy.example.com`,baseUrlDescription:`Anthropic-compatible proxy endpoint`,isOAuth:!0,defaultModelId:`sonnet`,oauthTokenDomains:[`ims-na1.adobelogin.com`,`ims-na1-stg1.adobelogin.com`,`*.adobelogin.com`,`*.adobe.io`,`firefall.adobe.io`,`admin.hlx.page`,`admin.hlx.live`,`admin.aem.page`,`admin.aem.live`],getModelIds:()=>{let e=e=>ae(e,w.get(e.id));for(let t of Q.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id,reasoning:t.reasoning,input:t.input,cost:t.cost}));return E(n),n}for(let t of C.values())if(t.models?.length)return t.models.map(t=>e(t));try{let e=localStorage.getItem(T);if(e){let t=JSON.parse(e);if(t.length)return t}}catch{}return[{id:`claude-sonnet-4-6`,name:`Claude Sonnet 4.6`}]},onOAuthLogin:async(e,n,r)=>{let i=S(),a=await D(i),o=O(a),s=k(a),c=A(a),l=N?null:await ee(),u=N?null:v({pageHref:l.href,pageOrigin:l.origin,configuredRedirectUri:x.redirectUri},()=>crypto.randomUUID()),d=N?x.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:u.redirectUri,f=u?.oauthState,p=u?.expectedNonce??null,m=new URLSearchParams({client_id:o,scope:s,response_type:`token`,redirect_uri:d});f&&m.set(`state`,f),r?.forceReauth&&m.set(`prompt`,`login`);let h=await e(`${M(c)}/ims/authorize/v2?${m}`);if(!h)return;if(p&&h)try{if(new URL(h).searchParams.get(`nonce`)!==p){console.error(`[adobe] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let g=F(h);if(!g){console.error(`[adobe] Could not extract token from redirect URL`);return}let _=await se(g.accessToken,c);await t({providerId:`adobe`,accessToken:g.accessToken,tokenExpiresAt:Date.now()+g.expiresIn*1e3,userName:_.name,userAvatar:_.avatar,baseUrl:x.proxyEndpoint?void 0:i}),await $().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),n()},onOAuthLogout:async()=>{let e=P();if(e?.accessToken)try{let t=C.values().next().value??{},n=t.clientId||x.clientId,r=A(t);if(n){let t=await fetch(`${M(r)}/ims/revoke`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:e.accessToken,token_type_hint:`access_token`,client_id:n})});t.ok||console.warn(`[adobe] Token revocation returned ${t.status}, token may still be valid server-side`)}}catch(e){console.warn(`[adobe] Failed to revoke token:`,e instanceof Error?e.message:String(e))}await t({providerId:`adobe`,accessToken:``})},onSilentRenew:async()=>P()?.accessToken?z():null,refreshModels:async e=>{await $(e);let t=I.getModelIds?.();t?.length&&E(t)}};let L=null;const ce=oe();async function R(){let e=P();if(!e?.accessToken)throw Error(`Not logged in to Adobe — please log in first`);if((e.tokenExpiresAt??0)-Date.now()>6e4)return e.accessToken;console.log(`[adobe] Token expired or expiring soon, attempting silent renewal...`);let t=await ce.run(()=>z());if(t)return t;let n=P();if((n?.tokenExpiresAt??0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`Adobe session expired — please log in again`)}function le(){let e=P();return!e?.tokenExpiresAt||Date.now()>e.tokenExpiresAt-6e4}async function z(){if(typeof window>`u`){let t=e();if(!t)return null;try{let{accessToken:e}=await t.call(`silent-renew`,{providerId:`adobe`},{timeoutMs:13e4});return e}catch(e){return console.warn(`[adobe] worker→page silent-renew bridge failed:`,e instanceof Error?e.message:String(e)),null}}return L||(L=U().finally(()=>{L=null}),L)}function B(e,t){let n=O(t),r=k(t),i=A(t),a=N?null:v({pageHref:window.location.href,pageOrigin:window.location.origin,configuredRedirectUri:x.redirectUri},()=>crypto.randomUUID()),o=N?x.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:a.redirectUri,s=a?.oauthState,c=a?.expectedNonce??null,l=new URLSearchParams({client_id:n,scope:r,response_type:`token`,redirect_uri:o,prompt:`none`});return s&&l.set(`state`,s),{authorizeUrl:`${M(i)}/ims/authorize/v2?${l}`,expectedNonce:c,proxyEndpoint:e}}function V(e,t){if(!t)return!0;try{if(new URL(e).searchParams.get(`nonce`)!==t)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),!1}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}return!0}async function H(e,n){let r=P();await t({providerId:`adobe`,accessToken:e.accessToken,tokenExpiresAt:Date.now()+e.expiresIn*1e3,userName:r?.userName,userAvatar:r?.userAvatar,baseUrl:x.proxyEndpoint?void 0:n})}async function U(){try{let e=S(),{authorizeUrl:t,expectedNonce:n}=B(e,await D(e)),{createOAuthLauncher:r}=await import(`./oauth-service-foejPYvF.js`),i=await r()(t,{interactive:!1});if(!i||!V(i,n))return null;let a=F(i);return a?(await H(a,e),console.log(`[adobe] Token renewed silently`),await $().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),a.accessToken):null}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}}const W=`X-Slicc-Version`;function G(e){let t={};if(e.headers)for(let[n,r]of Object.entries(e.headers))n.toLowerCase()!==`x-slicc-version`&&(t[n]=r);return t[W]=`5.67.1`,{...e,headers:t}}const K=new Set;function q(e,t){if(e.headers){for(let[t,n]of Object.entries(e.headers))if(t.toLowerCase()===`x-session-id`&&n!=null)return e}return K.has(t)||(K.add(t),console.warn(`[adobe] Missing X-Session-Id from ${t} — using daily fallback. Attach an X-Session-Id header at the call site (see scoop-context.ts streamWithSessionId or docs/pitfalls.md).`)),{...e,headers:{...e.headers??{},"X-Session-Id":_(`adobe-provider-fallback`)}}}function ue(){K.clear()}function J(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:`adobe-anthropic`,provider:`adobe`,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const Y=(e,t,n={})=>{let r=i();return(async()=>{try{let i=await R();if(String(e.api).includes(`openai`)){let a=m({...e,baseUrl:`${S()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,G(q({...n,apiKey:i},`streamAdobe[openai]`)));for await(let e of a)r.push(e)}else{let a=g({...e,baseUrl:S(),api:`anthropic-messages`},t,G(q(b(e,l(e.id,e.name,{...n,apiKey:i})),`streamAdobe[anthropic]`)));for await(let e of a)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(J(e,t)),r.end()}})(),r},X=(e,t,n)=>{let r=i();return(async()=>{try{let i=await R();if(String(e.api).includes(`openai`)){let a=h({...e,baseUrl:`${S()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},t,G(q({...n,apiKey:i},`streamSimpleAdobe[openai]`)));for await(let e of a)r.push(e)}else{let a=p({...e,baseUrl:S(),api:`anthropic-messages`},t,G(q(b(e,l(e.id,e.name,{...n,apiKey:i})),`streamSimpleAdobe[anthropic]`)));for await(let e of a)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(J(e,t)),r.end()}})(),r};function Z(e){let t={id:e.id,name:e.name};return e.api!==void 0&&(t.api=e.api),e.context_window!==void 0&&(t.context_window=e.context_window),e.max_tokens!==void 0&&(t.max_tokens=e.max_tokens),e.reasoning!==void 0&&(t.reasoning=e.reasoning),e.input!==void 0&&(t.input=e.input),t}function de(){let e=new Map;for(let t of c())try{for(let n of s(t))e.set(n.id,n)}catch{}return e}function fe(e,t){let n={input:0,output:0,cacheRead:0,cacheWrite:0},r=o(e);if(!r)return n;let i;for(let e of t.values()){let t=o(e.id);!t||t.family!==r.family||(!i||t.major>i.major||t.major===i.major&&t.minor>i.minor)&&(i={major:t.major,minor:t.minor,cost:e.cost})}return i?.cost??n}function pe(e,t,n){let r=`adobe-${e.api===`openai`?`openai`:`anthropic`}`,i=n.get(e.id);if(i)return{...i,provider:`adobe`,api:r};let a=fe(e.id,n);return{id:e.id,name:e.name??e.id,provider:`adobe`,api:r,baseUrl:t,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:a,inputCost:a.input,outputCost:a.output,cacheReadCost:a.cacheRead,cacheWriteCost:a.cacheWrite,reasoning:!0}}function me(e,t){for(let t of e)w.set(t.id,Z(t));let n=de();return e.map(e=>pe(e,t,n))}async function he(e){try{let t=e??await R(),n=S(),r=await fetch(`${n}/v1/models`,{headers:{Authorization:`Bearer ${t}`,[W]:`5.67.1`}});if(!r.ok)console.warn(`[adobe] Proxy /v1/models returned ${r.status}, falling back to Anthropic models`);else{let e=await r.json();if(e.data?.length)return me(e.data,n)}}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return null}const Q=new Map;function ge(){return s(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}async function $(e){let t=S(),n=Q.get(t);if(n)return n;let r=await he(e);return r?(Q.set(t,r),r):ge()}function _e(){d({api:`adobe-anthropic`,stream:Y,streamSimple:X}),d({api:`adobe-openai`,stream:Y,streamSimple:X})}export{ue as __resetAdobeSessionIdWarningCacheForTests,I as config,$ as getAdobeModels,R as getValidAccessToken,le as isTokenExpired,_e as register};
@@ -1,39 +0,0 @@
1
- import{f as e,i as t,n,o as r,r as i,t as a}from"./transform-messages-CVIV-EgO.js";import{t as o}from"./provider-env-DwY8YuMk.js";import{n as s,t as c}from"./json-parse-CpLf0aqK.js";import{t as l}from"./headers-CbDaTl3c.js";import{t as u}from"./sanitize-unicode-DmIE6hZJ.js";import{n as ee,t as d}from"./github-copilot-headers-DRgtIyTm.js";function f(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function p(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let te=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return te=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function m(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const ne=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var h=class extends Error{},g=class e extends h{constructor(t,n,r,i,a){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`request-id`),this.error=n,this.type=a??null}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new re({message:r,cause:ne(n)});let a=n,o=a?.error?.type;return t===400?new ae(t,a,r,i,o):t===401?new oe(t,a,r,i,o):t===403?new se(t,a,r,i,o):t===404?new ce(t,a,r,i,o):t===409?new le(t,a,r,i,o):t===422?new ue(t,a,r,i,o):t===429?new de(t,a,r,i,o):t>=500?new fe(t,a,r,i,o):new e(t,a,r,i,o)}},_=class extends g{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},re=class extends g{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},ie=class extends re{constructor({message:e}={}){super({message:e??`Request timed out.`})}},ae=class extends g{},oe=class extends g{},se=class extends g{},ce=class extends g{},le=class extends g{},ue=class extends g{},de=class extends g{},fe=class extends g{};const pe=/^[a-z][a-z0-9+.-]*:/i,me=e=>pe.test(e);let he=e=>(he=Array.isArray,he(e)),ge=he;function _e(e){return typeof e==`object`?e??{}:{}}function ve(e){if(!e)return!0;for(let t in e)return!1;return!0}function ye(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const be=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new h(`${e} must be an integer`);if(t<0)throw new h(`${e} must be a positive integer`);return t},xe=e=>{try{return JSON.parse(e)}catch{return}},Se=e=>new Promise(t=>setTimeout(t,e)),v=`0.91.1`,Ce=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function we(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const Te=()=>{let e=we();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":Oe(Deno.build.os),"X-Stainless-Arch":De(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":Oe(globalThis.process.platform??`unknown`),"X-Stainless-Arch":De(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Ee();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Ee(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const De=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Oe=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let ke;const Ae=()=>ke??=Te();function je(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Me(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Ne(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Me({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Pe(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Fe(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Ie=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function Le(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new h(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}function Re(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let ze;function Be(e){let t;return(ze??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let Ve;function He(e){let t;return(Ve??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var y,b,Ue=class{constructor(){y.set(this,void 0),b.set(this,void 0),f(this,y,new Uint8Array,`f`),f(this,b,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?Be(e):e;f(this,y,Re([p(this,y,`f`),t]),`f`);let n=[],r;for(;(r=We(p(this,y,`f`),p(this,b,`f`)))!=null;){if(r.carriage&&p(this,b,`f`)==null){f(this,b,r.index,`f`);continue}if(p(this,b,`f`)!=null&&(r.index!==p(this,b,`f`)+1||r.carriage)){n.push(He(p(this,y,`f`).subarray(0,p(this,b,`f`)-1))),f(this,y,p(this,y,`f`).subarray(p(this,b,`f`)),`f`),f(this,b,null,`f`);continue}let e=p(this,b,`f`)===null?r.preceding:r.preceding-1,t=He(p(this,y,`f`).subarray(0,e));n.push(t),f(this,y,p(this,y,`f`).subarray(r.index),`f`),f(this,b,null,`f`)}return n}flush(){return p(this,y,`f`).length?this.decode(`
2
- `):[]}};y=new WeakMap,b=new WeakMap,Ue.NEWLINE_CHARS=new Set([`
3
- `,`\r`]),Ue.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function We(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ge(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}const Ke={off:0,error:200,warn:300,info:400,debug:500},qe=(e,t,n)=>{if(e){if(ye(Ke,e))return e;S(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ke))}`)}};function x(){}function Je(e,t,n){return!t||Ke[e]>Ke[n]?x:t[e].bind(t)}const Ye={error:x,warn:x,info:x,debug:x};let Xe=new WeakMap;function S(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Ye;let r=Xe.get(t);if(r&&r[0]===n)return r[1];let i={error:Je(`error`,t,n),warn:Je(`warn`,t,n),info:Je(`info`,t,n),debug:Je(`debug`,t,n)};return Xe.set(t,[n,i]),i}const C=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Ze,Qe=class e{constructor(e,t,n){this.iterator=e,Ze.set(this,void 0),this.controller=t,f(this,Ze,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?S(r):console;async function*o(){if(i)throw new h("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of $e(t,n)){if(e.event===`completion`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event===`message_start`||e.event===`message_delta`||e.event===`message_stop`||e.event===`content_block_start`||e.event===`content_block_delta`||e.event===`content_block_stop`||e.event===`message`||e.event===`user.message`||e.event===`user.interrupt`||e.event===`user.tool_confirmation`||e.event===`user.custom_tool_result`||e.event===`agent.message`||e.event===`agent.thinking`||e.event===`agent.tool_use`||e.event===`agent.tool_result`||e.event===`agent.mcp_tool_use`||e.event===`agent.mcp_tool_result`||e.event===`agent.custom_tool_use`||e.event===`agent.thread_context_compacted`||e.event===`session.status_running`||e.event===`session.status_idle`||e.event===`session.status_rescheduled`||e.event===`session.status_terminated`||e.event===`session.error`||e.event===`session.deleted`||e.event===`span.model_request_start`||e.event===`span.model_request_end`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event!==`ping`&&e.event===`error`){let n=xe(e.data)??e.data,r=n?.error?.type;throw new g(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(m(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new Ue,n=Pe(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new h("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(m(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Ze=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,p(this,Ze,`f`)),new e(()=>i(n),this.controller,p(this,Ze,`f`))]}toReadableStream(){let e=this,t;return Me({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Be(JSON.stringify(n)+`
4
- `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*$e(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new h(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new h(`Attempted to iterate over a response with no body`);let n=new tt,r=new Ue,i=Pe(e.body);for await(let e of et(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*et(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Be(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Ge(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var tt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=nt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function nt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function rt(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return S(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):Qe.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:it(await n.json(),n):await n.text()})();return S(e).debug(`[${r}] response parsed`,C({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function it(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`request-id`),enumerable:!1})}var w,at=class e extends Promise{constructor(e,t,n=rt){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,w.set(this,void 0),f(this,w,e,`f`)}_thenUnwrap(t){return new e(p(this,w,`f`),this.responsePromise,async(e,n)=>it(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(p(this,w,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};w=new WeakMap;var ot,st=class{constructor(e,t,n,r){ot.set(this,void 0),f(this,ot,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new h("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await p(this,ot,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ot=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ct=class extends at{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await rt(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},T=class extends st{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{..._e(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{..._e(this.options.query),after_id:e}}:null}},E=class extends st{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{..._e(this.options.query),page:e}}:null}};const lt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function D(e,t,n){return lt(),new File(e,t??`unknown_file`,n)}function ut(e,t){let n=typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``;return t?n.split(/[\\/]/).pop()||void 0:n}const dt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,ft=async(e,t,n=!0)=>({...e,body:await ht(e.body,t,n)}),pt=new WeakMap;function mt(e){let t=typeof e==`function`?e:e.fetch,n=pt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return pt.set(t,r),r}const ht=async(e,t,n=!0)=>{if(!await mt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>_t(r,e,t,n))),r},gt=e=>e instanceof Blob&&`name`in e,_t=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i={},a=n.headers.get(`Content-Type`);a&&(i={type:a}),e.append(t,D([await n.blob()],ut(n,r),i))}else if(dt(n))e.append(t,D([await new Response(Ne(n)).blob()],ut(n,r)));else if(gt(n))e.append(t,D([n],ut(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>_t(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>_t(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},vt=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,yt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&vt(e),bt=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function xt(e,t,n){if(lt(),e=await e,t||=ut(e,!0),yt(e))return e instanceof File&&t==null&&n==null?e:D([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(bt(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),D(await St(r),t,n)}let r=await St(e);if(!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return D(r,t,n)}async function St(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(vt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(dt(e))for await(let n of e)t.push(...await St(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Ct(e)}`)}return t}function Ct(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var O=class{constructor(e){this._client=e}};const wt=Symbol.for(`brand.privateNullableHeaders`);function*Tt(e){if(!e)return;if(wt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ge(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ge(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const k=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Tt(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[wt]:!0,values:t,nulls:n}};function Et(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Dt=Object.freeze(Object.create(null)),A=((e=Et)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Dt)??Dt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new h(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
- `)}\n${a}\n${t}`)}return a})(Et);var Ot=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/environments/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/environments/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/environments?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/environments/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/environments/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};const j=Symbol(`anthropic.sdk.stainlessHelper`);function kt(e){return typeof e==`object`&&!!e&&j in e}function At(e,t){let n=new Set;if(e)for(let t of e)kt(t)&&n.add(t[j]);if(t){for(let e of t)if(kt(e)&&n.add(e[j]),Array.isArray(e.content))for(let t of e.content)kt(t)&&n.add(t[j])}return Array.from(n)}function jt(e,t){let n=At(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function Mt(e){return kt(e)?{"x-stainless-helper":e[j]}:{}}var Nt=class extends O{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,T,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/files/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/files/${e}/content?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/files/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}upload(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/files?beta=true`,ft({body:r,...t,headers:k([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},Mt(r.file),t?.headers])},this._client))}},Pt=class extends O{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/models/${e}?beta=true`,{...n,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models?beta=true`,T,{query:r,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},Ft=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/user_profiles/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/user_profiles?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},It=class extends O{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/agents/${e}/versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Lt=class extends O{constructor(){super(...arguments),this.versions=new It(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(A`/v1/agents/${e}?beta=true`,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/agents/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/agents?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/agents/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Lt.Versions=It;var Rt=class extends O{create(e,t,n){let{view:r,betas:i,...a}=t;return this._client.post(A`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:r},body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{memory_store_id:r,view:i,betas:a,...o}=t;return this._client.post(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{view:i},body:o,...n,headers:k([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/memory_stores/${e}/memories?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{memory_store_id:r,expected_content_sha256:i,betas:a}=t;return this._client.delete(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:k([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},zt=class extends O{retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(A`/v1/memory_stores/${r}/memory_versions/${e}?beta=true`,{query:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/memory_stores/${e}/memory_versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}redact(e,t,n){let{memory_store_id:r,betas:i}=t;return this._client.post(A`/v1/memory_stores/${r}/memory_versions/${e}/redact?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Bt=class extends O{constructor(){super(...arguments),this.memories=new Rt(this._client),this.memoryVersions=new zt(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/memory_stores?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/memory_stores/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/memory_stores/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/memory_stores?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/memory_stores/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Bt.Memories=Rt,Bt.MemoryVersions=zt;const Vt={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Ht(e){return e?.output_format??e?.output_config?.format}function Ut(e,t,n){let r=Ht(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>{if(e.type===`text`){let t=Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(t,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return e}),parsed_output:null}:Wt(e,t,n)}function Wt(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=Gt(t,e.text);r===null&&(r=i);let a=Object.defineProperty({...e},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Gt(e,t){let n=Ht(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new h(`Failed to parse structured output: ${e}`)}}const Kt=e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if(r===`\\`){t++;continue}if(r===`{`){n.push({type:`brace`,value:`{`}),t++;continue}if(r===`}`){n.push({type:`brace`,value:`}`}),t++;continue}if(r===`[`){n.push({type:`paren`,value:`[`}),t++;continue}if(r===`]`){n.push({type:`paren`,value:`]`}),t++;continue}if(r===`:`){n.push({type:`separator`,value:`:`}),t++;continue}if(r===`,`){n.push({type:`delimiter`,value:`,`}),t++;continue}if(r===`"`){let i=``,a=!1;for(r=e[++t];r!==`"`;){if(t===e.length){a=!0;break}if(r===`\\`){if(t++,t===e.length){a=!0;break}i+=r+e[t],r=e[++t]}else i+=r,r=e[++t]}r=e[++t],a||n.push({type:`string`,value:i});continue}if(r&&/\s/.test(r)){t++;continue}let i=/[0-9]/;if(r&&i.test(r)||r===`-`||r===`.`){let a=``;for(r===`-`&&(a+=r,r=e[++t]);r&&i.test(r)||r===`.`;)a+=r,r=e[++t];n.push({type:`number`,value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let i=``;for(;r&&a.test(r)&&t!==e.length;)i+=r,r=e[++t];if(i==`true`||i==`false`||i===`null`)n.push({type:`name`,value:i});else{t++;continue}continue}t++}return n},M=e=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case`separator`:return e=e.slice(0,e.length-1),M(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),M(e);case`string`:let r=e[e.length-2];if(r?.type===`delimiter`||r?.type===`brace`&&r.value===`{`)return e=e.slice(0,e.length-1),M(e);break;case`delimiter`:return e=e.slice(0,e.length-1),M(e)}return e},qt=e=>{let t=[];return e.map(e=>{e.type===`brace`&&(e.value===`{`?t.push(`}`):t.splice(t.lastIndexOf(`}`),1)),e.type===`paren`&&(e.value===`[`?t.push(`]`):t.splice(t.lastIndexOf(`]`),1))}),t.length>0&&t.reverse().map(t=>{t===`}`?e.push({type:`brace`,value:`}`}):t===`]`&&e.push({type:`paren`,value:`]`})}),e},Jt=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},Yt=e=>JSON.parse(Jt(qt(M(Kt(e)))));var N,P,F,Xt,Zt,Qt,$t,en,tn,I,nn,rn,an,L,on,sn,cn,ln,un,dn,fn,pn,mn,hn;const gn=`__json_buf`;function _n(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var vn=class e{constructor(e,t){N.add(this),this.messages=[],this.receivedMessages=[],P.set(this,void 0),F.set(this,null),this.controller=new AbortController,Xt.set(this,void 0),Zt.set(this,()=>{}),Qt.set(this,()=>{}),$t.set(this,void 0),en.set(this,()=>{}),tn.set(this,()=>{}),I.set(this,{}),nn.set(this,!1),rn.set(this,!1),an.set(this,!1),L.set(this,!1),on.set(this,void 0),sn.set(this,void 0),cn.set(this,void 0),dn.set(this,e=>{if(f(this,rn,!0,`f`),m(e)&&(e=new _),e instanceof _)return f(this,an,!0,`f`),this._emit(`abort`,e);if(e instanceof h)return this._emit(`error`,e);if(e instanceof Error){let t=new h(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new h(String(e)))}),f(this,Xt,new Promise((e,t)=>{f(this,Zt,e,`f`),f(this,Qt,t,`f`)}),`f`),f(this,$t,new Promise((e,t)=>{f(this,en,e,`f`),f(this,tn,t,`f`)}),`f`),p(this,Xt,`f`).catch(()=>{}),p(this,$t,`f`).catch(()=>{}),f(this,F,e,`f`),f(this,cn,t?.logger??console,`f`)}get response(){return p(this,on,`f`)}get request_id(){return p(this,sn,`f`)}async withResponse(){f(this,L,!0,`f`);let e=await p(this,Xt,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return f(a,F,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},p(this,dn,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{p(this,N,`m`,fn).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)p(this,N,`m`,pn).call(this,e);if(i.controller.signal?.aborted)throw new _;p(this,N,`m`,mn).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(f(this,on,e,`f`),f(this,sn,e?.headers.get(`request-id`),`f`),p(this,Zt,`f`).call(this,e),this._emit(`connect`))}get ended(){return p(this,nn,`f`)}get errored(){return p(this,rn,`f`)}get aborted(){return p(this,an,`f`)}abort(){this.controller.abort()}on(e,t){return(p(this,I,`f`)[e]||(p(this,I,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=p(this,I,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(p(this,I,`f`)[e]||(p(this,I,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{f(this,L,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){f(this,L,!0,`f`),await p(this,$t,`f`)}get currentMessage(){return p(this,P,`f`)}async finalMessage(){return await this.done(),p(this,N,`m`,ln).call(this)}async finalText(){return await this.done(),p(this,N,`m`,un).call(this)}_emit(e,...t){if(p(this,nn,`f`))return;e===`end`&&(f(this,nn,!0,`f`),p(this,en,`f`).call(this));let n=p(this,I,`f`)[e];if(n&&(p(this,I,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!p(this,L,`f`)&&!n?.length&&Promise.reject(e),p(this,Qt,`f`).call(this,e),p(this,tn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!p(this,L,`f`)&&!n?.length&&Promise.reject(e),p(this,Qt,`f`).call(this,e),p(this,tn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,p(this,N,`m`,ln).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{p(this,N,`m`,fn).call(this),this._connected(null);let t=Qe.fromReadableStream(e,this.controller);for await(let e of t)p(this,N,`m`,pn).call(this,e);if(t.controller.signal?.aborted)throw new _;p(this,N,`m`,mn).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(P=new WeakMap,F=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,en=new WeakMap,tn=new WeakMap,I=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,L=new WeakMap,on=new WeakMap,sn=new WeakMap,cn=new WeakMap,dn=new WeakMap,N=new WeakSet,ln=function(){if(this.receivedMessages.length===0)throw new h(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},un=function(){if(this.receivedMessages.length===0)throw new h(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new h(`stream ended without producing a content block with type=text`);return e.join(` `)},fn=function(){this.ended||f(this,P,void 0,`f`)},pn=function(e){if(this.ended)return;let t=p(this,N,`m`,hn).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:_n(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;case`compaction_delta`:n.type===`compaction`&&n.content&&this._emit(`compaction`,n.content);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(Ut(t,p(this,F,`f`),{logger:p(this,cn,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:f(this,P,t,`f`);break;case`content_block_start`:case`message_delta`:break}},mn=function(){if(this.ended)throw new h(`stream has ended, this shouldn't happen`);let e=p(this,P,`f`);if(!e)throw new h(`request ended without sending any chunks`);return f(this,P,void 0,`f`),Ut(e,p(this,F,`f`),{logger:p(this,cn,`f`)})},hn=function(e){let t=p(this,P,`f`);if(e.type===`message_start`){if(t)throw new h(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new h(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(t.usage.iterations=e.usage.iterations),t;case`content_block_start`:return t.content.push(e.content_block),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&_n(n)){let r=n[gn]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,gn,{value:r,enumerable:!1,writable:!0}),r)try{i.input=Yt(r)}catch(e){let t=new h(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${e}. JSON: ${r}`);p(this,dn,`f`).call(this,t)}t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;case`compaction_delta`:n?.type===`compaction`&&(t.content[e.index]={...n,content:(n.content||``)+e.delta.content});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Qe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},yn=class extends Error{constructor(e){let t=typeof e==`string`?e:e.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(` `);super(t),this.name=`ToolError`,this.content=e}},bn,R,z,B,V,H,U,W,xn,Sn,Cn;function wn(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var Tn=class{constructor(e,t,n){bn.add(this),this.client=e,R.set(this,!1),z.set(this,!1),B.set(this,void 0),V.set(this,void 0),H.set(this,void 0),U.set(this,void 0),W.set(this,void 0),xn.set(this,0),f(this,B,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=[`BetaToolRunner`,...At(t.tools,t.messages)].join(`, `);f(this,V,{...n,headers:k([{"x-stainless-helper":r},n?.headers])},`f`),f(this,W,wn(),`f`),t.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(R=new WeakMap,z=new WeakMap,B=new WeakMap,V=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,xn=new WeakMap,bn=new WeakSet,Sn=async function(){let e=p(this,B,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(p(this,H,`f`)!==void 0)try{let e=await p(this,H,`f`);t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}let n=e.contextTokenThreshold??1e5;if(t<n)return!1;let r=e.model??p(this,B,`f`).params.model,i=e.summaryPrompt??`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
7
- 1. Task Overview
8
- The user's core request and success criteria
9
- Any clarifications or constraints they specified
10
- 2. Current State
11
- What has been completed so far
12
- Files created, modified, or analyzed (with paths if relevant)
13
- Key outputs or artifacts produced
14
- 3. Important Discoveries
15
- Technical constraints or requirements uncovered
16
- Decisions made and their rationale
17
- Errors encountered and how they were resolved
18
- What approaches were tried that didn't work (and why)
19
- 4. Next Steps
20
- Specific actions needed to complete the task
21
- Any blockers or open questions to resolve
22
- Priority order if multiple steps remain
23
- 5. Context to Preserve
24
- User preferences or style requirements
25
- Domain-specific details that aren't obvious
26
- Any promises made to the user
27
- Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
28
- Wrap your summary in <summary></summary> tags.`,a=p(this,B,`f`).params.messages;if(a[a.length-1].role===`assistant`){let e=a[a.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>e.type!==`tool_use`);t.length===0?a.pop():e.content=t}}let o=await this.client.beta.messages.create({model:r,messages:[...a,{role:`user`,content:[{type:`text`,text:i}]}],max_tokens:p(this,B,`f`).params.max_tokens},{signal:p(this,V,`f`).signal,headers:k([p(this,V,`f`).headers,{"x-stainless-helper":`compaction`}])});if(o.content[0]?.type!==`text`)throw new h(`Expected text response for compaction`);return p(this,B,`f`).params.messages=[{role:`user`,content:o.content}],!0},Symbol.asyncIterator)](){var e;if(p(this,R,`f`))throw new h(`Cannot iterate over a consumed stream`);f(this,R,!0,`f`),f(this,z,!0,`f`),f(this,U,void 0,`f`);try{for(;;){let t;try{if(p(this,B,`f`).params.max_iterations&&p(this,xn,`f`)>=p(this,B,`f`).params.max_iterations)break;f(this,z,!1,`f`),f(this,U,void 0,`f`),f(this,xn,(e=p(this,xn,`f`),e++,e),`f`),f(this,H,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=p(this,B,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},p(this,V,`f`)),f(this,H,t.finalMessage(),`f`),p(this,H,`f`).catch(()=>{}),yield t):(f(this,H,this.client.beta.messages.create({...i,stream:!1},p(this,V,`f`)),`f`),yield p(this,H,`f`)),!await p(this,bn,`m`,Sn).call(this)){if(!p(this,z,`f`)){let{role:e,content:t}=await p(this,H,`f`);p(this,B,`f`).params.messages.push({role:e,content:t})}let e=await p(this,bn,`m`,Cn).call(this,p(this,B,`f`).params.messages.at(-1));if(e)p(this,B,`f`).params.messages.push(e);else if(!p(this,z,`f`))break}}finally{t&&t.abort()}}if(!p(this,H,`f`))throw new h(`ToolRunner concluded without a message from the server`);p(this,W,`f`).resolve(await p(this,H,`f`))}catch(e){throw f(this,R,!1,`f`),p(this,W,`f`).promise.catch(()=>{}),p(this,W,`f`).reject(e),f(this,W,wn(),`f`),e}}setMessagesParams(e){typeof e==`function`?p(this,B,`f`).params=e(p(this,B,`f`).params):p(this,B,`f`).params=e,f(this,z,!0,`f`),f(this,U,void 0,`f`)}setRequestOptions(e){typeof e==`function`?f(this,V,e(p(this,V,`f`)),`f`):f(this,V,{...p(this,V,`f`),...e},`f`)}async generateToolResponse(e=p(this,V,`f`).signal){let t=await p(this,H,`f`)??this.params.messages.at(-1);return t?p(this,bn,`m`,Cn).call(this,t,e):null}done(){return p(this,W,`f`).promise}async runUntilDone(){if(!p(this,R,`f`))for await(let e of this);return this.done()}get params(){return p(this,B,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};Cn=async function(e,t=p(this,V,`f`).signal){return p(this,U,`f`)===void 0&&f(this,U,En(p(this,B,`f`).params,e,{...p(this,V,`f`),signal:t}),`f`),p(this,U,`f`)};async function En(e,t=e.messages.at(-1),n){if(!t||t.role!==`assistant`||!t.content||typeof t.content==`string`)return null;let r=t.content.filter(e=>e.type===`tool_use`);return r.length===0?null:{role:`user`,content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>(`name`in e?e.name:e.mcp_server_name)===t.name);if(!r||!(`run`in r))return{type:`tool_result`,tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0};try{let e=t.input;`parse`in r&&r.parse&&(e=r.parse(e));let i=await r.run(e,{toolUseBlock:t,signal:n?.signal});return{type:`tool_result`,tool_use_id:t.id,content:i}}catch(e){return{type:`tool_result`,tool_use_id:t.id,content:e instanceof yn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}var Dn=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new Ue;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,n){if(!t.body)throw n.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new h(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new h(`Attempted to iterate over a response with no body`);return new e(Pe(t.body),n)}},On=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/messages/batches?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/messages/batches/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/messages/batches?beta=true`,T,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/messages/batches/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}async results(e,t={},n){let r=await this.retrieve(e);if(!r.results_url)throw new h(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);let{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:k([{"anthropic-beta":[...i??[],`message-batches-2024-09-24`].toString(),Accept:`application/binary`},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Dn.fromResponse(t.response,t.controller))}};const kn={"claude-1.3":`November 6th, 2024`,"claude-1.3-100k":`November 6th, 2024`,"claude-instant-1.1":`November 6th, 2024`,"claude-instant-1.1-100k":`November 6th, 2024`,"claude-instant-1.2":`November 6th, 2024`,"claude-3-sonnet-20240229":`July 21st, 2025`,"claude-3-opus-20240229":`January 5th, 2026`,"claude-2.1":`July 21st, 2025`,"claude-2.0":`July 21st, 2025`,"claude-3-7-sonnet-latest":`February 19th, 2026`,"claude-3-7-sonnet-20250219":`February 19th, 2026`},An=[`claude-mythos-preview`,`claude-opus-4-6`];var jn=class extends O{constructor(){super(...arguments),this.batches=new On(this._client)}create(e,t){let n=Mn(e),{betas:r,...i}=n;i.model in kn&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${kn[i.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),An.includes(i.model)&&i.thinking&&i.thinking.type===`enabled`&&console.warn(`Using Claude with ${i.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let a=this._client._options.timeout;if(!i.stream&&a==null){let e=Vt[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,e)}let o=jt(i.tools,i.messages);return this._client.post(`/v1/messages?beta=true`,{body:i,timeout:a??6e5,...t,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},o,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:k([{"anthropic-beta":[...e.betas??[],`structured-outputs-2025-12-15`].toString()},t?.headers])},this.create(e,t).then(t=>Wt(t,e,{logger:this._client.logger??console}))}stream(e,t){return vn.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...r}=Mn(e);return this._client.post(`/v1/messages/count_tokens?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`token-counting-2024-11-01`].toString()},t?.headers])})}toolRunner(e,t){return new Tn(this._client,e,t)}};function Mn(e){if(!e.output_format)return e;if(e.output_config?.format)throw new h(`Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).`);let{output_format:t,...n}=e;return{...n,output_config:{...e.output_config,format:t}}}jn.Batches=On,jn.BetaToolRunner=Tn,jn.ToolError=yn;var Nn=class extends O{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/sessions/${e}/events?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}send(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}/events?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/sessions/${e}/events/stream?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}},Pn=class extends O{retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get(A`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.post(A`/v1/sessions/${r}/resources/${e}?beta=true`,{body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/sessions/${e}/resources?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{session_id:r,betas:i}=t;return this._client.delete(A`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}add(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}/resources?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Fn=class extends O{constructor(){super(...arguments),this.events=new Nn(this._client),this.resources=new Pn(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/sessions?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/sessions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/sessions?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/sessions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/sessions/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Fn.Events=Nn,Fn.Resources=Pn;var In=class extends O{create(e,t={},n){let{betas:r,...i}=t??{};return this._client.post(A`/v1/skills/${e}/versions?beta=true`,ft({body:i,...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])},this._client))}retrieve(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get(A`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/skills/${e}/versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}delete(e,t,n){let{skill_id:r,betas:i}=t;return this._client.delete(A`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}},Ln=class extends O{constructor(){super(...arguments),this.versions=new In(this._client)}create(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/v1/skills?beta=true`,ft({body:r,...t,headers:k([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/skills/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/skills?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/skills/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}};Ln.Versions=In;var Rn=class extends O{create(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/vaults/${e}/credentials?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{vault_id:r,betas:i}=t;return this._client.get(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{vault_id:r,betas:i,...a}=t;return this._client.post(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/vaults/${e}/credentials?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{vault_id:r,betas:i}=t;return this._client.delete(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post(A`/v1/vaults/${r}/credentials/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},zn=class extends O{constructor(){super(...arguments),this.credentials=new Rn(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/vaults?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/vaults/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/vaults/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/vaults?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/vaults/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/vaults/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};zn.Credentials=Rn;var G=class extends O{constructor(){super(...arguments),this.models=new Pt(this._client),this.messages=new jn(this._client),this.agents=new Lt(this._client),this.environments=new Ot(this._client),this.sessions=new Fn(this._client),this.vaults=new zn(this._client),this.memoryStores=new Bt(this._client),this.files=new Nt(this._client),this.skills=new Ln(this._client),this.userProfiles=new Ft(this._client)}};G.Models=Pt,G.Messages=jn,G.Agents=Lt,G.Environments=Ot,G.Sessions=Fn,G.Vaults=zn,G.MemoryStores=Bt,G.Files=Nt,G.Skills=Ln,G.UserProfiles=Ft;var Bn=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/complete`,{body:r,timeout:this._client._options.timeout??6e5,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers]),stream:e.stream??!1})}};function Vn(e){return e?.output_config?.format}function Hn(e,t,n){let r=Vn(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>e.type===`text`?Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1}):e),parsed_output:null}:Un(e,t,n)}function Un(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=Wn(t,e.text);return r===null&&(r=n),Object.defineProperty({...e},"parsed_output",{value:n,enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Wn(e,t){let n=Vn(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new h(`Failed to parse structured output: ${e}`)}}var K,q,J,Gn,Kn,qn,Jn,Yn,Xn,Y,X,Zn,Qn,Z,$n,er,tr,nr,rr,ir,ar,or,sr,cr;const lr=`__json_buf`;function ur(e){return e.type===`tool_use`||e.type===`server_tool_use`}var dr=class e{constructor(e,t){K.add(this),this.messages=[],this.receivedMessages=[],q.set(this,void 0),J.set(this,null),this.controller=new AbortController,Gn.set(this,void 0),Kn.set(this,()=>{}),qn.set(this,()=>{}),Jn.set(this,void 0),Yn.set(this,()=>{}),Xn.set(this,()=>{}),Y.set(this,{}),X.set(this,!1),Zn.set(this,!1),Qn.set(this,!1),Z.set(this,!1),$n.set(this,void 0),er.set(this,void 0),tr.set(this,void 0),ir.set(this,e=>{if(f(this,Zn,!0,`f`),m(e)&&(e=new _),e instanceof _)return f(this,Qn,!0,`f`),this._emit(`abort`,e);if(e instanceof h)return this._emit(`error`,e);if(e instanceof Error){let t=new h(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new h(String(e)))}),f(this,Gn,new Promise((e,t)=>{f(this,Kn,e,`f`),f(this,qn,t,`f`)}),`f`),f(this,Jn,new Promise((e,t)=>{f(this,Yn,e,`f`),f(this,Xn,t,`f`)}),`f`),p(this,Gn,`f`).catch(()=>{}),p(this,Jn,`f`).catch(()=>{}),f(this,J,e,`f`),f(this,tr,t?.logger??console,`f`)}get response(){return p(this,$n,`f`)}get request_id(){return p(this,er,`f`)}async withResponse(){f(this,Z,!0,`f`);let e=await p(this,Gn,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return f(a,J,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},p(this,ir,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{p(this,K,`m`,ar).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)p(this,K,`m`,or).call(this,e);if(i.controller.signal?.aborted)throw new _;p(this,K,`m`,sr).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(f(this,$n,e,`f`),f(this,er,e?.headers.get(`request-id`),`f`),p(this,Kn,`f`).call(this,e),this._emit(`connect`))}get ended(){return p(this,X,`f`)}get errored(){return p(this,Zn,`f`)}get aborted(){return p(this,Qn,`f`)}abort(){this.controller.abort()}on(e,t){return(p(this,Y,`f`)[e]||(p(this,Y,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=p(this,Y,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(p(this,Y,`f`)[e]||(p(this,Y,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{f(this,Z,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){f(this,Z,!0,`f`),await p(this,Jn,`f`)}get currentMessage(){return p(this,q,`f`)}async finalMessage(){return await this.done(),p(this,K,`m`,nr).call(this)}async finalText(){return await this.done(),p(this,K,`m`,rr).call(this)}_emit(e,...t){if(p(this,X,`f`))return;e===`end`&&(f(this,X,!0,`f`),p(this,Yn,`f`).call(this));let n=p(this,Y,`f`)[e];if(n&&(p(this,Y,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!p(this,Z,`f`)&&!n?.length&&Promise.reject(e),p(this,qn,`f`).call(this,e),p(this,Xn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!p(this,Z,`f`)&&!n?.length&&Promise.reject(e),p(this,qn,`f`).call(this,e),p(this,Xn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,p(this,K,`m`,nr).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{p(this,K,`m`,ar).call(this),this._connected(null);let t=Qe.fromReadableStream(e,this.controller);for await(let e of t)p(this,K,`m`,or).call(this,e);if(t.controller.signal?.aborted)throw new _;p(this,K,`m`,sr).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(q=new WeakMap,J=new WeakMap,Gn=new WeakMap,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,Y=new WeakMap,X=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,Z=new WeakMap,$n=new WeakMap,er=new WeakMap,tr=new WeakMap,ir=new WeakMap,K=new WeakSet,nr=function(){if(this.receivedMessages.length===0)throw new h(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},rr=function(){if(this.receivedMessages.length===0)throw new h(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new h(`stream ended without producing a content block with type=text`);return e.join(` `)},ar=function(){this.ended||f(this,q,void 0,`f`)},or=function(e){if(this.ended)return;let t=p(this,K,`m`,cr).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:ur(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(Hn(t,p(this,J,`f`),{logger:p(this,tr,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:f(this,q,t,`f`);break;case`content_block_start`:case`message_delta`:break}},sr=function(){if(this.ended)throw new h(`stream has ended, this shouldn't happen`);let e=p(this,q,`f`);if(!e)throw new h(`request ended without sending any chunks`);return f(this,q,void 0,`f`),Hn(e,p(this,J,`f`),{logger:p(this,tr,`f`)})},cr=function(e){let t=p(this,q,`f`);if(e.type===`message_start`){if(t)throw new h(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new h(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case`content_block_start`:return t.content.push({...e.content_block}),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&ur(n)){let r=n[lr]||``;r+=e.delta.partial_json;let i={...n};Object.defineProperty(i,lr,{value:r,enumerable:!1,writable:!0}),r&&(i.input=Yt(r)),t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Qe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},fr=class extends O{create(e,t){return this._client.post(`/v1/messages/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(A`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/v1/messages/batches`,T,{query:e,...t})}delete(e,t){return this._client.delete(A`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(A`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new h(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:k([{Accept:`application/binary`},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Dn.fromResponse(t.response,t.controller))}},pr=class extends O{constructor(){super(...arguments),this.batches=new fr(this._client)}create(e,t){e.model in mr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${mr[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),hr.includes(e.model)&&e.thinking&&e.thinking.type===`enabled`&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let n=this._client._options.timeout;if(!e.stream&&n==null){let t=Vt[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let r=jt(e.tools,e.messages);return this._client.post(`/v1/messages`,{body:e,timeout:n??6e5,...t,headers:k([r,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>Un(t,e,{logger:this._client.logger??console}))}stream(e,t){return dr.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post(`/v1/messages/count_tokens`,{body:e,...t})}};const mr={"claude-1.3":`November 6th, 2024`,"claude-1.3-100k":`November 6th, 2024`,"claude-instant-1.1":`November 6th, 2024`,"claude-instant-1.1-100k":`November 6th, 2024`,"claude-instant-1.2":`November 6th, 2024`,"claude-3-sonnet-20240229":`July 21st, 2025`,"claude-3-opus-20240229":`January 5th, 2026`,"claude-2.1":`July 21st, 2025`,"claude-2.0":`July 21st, 2025`,"claude-3-7-sonnet-latest":`February 19th, 2026`,"claude-3-7-sonnet-20250219":`February 19th, 2026`,"claude-3-5-haiku-latest":`February 19th, 2026`,"claude-3-5-haiku-20241022":`February 19th, 2026`,"claude-opus-4-0":`June 15th, 2026`,"claude-opus-4-20250514":`June 15th, 2026`,"claude-sonnet-4-0":`June 15th, 2026`,"claude-sonnet-4-20250514":`June 15th, 2026`},hr=[`claude-mythos-preview`,`claude-opus-4-6`];pr.Batches=fr;var gr=class extends O{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/models/${e}`,{...n,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models`,T,{query:r,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}};const _r=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var vr,yr,br,xr,Q=class{constructor({baseURL:e=_r(`ANTHROPIC_BASE_URL`),apiKey:t=_r(`ANTHROPIC_API_KEY`)??null,authToken:n=_r(`ANTHROPIC_AUTH_TOKEN`)??null,...r}={}){vr.add(this),br.set(this,void 0);let i={apiKey:t,authToken:n,...r,baseURL:e||`https://api.anthropic.com`};if(!i.dangerouslyAllowBrowser&&Ce())throw new h(`It looks like you're running in a browser-like environment.
29
-
30
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
31
- If you understand the risks and have appropriate mitigations in place,
32
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
33
-
34
- new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
35
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??yr.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=qe(i.logLevel,`ClientOptions.logLevel`,this)??qe(_r(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??je(),f(this,br,Ie,`f`),this._options=i,this.apiKey=typeof t==`string`?t:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted`)}async authHeaders(e){return k([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return k([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return k([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Le(e)}getUserAgent(){return`${this.constructor.name}/JS ${v}`}defaultIdempotencyKey(){return`stainless-node-retry-${te()}`}makeStatusError(e,t,n,r){return g.generate(e,t,n,r)}buildURL(e,t,n){let r=!p(this,vr,`m`,xr).call(this)&&n||this.baseURL,i=me(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!ve(a)||!ve(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new h(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details`);return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new at(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(S(this).debug(`[${c}] sending request`,C({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new _;let ee=new AbortController,d=await this.fetchWithTimeout(o,a,s,ee).catch(ne),f=Date.now();if(d instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new _;let i=m(d)||/timed? ?out/i.test(String(d)+(`cause`in d?String(d.cause):``));if(t)return S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),this.retryRequest(r,t,n??c);throw S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),i?new ie:new re({cause:d})}let p=`[${c}${l}${[...d.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${d.ok?`succeeded`:`failed`} with status ${d.status} in ${f-u}ms`;if(!d.ok){let e=await this.shouldRetry(d);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Fe(d.body),S(this).info(`${p} - ${e}`),S(this).debug(`[${c}] response error (${e})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),this.retryRequest(r,t,n??c,d.headers)}let i=e?`error; no more retries left`:`error; not retryable`;S(this).info(`${p} - ${i}`);let a=await d.text().catch(e=>ne(e).message),o=xe(a),s=o?void 0:a;throw S(this).debug(`[${c}] response error (${i})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(d.status,o,s,d.headers)}return S(this).info(p),S(this).debug(`[${c}] response start`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),{response:d,options:r,controller:ee,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new ct(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Se(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new h(`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`);return n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&be(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=k([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Ae(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=k([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:Ne(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:p(this,br,`f`).call(this,{body:e,headers:n})}};yr=Q,br=new WeakMap,vr=new WeakSet,xr=function(){return this.baseURL!==`https://api.anthropic.com`},Q.Anthropic=yr,Q.HUMAN_PROMPT=`\\n\\nHuman:`,Q.AI_PROMPT=`\\n\\nAssistant:`,Q.DEFAULT_TIMEOUT=6e5,Q.AnthropicError=h,Q.APIError=g,Q.APIConnectionError=re,Q.APIConnectionTimeoutError=ie,Q.APIUserAbortError=_,Q.NotFoundError=ce,Q.ConflictError=le,Q.RateLimitError=de,Q.BadRequestError=ae,Q.AuthenticationError=oe,Q.InternalServerError=fe,Q.PermissionDeniedError=se,Q.UnprocessableEntityError=ue,Q.toFile=xt;var $=class extends Q{constructor(){super(...arguments),this.completions=new Bn(this),this.messages=new pr(this),this.models=new gr(this),this.beta=new G(this)}};$.Completions=Bn,$.Messages=pr,$.Models=gr,$.Beta=G;function Sr(e,t){return e||(o(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}function Cr(e,t,n){let r=Sr(t,n);if(r===`none`)return{retention:r};let i=r===`long`&&Or(e).supportsLongCacheRetention?`1h`:void 0;return{retention:r,cacheControl:{type:`ephemeral`,...i&&{ttl:i}}}}const wr=new Map([`Read`,`Write`,`Edit`,`Bash`,`Grep`,`Glob`,`AskUserQuestion`,`EnterPlanMode`,`ExitPlanMode`,`KillShell`,`NotebookEdit`,`Skill`,`Task`,`TaskOutput`,`TodoWrite`,`WebFetch`,`WebSearch`].map(e=>[e.toLowerCase(),e])),Tr=e=>wr.get(e.toLowerCase())??e,Er=(e,t)=>{if(t&&t.length>0){let n=e.toLowerCase(),r=t.find(e=>e.name.toLowerCase()===n);if(r)return r.name}return e};function Dr(e){if(!e.some(e=>e.type===`image`))return u(e.map(e=>e.text).join(`
36
- `));let t=e.map(e=>e.type===`text`?{type:`text`,text:u(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}});return t.some(e=>e.type===`text`)||t.unshift({type:`text`,text:`(see attached image)`}),t}function Or(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:e.compat?.sendSessionAffinityHeaders??!1,supportsCacheControlOnTools:e.compat?.supportsCacheControlOnTools??!0,supportsTemperature:e.compat?.supportsTemperature??!0,allowEmptySignature:e.compat?.allowEmptySignature??!1}}function kr(...e){let t={};for(let n of e)n&&Object.assign(t,n);return t}function Ar(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function jr(e,t,n){if(!t&&!(Ar(n,`authorization`)||Ar(n,`x-api-key`)||Ar(n,`cf-aig-authorization`)))throw Error(`No API key for provider: ${e}`)}const Mr=new Set([`message_start`,`message_delta`,`message_stop`,`content_block_start`,`content_block_delta`,`content_block_stop`]);function Nr(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
37
- `),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Pr(e,t){if(e===``)return Nr(t);if(t.raw.push(e),e.startsWith(`:`))return null;let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);return i.startsWith(` `)&&(i=i.slice(1)),r===`event`?t.event=i:r===`data`&&t.data.push(i),null}function Fr(e){let t=e.indexOf(`\r`),n=e.indexOf(`
38
- `);return t===-1?n:n===-1?t:Math.min(t,n)}function Ir(e){let t=Fr(e);if(t===-1)return null;let n=t+1;return e[t]===`\r`&&e[n]===`
39
- `&&(n+=1),{line:e.slice(0,t),rest:e.slice(n)}}async function*Lr(e,t){let n=e.getReader(),r=new TextDecoder,i={event:null,data:[],raw:[]},a=``;try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{value:e,done:o}=await n.read();if(o)break;a+=r.decode(e,{stream:!0});let s=Ir(a);for(;s;){a=s.rest;let e=Pr(s.line,i);e&&(yield e),s=Ir(a)}}a+=r.decode();let e=Ir(a);for(;e;){a=e.rest;let t=Pr(e.line,i);t&&(yield t),e=Ir(a)}if(a.length>0){let e=Pr(a,i);e&&(yield e)}let o=Nr(i);o&&(yield o)}finally{n.releaseLock()}}async function*Rr(e,t){if(!e.body)throw Error(`Attempted to iterate over an Anthropic response with no body`);let n=!1,r=!1;for await(let i of Lr(e.body,t)){if(i.event===`error`)throw Error(i.data);if(Mr.has(i.event??``))try{let e=c(i.data);e.type===`message_start`?n=!0:e.type===`message_stop`&&(r=!0),yield e}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Could not parse Anthropic SSE event ${i.event}: ${t}; data=${i.data}; raw=${i.raw.join(`\\n`)}`)}}if(n&&!r)throw Error(`Anthropic stream ended before message_stop`)}const zr=(t,n,i)=>{let a=new e;return(async()=>{let e={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let o,c;if(i?.client)o=i.client,c=!1;else{let e=i?.apiKey;jr(t.provider,e,i?.headers);let r;if(t.provider===`github-copilot`){let e=ee(n.messages);r=d({messages:n.messages,hasImages:e})}let a=Sr(i?.cacheRetention,i?.env)===`none`?void 0:i?.sessionId,s=Ur(t,e,i?.interleavedThinking??!0,qr(t,n),i?.headers,r,a);o=s.client,c=s.isOAuthToken}let u=Wr(t,n,c,i),f=await i?.onPayload?.(u,t);f!==void 0&&(u=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},maxRetries:i?.maxRetries??0},te=await o.messages.create({...u,stream:!0},p).asResponse();await i?.onResponse?.({status:te.status,headers:l(te.headers)},t),a.push({type:`start`,partial:e});let m=e.content;for await(let o of Rr(te,i?.signal))if(o.type===`message_start`)e.responseId=o.message.id,e.usage.input=o.message.usage.input_tokens||0,e.usage.output=o.message.usage.output_tokens||0,e.usage.cacheRead=o.message.usage.cache_read_input_tokens||0,e.usage.cacheWrite=o.message.usage.cache_creation_input_tokens||0,e.usage.cacheWrite1h=o.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,r(t,e.usage);else if(o.type===`content_block_start`){if(o.content_block.type===`text`){let t={type:`text`,text:``,index:o.index};e.content.push(t),a.push({type:`text_start`,contentIndex:e.content.length-1,partial:e})}else if(o.content_block.type===`thinking`){let t={type:`thinking`,thinking:``,thinkingSignature:``,index:o.index};e.content.push(t),a.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(o.content_block.type===`redacted_thinking`){let t={type:`thinking`,thinking:`[Reasoning redacted]`,thinkingSignature:o.content_block.data,redacted:!0,index:o.index};e.content.push(t),a.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(o.content_block.type===`tool_use`){let t={type:`toolCall`,id:o.content_block.id,name:c?Er(o.content_block.name,n.tools):o.content_block.name,arguments:o.content_block.input??{},partialJson:``,index:o.index};e.content.push(t),a.push({type:`toolcall_start`,contentIndex:e.content.length-1,partial:e})}}else if(o.type===`content_block_delta`){if(o.delta.type===`text_delta`){let t=m.findIndex(e=>e.index===o.index),n=m[t];n&&n.type===`text`&&(n.text+=o.delta.text,a.push({type:`text_delta`,contentIndex:t,delta:o.delta.text,partial:e}))}else if(o.delta.type===`thinking_delta`){let t=m.findIndex(e=>e.index===o.index),n=m[t];n&&n.type===`thinking`&&(n.thinking+=o.delta.thinking,a.push({type:`thinking_delta`,contentIndex:t,delta:o.delta.thinking,partial:e}))}else if(o.delta.type===`input_json_delta`){let t=m.findIndex(e=>e.index===o.index),n=m[t];n&&n.type===`toolCall`&&(n.partialJson+=o.delta.partial_json,n.arguments=s(n.partialJson),a.push({type:`toolcall_delta`,contentIndex:t,delta:o.delta.partial_json,partial:e}))}else if(o.delta.type===`signature_delta`){let e=m[m.findIndex(e=>e.index===o.index)];e&&e.type===`thinking`&&(e.thinkingSignature=e.thinkingSignature||``,e.thinkingSignature+=o.delta.signature)}}else if(o.type===`content_block_stop`){let t=m.findIndex(e=>e.index===o.index),n=m[t];n&&(delete n.index,n.type===`text`?a.push({type:`text_end`,contentIndex:t,content:n.text,partial:e}):n.type===`thinking`?a.push({type:`thinking_end`,contentIndex:t,content:n.thinking,partial:e}):n.type===`toolCall`&&(n.arguments=s(n.partialJson),delete n.partialJson,a.push({type:`toolcall_end`,contentIndex:t,toolCall:n,partial:e})))}else if(o.type===`message_delta`){if(o.delta.stop_reason){let t=Yr(o.delta.stop_reason,o.delta.stop_details);e.stopReason=t.stopReason,t.errorMessage&&(e.errorMessage=t.errorMessage)}o.usage.input_tokens!=null&&(e.usage.input=o.usage.input_tokens),o.usage.output_tokens!=null&&(e.usage.output=o.usage.output_tokens),o.usage.cache_read_input_tokens!=null&&(e.usage.cacheRead=o.usage.cache_read_input_tokens),o.usage.cache_creation_input_tokens!=null&&(e.usage.cacheWrite=o.usage.cache_creation_input_tokens);let n=o.usage.output_tokens_details?.thinking_tokens;n!=null&&(e.usage.reasoning=n),e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,r(t,e.usage)}if(i?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(e.errorMessage||`An unknown error occurred`);a.push({type:`done`,reason:e.stopReason,message:e}),a.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson;e.stopReason=i?.signal?.aborted?`aborted`:`error`,e.errorMessage=t instanceof Error?t.message:JSON.stringify(t),a.push({type:`error`,reason:e.stopReason,error:e}),a.end()}})(),a};function Br(e,t){let n=t?e.thinkingLevelMap?.[t]:void 0;if(typeof n==`string`)return n;switch(t){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`high`:return`high`;default:return`high`}}const Vr=(e,r,a)=>{jr(e.provider,a?.apiKey,a?.headers);let o=i(e,r,a,a?.apiKey);if(!a?.reasoning)return zr(e,r,{...o,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let t=Br(e,a.reasoning);return zr(e,r,{...o,thinkingEnabled:!0,effort:t})}let s=n(o.maxTokens,e.maxTokens,a.reasoning,a.thinkingBudgets),c=t(e,r,s.maxTokens);return zr(e,r,{...o,maxTokens:c,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(s.thinkingBudget,Math.max(0,c-1024))})};function Hr(e){return e.includes(`sk-ant-oat`)}function Ur(e,t,n,r,i,a,o){let s=n&&e.compat?.forceAdaptiveThinking!==!0,c=[];if(r&&c.push(`fine-grained-tool-streaming-2025-05-14`),s&&c.push(`interleaved-thinking-2025-05-14`),e.provider===`github-copilot`)return{client:new $({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:kr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...c.length>0?{"anthropic-beta":c.join(`,`)}:{}},e.headers,a,i)}),isOAuthToken:!1};if(t&&Hr(t))return{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:kr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"anthropic-beta":[`claude-code-20250219`,`oauth-2025-04-20`,...c].join(`,`),"user-agent":`claude-cli/2.1.75`,"x-app":`cli`},e.headers,i)}),isOAuthToken:!0};let l=o&&Or(e).sendSessionAffinityHeaders?{"x-session-affinity":o}:{},u=kr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...c.length>0?{"anthropic-beta":c.join(`,`)}:{}},l,e.headers,i);return{client:new $({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:u}),isOAuthToken:!1}}function Wr(e,t,n,r){let{cacheControl:i}=Cr(e,r?.cacheRetention,r?.env),a=Or(e),o={model:e.id,messages:Kr(t.messages,e,n,i,a.allowEmptySignature),max_tokens:r?.maxTokens??e.maxTokens,stream:!0};if(n?(o.system=[{type:`text`,text:`You are Claude Code, Anthropic's official CLI for Claude.`,...i?{cache_control:i}:{}}],t.systemPrompt&&o.system.push({type:`text`,text:u(t.systemPrompt),...i?{cache_control:i}:{}})):t.systemPrompt&&(o.system=[{type:`text`,text:u(t.systemPrompt),...i?{cache_control:i}:{}}]),r?.temperature!==void 0&&!r?.thinkingEnabled&&a.supportsTemperature&&(o.temperature=r.temperature),t.tools&&t.tools.length>0&&(o.tools=Jr(t.tools,n,a.supportsEagerToolInputStreaming,a.supportsCacheControlOnTools?i:void 0)),e.reasoning)if(r?.thinkingEnabled){let t=r.thinkingDisplay??`summarized`;e.compat?.forceAdaptiveThinking===!0?(o.thinking={type:`adaptive`,display:t},r.effort&&(o.output_config=(r.effort,{effort:r.effort}))):o.thinking={type:`enabled`,budget_tokens:r.thinkingBudgetTokens||1024,display:t}}else r?.thinkingEnabled===!1&&e.thinkingLevelMap?.off!==null&&(o.thinking={type:`disabled`});if(r?.metadata){let e=r.metadata.user_id;typeof e==`string`&&(o.metadata={user_id:e})}return r?.toolChoice&&(typeof r.toolChoice==`string`?o.tool_choice={type:r.toolChoice}:o.tool_choice=r.toolChoice),o}function Gr(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function Kr(e,t,n,r,i=!1){let o=[],s=a(e,t,Gr);for(let e=0;e<s.length;e++){let t=s[e];if(t.role===`user`)if(typeof t.content==`string`)t.content.trim().length>0&&o.push({role:`user`,content:u(t.content)});else{let e=t.content.map(e=>e.type===`text`?{type:`text`,text:u(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}}).filter(e=>e.type!==`text`||e.text.trim().length>0);if(e.length===0)continue;o.push({role:`user`,content:e})}else if(t.role===`assistant`){let e=[];for(let r of t.content)if(r.type===`text`){if(r.text.trim().length===0)continue;e.push({type:`text`,text:u(r.text)})}else if(r.type===`thinking`){if(r.redacted){e.push({type:`redacted_thinking`,data:r.thinkingSignature});continue}if(r.thinking.trim().length===0)continue;!r.thinkingSignature||r.thinkingSignature.trim().length===0?e.push(i?{type:`thinking`,thinking:u(r.thinking),signature:``}:{type:`text`,text:u(r.thinking)}):e.push({type:`thinking`,thinking:u(r.thinking),signature:r.thinkingSignature})}else r.type===`toolCall`&&e.push({type:`tool_use`,id:r.id,name:n?Tr(r.name):r.name,input:r.arguments??{}});if(e.length===0)continue;o.push({role:`assistant`,content:e})}else if(t.role===`toolResult`){let n=[];n.push({type:`tool_result`,tool_use_id:t.toolCallId,content:Dr(t.content),is_error:t.isError});let r=e+1;for(;r<s.length&&s[r].role===`toolResult`;){let e=s[r];n.push({type:`tool_result`,tool_use_id:e.toolCallId,content:Dr(e.content),is_error:e.isError}),r++}e=r-1,o.push({role:`user`,content:n})}}if(r&&o.length>0){let e=o[o.length-1];if(e.role===`user`)if(Array.isArray(e.content)){let t=e.content[e.content.length-1];t&&(t.type===`text`||t.type===`image`||t.type===`tool_result`)&&(t.cache_control=r)}else typeof e.content==`string`&&(e.content=[{type:`text`,text:e.content,cache_control:r}])}return o}function qr(e,t){return!!t.tools?.length&&!Or(e).supportsEagerToolInputStreaming}function Jr(e,t,n,r){return e?e.map((i,a)=>{let o=i.parameters;return{name:t?Tr(i.name):i.name,description:i.description,...n?{eager_input_streaming:!0}:{},input_schema:{type:`object`,properties:o.properties??{},required:o.required??[]},...r&&a===e.length-1?{cache_control:r}:{}}}):[]}function Yr(e,t){switch(e){case`end_turn`:return{stopReason:`stop`};case`max_tokens`:return{stopReason:`length`};case`tool_use`:return{stopReason:`toolUse`};case`refusal`:return{stopReason:`error`,errorMessage:t?.explanation||`The model refused to complete the request`};case`pause_turn`:return{stopReason:`stop`};case`stop_sequence`:return{stopReason:`stop`};case`sensitive`:return{stopReason:`error`};default:throw Error(`Unhandled stop reason: ${e}`)}}export{zr as stream,Vr as streamSimple};
@@ -1,39 +0,0 @@
1
- import{o as e,t}from"./models-CzSI8IsT.js";import{t as n}from"./provider-env-D37PhSJu.js";import{n as r,t as i}from"./json-parse-rb7sUwcH.js";import{i as a,n as o,r as s,t as c}from"./transform-messages-fFaW-DLG.js";import{t as l}from"./headers-CbDaTl3c.js";import{t as u}from"./sanitize-unicode-DmIE6hZJ.js";import{n as ee,t as d}from"./github-copilot-headers-DRgtIyTm.js";function f(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function p(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var te=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return te=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function m(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var ne=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},h=class extends Error{},g=class e extends h{constructor(t,n,r,i,a){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`request-id`),this.error=n,this.type=a??null}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new re({message:r,cause:ne(n)});let a=n,o=a?.error?.type;return t===400?new ae(t,a,r,i,o):t===401?new oe(t,a,r,i,o):t===403?new se(t,a,r,i,o):t===404?new ce(t,a,r,i,o):t===409?new le(t,a,r,i,o):t===422?new ue(t,a,r,i,o):t===429?new de(t,a,r,i,o):t>=500?new fe(t,a,r,i,o):new e(t,a,r,i,o)}},_=class extends g{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},re=class extends g{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},ie=class extends re{constructor({message:e}={}){super({message:e??`Request timed out.`})}},ae=class extends g{},oe=class extends g{},se=class extends g{},ce=class extends g{},le=class extends g{},ue=class extends g{},de=class extends g{},fe=class extends g{},pe=/^[a-z][a-z0-9+.-]*:/i,me=e=>pe.test(e),he=e=>(he=Array.isArray,he(e)),ge=he;function _e(e){return typeof e==`object`?e??{}:{}}function ve(e){if(!e)return!0;for(let t in e)return!1;return!0}function ye(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var be=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new h(`${e} must be an integer`);if(t<0)throw new h(`${e} must be a positive integer`);return t},xe=e=>{try{return JSON.parse(e)}catch{return}},Se=e=>new Promise(t=>setTimeout(t,e)),v=`0.91.1`,Ce=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function we(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var Te=()=>{let e=we();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":Oe(Deno.build.os),"X-Stainless-Arch":De(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":Oe(globalThis.process.platform??`unknown`),"X-Stainless-Arch":De(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Ee();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":v,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Ee(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var De=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Oe=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),ke,Ae=()=>ke??=Te();function je(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Me(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Ne(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Me({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Pe(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Fe(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Ie=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function Le(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new h(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}function Re(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var ze;function Be(e){let t;return(ze??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Ve;function He(e){let t;return(Ve??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var y,b,Ue=class{constructor(){y.set(this,void 0),b.set(this,void 0),f(this,y,new Uint8Array,`f`),f(this,b,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?Be(e):e;f(this,y,Re([p(this,y,`f`),t]),`f`);let n=[],r;for(;(r=We(p(this,y,`f`),p(this,b,`f`)))!=null;){if(r.carriage&&p(this,b,`f`)==null){f(this,b,r.index,`f`);continue}if(p(this,b,`f`)!=null&&(r.index!==p(this,b,`f`)+1||r.carriage)){n.push(He(p(this,y,`f`).subarray(0,p(this,b,`f`)-1))),f(this,y,p(this,y,`f`).subarray(p(this,b,`f`)),`f`),f(this,b,null,`f`);continue}let e=p(this,b,`f`)===null?r.preceding:r.preceding-1,t=He(p(this,y,`f`).subarray(0,e));n.push(t),f(this,y,p(this,y,`f`).subarray(r.index),`f`),f(this,b,null,`f`)}return n}flush(){return p(this,y,`f`).length?this.decode(`
2
- `):[]}};y=new WeakMap,b=new WeakMap,Ue.NEWLINE_CHARS=new Set([`
3
- `,`\r`]),Ue.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function We(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ge(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var Ke={off:0,error:200,warn:300,info:400,debug:500},qe=(e,t,n)=>{if(e){if(ye(Ke,e))return e;S(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ke))}`)}};function x(){}function Je(e,t,n){return!t||Ke[e]>Ke[n]?x:t[e].bind(t)}var Ye={error:x,warn:x,info:x,debug:x},Xe=new WeakMap;function S(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Ye;let r=Xe.get(t);if(r&&r[0]===n)return r[1];let i={error:Je(`error`,t,n),warn:Je(`warn`,t,n),info:Je(`info`,t,n),debug:Je(`debug`,t,n)};return Xe.set(t,[n,i]),i}var C=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),Ze,Qe=class e{constructor(e,t,n){this.iterator=e,Ze.set(this,void 0),this.controller=t,f(this,Ze,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?S(r):console;async function*o(){if(i)throw new h("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of $e(t,n)){if(e.event===`completion`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event===`message_start`||e.event===`message_delta`||e.event===`message_stop`||e.event===`content_block_start`||e.event===`content_block_delta`||e.event===`content_block_stop`||e.event===`message`||e.event===`user.message`||e.event===`user.interrupt`||e.event===`user.tool_confirmation`||e.event===`user.custom_tool_result`||e.event===`agent.message`||e.event===`agent.thinking`||e.event===`agent.tool_use`||e.event===`agent.tool_result`||e.event===`agent.mcp_tool_use`||e.event===`agent.mcp_tool_result`||e.event===`agent.custom_tool_use`||e.event===`agent.thread_context_compacted`||e.event===`session.status_running`||e.event===`session.status_idle`||e.event===`session.status_rescheduled`||e.event===`session.status_terminated`||e.event===`session.error`||e.event===`session.deleted`||e.event===`span.model_request_start`||e.event===`span.model_request_end`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event!==`ping`&&e.event===`error`){let n=xe(e.data)??e.data,r=n?.error?.type;throw new g(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(m(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new Ue,n=Pe(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new h("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(m(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Ze=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,p(this,Ze,`f`)),new e(()=>i(n),this.controller,p(this,Ze,`f`))]}toReadableStream(){let e=this,t;return Me({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Be(JSON.stringify(n)+`
4
- `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*$e(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new h(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new h(`Attempted to iterate over a response with no body`);let n=new tt,r=new Ue,i=Pe(e.body);for await(let e of et(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*et(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Be(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Ge(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var tt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=nt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function nt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function rt(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return S(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):Qe.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:it(await n.json(),n):await n.text()})();return S(e).debug(`[${r}] response parsed`,C({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function it(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`request-id`),enumerable:!1})}var w,at=class e extends Promise{constructor(e,t,n=rt){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,w.set(this,void 0),f(this,w,e,`f`)}_thenUnwrap(t){return new e(p(this,w,`f`),this.responsePromise,async(e,n)=>it(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(p(this,w,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};w=new WeakMap;var ot,st=class{constructor(e,t,n,r){ot.set(this,void 0),f(this,ot,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new h("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await p(this,ot,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ot=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ct=class extends at{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await rt(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},T=class extends st{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{..._e(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{..._e(this.options.query),after_id:e}}:null}},E=class extends st{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{..._e(this.options.query),page:e}}:null}},lt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function D(e,t,n){return lt(),new File(e,t??`unknown_file`,n)}function ut(e,t){let n=typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``;return t?n.split(/[\\/]/).pop()||void 0:n}var dt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,ft=async(e,t,n=!0)=>({...e,body:await ht(e.body,t,n)}),pt=new WeakMap;function mt(e){let t=typeof e==`function`?e:e.fetch,n=pt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return pt.set(t,r),r}var ht=async(e,t,n=!0)=>{if(!await mt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>_t(r,e,t,n))),r},gt=e=>e instanceof Blob&&`name`in e,_t=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i={},a=n.headers.get(`Content-Type`);a&&(i={type:a}),e.append(t,D([await n.blob()],ut(n,r),i))}else if(dt(n))e.append(t,D([await new Response(Ne(n)).blob()],ut(n,r)));else if(gt(n))e.append(t,D([n],ut(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>_t(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>_t(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},vt=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,yt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&vt(e),bt=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function xt(e,t,n){if(lt(),e=await e,t||=ut(e,!0),yt(e))return e instanceof File&&t==null&&n==null?e:D([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(bt(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),D(await St(r),t,n)}let r=await St(e);if(!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return D(r,t,n)}async function St(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(vt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(dt(e))for await(let n of e)t.push(...await St(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Ct(e)}`)}return t}function Ct(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var O=class{constructor(e){this._client=e}},wt=Symbol.for(`brand.privateNullableHeaders`);function*Tt(e){if(!e)return;if(wt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ge(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ge(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var k=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Tt(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[wt]:!0,values:t,nulls:n}};function Et(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Dt=Object.freeze(Object.create(null)),A=((e=Et)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Dt)??Dt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new h(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
- `)}\n${a}\n${t}`)}return a})(Et),Ot=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/environments/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/environments/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/environments?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/environments/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/environments/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},j=Symbol(`anthropic.sdk.stainlessHelper`);function kt(e){return typeof e==`object`&&!!e&&j in e}function At(e,t){let n=new Set;if(e)for(let t of e)kt(t)&&n.add(t[j]);if(t){for(let e of t)if(kt(e)&&n.add(e[j]),Array.isArray(e.content))for(let t of e.content)kt(t)&&n.add(t[j])}return Array.from(n)}function jt(e,t){let n=At(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function Mt(e){return kt(e)?{"x-stainless-helper":e[j]}:{}}var Nt=class extends O{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,T,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/files/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/files/${e}/content?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/files/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}upload(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/files?beta=true`,ft({body:r,...t,headers:k([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},Mt(r.file),t?.headers])},this._client))}},Pt=class extends O{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/models/${e}?beta=true`,{...n,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models?beta=true`,T,{query:r,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},Ft=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/user_profiles/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/user_profiles?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},It=class extends O{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/agents/${e}/versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Lt=class extends O{constructor(){super(...arguments),this.versions=new It(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(A`/v1/agents/${e}?beta=true`,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/agents/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/agents?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/agents/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Lt.Versions=It;var Rt=class extends O{create(e,t,n){let{view:r,betas:i,...a}=t;return this._client.post(A`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:r},body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{memory_store_id:r,view:i,betas:a,...o}=t;return this._client.post(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{view:i},body:o,...n,headers:k([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/memory_stores/${e}/memories?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{memory_store_id:r,expected_content_sha256:i,betas:a}=t;return this._client.delete(A`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:k([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},zt=class extends O{retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(A`/v1/memory_stores/${r}/memory_versions/${e}?beta=true`,{query:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/memory_stores/${e}/memory_versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}redact(e,t,n){let{memory_store_id:r,betas:i}=t;return this._client.post(A`/v1/memory_stores/${r}/memory_versions/${e}/redact?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Bt=class extends O{constructor(){super(...arguments),this.memories=new Rt(this._client),this.memoryVersions=new zt(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/memory_stores?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/memory_stores/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/memory_stores/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/memory_stores?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/memory_stores/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Bt.Memories=Rt,Bt.MemoryVersions=zt;var Vt={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Ht(e){return e?.output_format??e?.output_config?.format}function Ut(e,t,n){let r=Ht(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>{if(e.type===`text`){let t=Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(t,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return e}),parsed_output:null}:Wt(e,t,n)}function Wt(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=Gt(t,e.text);r===null&&(r=i);let a=Object.defineProperty({...e},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Gt(e,t){let n=Ht(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new h(`Failed to parse structured output: ${e}`)}}var Kt=e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if(r===`\\`){t++;continue}if(r===`{`){n.push({type:`brace`,value:`{`}),t++;continue}if(r===`}`){n.push({type:`brace`,value:`}`}),t++;continue}if(r===`[`){n.push({type:`paren`,value:`[`}),t++;continue}if(r===`]`){n.push({type:`paren`,value:`]`}),t++;continue}if(r===`:`){n.push({type:`separator`,value:`:`}),t++;continue}if(r===`,`){n.push({type:`delimiter`,value:`,`}),t++;continue}if(r===`"`){let i=``,a=!1;for(r=e[++t];r!==`"`;){if(t===e.length){a=!0;break}if(r===`\\`){if(t++,t===e.length){a=!0;break}i+=r+e[t],r=e[++t]}else i+=r,r=e[++t]}r=e[++t],a||n.push({type:`string`,value:i});continue}if(r&&/\s/.test(r)){t++;continue}let i=/[0-9]/;if(r&&i.test(r)||r===`-`||r===`.`){let a=``;for(r===`-`&&(a+=r,r=e[++t]);r&&i.test(r)||r===`.`;)a+=r,r=e[++t];n.push({type:`number`,value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let i=``;for(;r&&a.test(r)&&t!==e.length;)i+=r,r=e[++t];if(i==`true`||i==`false`||i===`null`)n.push({type:`name`,value:i});else{t++;continue}continue}t++}return n},M=e=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case`separator`:return e=e.slice(0,e.length-1),M(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),M(e);case`string`:let r=e[e.length-2];if(r?.type===`delimiter`||r?.type===`brace`&&r.value===`{`)return e=e.slice(0,e.length-1),M(e);break;case`delimiter`:return e=e.slice(0,e.length-1),M(e)}return e},qt=e=>{let t=[];return e.map(e=>{e.type===`brace`&&(e.value===`{`?t.push(`}`):t.splice(t.lastIndexOf(`}`),1)),e.type===`paren`&&(e.value===`[`?t.push(`]`):t.splice(t.lastIndexOf(`]`),1))}),t.length>0&&t.reverse().map(t=>{t===`}`?e.push({type:`brace`,value:`}`}):t===`]`&&e.push({type:`paren`,value:`]`})}),e},Jt=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},Yt=e=>JSON.parse(Jt(qt(M(Kt(e))))),N,P,F,Xt,Zt,Qt,$t,en,tn,I,nn,rn,an,L,on,sn,cn,ln,un,dn,fn,pn,mn,hn,gn=`__json_buf`;function _n(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var vn=class e{constructor(e,t){N.add(this),this.messages=[],this.receivedMessages=[],P.set(this,void 0),F.set(this,null),this.controller=new AbortController,Xt.set(this,void 0),Zt.set(this,()=>{}),Qt.set(this,()=>{}),$t.set(this,void 0),en.set(this,()=>{}),tn.set(this,()=>{}),I.set(this,{}),nn.set(this,!1),rn.set(this,!1),an.set(this,!1),L.set(this,!1),on.set(this,void 0),sn.set(this,void 0),cn.set(this,void 0),dn.set(this,e=>{if(f(this,rn,!0,`f`),m(e)&&(e=new _),e instanceof _)return f(this,an,!0,`f`),this._emit(`abort`,e);if(e instanceof h)return this._emit(`error`,e);if(e instanceof Error){let t=new h(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new h(String(e)))}),f(this,Xt,new Promise((e,t)=>{f(this,Zt,e,`f`),f(this,Qt,t,`f`)}),`f`),f(this,$t,new Promise((e,t)=>{f(this,en,e,`f`),f(this,tn,t,`f`)}),`f`),p(this,Xt,`f`).catch(()=>{}),p(this,$t,`f`).catch(()=>{}),f(this,F,e,`f`),f(this,cn,t?.logger??console,`f`)}get response(){return p(this,on,`f`)}get request_id(){return p(this,sn,`f`)}async withResponse(){f(this,L,!0,`f`);let e=await p(this,Xt,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return f(a,F,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},p(this,dn,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{p(this,N,`m`,fn).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)p(this,N,`m`,pn).call(this,e);if(i.controller.signal?.aborted)throw new _;p(this,N,`m`,mn).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(f(this,on,e,`f`),f(this,sn,e?.headers.get(`request-id`),`f`),p(this,Zt,`f`).call(this,e),this._emit(`connect`))}get ended(){return p(this,nn,`f`)}get errored(){return p(this,rn,`f`)}get aborted(){return p(this,an,`f`)}abort(){this.controller.abort()}on(e,t){return(p(this,I,`f`)[e]||(p(this,I,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=p(this,I,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(p(this,I,`f`)[e]||(p(this,I,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{f(this,L,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){f(this,L,!0,`f`),await p(this,$t,`f`)}get currentMessage(){return p(this,P,`f`)}async finalMessage(){return await this.done(),p(this,N,`m`,ln).call(this)}async finalText(){return await this.done(),p(this,N,`m`,un).call(this)}_emit(e,...t){if(p(this,nn,`f`))return;e===`end`&&(f(this,nn,!0,`f`),p(this,en,`f`).call(this));let n=p(this,I,`f`)[e];if(n&&(p(this,I,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!p(this,L,`f`)&&!n?.length&&Promise.reject(e),p(this,Qt,`f`).call(this,e),p(this,tn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!p(this,L,`f`)&&!n?.length&&Promise.reject(e),p(this,Qt,`f`).call(this,e),p(this,tn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,p(this,N,`m`,ln).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{p(this,N,`m`,fn).call(this),this._connected(null);let t=Qe.fromReadableStream(e,this.controller);for await(let e of t)p(this,N,`m`,pn).call(this,e);if(t.controller.signal?.aborted)throw new _;p(this,N,`m`,mn).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(P=new WeakMap,F=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,en=new WeakMap,tn=new WeakMap,I=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,L=new WeakMap,on=new WeakMap,sn=new WeakMap,cn=new WeakMap,dn=new WeakMap,N=new WeakSet,ln=function(){if(this.receivedMessages.length===0)throw new h(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},un=function(){if(this.receivedMessages.length===0)throw new h(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new h(`stream ended without producing a content block with type=text`);return e.join(` `)},fn=function(){this.ended||f(this,P,void 0,`f`)},pn=function(e){if(this.ended)return;let t=p(this,N,`m`,hn).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:_n(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;case`compaction_delta`:n.type===`compaction`&&n.content&&this._emit(`compaction`,n.content);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(Ut(t,p(this,F,`f`),{logger:p(this,cn,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:f(this,P,t,`f`);break;case`content_block_start`:case`message_delta`:break}},mn=function(){if(this.ended)throw new h(`stream has ended, this shouldn't happen`);let e=p(this,P,`f`);if(!e)throw new h(`request ended without sending any chunks`);return f(this,P,void 0,`f`),Ut(e,p(this,F,`f`),{logger:p(this,cn,`f`)})},hn=function(e){let t=p(this,P,`f`);if(e.type===`message_start`){if(t)throw new h(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new h(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(t.usage.iterations=e.usage.iterations),t;case`content_block_start`:return t.content.push(e.content_block),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&_n(n)){let r=n[gn]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,gn,{value:r,enumerable:!1,writable:!0}),r)try{i.input=Yt(r)}catch(e){let t=new h(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${e}. JSON: ${r}`);p(this,dn,`f`).call(this,t)}t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;case`compaction_delta`:n?.type===`compaction`&&(t.content[e.index]={...n,content:(n.content||``)+e.delta.content});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Qe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},yn=class extends Error{constructor(e){let t=typeof e==`string`?e:e.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(` `);super(t),this.name=`ToolError`,this.content=e}},bn=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
7
- 1. Task Overview
8
- The user's core request and success criteria
9
- Any clarifications or constraints they specified
10
- 2. Current State
11
- What has been completed so far
12
- Files created, modified, or analyzed (with paths if relevant)
13
- Key outputs or artifacts produced
14
- 3. Important Discoveries
15
- Technical constraints or requirements uncovered
16
- Decisions made and their rationale
17
- Errors encountered and how they were resolved
18
- What approaches were tried that didn't work (and why)
19
- 4. Next Steps
20
- Specific actions needed to complete the task
21
- Any blockers or open questions to resolve
22
- Priority order if multiple steps remain
23
- 5. Context to Preserve
24
- User preferences or style requirements
25
- Domain-specific details that aren't obvious
26
- Any promises made to the user
27
- Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
28
- Wrap your summary in <summary></summary> tags.`,xn,R,z,B,V,H,U,W,Sn,Cn,wn;function Tn(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var En=class{constructor(e,t,n){xn.add(this),this.client=e,R.set(this,!1),z.set(this,!1),B.set(this,void 0),V.set(this,void 0),H.set(this,void 0),U.set(this,void 0),W.set(this,void 0),Sn.set(this,0),f(this,B,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=[`BetaToolRunner`,...At(t.tools,t.messages)].join(`, `);f(this,V,{...n,headers:k([{"x-stainless-helper":r},n?.headers])},`f`),f(this,W,Tn(),`f`),t.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(R=new WeakMap,z=new WeakMap,B=new WeakMap,V=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,Sn=new WeakMap,xn=new WeakSet,Cn=async function(){let e=p(this,B,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(p(this,H,`f`)!==void 0)try{let e=await p(this,H,`f`);t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}let n=e.contextTokenThreshold??1e5;if(t<n)return!1;let r=e.model??p(this,B,`f`).params.model,i=e.summaryPrompt??bn,a=p(this,B,`f`).params.messages;if(a[a.length-1].role===`assistant`){let e=a[a.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>e.type!==`tool_use`);t.length===0?a.pop():e.content=t}}let o=await this.client.beta.messages.create({model:r,messages:[...a,{role:`user`,content:[{type:`text`,text:i}]}],max_tokens:p(this,B,`f`).params.max_tokens},{signal:p(this,V,`f`).signal,headers:k([p(this,V,`f`).headers,{"x-stainless-helper":`compaction`}])});if(o.content[0]?.type!==`text`)throw new h(`Expected text response for compaction`);return p(this,B,`f`).params.messages=[{role:`user`,content:o.content}],!0},Symbol.asyncIterator)](){var e;if(p(this,R,`f`))throw new h(`Cannot iterate over a consumed stream`);f(this,R,!0,`f`),f(this,z,!0,`f`),f(this,U,void 0,`f`);try{for(;;){let t;try{if(p(this,B,`f`).params.max_iterations&&p(this,Sn,`f`)>=p(this,B,`f`).params.max_iterations)break;f(this,z,!1,`f`),f(this,U,void 0,`f`),f(this,Sn,(e=p(this,Sn,`f`),e++,e),`f`),f(this,H,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=p(this,B,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},p(this,V,`f`)),f(this,H,t.finalMessage(),`f`),p(this,H,`f`).catch(()=>{}),yield t):(f(this,H,this.client.beta.messages.create({...i,stream:!1},p(this,V,`f`)),`f`),yield p(this,H,`f`)),!await p(this,xn,`m`,Cn).call(this)){if(!p(this,z,`f`)){let{role:e,content:t}=await p(this,H,`f`);p(this,B,`f`).params.messages.push({role:e,content:t})}let e=await p(this,xn,`m`,wn).call(this,p(this,B,`f`).params.messages.at(-1));if(e)p(this,B,`f`).params.messages.push(e);else if(!p(this,z,`f`))break}}finally{t&&t.abort()}}if(!p(this,H,`f`))throw new h(`ToolRunner concluded without a message from the server`);p(this,W,`f`).resolve(await p(this,H,`f`))}catch(e){throw f(this,R,!1,`f`),p(this,W,`f`).promise.catch(()=>{}),p(this,W,`f`).reject(e),f(this,W,Tn(),`f`),e}}setMessagesParams(e){typeof e==`function`?p(this,B,`f`).params=e(p(this,B,`f`).params):p(this,B,`f`).params=e,f(this,z,!0,`f`),f(this,U,void 0,`f`)}setRequestOptions(e){typeof e==`function`?f(this,V,e(p(this,V,`f`)),`f`):f(this,V,{...p(this,V,`f`),...e},`f`)}async generateToolResponse(e=p(this,V,`f`).signal){let t=await p(this,H,`f`)??this.params.messages.at(-1);return t?p(this,xn,`m`,wn).call(this,t,e):null}done(){return p(this,W,`f`).promise}async runUntilDone(){if(!p(this,R,`f`))for await(let e of this);return this.done()}get params(){return p(this,B,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};wn=async function(e,t=p(this,V,`f`).signal){return p(this,U,`f`)===void 0&&f(this,U,Dn(p(this,B,`f`).params,e,{...p(this,V,`f`),signal:t}),`f`),p(this,U,`f`)};async function Dn(e,t=e.messages.at(-1),n){if(!t||t.role!==`assistant`||!t.content||typeof t.content==`string`)return null;let r=t.content.filter(e=>e.type===`tool_use`);return r.length===0?null:{role:`user`,content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>(`name`in e?e.name:e.mcp_server_name)===t.name);if(!r||!(`run`in r))return{type:`tool_result`,tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0};try{let e=t.input;`parse`in r&&r.parse&&(e=r.parse(e));let i=await r.run(e,{toolUseBlock:t,signal:n?.signal});return{type:`tool_result`,tool_use_id:t.id,content:i}}catch(e){return{type:`tool_result`,tool_use_id:t.id,content:e instanceof yn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}var On=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new Ue;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,n){if(!t.body)throw n.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new h(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new h(`Attempted to iterate over a response with no body`);return new e(Pe(t.body),n)}},kn=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/messages/batches?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/messages/batches/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/messages/batches?beta=true`,T,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/messages/batches/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}async results(e,t={},n){let r=await this.retrieve(e);if(!r.results_url)throw new h(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);let{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:k([{"anthropic-beta":[...i??[],`message-batches-2024-09-24`].toString(),Accept:`application/binary`},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>On.fromResponse(t.response,t.controller))}},An={"claude-1.3":`November 6th, 2024`,"claude-1.3-100k":`November 6th, 2024`,"claude-instant-1.1":`November 6th, 2024`,"claude-instant-1.1-100k":`November 6th, 2024`,"claude-instant-1.2":`November 6th, 2024`,"claude-3-sonnet-20240229":`July 21st, 2025`,"claude-3-opus-20240229":`January 5th, 2026`,"claude-2.1":`July 21st, 2025`,"claude-2.0":`July 21st, 2025`,"claude-3-7-sonnet-latest":`February 19th, 2026`,"claude-3-7-sonnet-20250219":`February 19th, 2026`},jn=[`claude-mythos-preview`,`claude-opus-4-6`],Mn=class extends O{constructor(){super(...arguments),this.batches=new kn(this._client)}create(e,t){let n=Nn(e),{betas:r,...i}=n;i.model in An&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${An[i.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),jn.includes(i.model)&&i.thinking&&i.thinking.type===`enabled`&&console.warn(`Using Claude with ${i.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let a=this._client._options.timeout;if(!i.stream&&a==null){let e=Vt[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,e)}let o=jt(i.tools,i.messages);return this._client.post(`/v1/messages?beta=true`,{body:i,timeout:a??6e5,...t,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},o,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:k([{"anthropic-beta":[...e.betas??[],`structured-outputs-2025-12-15`].toString()},t?.headers])},this.create(e,t).then(t=>Wt(t,e,{logger:this._client.logger??console}))}stream(e,t){return vn.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...r}=Nn(e);return this._client.post(`/v1/messages/count_tokens?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`token-counting-2024-11-01`].toString()},t?.headers])})}toolRunner(e,t){return new En(this._client,e,t)}};function Nn(e){if(!e.output_format)return e;if(e.output_config?.format)throw new h(`Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).`);let{output_format:t,...n}=e;return{...n,output_config:{...e.output_config,format:t}}}Mn.Batches=kn,Mn.BetaToolRunner=En,Mn.ToolError=yn;var Pn=class extends O{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/sessions/${e}/events?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}send(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}/events?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/sessions/${e}/events/stream?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}},Fn=class extends O{retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get(A`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.post(A`/v1/sessions/${r}/resources/${e}?beta=true`,{body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/sessions/${e}/resources?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{session_id:r,betas:i}=t;return this._client.delete(A`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}add(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}/resources?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},In=class extends O{constructor(){super(...arguments),this.events=new Pn(this._client),this.resources=new Fn(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/sessions?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/sessions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/sessions/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/sessions?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/sessions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/sessions/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};In.Events=Pn,In.Resources=Fn;var Ln=class extends O{create(e,t={},n){let{betas:r,...i}=t??{};return this._client.post(A`/v1/skills/${e}/versions?beta=true`,ft({body:i,...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])},this._client))}retrieve(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get(A`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/skills/${e}/versions?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}delete(e,t,n){let{skill_id:r,betas:i}=t;return this._client.delete(A`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}},Rn=class extends O{constructor(){super(...arguments),this.versions=new Ln(this._client)}create(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/v1/skills?beta=true`,ft({body:r,...t,headers:k([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/skills/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/skills?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/skills/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}};Rn.Versions=Ln;var zn=class extends O{create(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/vaults/${e}/credentials?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{vault_id:r,betas:i}=t;return this._client.get(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{vault_id:r,betas:i,...a}=t;return this._client.post(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{body:a,...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(A`/v1/vaults/${e}/credentials?beta=true`,E,{query:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{vault_id:r,betas:i}=t;return this._client.delete(A`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post(A`/v1/vaults/${r}/credentials/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Bn=class extends O{constructor(){super(...arguments),this.credentials=new zn(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/vaults?beta=true`,{body:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/vaults/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(A`/v1/vaults/${e}?beta=true`,{body:i,...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/vaults?beta=true`,E,{query:r,...t,headers:k([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(A`/v1/vaults/${e}?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(A`/v1/vaults/${e}/archive?beta=true`,{...n,headers:k([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Bn.Credentials=zn;var G=class extends O{constructor(){super(...arguments),this.models=new Pt(this._client),this.messages=new Mn(this._client),this.agents=new Lt(this._client),this.environments=new Ot(this._client),this.sessions=new In(this._client),this.vaults=new Bn(this._client),this.memoryStores=new Bt(this._client),this.files=new Nt(this._client),this.skills=new Rn(this._client),this.userProfiles=new Ft(this._client)}};G.Models=Pt,G.Messages=Mn,G.Agents=Lt,G.Environments=Ot,G.Sessions=In,G.Vaults=Bn,G.MemoryStores=Bt,G.Files=Nt,G.Skills=Rn,G.UserProfiles=Ft;var Vn=class extends O{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/complete`,{body:r,timeout:this._client._options.timeout??6e5,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers]),stream:e.stream??!1})}};function Hn(e){return e?.output_config?.format}function Un(e,t,n){let r=Hn(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>e.type===`text`?Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1}):e),parsed_output:null}:Wn(e,t,n)}function Wn(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=Gn(t,e.text);return r===null&&(r=n),Object.defineProperty({...e},"parsed_output",{value:n,enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Gn(e,t){let n=Hn(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new h(`Failed to parse structured output: ${e}`)}}var K,q,J,Kn,qn,Jn,Yn,Xn,Zn,Y,X,Qn,$n,Z,er,tr,nr,rr,ir,ar,or,sr,cr,lr,ur=`__json_buf`;function dr(e){return e.type===`tool_use`||e.type===`server_tool_use`}var fr=class e{constructor(e,t){K.add(this),this.messages=[],this.receivedMessages=[],q.set(this,void 0),J.set(this,null),this.controller=new AbortController,Kn.set(this,void 0),qn.set(this,()=>{}),Jn.set(this,()=>{}),Yn.set(this,void 0),Xn.set(this,()=>{}),Zn.set(this,()=>{}),Y.set(this,{}),X.set(this,!1),Qn.set(this,!1),$n.set(this,!1),Z.set(this,!1),er.set(this,void 0),tr.set(this,void 0),nr.set(this,void 0),ar.set(this,e=>{if(f(this,Qn,!0,`f`),m(e)&&(e=new _),e instanceof _)return f(this,$n,!0,`f`),this._emit(`abort`,e);if(e instanceof h)return this._emit(`error`,e);if(e instanceof Error){let t=new h(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new h(String(e)))}),f(this,Kn,new Promise((e,t)=>{f(this,qn,e,`f`),f(this,Jn,t,`f`)}),`f`),f(this,Yn,new Promise((e,t)=>{f(this,Xn,e,`f`),f(this,Zn,t,`f`)}),`f`),p(this,Kn,`f`).catch(()=>{}),p(this,Yn,`f`).catch(()=>{}),f(this,J,e,`f`),f(this,nr,t?.logger??console,`f`)}get response(){return p(this,er,`f`)}get request_id(){return p(this,tr,`f`)}async withResponse(){f(this,Z,!0,`f`);let e=await p(this,Kn,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return f(a,J,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},p(this,ar,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{p(this,K,`m`,or).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)p(this,K,`m`,sr).call(this,e);if(i.controller.signal?.aborted)throw new _;p(this,K,`m`,cr).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(f(this,er,e,`f`),f(this,tr,e?.headers.get(`request-id`),`f`),p(this,qn,`f`).call(this,e),this._emit(`connect`))}get ended(){return p(this,X,`f`)}get errored(){return p(this,Qn,`f`)}get aborted(){return p(this,$n,`f`)}abort(){this.controller.abort()}on(e,t){return(p(this,Y,`f`)[e]||(p(this,Y,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=p(this,Y,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(p(this,Y,`f`)[e]||(p(this,Y,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{f(this,Z,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){f(this,Z,!0,`f`),await p(this,Yn,`f`)}get currentMessage(){return p(this,q,`f`)}async finalMessage(){return await this.done(),p(this,K,`m`,rr).call(this)}async finalText(){return await this.done(),p(this,K,`m`,ir).call(this)}_emit(e,...t){if(p(this,X,`f`))return;e===`end`&&(f(this,X,!0,`f`),p(this,Xn,`f`).call(this));let n=p(this,Y,`f`)[e];if(n&&(p(this,Y,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!p(this,Z,`f`)&&!n?.length&&Promise.reject(e),p(this,Jn,`f`).call(this,e),p(this,Zn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!p(this,Z,`f`)&&!n?.length&&Promise.reject(e),p(this,Jn,`f`).call(this,e),p(this,Zn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,p(this,K,`m`,rr).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{p(this,K,`m`,or).call(this),this._connected(null);let t=Qe.fromReadableStream(e,this.controller);for await(let e of t)p(this,K,`m`,sr).call(this,e);if(t.controller.signal?.aborted)throw new _;p(this,K,`m`,cr).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(q=new WeakMap,J=new WeakMap,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,Zn=new WeakMap,Y=new WeakMap,X=new WeakMap,Qn=new WeakMap,$n=new WeakMap,Z=new WeakMap,er=new WeakMap,tr=new WeakMap,nr=new WeakMap,ar=new WeakMap,K=new WeakSet,rr=function(){if(this.receivedMessages.length===0)throw new h(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},ir=function(){if(this.receivedMessages.length===0)throw new h(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new h(`stream ended without producing a content block with type=text`);return e.join(` `)},or=function(){this.ended||f(this,q,void 0,`f`)},sr=function(e){if(this.ended)return;let t=p(this,K,`m`,lr).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:dr(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(Un(t,p(this,J,`f`),{logger:p(this,nr,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:f(this,q,t,`f`);break;case`content_block_start`:case`message_delta`:break}},cr=function(){if(this.ended)throw new h(`stream has ended, this shouldn't happen`);let e=p(this,q,`f`);if(!e)throw new h(`request ended without sending any chunks`);return f(this,q,void 0,`f`),Un(e,p(this,J,`f`),{logger:p(this,nr,`f`)})},lr=function(e){let t=p(this,q,`f`);if(e.type===`message_start`){if(t)throw new h(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new h(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case`content_block_start`:return t.content.push({...e.content_block}),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&dr(n)){let r=n[ur]||``;r+=e.delta.partial_json;let i={...n};Object.defineProperty(i,ur,{value:r,enumerable:!1,writable:!0}),r&&(i.input=Yt(r)),t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Qe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},pr=class extends O{create(e,t){return this._client.post(`/v1/messages/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(A`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/v1/messages/batches`,T,{query:e,...t})}delete(e,t){return this._client.delete(A`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(A`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new h(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:k([{Accept:`application/binary`},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>On.fromResponse(t.response,t.controller))}},mr=class extends O{constructor(){super(...arguments),this.batches=new pr(this._client)}create(e,t){e.model in hr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${hr[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),gr.includes(e.model)&&e.thinking&&e.thinking.type===`enabled`&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let n=this._client._options.timeout;if(!e.stream&&n==null){let t=Vt[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let r=jt(e.tools,e.messages);return this._client.post(`/v1/messages`,{body:e,timeout:n??6e5,...t,headers:k([r,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>Wn(t,e,{logger:this._client.logger??console}))}stream(e,t){return fr.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post(`/v1/messages/count_tokens`,{body:e,...t})}},hr={"claude-1.3":`November 6th, 2024`,"claude-1.3-100k":`November 6th, 2024`,"claude-instant-1.1":`November 6th, 2024`,"claude-instant-1.1-100k":`November 6th, 2024`,"claude-instant-1.2":`November 6th, 2024`,"claude-3-sonnet-20240229":`July 21st, 2025`,"claude-3-opus-20240229":`January 5th, 2026`,"claude-2.1":`July 21st, 2025`,"claude-2.0":`July 21st, 2025`,"claude-3-7-sonnet-latest":`February 19th, 2026`,"claude-3-7-sonnet-20250219":`February 19th, 2026`,"claude-3-5-haiku-latest":`February 19th, 2026`,"claude-3-5-haiku-20241022":`February 19th, 2026`,"claude-opus-4-0":`June 15th, 2026`,"claude-opus-4-20250514":`June 15th, 2026`,"claude-sonnet-4-0":`June 15th, 2026`,"claude-sonnet-4-20250514":`June 15th, 2026`},gr=[`claude-mythos-preview`,`claude-opus-4-6`];mr.Batches=pr;var _r=class extends O{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(A`/v1/models/${e}`,{...n,headers:k([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models`,T,{query:r,...t,headers:k([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},vr=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},yr,br,xr,Sr,Cr=`\\n\\nHuman:`,wr=`\\n\\nAssistant:`,Q=class{constructor({baseURL:e=vr(`ANTHROPIC_BASE_URL`),apiKey:t=vr(`ANTHROPIC_API_KEY`)??null,authToken:n=vr(`ANTHROPIC_AUTH_TOKEN`)??null,...r}={}){yr.add(this),xr.set(this,void 0);let i={apiKey:t,authToken:n,...r,baseURL:e||`https://api.anthropic.com`};if(!i.dangerouslyAllowBrowser&&Ce())throw new h(`It looks like you're running in a browser-like environment.
29
-
30
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
31
- If you understand the risks and have appropriate mitigations in place,
32
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
33
-
34
- new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
35
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??br.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=qe(i.logLevel,`ClientOptions.logLevel`,this)??qe(vr(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??je(),f(this,xr,Ie,`f`),this._options=i,this.apiKey=typeof t==`string`?t:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted`)}async authHeaders(e){return k([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return k([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return k([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Le(e)}getUserAgent(){return`${this.constructor.name}/JS ${v}`}defaultIdempotencyKey(){return`stainless-node-retry-${te()}`}makeStatusError(e,t,n,r){return g.generate(e,t,n,r)}buildURL(e,t,n){let r=!p(this,yr,`m`,Sr).call(this)&&n||this.baseURL,i=me(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!ve(a)||!ve(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new h(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details`);return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new at(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(S(this).debug(`[${c}] sending request`,C({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new _;let ee=new AbortController,d=await this.fetchWithTimeout(o,a,s,ee).catch(ne),f=Date.now();if(d instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new _;let i=m(d)||/timed? ?out/i.test(String(d)+(`cause`in d?String(d.cause):``));if(t)return S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),this.retryRequest(r,t,n??c);throw S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),i?new ie:new re({cause:d})}let p=`[${c}${l}${[...d.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${d.ok?`succeeded`:`failed`} with status ${d.status} in ${f-u}ms`;if(!d.ok){let e=await this.shouldRetry(d);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Fe(d.body),S(this).info(`${p} - ${e}`),S(this).debug(`[${c}] response error (${e})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),this.retryRequest(r,t,n??c,d.headers)}let i=e?`error; no more retries left`:`error; not retryable`;S(this).info(`${p} - ${i}`);let a=await d.text().catch(e=>ne(e).message),o=xe(a),s=o?void 0:a;throw S(this).debug(`[${c}] response error (${i})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(d.status,o,s,d.headers)}return S(this).info(p),S(this).debug(`[${c}] response start`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),{response:d,options:r,controller:ee,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new ct(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Se(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new h(`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`);return n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&be(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=k([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Ae(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=k([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:Ne(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:p(this,xr,`f`).call(this,{body:e,headers:n})}};br=Q,xr=new WeakMap,yr=new WeakSet,Sr=function(){return this.baseURL!==`https://api.anthropic.com`},Q.Anthropic=br,Q.HUMAN_PROMPT=Cr,Q.AI_PROMPT=wr,Q.DEFAULT_TIMEOUT=6e5,Q.AnthropicError=h,Q.APIError=g,Q.APIConnectionError=re,Q.APIConnectionTimeoutError=ie,Q.APIUserAbortError=_,Q.NotFoundError=ce,Q.ConflictError=le,Q.RateLimitError=de,Q.BadRequestError=ae,Q.AuthenticationError=oe,Q.InternalServerError=fe,Q.PermissionDeniedError=se,Q.UnprocessableEntityError=ue,Q.toFile=xt;var $=class extends Q{constructor(){super(...arguments),this.completions=new Vn(this),this.messages=new mr(this),this.models=new _r(this),this.beta=new G(this)}};$.Completions=Vn,$.Messages=mr,$.Models=_r,$.Beta=G;function Tr(e,t){return e||(n(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}function Er(e,t,n){let r=Tr(t,n);if(r===`none`)return{retention:r};let i=r===`long`&&Pr(e).supportsLongCacheRetention?`1h`:void 0;return{retention:r,cacheControl:{type:`ephemeral`,...i&&{ttl:i}}}}var Dr=`2.1.75`,Or=new Map([`Read`,`Write`,`Edit`,`Bash`,`Grep`,`Glob`,`AskUserQuestion`,`EnterPlanMode`,`ExitPlanMode`,`KillShell`,`NotebookEdit`,`Skill`,`Task`,`TaskOutput`,`TodoWrite`,`WebFetch`,`WebSearch`].map(e=>[e.toLowerCase(),e])),kr=e=>Or.get(e.toLowerCase())??e,Ar=(e,t)=>{if(t&&t.length>0){let n=e.toLowerCase(),r=t.find(e=>e.name.toLowerCase()===n);if(r)return r.name}return e};function jr(e){if(!e.some(e=>e.type===`image`))return u(e.map(e=>e.text).join(`
36
- `));let t=e.map(e=>e.type===`text`?{type:`text`,text:u(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}});return t.some(e=>e.type===`text`)||t.unshift({type:`text`,text:`(see attached image)`}),t}var Mr=`fine-grained-tool-streaming-2025-05-14`,Nr=`interleaved-thinking-2025-05-14`;function Pr(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:e.compat?.sendSessionAffinityHeaders??!1,supportsCacheControlOnTools:e.compat?.supportsCacheControlOnTools??!0,supportsTemperature:e.compat?.supportsTemperature??!0,allowEmptySignature:e.compat?.allowEmptySignature??!1}}function Fr(...e){let t={};for(let n of e)n&&Object.assign(t,n);return t}function Ir(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function Lr(e,t,n){if(!t&&!(Ir(n,`authorization`)||Ir(n,`x-api-key`)||Ir(n,`cf-aig-authorization`)))throw Error(`No API key for provider: ${e}`)}var Rr=new Set([`message_start`,`message_delta`,`message_stop`,`content_block_start`,`content_block_delta`,`content_block_stop`]);function zr(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
37
- `),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Br(e,t){if(e===``)return zr(t);if(t.raw.push(e),e.startsWith(`:`))return null;let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);return i.startsWith(` `)&&(i=i.slice(1)),r===`event`?t.event=i:r===`data`&&t.data.push(i),null}function Vr(e){let t=e.indexOf(`\r`),n=e.indexOf(`
38
- `);return t===-1?n:n===-1?t:Math.min(t,n)}function Hr(e){let t=Vr(e);if(t===-1)return null;let n=t+1;return e[t]===`\r`&&e[n]===`
39
- `&&(n+=1),{line:e.slice(0,t),rest:e.slice(n)}}async function*Ur(e,t){let n=e.getReader(),r=new TextDecoder,i={event:null,data:[],raw:[]},a=``;try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{value:e,done:o}=await n.read();if(o)break;a+=r.decode(e,{stream:!0});let s=Hr(a);for(;s;){a=s.rest;let e=Br(s.line,i);e&&(yield e),s=Hr(a)}}a+=r.decode();let e=Hr(a);for(;e;){a=e.rest;let t=Br(e.line,i);t&&(yield t),e=Hr(a)}if(a.length>0){let e=Br(a,i);e&&(yield e)}let o=zr(i);o&&(yield o)}finally{n.releaseLock()}}async function*Wr(e,t){if(!e.body)throw Error(`Attempted to iterate over an Anthropic response with no body`);let n=!1,r=!1;for await(let a of Ur(e.body,t)){if(a.event===`error`)throw Error(a.data);if(Rr.has(a.event??``))try{let e=i(a.data);e.type===`message_start`?n=!0:e.type===`message_stop`&&(r=!0),yield e}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Could not parse Anthropic SSE event ${a.event}: ${t}; data=${a.data}; raw=${a.raw.join(`\\n`)}`)}}if(n&&!r)throw Error(`Anthropic stream ended before message_stop`)}var Gr=(n,i,a)=>{let o=new e;return(async()=>{let e={role:`assistant`,content:[],api:n.api,provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s,c;if(a?.client)s=a.client,c=!1;else{let e=a?.apiKey;Lr(n.provider,e,a?.headers);let t;if(n.provider===`github-copilot`){let e=ee(i.messages);t=d({messages:i.messages,hasImages:e})}let r=Tr(a?.cacheRetention,a?.env)===`none`?void 0:a?.sessionId,o=Yr(n,e,a?.interleavedThinking??!0,$r(n,i),a?.headers,t,r);s=o.client,c=o.isOAuthToken}let u=Xr(n,i,c,a),f=await a?.onPayload?.(u,n);f!==void 0&&(u=f);let p={...a?.signal?{signal:a.signal}:{},...a?.timeoutMs===void 0?{}:{timeout:a.timeoutMs},maxRetries:a?.maxRetries??0},te=await s.messages.create({...u,stream:!0},p).asResponse();await a?.onResponse?.({status:te.status,headers:l(te.headers)},n),o.push({type:`start`,partial:e});let m=e.content;for await(let s of Wr(te,a?.signal))if(s.type===`message_start`)e.responseId=s.message.id,e.usage.input=s.message.usage.input_tokens||0,e.usage.output=s.message.usage.output_tokens||0,e.usage.cacheRead=s.message.usage.cache_read_input_tokens||0,e.usage.cacheWrite=s.message.usage.cache_creation_input_tokens||0,e.usage.cacheWrite1h=s.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,t(n,e.usage);else if(s.type===`content_block_start`){if(s.content_block.type===`text`){let t={type:`text`,text:``,index:s.index};e.content.push(t),o.push({type:`text_start`,contentIndex:e.content.length-1,partial:e})}else if(s.content_block.type===`thinking`){let t={type:`thinking`,thinking:``,thinkingSignature:``,index:s.index};e.content.push(t),o.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(s.content_block.type===`redacted_thinking`){let t={type:`thinking`,thinking:`[Reasoning redacted]`,thinkingSignature:s.content_block.data,redacted:!0,index:s.index};e.content.push(t),o.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(s.content_block.type===`tool_use`){let t={type:`toolCall`,id:s.content_block.id,name:c?Ar(s.content_block.name,i.tools):s.content_block.name,arguments:s.content_block.input??{},partialJson:``,index:s.index};e.content.push(t),o.push({type:`toolcall_start`,contentIndex:e.content.length-1,partial:e})}}else if(s.type===`content_block_delta`){if(s.delta.type===`text_delta`){let t=m.findIndex(e=>e.index===s.index),n=m[t];n&&n.type===`text`&&(n.text+=s.delta.text,o.push({type:`text_delta`,contentIndex:t,delta:s.delta.text,partial:e}))}else if(s.delta.type===`thinking_delta`){let t=m.findIndex(e=>e.index===s.index),n=m[t];n&&n.type===`thinking`&&(n.thinking+=s.delta.thinking,o.push({type:`thinking_delta`,contentIndex:t,delta:s.delta.thinking,partial:e}))}else if(s.delta.type===`input_json_delta`){let t=m.findIndex(e=>e.index===s.index),n=m[t];n&&n.type===`toolCall`&&(n.partialJson+=s.delta.partial_json,n.arguments=r(n.partialJson),o.push({type:`toolcall_delta`,contentIndex:t,delta:s.delta.partial_json,partial:e}))}else if(s.delta.type===`signature_delta`){let e=m[m.findIndex(e=>e.index===s.index)];e&&e.type===`thinking`&&(e.thinkingSignature=e.thinkingSignature||``,e.thinkingSignature+=s.delta.signature)}}else if(s.type===`content_block_stop`){let t=m.findIndex(e=>e.index===s.index),n=m[t];n&&(delete n.index,n.type===`text`?o.push({type:`text_end`,contentIndex:t,content:n.text,partial:e}):n.type===`thinking`?o.push({type:`thinking_end`,contentIndex:t,content:n.thinking,partial:e}):n.type===`toolCall`&&(n.arguments=r(n.partialJson),delete n.partialJson,o.push({type:`toolcall_end`,contentIndex:t,toolCall:n,partial:e})))}else if(s.type===`message_delta`){if(s.delta.stop_reason){let t=ti(s.delta.stop_reason,s.delta.stop_details);e.stopReason=t.stopReason,t.errorMessage&&(e.errorMessage=t.errorMessage)}s.usage.input_tokens!=null&&(e.usage.input=s.usage.input_tokens),s.usage.output_tokens!=null&&(e.usage.output=s.usage.output_tokens),s.usage.cache_read_input_tokens!=null&&(e.usage.cacheRead=s.usage.cache_read_input_tokens),s.usage.cache_creation_input_tokens!=null&&(e.usage.cacheWrite=s.usage.cache_creation_input_tokens);let r=s.usage.output_tokens_details?.thinking_tokens;r!=null&&(e.usage.reasoning=r),e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,t(n,e.usage)}if(a?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(e.errorMessage||`An unknown error occurred`);o.push({type:`done`,reason:e.stopReason,message:e}),o.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson;e.stopReason=a?.signal?.aborted?`aborted`:`error`,e.errorMessage=t instanceof Error?t.message:JSON.stringify(t),o.push({type:`error`,reason:e.stopReason,error:e}),o.end()}})(),o};function Kr(e,t){let n=t?e.thinkingLevelMap?.[t]:void 0;if(typeof n==`string`)return n;switch(t){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`high`:return`high`;default:return`high`}}var qr=(e,t,n)=>{Lr(e.provider,n?.apiKey,n?.headers);let r=s(e,t,n,n?.apiKey);if(!n?.reasoning)return Gr(e,t,{...r,thinkingEnabled:!1});if(e.compat?.forceAdaptiveThinking===!0){let i=Kr(e,n.reasoning);return Gr(e,t,{...r,thinkingEnabled:!0,effort:i})}let i=o(r.maxTokens,e.maxTokens,n.reasoning,n.thinkingBudgets),c=a(e,t,i.maxTokens);return Gr(e,t,{...r,maxTokens:c,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(i.thinkingBudget,Math.max(0,c-1024))})};function Jr(e){return e.includes(`sk-ant-oat`)}function Yr(e,t,n,r,i,a,o){let s=n&&e.compat?.forceAdaptiveThinking!==!0,c=[];if(r&&c.push(Mr),s&&c.push(Nr),e.provider===`github-copilot`)return{client:new $({apiKey:null,authToken:t??null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...c.length>0?{"anthropic-beta":c.join(`,`)}:{}},e.headers,a,i)}),isOAuthToken:!1};if(t&&Jr(t))return{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"anthropic-beta":[`claude-code-20250219`,`oauth-2025-04-20`,...c].join(`,`),"user-agent":`claude-cli/${Dr}`,"x-app":`cli`},e.headers,i)}),isOAuthToken:!0};let l=o&&Pr(e).sendSessionAffinityHeaders?{"x-session-affinity":o}:{},u=Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...c.length>0?{"anthropic-beta":c.join(`,`)}:{}},l,e.headers,i);return{client:new $({apiKey:t??null,authToken:null,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:u}),isOAuthToken:!1}}function Xr(e,t,n,r){let{cacheControl:i}=Er(e,r?.cacheRetention,r?.env),a=Pr(e),o={model:e.id,messages:Qr(t.messages,e,n,i,a.allowEmptySignature),max_tokens:r?.maxTokens??e.maxTokens,stream:!0};if(n?(o.system=[{type:`text`,text:`You are Claude Code, Anthropic's official CLI for Claude.`,...i?{cache_control:i}:{}}],t.systemPrompt&&o.system.push({type:`text`,text:u(t.systemPrompt),...i?{cache_control:i}:{}})):t.systemPrompt&&(o.system=[{type:`text`,text:u(t.systemPrompt),...i?{cache_control:i}:{}}]),r?.temperature!==void 0&&!r?.thinkingEnabled&&a.supportsTemperature&&(o.temperature=r.temperature),t.tools&&t.tools.length>0&&(o.tools=ei(t.tools,n,a.supportsEagerToolInputStreaming,a.supportsCacheControlOnTools?i:void 0)),e.reasoning)if(r?.thinkingEnabled){let t=r.thinkingDisplay??`summarized`;e.compat?.forceAdaptiveThinking===!0?(o.thinking={type:`adaptive`,display:t},r.effort&&(o.output_config=(r.effort,{effort:r.effort}))):o.thinking={type:`enabled`,budget_tokens:r.thinkingBudgetTokens||1024,display:t}}else r?.thinkingEnabled===!1&&e.thinkingLevelMap?.off!==null&&(o.thinking={type:`disabled`});if(r?.metadata){let e=r.metadata.user_id;typeof e==`string`&&(o.metadata={user_id:e})}return r?.toolChoice&&(typeof r.toolChoice==`string`?o.tool_choice={type:r.toolChoice}:o.tool_choice=r.toolChoice),o}function Zr(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function Qr(e,t,n,r,i=!1){let a=[],o=c(e,t,Zr);for(let e=0;e<o.length;e++){let t=o[e];if(t.role===`user`)if(typeof t.content==`string`)t.content.trim().length>0&&a.push({role:`user`,content:u(t.content)});else{let e=t.content.map(e=>e.type===`text`?{type:`text`,text:u(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}}).filter(e=>e.type!==`text`||e.text.trim().length>0);if(e.length===0)continue;a.push({role:`user`,content:e})}else if(t.role===`assistant`){let e=[];for(let r of t.content)if(r.type===`text`){if(r.text.trim().length===0)continue;e.push({type:`text`,text:u(r.text)})}else if(r.type===`thinking`){if(r.redacted){e.push({type:`redacted_thinking`,data:r.thinkingSignature});continue}if(r.thinking.trim().length===0)continue;!r.thinkingSignature||r.thinkingSignature.trim().length===0?e.push(i?{type:`thinking`,thinking:u(r.thinking),signature:``}:{type:`text`,text:u(r.thinking)}):e.push({type:`thinking`,thinking:u(r.thinking),signature:r.thinkingSignature})}else r.type===`toolCall`&&e.push({type:`tool_use`,id:r.id,name:n?kr(r.name):r.name,input:r.arguments??{}});if(e.length===0)continue;a.push({role:`assistant`,content:e})}else if(t.role===`toolResult`){let n=[];n.push({type:`tool_result`,tool_use_id:t.toolCallId,content:jr(t.content),is_error:t.isError});let r=e+1;for(;r<o.length&&o[r].role===`toolResult`;){let e=o[r];n.push({type:`tool_result`,tool_use_id:e.toolCallId,content:jr(e.content),is_error:e.isError}),r++}e=r-1,a.push({role:`user`,content:n})}}if(r&&a.length>0){let e=a[a.length-1];if(e.role===`user`)if(Array.isArray(e.content)){let t=e.content[e.content.length-1];t&&(t.type===`text`||t.type===`image`||t.type===`tool_result`)&&(t.cache_control=r)}else typeof e.content==`string`&&(e.content=[{type:`text`,text:e.content,cache_control:r}])}return a}function $r(e,t){return!!t.tools?.length&&!Pr(e).supportsEagerToolInputStreaming}function ei(e,t,n,r){return e?e.map((i,a)=>{let o=i.parameters;return{name:t?kr(i.name):i.name,description:i.description,...n?{eager_input_streaming:!0}:{},input_schema:{type:`object`,properties:o.properties??{},required:o.required??[]},...r&&a===e.length-1?{cache_control:r}:{}}}):[]}function ti(e,t){switch(e){case`end_turn`:return{stopReason:`stop`};case`max_tokens`:return{stopReason:`length`};case`tool_use`:return{stopReason:`toolUse`};case`refusal`:return{stopReason:`error`,errorMessage:t?.explanation||`The model refused to complete the request`};case`pause_turn`:return{stopReason:`stop`};case`stop_sequence`:return{stopReason:`stop`};case`sensitive`:return{stopReason:`error`};default:throw Error(`Unhandled stop reason: ${e}`)}}export{Gr as stream,qr as streamSimple};