@cline/core 0.0.95 → 0.2.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 (167) hide show
  1. package/dist/ClineCore.d.ts +6 -1
  2. package/dist/account/rpc.d.ts +3 -1
  3. package/dist/cline-core/runtime-services.d.ts +4 -2
  4. package/dist/cloud/controller.d.ts +5 -2
  5. package/dist/cloud/hub-client.d.ts +51 -0
  6. package/dist/cloud/hub-protocol.d.ts +18 -0
  7. package/dist/cloud/index.d.ts +2 -0
  8. package/dist/cloud/index.js +16 -16
  9. package/dist/cloud/types.d.ts +4 -1
  10. package/dist/extensions/context/compaction-shared.d.ts +1 -0
  11. package/dist/extensions/context/compaction.d.ts +7 -0
  12. package/dist/extensions/context/summarize-conversation.d.ts +7 -0
  13. package/dist/extensions/context/summary-generation.d.ts +14 -0
  14. package/dist/extensions/mcp/apps.d.ts +16 -0
  15. package/dist/extensions/mcp/client.d.ts +1 -0
  16. package/dist/extensions/mcp/index.d.ts +5 -1
  17. package/dist/extensions/mcp/manager.d.ts +2 -1
  18. package/dist/extensions/mcp/session-apps.d.ts +28 -0
  19. package/dist/extensions/mcp/types.d.ts +22 -0
  20. package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
  21. package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
  22. package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
  23. package/dist/hub/client/index.d.ts +6 -0
  24. package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
  25. package/dist/hub/client/plugin-commands.d.ts +4 -0
  26. package/dist/hub/client/session-client.d.ts +2 -0
  27. package/dist/hub/daemon/entry.js +241 -228
  28. package/dist/hub/index.d.ts +1 -0
  29. package/dist/hub/index.js +231 -218
  30. package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
  31. package/dist/hub/server/cloud-session-service.d.ts +50 -0
  32. package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
  33. package/dist/hub/server/handlers/context.d.ts +13 -2
  34. package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
  35. package/dist/hub/server/hub-server-options.d.ts +3 -0
  36. package/dist/hub/server/hub-server-transport.d.ts +2 -0
  37. package/dist/index.d.ts +8 -4
  38. package/dist/index.js +278 -258
  39. package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
  40. package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
  41. package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-b1d8eb67.js +1 -0
  42. package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-33qvrctr.js +1 -0
  43. package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-paabhz8w.js +1 -0
  44. package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-yhsfqcy1.js +1 -0
  45. package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +21 -0
  46. package/dist/plugin-runtime/node_modules/@cline/core/dist/community-gqgs7446.js +1 -0
  47. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-822304b0.js +1 -0
  48. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-hky2m2yx.js +1 -0
  49. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-sqf1kd37.js +1 -0
  50. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-tx1kp6xn.js +1 -0
  51. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-6cpgjxme.js +2 -0
  52. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-fxchqbze.js +2 -0
  53. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-m3bzwmzc.js +1 -0
  54. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-pr9sb5fr.js +1 -0
  55. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-nckraycx.js +1 -0
  56. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-w91yq3tm.js +1 -0
  57. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-xdyxc2tf.js +1 -0
  58. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-yxsvs11a.js +1 -0
  59. package/dist/plugin-runtime/node_modules/@cline/core/dist/google-pgdk2dm9.js +1 -0
  60. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1160 -0
  61. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1147 -0
  62. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-02jpyn9y.js +85 -0
  63. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0cb4390m.js +137 -0
  64. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0f8xrhgt.js +209 -0
  65. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1f8vb421.js +2 -0
  66. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-28c7m0fv.js +16 -0
  67. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-2em3jg4q.js +1 -0
  68. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4n1zpzbe.js +2 -0
  69. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-54eea0ex.js +2 -0
  70. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5j92dtg5.js +16 -0
  71. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6akf3a5d.js +2 -0
  72. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6k6ep10s.js +136 -0
  73. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-71ym4q6s.js +2 -0
  74. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-91p1ghfk.js +14 -0
  75. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9qkpjy7x.js +2 -0
  76. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9swk4nej.js +3 -0
  77. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-aa2s5myc.js +1 -0
  78. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ae0ajw38.js +13 -0
  79. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bxvyzjhc.js +1 -0
  80. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bzy863k0.js +6 -0
  81. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d96n0s70.js +20 -0
  82. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-dsd6vt8c.js +1 -0
  83. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-e2q4azd9.js +119 -0
  84. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-egd18jj2.js +4 -0
  85. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-eh83hr16.js +2 -0
  86. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ev9r2dy3.js +1204 -0
  87. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f2mvvryf.js +190 -0
  88. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7gn5v3f.js +2 -0
  89. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7s1a560.js +12 -0
  90. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkhq3jtz.js +21 -0
  91. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-j8r18nfg.js +15 -0
  92. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-jhny555h.js +6 -0
  93. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m1gpa2eg.js +146 -0
  94. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m2ad6tgj.js +1 -0
  95. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m7mks2jq.js +4 -0
  96. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-mcnngj50.js +62 -0
  97. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-n2srkkh0.js +39 -0
  98. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nbs1tsny.js +142 -0
  99. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nqjnz7m4.js +9 -0
  100. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rmhzyxr8.js +3 -0
  101. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rtzf3vvk.js +6 -0
  102. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sw74pcm3.js +2 -0
  103. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t3eanyjj.js +3 -0
  104. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-tseksj1v.js +1 -0
  105. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v0ctpcdr.js +12 -0
  106. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-dx8bd4wq.js +1 -0
  107. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v695918t.js +14 -0
  108. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v96yy1pw.js +1 -0
  109. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vfm7r9wk.js +65 -0
  110. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xecthgrg.js +9 -0
  111. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xn1xhp06.js +9 -0
  112. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yfdscfdx.js +1 -0
  113. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yrnwqsdt.js +2 -0
  114. package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
  115. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-3mgy2y9y.js +473 -0
  116. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-w1xrs0vd.js +1 -0
  117. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-9tppg77c.js +1 -0
  118. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-y658kpzy.js +1 -0
  119. package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-cmhqd91b.js +1 -0
  120. package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-qkjjf8mm.js +2 -0
  121. package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-8z6y9d1h.js +1 -0
  122. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-cfmja1ez.js +1 -0
  123. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-1t7n5sxj.js +1 -0
  124. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-k6yqgnyd.js +1 -0
  125. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-6rdyebbq.js +1 -0
  126. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
  127. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
  128. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-1h068py9.js +1 -0
  129. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-7jchft51.js +1 -0
  130. package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-qfxfsrn4.js +1 -0
  131. package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
  132. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
  133. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
  134. package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
  135. package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
  136. package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
  137. package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
  138. package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
  139. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
  140. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
  141. package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
  142. package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
  143. package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
  144. package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
  145. package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
  146. package/dist/plugin-runtime/package.json +1 -0
  147. package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
  148. package/dist/remote/remote-environments.d.ts +1 -0
  149. package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
  150. package/dist/runtime/host/local-runtime-host.d.ts +10 -0
  151. package/dist/runtime/host/runtime-host.d.ts +6 -0
  152. package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
  153. package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
  154. package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
  155. package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
  156. package/dist/services/llms/cline-recommended-models.d.ts +2 -0
  157. package/dist/services/local-runtime-bootstrap.d.ts +1 -0
  158. package/dist/services/plugin-command-api.d.ts +47 -0
  159. package/dist/services/plugin-commands.d.ts +25 -27
  160. package/dist/services/skills-cli.d.ts +2 -0
  161. package/dist/services/telemetry/core-events.d.ts +26 -0
  162. package/dist/services/telemetry/index.js +1 -1
  163. package/dist/services/telemetry/run-health.d.ts +40 -0
  164. package/dist/services/telemetry/stall-signals.d.ts +12 -0
  165. package/dist/types/config.d.ts +1 -0
  166. package/dist/types/session.d.ts +7 -0
  167. package/package.json +6 -5
@@ -0,0 +1,9 @@
1
+ import{e,n,r,L,m,o,t,p,d,s,a}from"./index-mcnngj50.js";var Ne="vercel.ai.error",At=Symbol.for(Ne),ce,pe,S=class i extends(pe=Error,ce=At,pe){constructor({name:u,message:l,cause:c}){super(l);this[ce]=!0,this.name=u,this.cause=c}static isInstance(u){return i.hasMarker(u,Ne)}static hasMarker(u,l){let c=Symbol.for(l);return u!=null&&typeof u==="object"&&c in u&&typeof u[c]==="boolean"&&u[c]===!0}},Ue="AI_APICallError",je=`vercel.ai.error.${Ue}`,_t=Symbol.for(je),de,fe,A=class extends(fe=S,de=_t,fe){constructor({message:i,url:u,requestBodyValues:l,statusCode:c,responseHeaders:f,responseBody:h,cause:g,isRetryable:y=c!=null&&(c===408||c===409||c===429||c>=500),data:v}){super({name:Ue,message:i,cause:g});this[de]=!0,this.url=u,this.requestBodyValues=l,this.statusCode=c,this.responseHeaders=f,this.responseBody=h,this.isRetryable=y,this.data=v}static isInstance(i){return S.hasMarker(i,je)}},We="AI_EmptyResponseBodyError",Je=`vercel.ai.error.${We}`,qt=Symbol.for(Je),me,he,Ur=class extends(he=S,me=qt,he){constructor({message:i="Empty response body"}={}){super({name:We,message:i});this[me]=!0}static isInstance(i){return S.hasMarker(i,Je)}};function Be(i){if(i==null)return"unknown error";if(typeof i==="string")return i;if(i instanceof Error)return i.message;return JSON.stringify(i)}var Le="AI_InvalidArgumentError",ze=`vercel.ai.error.${Le}`,Ft=Symbol.for(ze),ge,ye,re=class extends(ye=S,ge=Ft,ye){constructor({message:i,cause:u,argument:l}){super({name:Le,message:i,cause:u});this[ge]=!0,this.argument=l}static isInstance(i){return S.hasMarker(i,ze)}},Ke="AI_InvalidPromptError",Ve=`vercel.ai.error.${Ke}`,Nt=Symbol.for(Ve),ve,be,jr=class extends(be=S,ve=Nt,be){constructor({prompt:i,message:u,cause:l}){super({name:Ke,message:`Invalid prompt: ${u}`,cause:l});this[ve]=!0,this.prompt=i}static isInstance(i){return S.hasMarker(i,Ve)}},He="AI_InvalidResponseDataError",Ge=`vercel.ai.error.${He}`,Ut=Symbol.for(Ge),Ie,we,Wr=class extends(we=S,Ie=Ut,we){constructor({data:i,message:u=`Invalid response data: ${JSON.stringify(i)}.`}){super({name:He,message:u});this[Ie]=!0,this.data=i}static isInstance(i){return S.hasMarker(i,Ge)}},Qe="AI_JSONParseError",Ye=`vercel.ai.error.${Qe}`,jt=Symbol.for(Ye),Se,xe,Jr=class extends(xe=S,Se=jt,xe){constructor({text:i,cause:u}){super({name:Qe,message:`JSON parsing failed: Text: ${i}.
2
+ Error message: ${Be(u)}`,cause:u});this[Se]=!0,this.text=i}static isInstance(i){return S.hasMarker(i,Ye)}},Ze="AI_LoadAPIKeyError",Xe=`vercel.ai.error.${Ze}`,Wt=Symbol.for(Xe),Te,ke,ne=class extends(ke=S,Te=Wt,ke){constructor({message:i}){super({name:Ze,message:i});this[Te]=!0}static isInstance(i){return S.hasMarker(i,Xe)}},et="AI_LoadSettingError",tt=`vercel.ai.error.${et}`,Jt=Symbol.for(tt),Ee,Ce,Br=class extends(Ce=S,Ee=Jt,Ce){constructor({message:i}){super({name:et,message:i});this[Ee]=!0}static isInstance(i){return S.hasMarker(i,tt)}},rt="AI_NoContentGeneratedError",nt=`vercel.ai.error.${rt}`,Bt=Symbol.for(nt),Pe,$e,Lr=class extends($e=S,Pe=Bt,$e){constructor({message:i="No content generated."}={}){super({name:rt,message:i});this[Pe]=!0}static isInstance(i){return S.hasMarker(i,nt)}},st="AI_NoSuchModelError",ot=`vercel.ai.error.${st}`,Lt=Symbol.for(ot),Oe,Re,se=class extends(Re=S,Oe=Lt,Re){constructor({errorName:i=st,modelId:u,modelType:l,message:c=`No such ${l}: ${u}`}){super({name:i,message:c});this[Oe]=!0,this.modelId=u,this.modelType=l}static isInstance(i){return S.hasMarker(i,ot)}},it="AI_TooManyEmbeddingValuesForCallError",at=`vercel.ai.error.${it}`,zt=Symbol.for(at),Me,De,zr=class extends(De=S,Me=zt,De){constructor(i){super({name:it,message:`Too many values for a single embedding call. The ${i.provider} model "${i.modelId}" can only embed up to ${i.maxEmbeddingsPerCall} values per call, but ${i.values.length} values were provided.`});this[Me]=!0,this.provider=i.provider,this.modelId=i.modelId,this.maxEmbeddingsPerCall=i.maxEmbeddingsPerCall,this.values=i.values}static isInstance(i){return S.hasMarker(i,at)}},ut="AI_TypeValidationError",lt=`vercel.ai.error.${ut}`,Kt=Symbol.for(lt),Ae,_e,Kr=class i extends(_e=S,Ae=Kt,_e){constructor({value:u,cause:l,context:c}){let f="Type validation failed";if(c==null?void 0:c.field)f+=` for ${c.field}`;if((c==null?void 0:c.entityName)||(c==null?void 0:c.entityId)){f+=" (";let h=[];if(c.entityName)h.push(c.entityName);if(c.entityId)h.push(`id: "${c.entityId}"`);f+=h.join(", "),f+=")"}super({name:ut,message:`${f}: Value: ${JSON.stringify(u)}.
3
+ Error message: ${Be(l)}`,cause:l});this[Ae]=!0,this.value=u,this.context=c}static isInstance(u){return S.hasMarker(u,lt)}static wrap({value:u,cause:l,context:c}){var f,h,g;if(i.isInstance(l)&&l.value===u&&((f=l.context)==null?void 0:f.field)===(c==null?void 0:c.field)&&((h=l.context)==null?void 0:h.entityName)===(c==null?void 0:c.entityName)&&((g=l.context)==null?void 0:g.entityId)===(c==null?void 0:c.entityId))return l;return new i({value:u,cause:l,context:c})}},ct="AI_UnsupportedFunctionalityError",pt=`vercel.ai.error.${ct}`,Vt=Symbol.for(pt),qe,Fe,Vr=class extends(Fe=S,qe=Vt,Fe){constructor({functionality:i,message:u=`'${i}' functionality not supported.`}){super({name:ct,message:u});this[qe]=!0,this.functionality=i}static isInstance(i){return S.hasMarker(i,pt)}};function dt(i,u){let l=[],c=[],f,h=u?.logger;for(let g of i)switch(g.role){case"system":if(f)f+=`
4
+
5
+ `+g.content;else f=g.content;break;case"user":for(let y of g.content){let v=Ht(y,c,h);if(v)l.push(v)}break;case"assistant":{let y=Qt(g.content,c,h);l.push(...y);break}case"tool":{let y=Yt(g.content,c,h,u?.includeToolApprovalResponsesAsContext??!1);l.push(...y);break}}if(u?.mode?.type==="object-json"){let g=Zt(u.mode.schema);l.push({type:"text",text:g})}return{parts:l,systemPrompt:f,warnings:c}}function Ht(i,u,l){switch(i.type){case"text":return{type:"text",text:i.text};case"file":return Gt(i,u,l);default:{let f=`Unknown user message part type: ${i.type}`;if(u.push(f),l)l.warn(f);return null}}}function Gt(i,u,l){let{data:c,mediaType:f,filename:h}=i;if(typeof c==="string"){if(c.startsWith("data:"))return{type:"file",mime:f,filename:h,url:c};if(c.startsWith("http://")||c.startsWith("https://")){let y=`Remote URLs are not supported for file input: ${c.substring(0,50)}...`;if(u.push(y),l)l.warn(y);return null}return{type:"file",mime:f,filename:h,url:`data:${f};base64,${Xt(c)}`}}if(c instanceof Uint8Array){let y=er(c);return{type:"file",mime:f,filename:h,url:`data:${f};base64,${y}`}}if(c instanceof URL){let y=c.toString();if(y.startsWith("data:"))return{type:"file",mime:f,filename:h,url:y};let v=`Remote URLs are not supported for file input: ${y.substring(0,50)}...`;if(u.push(v),l)l.warn(v);return null}let g=`Unsupported file data type: ${typeof c}`;if(u.push(g),l)l.warn(g);return null}function Qt(i,u,l){let c=[];for(let f of i)switch(f.type){case"text":c.push({type:"text",text:`[Assistant]: ${f.text}`,synthetic:!0});break;case"reasoning":c.push({type:"text",text:`[Reasoning]: ${f.text}`,synthetic:!0});break;case"tool-call":c.push({type:"text",text:`[Tool Call: ${f.toolName}]: ${JSON.stringify(f.input)}`,synthetic:!0});break;case"tool-result":{let h=It(f);c.push({type:"text",text:`[Tool Result: ${f.toolName}]: ${h}`,synthetic:!0});break}case"file":{if(u.push("File parts in assistant messages are not yet supported"),l)l.warn("File parts in assistant messages are not yet supported");break}}return c}function Yt(i,u,l,c=!1){let f=[],h="Tool results in prompts are included as context only. OpenCode executes tools server-side and cannot use client-provided results.";if(i.some((y)=>y.type==="tool-result")&&!u.includes("Tool results in prompts are included as context only. OpenCode executes tools server-side and cannot use client-provided results.")){if(u.push("Tool results in prompts are included as context only. OpenCode executes tools server-side and cannot use client-provided results."),l)l.warn("Tool results in prompts are included as context only. OpenCode executes tools server-side and cannot use client-provided results.")}for(let y of i){if(y.type==="tool-result"){let v=It(y);f.push({type:"text",text:`[Tool Result: ${y.toolName}]: ${v}`,synthetic:!0});continue}if(y.type==="tool-approval-response"&&c){let v=y.reason?` (${y.reason})`:"";f.push({type:"text",text:`[Tool Approval: ${y.approvalId}]: ${y.approved?"approved":"denied"}${v}`,synthetic:!0});continue}}return f}function It(i){let u=i.output;switch(u.type){case"text":return u.value;case"json":return JSON.stringify(u.value,null,2);case"error-text":return`Error: ${u.value}`;case"error-json":return`Error: ${JSON.stringify(u.value)}`;case"content":return u.value.map((l)=>{if(l.type==="text")return l.text;if(l.type==="file-data")return`[File: ${l.mediaType}]`;if(l.type==="file-url")return`[File URL: ${l.url}]`;if(l.type==="file-id")return"[File ID]";if(l.type==="image-data")return`[Image: ${l.mediaType}]`;if(l.type==="image-url")return`[Image URL: ${l.url}]`;if(l.type==="image-file-id")return"[Image File ID]";return"[Content]"}).join(`
6
+ `);case"execution-denied":return u.reason?`Execution denied: ${u.reason}`:"Execution denied";default:return JSON.stringify(u)}}function Zt(i){let u="IMPORTANT: You must respond with valid JSON only. Do not include any text before or after the JSON. Do not include markdown code blocks.";if(i)u+=`
7
+
8
+ The JSON must conform to this schema:
9
+ `+JSON.stringify(i,null,2);return u}function Xt(i){return i.replace(/\s/g,"")}function er(i){if(typeof Buffer<"u")return Buffer.from(i).toString("base64");let u="";for(let l=0;l<i.length;l++)u+=String.fromCharCode(i[l]);return btoa(u)}function wt(i){if(!i||typeof i!=="object")return!1;let u=i;if(typeof u.name==="string"&&u.name==="ProviderAuthError")return!0;if(typeof u.statusCode==="number"&&(u.statusCode===401||u.statusCode===403))return!0;if(typeof u.message==="string"){let l=u.message.toLowerCase();return l.includes("unauthorized")||l.includes("authentication")||l.includes("api key")||l.includes("invalid key")||l.includes("auth failed")}return!1}function St(i){if(!i||typeof i!=="object")return!1;let u=i;if(typeof u.name==="string"){if(u.name.toLowerCase().includes("timeout"))return!0}if(typeof u.code==="string"){let l=u.code.toUpperCase();if(l==="ETIMEDOUT"||l==="ESOCKETTIMEDOUT")return!0}if(typeof u.message==="string"){let l=u.message.toLowerCase();return l.includes("timeout")||l.includes("timed out")}return!1}function H(i){if(!i||typeof i!=="object")return!1;let u=i;if(typeof u.name==="string"&&u.name==="AbortError")return!0;if(typeof u.code==="string"&&u.code.toUpperCase()==="ABORT_ERR")return!0;if(typeof u.name==="string"&&u.name==="MessageAbortedError")return!0;return!1}function tr(i){let u=E(i),l=sr(i);return new ne({message:l?`OpenCode authentication error (${l}): ${u}`:`OpenCode authentication error: ${u}`})}function xt(i,u){let l=E(i),c=Y(i),f=u?.isRetryable??or(i);return new A({message:l,url:"opencode://session",requestBodyValues:{},statusCode:c,isRetryable:f,data:{errorType:u?.errorType??nr(i),sessionId:u?.sessionId,messageId:u?.messageId,modelId:u?.modelId}})}function rr(i,u){let l=u?.modelId?` for model "${u.modelId}"`:"",c=E(i);return new A({message:`OpenCode returned an empty JSON response${l}. This usually means the OpenCode server rejected the request before returning response data, often because the configured provider/model is unavailable or invalid. Check the model ID and OpenCode provider configuration. Original error: ${c}`,url:"opencode://session",requestBodyValues:{},statusCode:u?.statusCode??Y(i),isRetryable:!1,data:{errorType:"EmptyJSONResponse",sessionId:u?.sessionId,messageId:u?.messageId,modelId:u?.modelId}})}function ft(i,u){let l=u?.modelId?` for model "${u.modelId}"`:"",c=i?` Original error: ${E(i)}`:"";return new A({message:`OpenCode returned no response data${l}. This usually means the configured provider/model ID is invalid or unavailable. Run \`opencode models\` to list available model IDs and check the OpenCode provider configuration.`+c,url:"opencode://session",requestBodyValues:{},statusCode:u?.statusCode??Y(i),isRetryable:!1,data:{errorType:"EmptyResponseData",sessionId:u?.sessionId,messageId:u?.messageId,modelId:u?.modelId}})}function Tt(i,u){let l=u?` during ${u}`:"";return new A({message:`OpenCode request timed out after ${i}ms${l}`,url:"opencode://session",requestBodyValues:{},isRetryable:!0})}function E(i){if(!i)return"Unknown error";if(typeof i==="string")return i;if(i instanceof Error)return i.message;if(typeof i==="object"){let u=i;if(typeof u.message==="string")return u.message;if(typeof u.error==="string")return u.error;if(typeof u.data==="object"&&u.data!==null){let l=u.data;if(typeof l.message==="string")return l.message}}return"Unknown error"}function Y(i){if(!i||typeof i!=="object")return;let u=i;if(typeof u.statusCode==="number")return u.statusCode;if(typeof u.status==="number")return u.status;return}function nr(i){if(!i||typeof i!=="object")return;let u=i;if(typeof u.name==="string")return u.name;if(typeof u.type==="string")return u.type;return}function sr(i){if(!i||typeof i!=="object")return;let u=i;if(typeof u.data==="object"&&u.data!==null){let l=u.data;if(typeof l.providerID==="string")return l.providerID}return}function or(i){if(H(i))return!1;if(St(i))return!0;if(wt(i))return!1;let u=Y(i);if(u!==void 0){if(u>=500&&u<600)return!0;if(u===429)return!0;if(u>=400&&u<500)return!1}return!1}function oe(i,u){if(A.isInstance(i)||ne.isInstance(i))return i;if(wt(i))return tr(i);if(St(i)){let l=u?.timeoutMs??ur(i)??ir;return Tt(l,"request")}if(ar(i))return rr(i,u);return xt(i,u)}var ir=5000;function ar(i){if(!i||typeof i!=="object")return!1;let u=i;return(i instanceof SyntaxError?"SyntaxError":typeof u.name==="string"?u.name:void 0)==="SyntaxError"&&typeof u.message==="string"&&u.message==="Unexpected end of JSON input"}function ur(i){if(!i||typeof i!=="object")return;let u=i,l=typeof u.timeoutMs==="number"?u.timeoutMs:typeof u.timeout==="number"?u.timeout:void 0;if(l===void 0||!Number.isFinite(l))return;return l>0?l:void 0}function mt(i){if(!i)return{unified:"other",raw:void 0};if(i.error)return lr(i.error);if(i.finish)return cr(i.finish);return{unified:"stop",raw:void 0}}function lr(i){let{name:u}=i;switch(u){case"MessageAbortedError":return{unified:"stop",raw:u};case"MessageOutputLengthError":return{unified:"length",raw:u};case"ContextOverflowError":return{unified:"length",raw:u};case"StructuredOutputError":return{unified:"error",raw:u};case"ProviderAuthError":case"APIError":case"UnknownError":return{unified:"error",raw:u};default:return{unified:"error",raw:u}}}function cr(i){let u=i.toLowerCase();if(u==="end_turn"||u==="stop"||u==="end")return{unified:"stop",raw:i};if(u==="max_tokens"||u==="length")return{unified:"length",raw:i};if(u==="tool_use"||u==="tool_calls"||u==="tool-calls")return{unified:"tool-calls",raw:i};if(u==="content_filter"||u==="content-filter"||u==="safety")return{unified:"content-filter",raw:i};if(u==="error")return{unified:"error",raw:i};return{unified:"other",raw:i}}function kt(i,u){if(u&&(i.unified==="tool-calls"||i.unified==="other"))return{unified:"stop",raw:i.raw};return i}function D(i,u){try{return JSON.stringify(i)??"{}"}catch(l){let c=l instanceof Error?l.message:String(l);return u?.(c),"{}"}}function pr(i){if(!i.startsWith("data:"))return null;let u=i.indexOf(",");if(u===-1)return null;let l=i.slice(5,u),c=i.slice(u+1),f=l.split(";"),h=f[0]?.trim(),g=h&&h.length>0?h:"application/octet-stream";if(f.slice(1).some((b)=>b.trim().toLowerCase()==="base64"))return{mediaType:g,data:c.replace(/\s+/g,"")};let v;try{v=decodeURIComponent(c)}catch{return null}return{mediaType:g,data:Buffer.from(v,"utf8").toString("base64")}}function Et(i){if(!i.url||!i.mime)return{error:"missing-metadata"};let u=i.source,l,c=!1;if(i.url.startsWith("data:")){let h=pr(i.url);if(!h)return{error:"invalid-data-url"};l={type:"file",mediaType:h.mediaType,data:h.data}}else if(i.url.startsWith("http://")||i.url.startsWith("https://"))l={type:"source-url",id:i.id??i.url,url:i.url,...i.filename?{title:i.filename}:{}};else{let h=i.filename??i.url.split("/").pop()??"file";l={type:"source-document",id:i.id??i.url,mediaType:i.mime,title:h,...h?{filename:h}:{}},c=!0}let f;if(i.source&&!c){let h=i.source.type;if(h==="file"||h==="symbol"||h==="resource"){let g=typeof i.source.path==="string"?i.source.path:typeof i.source.uri==="string"?i.source.uri:"source";f={id:`${i.id??"source"}-source`,mediaType:i.mime,title:g,...typeof i.source.path==="string"?{filename:i.source.path}:{}}}}return{plan:{sourceMetadata:u,primary:l,...f?{secondaryDocumentSource:f}:{}}}}var W="StructuredOutput";function dr(){return{textPartId:void 0,textStarted:!1,reasoningPartId:void 0,reasoningStarted:!1,toolStates:new Map,usage:{inputTokens:0,outputTokens:0,reasoningTokens:0,cachedInputTokens:0,cachedWriteTokens:0,totalCost:0},lastTextContent:"",lastReasoningContent:"",messageRoles:new Map,permissionRequests:new Set,questionRequests:new Set,pendingApprovals:new Map,structuredOutputCompleted:!1}}function G(i,u,l,c,f){if(!c.inputStarted)f.push({type:"tool-input-start",id:i,toolName:u,providerExecuted:!0,dynamic:!0}),c.inputStarted=!0;if(!c.inputClosed)f.push({type:"tool-input-end",id:i}),c.inputClosed=!0;if(!c.callEmitted)f.push({type:"tool-call",toolCallId:i,toolName:u,input:l,providerExecuted:!0,dynamic:!0}),c.callEmitted=!0}function j(i,u,l){let c=u.pendingApprovals.get(i);if(!c)return;if(u.pendingApprovals.delete(i),u.permissionRequests.has(c.approvalId))return;u.permissionRequests.add(c.approvalId),l.push({type:"tool-approval-request",approvalId:c.approvalId,toolCallId:c.toolCallId,providerMetadata:{opencode:{sessionId:c.sessionId,permission:c.permission,patterns:c.patterns}}})}function fr(i,u){if("properties"in i&&typeof i.properties==="object"&&i.properties!==null){let l=i.properties;if("part"in l&&typeof l.part==="object"&&l.part!==null)return l.part.sessionID===u;if("info"in l&&typeof l.info==="object"&&l.info!==null)return l.info.sessionID===u;if("sessionID"in l)return l.sessionID===u}return!1}function mr(i,u){if(i.type==="session.status"){let l=i;return l.properties.sessionID===u&&l.properties.status.type==="idle"}if(i.type==="session.idle")return i.properties.sessionID===u;return!1}function hr(i,u,l){let c=[];switch(i.type){case"message.part.updated":{let h=gr(i,u,l);c.push(...h);break}case"message.part.delta":{let h=yr(i,u);c.push(...h);break}case"message.updated":{let h=i.properties.info;u.messageRoles.set(h.id,h.role);break}case"permission.asked":{let f=i,h=f.properties.id,g=f.properties.tool?.callID;if(u.permissionRequests.has(h))break;let y=g?u.toolStates.get(g):void 0,v=g??h,b={approvalId:h,toolCallId:g??h,toolName:y?.toolName??"",providerExecuted:!0,permission:f.properties.permission,patterns:f.properties.patterns,sessionId:f.properties.sessionID};if(u.pendingApprovals.set(v,b),!g){j(v,u,c);break}if(y?.callEmitted)j(g,u,c);else if(y&&y.lastInput!==void 0)G(g,y.toolName,y.lastInput,y,c),j(g,u,c);break}case"question.asked":{let h=i.properties.id;if(!u.questionRequests.has(h)){u.questionRequests.add(h);let g="OpenCode question.asked events are not yet mapped to AI SDK responses. The provider cannot answer interactive questions automatically.";if(l)l.warn(g);c.push({type:"error",error:Error(`${g} Question ID: ${h}. If this blocks generation, answer/reject the question in OpenCode directly.`)})}break}case"session.status":case"session.idle":case"session.diff":case"question.replied":case"question.rejected":case"project.updated":case"server.instance.disposed":case"global.disposed":case"worktree.ready":case"worktree.failed":case"mcp.tools.changed":break;default:if(l&&l.debug)l.debug(`Unknown event type: ${i.type}`)}return c}function gr(i,u,l){let{part:c,delta:f}=i.properties,h=[];if(u.messageRoles.get(c.messageID)==="user")return h;switch(c.type){case"text":{let y=c;if(y.synthetic||y.ignored)break;h.push(...vr(y,f,u));break}case"reasoning":{let y=c;h.push(...br(y,f,u));break}case"tool":{let y=c;h.push(...Ir(y,u,l));break}case"step-finish":{Sr(c,u);break}case"step-start":case"subtask":case"snapshot":case"patch":case"agent":case"retry":case"compaction":break;case"file":{let y=c;h.push(...Ct(y));break}default:if(l&&l.debug)l.debug(`Unknown part type: ${c.type}`)}return h}function yr(i,u){let l=[],{partID:c,messageID:f,field:h,delta:g}=i.properties;if(!g)return l;if(u.messageRoles.get(f)==="user")return l;if(h==="reasoning"||u.reasoningPartId===c){if(!u.reasoningStarted||u.reasoningPartId!==c){if(u.reasoningStarted&&u.reasoningPartId&&u.reasoningPartId!==c)l.push({type:"reasoning-end",id:u.reasoningPartId});l.push({type:"reasoning-start",id:c}),u.reasoningStarted=!0,u.reasoningPartId=c,u.lastReasoningContent=""}l.push({type:"reasoning-delta",id:c,delta:g}),u.lastReasoningContent+=g}else{if(!u.textStarted||u.textPartId!==c){if(u.textStarted&&u.textPartId&&u.textPartId!==c)l.push({type:"text-end",id:u.textPartId});l.push({type:"text-start",id:c}),u.textStarted=!0,u.textPartId=c,u.lastTextContent=""}l.push({type:"text-delta",id:c,delta:g}),u.lastTextContent+=g}return l}function vr(i,u,l){let c=[],f=i.id;if(!l.textStarted||l.textPartId!==f){if(l.textStarted&&l.textPartId&&l.textPartId!==f)c.push({type:"text-end",id:l.textPartId});c.push({type:"text-start",id:f}),l.textStarted=!0,l.textPartId=f,l.lastTextContent=""}if(u)c.push({type:"text-delta",id:f,delta:u}),l.lastTextContent+=u;else if(i.text&&i.text!==l.lastTextContent){let h=i.text.slice(l.lastTextContent.length);if(h)c.push({type:"text-delta",id:f,delta:h}),l.lastTextContent=i.text}return c}function br(i,u,l){let c=[],f=i.id;if(!l.reasoningStarted||l.reasoningPartId!==f){if(l.reasoningStarted&&l.reasoningPartId&&l.reasoningPartId!==f)c.push({type:"reasoning-end",id:l.reasoningPartId});c.push({type:"reasoning-start",id:f}),l.reasoningStarted=!0,l.reasoningPartId=f,l.lastReasoningContent=""}if(u)c.push({type:"reasoning-delta",id:f,delta:u}),l.lastReasoningContent+=u;else if(i.text&&i.text!==l.lastReasoningContent){let h=i.text.slice(l.lastReasoningContent.length);if(h)c.push({type:"reasoning-delta",id:f,delta:h}),l.lastReasoningContent=i.text}return c}function Ir(i,u,l){let c=[],{callID:f,tool:h,state:g}=i;if(h===W)return wr(f,g,u,l);let y=u.toolStates.get(f);if(!y)y={callId:f,toolName:h,inputStarted:!1,inputClosed:!1,callEmitted:!1,resultEmitted:!1,emittedAttachmentIds:new Set},u.toolStates.set(f,y);switch(g.status){case"pending":if(!y.inputStarted)c.push({type:"tool-input-start",id:f,toolName:h,providerExecuted:!0,dynamic:!0}),y.inputStarted=!0;break;case"running":{if(!y.inputStarted)c.push({type:"tool-input-start",id:f,toolName:h,providerExecuted:!0,dynamic:!0,...g.title?{title:g.title}:{}}),y.inputStarted=!0;let v=D(g.input,(b)=>{if(l)l.warn(`Failed to serialize tool input for ${f}: ${b}`)});if(y.callEmitted){if(v!==y.lastInput&&l)l.warn(`Ignoring tool input change for ${f} after the tool call was registered; the input exposed for approval is immutable.`);break}if(!y.lastInput){if(v)c.push({type:"tool-input-delta",id:f,delta:v})}else if(v.startsWith(y.lastInput)){let b=v.slice(y.lastInput.length);if(b)c.push({type:"tool-input-delta",id:f,delta:b})}else if(v)c.push({type:"tool-input-delta",id:f,delta:v});if(y.lastInput=v,u.pendingApprovals.has(f)&&!y.callEmitted)G(f,h,v,y,c),j(f,u,c);break}case"completed":{let v=D(g.input,(b)=>{if(l)l.warn(`Failed to serialize tool input for ${f}: ${b}`)});if(G(f,h,v,y,c),j(f,u,c),!y.resultEmitted)c.push({type:"tool-result",toolCallId:f,toolName:h,result:g.output??"",isError:!1,dynamic:!0}),y.resultEmitted=!0;if(Array.isArray(g.attachments))for(let b of g.attachments){let w=b.id??`${b.url}|${b.mime}|${b.filename??""}`;if(y.emittedAttachmentIds.has(w))continue;c.push(...Ct(b)),y.emittedAttachmentIds.add(w)}break}case"error":{let v=D(g.input,(b)=>{if(l)l.warn(`Failed to serialize tool input for ${f}: ${b}`)});if(G(f,h,v,y,c),u.pendingApprovals.delete(f),!y.resultEmitted){if(c.push({type:"tool-result",toolCallId:f,toolName:h,result:g.error??"Unknown error",isError:!0,dynamic:!0}),y.resultEmitted=!0,l)l.warn(`Tool ${h} failed: ${g.error}`)}break}}return c}function wr(i,u,l,c){let f=[],h=`structured-output-${i}`,g=l.toolStates.get(i);if(!g)g={callId:i,toolName:W,inputStarted:!1,inputClosed:!1,callEmitted:!1,resultEmitted:!1,emittedAttachmentIds:new Set},l.toolStates.set(i,g);let y=(v,b)=>{let w=D(b,(T)=>{if(c)c.warn(`Failed to serialize StructuredOutput input for ${i}: ${T}`)});if(c)c.debug?.(`[StructuredOutput stream] callID=${i} status=${v} raw input=${JSON.stringify(b)} serialized=${w} lastInput=${g.lastInput??"(none)"}`);if(w==="{}"&&v!=="completed")return;if(!l.textStarted||l.textPartId!==h){if(l.textStarted&&l.textPartId&&l.textPartId!==h)f.push({type:"text-end",id:l.textPartId});f.push({type:"text-start",id:h}),l.textStarted=!0,l.textPartId=h,l.lastTextContent=""}if(!g.lastInput){if(w)f.push({type:"text-delta",id:h,delta:w})}else if(w.startsWith(g.lastInput)){let T=w.slice(g.lastInput.length);if(T)f.push({type:"text-delta",id:h,delta:T})}else if(w){if(c)c.debug?.(`[StructuredOutput stream] callID=${i} non-prefix change detected, emitting full input. prev=${g.lastInput} new=${w}`);f.push({type:"text-delta",id:h,delta:w})}g.lastInput=w,l.lastTextContent=w};switch(u.status){case"pending":y("pending",u.input);break;case"running":y("running",u.input);break;case"completed":if(y("completed",u.input),l.structuredOutputCompleted=!0,l.textStarted&&l.textPartId===h)f.push({type:"text-end",id:h}),l.textStarted=!1,l.textPartId=void 0;break;case"error":if(l.textStarted&&l.textPartId===h)f.push({type:"text-end",id:h}),l.textStarted=!1,l.textPartId=void 0;break}return f}function Sr(i,u){u.usage.inputTokens+=i.tokens.input,u.usage.outputTokens+=i.tokens.output,u.usage.reasoningTokens+=i.tokens.reasoning,u.usage.cachedInputTokens+=i.tokens.cache.read,u.usage.cachedWriteTokens+=i.tokens.cache.write,u.usage.totalCost+=i.cost}function Ct(i){let u=[],{plan:l}=Et(i);if(!l)return u;if(l.primary.type==="file")u.push({type:"file",mediaType:l.primary.mediaType,data:l.primary.data,...l.sourceMetadata?{providerMetadata:{opencode:{source:l.sourceMetadata}}}:{}});else if(l.primary.type==="source-url")u.push({type:"source",sourceType:"url",id:l.primary.id,url:l.primary.url,...l.primary.title?{title:l.primary.title}:{}});else u.push({type:"source",sourceType:"document",id:l.primary.id,mediaType:l.primary.mediaType,title:l.primary.title,...l.primary.filename?{filename:l.primary.filename}:{},...l.sourceMetadata?{providerMetadata:{opencode:{source:l.sourceMetadata}}}:{}});if(l.secondaryDocumentSource)u.push({type:"source",sourceType:"document",id:l.secondaryDocumentSource.id,mediaType:l.secondaryDocumentSource.mediaType,title:l.secondaryDocumentSource.title,...l.secondaryDocumentSource.filename?{filename:l.secondaryDocumentSource.filename}:{},...l.sourceMetadata?{providerMetadata:{opencode:{source:l.sourceMetadata}}}:{}});return u}function xr(i,u,l,c){let f=[],g={inputTokens:{total:i.usage.inputTokens+i.usage.cachedInputTokens+i.usage.cachedWriteTokens,noCache:i.usage.inputTokens,cacheRead:i.usage.cachedInputTokens,cacheWrite:i.usage.cachedWriteTokens},outputTokens:{total:i.usage.outputTokens,text:void 0,reasoning:i.usage.reasoningTokens},raw:{input_tokens:i.usage.inputTokens,output_tokens:i.usage.outputTokens,reasoning_tokens:i.usage.reasoningTokens,cache_read_input_tokens:i.usage.cachedInputTokens,cache_write_input_tokens:i.usage.cachedWriteTokens,total_cost:i.usage.totalCost}};if(i.textStarted&&i.textPartId)f.push({type:"text-end",id:i.textPartId});if(i.reasoningStarted&&i.reasoningPartId)f.push({type:"reasoning-end",id:i.reasoningPartId});return f.push({type:"finish",usage:g,finishReason:kt(u,i.structuredOutputCompleted),providerMetadata:{opencode:{sessionId:l,...c?{messageId:c}:{},cost:i.usage.totalCost}}}),f}function Tr(i){return i.some((u)=>u.type==="tool"&&u.tool===W&&u.state?.status==="completed")}function ht(i){return{type:"stream-start",warnings:i.map((l)=>({type:"other",message:l}))}}var gt={warn:(i)=>{console.warn(`[opencode-provider] ${i}`)},error:(i)=>{console.error(`[opencode-provider] ${i}`)},debug:(i)=>{console.debug(`[opencode-provider] ${i}`)}},kr={warn:()=>{},error:()=>{},debug:()=>{}};function Q(i,u){if(i===!1)return kr;if(i){if(u&&!i.debug)return{...i,debug:(l)=>i.warn(`[DEBUG] ${l}`)};return i}if(!u)return{...gt,debug:()=>{}};return gt}function yt(i,u){let l=[],c=[{name:"temperature",value:u.temperature},{name:"topP",value:u.topP},{name:"topK",value:u.topK},{name:"frequencyPenalty",value:u.frequencyPenalty},{name:"presencePenalty",value:u.presencePenalty},{name:"stopSequences",value:u.stopSequences},{name:"seed",value:u.seed},{name:"maxTokens",value:u.maxTokens}];for(let f of c)if(f.value!==void 0){let h=`Parameter '${f.name}' is not supported by OpenCode`;i.warn(h),l.push(h)}return l}var Er=t({warn:L().refine((i)=>typeof i==="function",{message:"warn must be a function"}),error:L().refine((i)=>typeof i==="function",{message:"error must be a function"}),debug:L().refine((i)=>i===void 0||typeof i==="function",{message:"debug must be a function"}).optional()}),Cr=t({permission:e(),pattern:e(),action:s(["allow","deny","ask"])}),Pt=t({sessionId:e().optional(),createNewSession:r().optional(),sessionTitle:e().optional(),agent:e().optional(),systemPrompt:e().optional(),tools:d(e(),r()).optional(),permission:o(Cr).optional(),variant:e().optional(),cwd:e().optional(),directory:e().optional(),outputFormatRetryCount:n().int().nonnegative().optional(),logger:p([Er,a(!1)]).optional(),verbose:r().optional()}),Pr=t({hostname:e().optional(),port:n().int().positive().optional(),baseUrl:e().url().optional(),autoStartServer:r().optional(),serverTimeout:n().int().positive().optional(),clientOptions:d(e(),m()).optional(),client:t({}).passthrough().optional(),clientManager:t({}).passthrough().optional(),defaultSettings:Pt.optional()});function $r(i,u){let l=[];if(!i)return{value:{},warnings:l};let c=Pt.safeParse(i);if(!c.success){let f=c.error.issues.map((h)=>`${h.path.join(".")}: ${h.message}`);l.push(`Settings validation warnings: ${f.join("; ")}`)}if(i.sessionId&&!Mr(i.sessionId))l.push(`Invalid session ID format: ${i.sessionId}`);if(i.outputFormatRetryCount!==void 0&&i.outputFormatRetryCount>10)l.push(`outputFormatRetryCount ${i.outputFormatRetryCount} is high; consider a value between 0 and 5`);if(u&&l.length>0)for(let f of l)u.warn(f);return{value:i,warnings:l}}function Or(i,u){let l=[];if(!i)return{value:{},warnings:l};let c=Pr.safeParse(i);if(!c.success){let f=c.error.issues.map((h)=>`${h.path.join(".")}: ${h.message}`);l.push(`Provider settings validation warnings: ${f.join("; ")}`)}if(i.port!==void 0&&(i.port<1||i.port>65535))l.push(`Port ${i.port} is outside valid range (1-65535)`);if(i.serverTimeout!==void 0&&i.serverTimeout<1000)l.push(`Server timeout ${i.serverTimeout}ms is very short, consider at least 5000ms`);if(i.clientManager&&i.client)l.push("Both clientManager and client were provided; clientManager will be used and client will be ignored.");if(i.client&&i.clientOptions)l.push("Both client and clientOptions were provided; clientOptions will be ignored because client takes precedence");if(i.clientOptions){let f=i.clientOptions;if(f.baseUrl!==void 0)l.push("clientOptions.baseUrl is ignored; use provider baseUrl or hostname/port instead");if(f.directory!==void 0)l.push("clientOptions.directory is ignored; use defaultSettings.directory or per-model directory instead")}if(u&&l.length>0)for(let f of l)u.warn(f);return{value:i,warnings:l}}function Rr(i,u){if(!i||typeof i!=="string"||i.trim().length===0){if(u)u.error("Model ID is required and must be a non-empty string");return null}let l=i.trim();if(l.includes("/")){let c=l.split("/");if(c.length===2&&c[0]&&c[1])return{providerID:c[0],modelID:c[1]};if(u)u.warn(`Model ID "${i}" contains multiple slashes, using first segment as provider`);let f=c[0],h=c.slice(1).join("/");return{providerID:f||"default",modelID:h||l}}return{providerID:"",modelID:l}}function Mr(i){if(!i||typeof i!=="string")return!1;return/^[a-zA-Z0-9_-]+$/.test(i)&&i.length>0&&i.length<=128}function Dr(i,u){if(!i&&!u)return{};if(!i)return{...u};if(!u)return{...i};return{...i,...u,tools:i.tools||u.tools?{...i.tools,...u.tools}:void 0,permission:u.permission??i.permission}}function Ar(i){return{inputTokens:{total:i.inputTokens+i.cachedInputTokens+i.cachedWriteTokens,noCache:i.inputTokens,cacheRead:i.cachedInputTokens,cacheWrite:i.cachedWriteTokens},outputTokens:{total:i.outputTokens,text:void 0,reasoning:i.reasoningTokens},raw:{input_tokens:i.inputTokens,output_tokens:i.outputTokens,reasoning_tokens:i.reasoningTokens,cache_read_input_tokens:i.cachedInputTokens,cache_write_input_tokens:i.cachedWriteTokens,total_cost:i.totalCost}}}function V(i){if(i&&typeof i==="object"&&(("data"in i)||("error"in i)))return i;return{data:i}}function vt(i){let u=i.providerOptions?.opencode?.messageID;if(u==null)return;if(typeof u!=="string")throw new re({argument:"providerOptions.opencode.messageID",message:"providerOptions.opencode.messageID must be a string"});if(!u.startsWith("msg_"))throw new re({argument:"providerOptions.opencode.messageID",message:"providerOptions.opencode.messageID must start with 'msg_'"});return u}function bt(i){let u=[];for(let l of i){if(l.role!=="tool")continue;for(let c of l.content){if(c.type!=="tool-approval-response")continue;let f=c;u.push({approvalId:f.approvalId,approved:f.approved,reason:f.reason})}}return u}var _r=class{specificationVersion="v3";modelId;provider="opencode";supportedUrls={};settings;logger;clientManager;sessionId;sessionInitPromise=null;repliedApprovalIdsBySession=new Map;parsedModelId;constructor(i){this.modelId=i.modelId,this.settings=i.settings,this.clientManager=i.clientManager,this.logger=Q(i.settings.logger,i.settings.verbose);let u=Rr(this.modelId,this.logger);if(!u)throw Error(`Invalid model ID: ${this.modelId}`);if(this.parsedModelId=u,$r(this.settings,this.logger),this.settings.sessionId)this.sessionId=this.settings.sessionId}async doGenerate(i){let u=[],l=yt(this.logger,{temperature:i.temperature,topP:i.topP,topK:i.topK,frequencyPenalty:i.frequencyPenalty,presencePenalty:i.presencePenalty,stopSequences:i.stopSequences,seed:i.seed,maxTokens:i.maxOutputTokens});for(let v of l)u.push({type:"other",message:v});if(i.tools&&i.tools.length>0)this.logger.warn("Custom tool definitions are ignored. OpenCode executes tools server-side."),u.push({type:"other",message:"Custom tool definitions are ignored. OpenCode executes tools server-side."});let c=bt(i.prompt),{parts:f,systemPrompt:h,warnings:g}=dt(i.prompt,{logger:this.logger,mode:{type:"regular"},includeToolApprovalResponsesAsContext:!1});for(let v of g)u.push({type:"other",message:v});let y=vt(i);try{if(i.abortSignal?.aborted){let I=Error("Request aborted");throw I.name="AbortError",I}let v=await this.getOrCreateSession(),b=await this.clientManager.getClient();if(c.length>0){let I=await this.replyToPendingApprovals(b,v,c);for(let F of I)u.push({type:"other",message:F})}let w=this.buildPromptRequestBody(v,f,h,i,y),T=i.abortSignal,O=async()=>{let I=this.getRequestDirectory();try{await b.session.abort({sessionID:v,...I?{directory:I}:{}})}catch{}},Z;try{Z=T?await b.session.prompt(w,{signal:T}):await b.session.prompt(w)}catch(I){if(H(I)||T?.aborted)await O();throw I}let{data:k,error:_}=V(Z);if(!k){if(T?.aborted){await O();let I=Error("Request aborted");throw I.name="AbortError",I}throw ft(_,{sessionId:v,modelId:this.modelId})}let P=k;this.logger.debug?.(`[doGenerate] raw parts from OpenCode: ${JSON.stringify(P.parts?.map((I)=>({type:I.type,...I.type==="text"?{text:I.text?.slice(0,200)}:{},...I.type==="tool"?{tool:I.tool,callID:I.callID,status:I.state?.status,input:I.state?.input}:{}})))}`);let C=this.extractContentFromParts(P.parts??[]);this.logger.debug?.(`[doGenerate] extracted content: ${JSON.stringify(C.map((I)=>({type:I.type,...I.type==="text"?{text:I.text?.slice(0,200)}:{},...I.type==="tool-call"?{toolName:I.toolName}:{}})))}`);let J=this.extractUsageFromParts(P.parts??[]),q=kt(mt(P.info),Tr(P.parts??[]));return{content:C,finishReason:q,usage:Ar(J),providerMetadata:{opencode:{sessionId:v,messageId:P.info?.id,cost:J.totalCost}},request:{body:w},warnings:u}}catch(v){if(H(v))throw v;throw oe(v,{sessionId:this.sessionId,modelId:this.modelId})}}async doStream(i){let u=[],l=yt(this.logger,{temperature:i.temperature,topP:i.topP,topK:i.topK,frequencyPenalty:i.frequencyPenalty,presencePenalty:i.presencePenalty,stopSequences:i.stopSequences,seed:i.seed,maxTokens:i.maxOutputTokens});if(u.push(...l),i.tools&&i.tools.length>0)this.logger.warn("Custom tool definitions are ignored. OpenCode executes tools server-side."),u.push("Custom tool definitions are ignored. OpenCode executes tools server-side.");let c=bt(i.prompt),{parts:f,systemPrompt:h,warnings:g}=dt(i.prompt,{logger:this.logger,mode:{type:"regular"},includeToolApprovalResponsesAsContext:!1});u.push(...g);let y=vt(i),v=await this.getOrCreateSession(),b=await this.clientManager.getClient(),w=this.buildPromptRequestBody(v,f,h,i,y),T=this.getRequestDirectory(),O=this.logger;return{stream:new ReadableStream({start:async(k)=>{let _=[...u],P=!1,C=new AbortController,J=this.clientManager.registerEventSubscription(C);try{let I=(await b.event.subscribe(T?{directory:T}:void 0,{signal:C.signal})).stream;if(!I)throw Error("Failed to subscribe to events");if(c.length>0){let x=await this.replyToPendingApprovals(b,v,c);_.push(...x)}k.enqueue(ht(_)),P=!0;let F,$t=new Promise((x)=>{F=x}),ie,Ot=new Promise((x)=>{ie=x}),ae=()=>{},B=i.abortSignal;if(B){let x=()=>ie?.();if(B.aborted)x();else B.addEventListener("abort",x,{once:!0}),ae=()=>B.removeEventListener("abort",x)}let z=!1,ue=(x)=>{if(z){F?.();return}z=!0;let R=oe(x,{sessionId:v,modelId:this.modelId});O.error(`Prompt error: ${E(R)}`);try{k.enqueue({type:"error",error:R})}catch(N){O.debug?.(`Failed to enqueue prompt error after stream closed: ${E(N)}`)}F?.()};b.session.prompt(w,{signal:C.signal}).then((x)=>{if(C.signal.aborted)return;let{data:R,error:N}=V(x);if(!R)ue(ft(N,{sessionId:v,modelId:this.modelId}))},(x)=>{if(C.signal.aborted)return;ue(x)});let le=dr(),X,ee=I[Symbol.asyncIterator](),te=!1,K=async()=>{if(te)return;if(te=!0,C.abort(),typeof ee.return==="function")try{await ee.return(void 0)}catch(x){O.debug?.(`Failed to close event stream iterator: ${E(x)}`)}};try{while(!0){let x=ee.next(),R=await Promise.race([x.then((M)=>({type:"event",value:M})),$t.then(()=>({type:"prompt-failed"})),Ot.then(()=>({type:"aborted"}))]);if(R.type==="prompt-failed"){await K();break}if(R.type==="aborted"){try{await b.session.abort({sessionID:v,...T?{directory:T}:{}},{signal:C.signal})}catch{}await K();break}let{done:N,value:U}=R.value;if(N){if(te=!0,!i.abortSignal?.aborted&&!z)z=!0,k.enqueue({type:"error",error:xt(Error("OpenCode event stream ended before the session finished; the response may be incomplete."),{sessionId:v,modelId:this.modelId,isRetryable:!1})});break}if(!fr(U,v))continue;let Rt=hr(U,le,O);for(let M of Rt)k.enqueue(M);if(U.type==="message.updated"){let M=U;if(M.properties.info.role==="assistant")X=M.properties.info}if(mr(U,v)){let M=mt(X),Mt=xr(le,M,v,X?.id);for(let Dt of Mt)k.enqueue(Dt);await K();break}}}finally{ae(),await K()}}catch(q){if(!P)k.enqueue(ht(_));if(!H(q)){let I=oe(q,{sessionId:v,modelId:this.modelId});O.error(`Stream error: ${E(I)}`),k.enqueue({type:"error",error:I})}}finally{C.abort(),J(),k.close()}}}),request:{body:w}}}getRequestDirectory(){return this.settings.directory??this.settings.cwd}getResponseFormat(i){if(i.responseFormat?.type!=="json")return;return{type:"json_schema",schema:i.responseFormat.schema??{type:"object",additionalProperties:!0},...this.settings.outputFormatRetryCount!==void 0?{retryCount:this.settings.outputFormatRetryCount}:{}}}buildPromptRequestBody(i,u,l,c,f){let h=this.getResponseFormat(c),g=this.getRequestDirectory();return{sessionID:i,...g?{directory:g}:{},...this.parsedModelId.providerID?{model:{providerID:this.parsedModelId.providerID,modelID:this.parsedModelId.modelID}}:{},...this.settings.agent?{agent:this.settings.agent}:{},...this.settings.tools?{tools:this.settings.tools}:{},...h?{format:h}:{},...l??this.settings.systemPrompt?{system:l??this.settings.systemPrompt}:{},...this.settings.variant?{variant:this.settings.variant}:{},...f?{messageID:f}:{},parts:u}}async replyToPendingApprovals(i,u,l){let c=i.permission;if(typeof c?.reply!=="function")return["OpenCode permission.reply is unavailable; tool approval responses were ignored."];let f=[],h=this.getRequestDirectory(),g=this.getRepliedApprovalIdsForSession(u),y=this.getPendingApprovalResponses(l,g);for(let v of y)try{let b=await c.reply({requestID:v.approvalId,reply:v.approved?"once":"reject",...v.reason?{message:v.reason}:{},...h?{directory:h}:{}}),{error:w}=V(b);if(w){let T=`Failed to apply tool approval response for ${v.approvalId}: ${E(w)}`;this.logger.warn(T),f.push(T);continue}g.add(v.approvalId)}catch(b){let w=`Failed to apply tool approval response for ${v.approvalId}: ${E(b)}`;this.logger.warn(w),f.push(w)}return f}getPendingApprovalResponses(i,u){let l=new Set,c=[];for(let f of i){if(l.has(f.approvalId))continue;if(l.add(f.approvalId),u.has(f.approvalId))continue;c.push(f)}return c}getRepliedApprovalIdsForSession(i){let u=this.repliedApprovalIdsBySession.get(i);if(u)return u;let l=new Set;return this.repliedApprovalIdsBySession.set(i,l),l}async getOrCreateSession(){if(this.sessionId&&!this.settings.createNewSession)return this.sessionId;if(!this.settings.createNewSession&&this.sessionInitPromise)return this.sessionInitPromise;let i=async()=>{let l=await this.clientManager.getClient(),c=this.getRequestDirectory(),f=await l.session.create({...c?{directory:c}:{},title:this.settings.sessionTitle??"AI SDK Session",...this.settings.permission?{permission:this.settings.permission}:{}}),{data:h,error:g}=V(f),y=h;if(!y?.id)throw Error(`Failed to create session: ${JSON.stringify(g??h)}`);return this.sessionId=y.id,this.logger.debug?.(`Created session: ${this.sessionId}`),this.sessionId};if(this.settings.createNewSession)return i();let u=i();this.sessionInitPromise=u;try{return await u}finally{if(this.sessionInitPromise===u)this.sessionInitPromise=null}}extractContentFromParts(i){let u=[];for(let l of i){if(l.type==="text"&&typeof l.text==="string"){if(!l.synthetic&&!l.ignored)u.push({type:"text",text:l.text});continue}if(l.type==="reasoning"&&typeof l.text==="string"){u.push({type:"reasoning",text:l.text});continue}if(l.type==="tool"){let c=this.extractToolParts(l);u.push(...c);continue}if(l.type==="file")u.push(...this.convertFilePartToContent(l))}return u}extractToolParts(i){let u=[],l=i;if(l.state.status==="completed"){if(l.tool===W){let f=D(l.state.input,(h)=>{this.logger.warn(`Failed to serialize StructuredOutput input for ${l.callID}: ${h}`)});return this.logger.debug?.(`[StructuredOutput doGenerate] callID=${l.callID} status=${l.state.status} raw input=${JSON.stringify(l.state.input)} serialized=${f}`),u.push({type:"text",text:f}),u}u.push({type:"tool-call",toolCallId:l.callID,toolName:l.tool,input:D(l.state.input,(f)=>{this.logger.warn(`Failed to serialize tool input for ${l.callID}: ${f}`)}),providerExecuted:!0,dynamic:!0}),u.push({type:"tool-result",toolCallId:l.callID,toolName:l.tool,result:l.state.output??"",dynamic:!0});let c=l.state.attachments??[];for(let f of c)if(f.type==="file")u.push(...this.convertFilePartToContent(f))}else if(l.state.status==="error"){if(l.tool===W)return u;u.push({type:"tool-call",toolCallId:l.callID,toolName:l.tool,input:D(l.state.input,(c)=>{this.logger.warn(`Failed to serialize tool input for ${l.callID}: ${c}`)}),providerExecuted:!0,dynamic:!0}),u.push({type:"tool-result",toolCallId:l.callID,toolName:l.tool,result:l.state.error??"Unknown error",isError:!0,dynamic:!0})}return u}convertFilePartToContent(i){let u=i;if(!u.url||!u.mime)return this.logger.debug?.(`Skipping file part with missing metadata: url=${String(u.url)} mime=${String(u.mime)}`),[];let{plan:l,error:c}=Et(u);if(!l){if(c==="invalid-data-url")this.logger.debug?.(`Skipping file part with invalid data URL: ${u.url.slice(0,80)}`);return[]}let f=[];if(l.primary.type==="file")f.push({type:"file",mediaType:l.primary.mediaType,data:l.primary.data,...l.sourceMetadata?{providerMetadata:{opencode:{source:l.sourceMetadata}}}:{}});else if(l.primary.type==="source-url")f.push({type:"source",sourceType:"url",id:l.primary.id,url:l.primary.url,...l.primary.title?{title:l.primary.title}:{}});else f.push({type:"source",sourceType:"document",id:l.primary.id,mediaType:l.primary.mediaType,title:l.primary.title,...l.primary.filename?{filename:l.primary.filename}:{},...l.sourceMetadata?{providerMetadata:{opencode:{source:l.sourceMetadata}}}:{}});if(l.secondaryDocumentSource)f.push({type:"source",sourceType:"document",id:l.secondaryDocumentSource.id,mediaType:l.secondaryDocumentSource.mediaType,title:l.secondaryDocumentSource.title,...l.secondaryDocumentSource.filename?{filename:l.secondaryDocumentSource.filename}:{},...l.sourceMetadata?{providerMetadata:{opencode:{source:l.sourceMetadata}}}:{}});return f}extractUsageFromParts(i){let u={inputTokens:0,outputTokens:0,reasoningTokens:0,cachedInputTokens:0,cachedWriteTokens:0,totalCost:0};for(let l of i)if(l.type==="step-finish"){let c=l;u.inputTokens+=c.tokens.input,u.outputTokens+=c.tokens.output,u.reasoningTokens+=c.tokens.reasoning,u.cachedInputTokens+=c.tokens.cache.read,u.cachedWriteTokens+=c.tokens.cache.write,u.totalCost+=c.cost}return u}getSessionId(){return this.sessionId}},qr=class i{static instance=null;client=null;server=null;options;logger;initPromise=null;isDisposed=!1;activeEventSubscriptions=new Set;exitHandler=null;startupAbort=null;constructor(u){let l=Object.fromEntries(Object.entries(u).filter(([c,f])=>f!==void 0));this.options={hostname:"127.0.0.1",port:4096,autoStartServer:!0,serverTimeout:1e4,...l},this.logger=Q(u.logger)}static getInstance(u){if(!i.instance)i.instance=new i(u??{});else if(u)i.instance.updateOptions(u);return i.instance}static createInstance(u){return new i(u)}static resetInstance(){if(i.instance)i.instance.dispose().catch(()=>{}),i.instance=null}updateOptions(u){if(!this.client&&!this.initPromise){let c=Object.fromEntries(Object.entries(u).filter(([f,h])=>h!==void 0));this.options={...this.options,...c},this.logger=Q(u.logger??this.options.logger);return}let l=Object.fromEntries(Object.entries(u).filter(([c,f])=>f!==void 0));if(Object.keys(l).length===0)return;if(l.client&&this.client&&l.client!==this.client){this.logger.warn("Client manager already initialized; provided preconfigured client was ignored because a client is already active — requests will keep flowing through the existing client. To use this client, pass an isolated manager via createOpencode({ clientManager: OpencodeClientManager.createInstance({ client }) }), or call OpencodeClientManager.resetInstance() before creating the provider.");return}this.logger.warn("Client manager already initialized; new options from createOpencode() were ignored. Use OpencodeClientManager.createInstance() with the clientManager provider setting for isolated configuration, or call OpencodeClientManager.resetInstance() first.")}async getClient(){if(this.isDisposed)throw Error("Client manager has been disposed");if(this.client)return this.client;if(this.initPromise)return this.initPromise;this.initPromise=this.initializeClient();try{return this.client=await this.initPromise,this.client}finally{this.initPromise=null}}async initializeClient(){if(this.options.client){if(this.options.clientOptions)this.logger.warn("Both client and clientOptions were provided; clientOptions will be ignored because client takes precedence.");return this.logger.debug?.("Using preconfigured OpenCode client"),this.options.client}let{createOpencodeClient:u,createOpencodeServer:l}=await import("./index-xecthgrg.js");if(this.options.baseUrl)return this.logger.debug?.(`Connecting to external OpenCode server at ${this.options.baseUrl}`),u(this.createManagedClientOptions(this.options.baseUrl));let c=`http://${this.options.hostname}:${this.options.port}`,f=await this.isServerRunning(c);if(this.isDisposed)throw Error("Client manager has been disposed");if(f)return this.logger.debug?.(`Connected to existing OpenCode server at ${c}`),u(this.createManagedClientOptions(c));if(this.options.autoStartServer){this.logger.debug?.(`Starting OpenCode server at ${c}`);let h=new AbortController;this.startupAbort=h;let g;try{g=await l({hostname:this.options.hostname,port:this.options.port,timeout:this.options.serverTimeout,signal:h.signal})}catch(y){if(this.isDisposed)throw Error("Client manager has been disposed");let v=E(y);if(v.includes("Timeout"))throw Tt(this.options.serverTimeout??1e4,"server startup");throw Error(`Failed to start OpenCode server: ${v}`)}finally{if(this.startupAbort===h)this.startupAbort=null}if(this.isDisposed){try{g.close()}catch{}throw Error("Client manager has been disposed")}return this.server=g,this.logger.debug?.(`OpenCode server started at ${g.url}`),this.registerExitHandler(),u(this.createManagedClientOptions(g.url))}throw Error(`No OpenCode server running at ${c} and autoStartServer is disabled`)}async isServerRunning(u){try{return(await fetch(`${u}/health`,{method:"GET",signal:AbortSignal.timeout(2000)})).ok}catch{try{return(await fetch(`${u}/config`,{method:"GET",signal:AbortSignal.timeout(2000)})).ok}catch{return!1}}}createManagedClientOptions(u){let l=this.options.clientOptions??{},c=l;if(c.baseUrl!==void 0)this.logger.warn("Ignoring clientOptions.baseUrl because provider baseUrl/hostname/port controls server routing.");if(c.directory!==void 0)this.logger.warn("Ignoring clientOptions.directory because directory is managed by model settings/defaultSettings.");if(c.responseStyle==="data")this.logger.warn('Ignoring clientOptions.responseStyle "data" because the provider requires fields-style SDK results.');return{...l,baseUrl:u,directory:this.options.cwd,responseStyle:"fields"}}getServerUrl(){if(this.server)return this.server.url;if(this.options.baseUrl)return this.options.baseUrl;return`http://${this.options.hostname}:${this.options.port}`}isServerManaged(){return this.server!==null}registerEventSubscription(u){return this.activeEventSubscriptions.add(u),()=>{this.activeEventSubscriptions.delete(u)}}async dispose(){if(this.isDisposed)return;this.isDisposed=!0,this.startupAbort?.abort(),this.startupAbort=null,this.unregisterExitHandler();for(let u of this.activeEventSubscriptions)u.abort();if(this.activeEventSubscriptions.clear(),i.instance===this)i.instance=null;if(this.server){this.logger.debug?.("Stopping managed OpenCode server");try{this.server.close()}catch(u){this.logger.warn(`Error stopping server: ${E(u)}`)}this.server=null}this.client=null,this.initPromise=null}registerExitHandler(){if(this.exitHandler)return;let u=()=>{let l=this.server;if(!l)return;this.server=null;try{l.close()}catch{}};this.exitHandler=u,process.once("exit",u)}unregisterExitHandler(){if(!this.exitHandler)return;process.removeListener("exit",this.exitHandler),this.exitHandler=null}};function Fr(i,u){return qr.getInstance({hostname:i.hostname,port:i.port,baseUrl:i.baseUrl,autoStartServer:i.autoStartServer,serverTimeout:i.serverTimeout,clientOptions:i.clientOptions,client:i.client,cwd:i.defaultSettings?.directory??i.defaultSettings?.cwd,logger:u})}function Nr(i){let u=Q(i?.defaultSettings?.logger);Or(i,u);let l=i?.clientManager??Fr(i??{},u),c=(h,g)=>{let y=Dr(i?.defaultSettings,g);return new _r({modelId:h,settings:y,clientManager:l})};return Object.assign((h,g)=>c(h,g),{languageModel:(h,g)=>c(h,g),chat:(h,g)=>c(h,g),provider:"opencode",specificationVersion:"v3",embeddingModel:(h)=>{throw new se({modelId:h,modelType:"embeddingModel"})},imageModel:(h)=>{throw new se({modelId:h,modelType:"imageModel"})},getClientManager:()=>l,dispose:async()=>{await l.dispose()}})}var pn=Nr();export{Nr as createOpencode};
@@ -0,0 +1,3 @@
1
+ import{N,F,be,b,H,Q,I,Te,j,Kt,Ht,fc,ge,C,Co,Ce,Ee,ft,en,Ke,u,l,z,Pe,k,A,Re,G,W,ee,$e,oe,qe,E,te,Do}from"./index-6k6ep10s.js";import{e,n,r,m,le,o,t,ae,p,w,M,d,on,s,a,Fe}from"./index-mcnngj50.js";var Wt=u(()=>l(t({type:a("error"),error:t({type:e(),message:e()})}))),ct=oe({errorSchema:Wt,errorToMessage:(i)=>i.error.message}),zn=u(()=>l(t({id:e(),type:a("file"),filename:e(),mime_type:e(),size_bytes:n(),created_at:e(),downloadable:r().nullish()})));function ut(i,h){if(i.type==="web_search_result_location"||i.type==="search_result_location"){let D=i.type==="web_search_result_location"?i.url:i.source;return{source:{type:"source",sourceType:"url",id:D,url:D,title:i.title??void 0,providerMetadata:{anthropic:{...i}}},citedText:i.cited_text}}let g=h[i.document_index];return{source:{type:"source",sourceType:"document",id:i.file_id??String(i.document_index),mediaType:g?.mediaType??"text/plain",title:i.document_title??g?.title??`Document ${i.document_index}`,filename:g?.filename,providerMetadata:{anthropic:{...i}}},citedText:i.cited_text}}var nt=()=>t({type:a("fallback"),from:t({model:e()}),to:t({model:e()})}),Vt=u(()=>l(nt())),Tt=()=>t({type:e(),category:e().nullish(),explanation:e().nullish(),recommended_model:e().nullish()}),Ct=()=>t({type:e(),status:t({type:e(),tool_uses:d(e(),t({type:e(),outcome:e().nullish(),explanation:e().nullish()})).nullish()})}),De=()=>p([t({type:a("code_execution_20250825"),tool_id:e()}),t({type:a("code_execution_20260120"),tool_id:e()}),t({type:a("direct")})]),St=()=>w("type",[t({type:a("web_search_result_location"),cited_text:e(),url:e(),title:e().nullable(),encrypted_index:e()}),t({type:a("page_location"),cited_text:e(),document_index:n(),document_title:e().nullable(),start_page_number:n(),end_page_number:n(),file_id:e().nullish()}),t({type:a("char_location"),cited_text:e(),document_index:n(),document_title:e().nullable(),start_char_index:n(),end_char_index:n(),file_id:e().nullish()}),t({type:a("content_block_location"),cited_text:e(),document_index:n(),document_title:e().nullable(),start_block_index:n(),end_block_index:n(),file_id:e().nullable()}),t({type:a("search_result_location"),cited_text:e(),search_result_index:n(),source:e(),title:e().nullable(),start_block_index:n(),end_block_index:n()})]),Nt=()=>p([e(),o(p([e(),t({type:a("text"),text:e(),citations:o(Fe()).nullable().optional()})]))]),ot=()=>t({type:e(),path:e(),reason:e()}),Xt=u(()=>l(t({type:a("message"),id:e().nullish(),model:e().nullish(),content:o(w("type",[t({type:a("text"),text:e(),citations:o(St()).nullable().optional()}),t({type:a("thinking"),thinking:e(),signature:e()}),t({type:a("redacted_thinking"),data:e()}),t({type:a("compaction"),content:e().nullish(),signature:e().nullish()}),t({type:a("tool_use"),id:e(),name:e(),input:m(),caller:De().optional(),toolset_name:e().nullish()}),t({type:a("server_tool_use"),id:e(),name:e(),input:d(e(),m()).nullish(),caller:De().optional()}),t({type:a("mcp_tool_use"),id:e(),name:e(),input:m(),server_name:e()}),t({type:a("mcp_tool_result"),tool_use_id:e(),is_error:r(),content:Nt()}),t({type:a("web_fetch_tool_result"),tool_use_id:e(),caller:De().optional(),content:p([t({type:a("web_fetch_result"),url:e(),retrieved_at:e().nullable(),content:t({type:a("document"),title:e().nullable(),citations:t({enabled:r()}).optional(),source:p([t({type:a("base64"),media_type:a("application/pdf"),data:e()}),t({type:a("text"),media_type:a("text/plain"),data:e()})])})}),t({type:a("web_fetch_tool_result_error"),error_code:e()})])}),t({type:a("web_search_tool_result"),tool_use_id:e(),caller:De().optional(),content:p([o(t({type:a("web_search_result"),url:e(),title:e().nullable(),encrypted_content:e(),page_age:e().nullish()})),t({type:a("web_search_tool_result_error"),error_code:e()})])}),t({type:a("code_execution_tool_result"),tool_use_id:e(),content:p([t({type:a("code_execution_result"),stdout:e(),stderr:e(),return_code:n(),content:o(t({type:a("code_execution_output"),file_id:e()})).optional().default([])}),t({type:a("encrypted_code_execution_result"),encrypted_stdout:e(),stderr:e(),return_code:n(),content:o(t({type:a("code_execution_output"),file_id:e()})).optional().default([])}),t({type:a("code_execution_tool_result_error"),error_code:e()})])}),t({type:a("bash_code_execution_tool_result"),tool_use_id:e(),content:w("type",[t({type:a("bash_code_execution_result"),content:o(t({type:a("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:n()}),t({type:a("bash_code_execution_tool_result_error"),error_code:e()})])}),t({type:a("text_editor_code_execution_tool_result"),tool_use_id:e(),content:w("type",[t({type:a("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:a("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:n().nullable(),start_line:n().nullable(),total_lines:n().nullable()}),t({type:a("text_editor_code_execution_create_result"),is_file_update:r()}),t({type:a("text_editor_code_execution_str_replace_result"),lines:o(e()).nullable(),new_lines:n().nullable(),new_start:n().nullable(),old_lines:n().nullable(),old_start:n().nullable()})])}),t({type:a("tool_search_tool_result"),tool_use_id:e(),content:p([t({type:a("tool_search_tool_search_result"),tool_references:o(t({type:a("tool_reference"),tool_name:e()}))}),t({type:a("tool_search_tool_result_error"),error_code:e()})])}),t({type:a("container_upload"),file_id:e()}),t({type:a("advisor_tool_result"),tool_use_id:e(),content:w("type",[t({type:a("advisor_result"),text:e(),stop_reason:e().nullish()}),t({type:a("advisor_redacted_result"),encrypted_content:e(),stop_reason:e().nullish()}),t({type:a("advisor_tool_result_error"),error_code:e()})])}),nt()])),stop_reason:e().nullish(),stop_sequence:e().nullish(),stop_details:Tt().nullish(),input_transformations:o(ot()).nullish(),safeguard_results:o(Ct()).nullish(),usage:ae({input_tokens:n(),output_tokens:n(),output_tokens_details:t({thinking_tokens:n().nullish()}).nullish(),cache_creation_input_tokens:n().nullish(),cache_read_input_tokens:n().nullish(),iterations:o(t({type:p([a("compaction"),a("message"),a("advisor_message"),a("fallback_message")]),model:e().nullish(),input_tokens:n(),output_tokens:n(),cache_creation_input_tokens:n().nullish(),cache_read_input_tokens:n().nullish()})).nullish()}),container:t({expires_at:e(),id:e(),skills:o(t({type:p([a("anthropic"),a("custom")]),skill_id:e(),version:e()})).nullish()}).nullish(),context_management:t({applied_edits:o(p([t({type:a("clear_tool_uses_20250919"),cleared_tool_uses:n(),cleared_input_tokens:n()}),t({type:a("clear_thinking_20251015"),cleared_thinking_turns:n(),cleared_input_tokens:n()}),t({type:a("compact_20260112")})]))}).nullish()}))),Gt=u(()=>l(w("type",[t({type:a("message_start"),message:t({id:e().nullish(),model:e().nullish(),role:e().nullish(),usage:ae({input_tokens:n(),cache_creation_input_tokens:n().nullish(),cache_read_input_tokens:n().nullish()}),content:o(w("type",[t({type:a("tool_use"),id:e(),name:e(),input:m(),caller:De().optional(),toolset_name:e().nullish()})])).nullish(),stop_reason:e().nullish(),input_transformations:o(ot()).nullish(),container:t({expires_at:e(),id:e()}).nullish()})}),t({type:a("content_block_start"),index:n(),content_block:w("type",[t({type:a("text"),text:e()}),t({type:a("thinking"),thinking:e()}),t({type:a("tool_use"),id:e(),name:e(),input:d(e(),m()).optional(),caller:De().optional(),toolset_name:e().nullish()}),t({type:a("redacted_thinking"),data:e()}),t({type:a("compaction"),content:e().nullish(),signature:e().nullish()}),t({type:a("server_tool_use"),id:e(),name:e(),input:d(e(),m()).nullish(),caller:De().optional()}),t({type:a("mcp_tool_use"),id:e(),name:e(),input:m(),server_name:e()}),t({type:a("mcp_tool_result"),tool_use_id:e(),is_error:r(),content:Nt()}),t({type:a("web_fetch_tool_result"),tool_use_id:e(),caller:De().optional(),content:p([t({type:a("web_fetch_result"),url:e(),retrieved_at:e().nullable(),content:t({type:a("document"),title:e().nullable(),citations:t({enabled:r()}).optional(),source:p([t({type:a("base64"),media_type:a("application/pdf"),data:e()}),t({type:a("text"),media_type:a("text/plain"),data:e()})])})}),t({type:a("web_fetch_tool_result_error"),error_code:e()})])}),t({type:a("web_search_tool_result"),tool_use_id:e(),caller:De().optional(),content:p([o(t({type:a("web_search_result"),url:e(),title:e().nullable(),encrypted_content:e(),page_age:e().nullish()})),t({type:a("web_search_tool_result_error"),error_code:e()})])}),t({type:a("code_execution_tool_result"),tool_use_id:e(),content:p([t({type:a("code_execution_result"),stdout:e(),stderr:e(),return_code:n(),content:o(t({type:a("code_execution_output"),file_id:e()})).optional().default([])}),t({type:a("encrypted_code_execution_result"),encrypted_stdout:e(),stderr:e(),return_code:n(),content:o(t({type:a("code_execution_output"),file_id:e()})).optional().default([])}),t({type:a("code_execution_tool_result_error"),error_code:e()})])}),t({type:a("bash_code_execution_tool_result"),tool_use_id:e(),content:w("type",[t({type:a("bash_code_execution_result"),content:o(t({type:a("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:n()}),t({type:a("bash_code_execution_tool_result_error"),error_code:e()})])}),t({type:a("text_editor_code_execution_tool_result"),tool_use_id:e(),content:w("type",[t({type:a("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:a("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:n().nullable(),start_line:n().nullable(),total_lines:n().nullable()}),t({type:a("text_editor_code_execution_create_result"),is_file_update:r()}),t({type:a("text_editor_code_execution_str_replace_result"),lines:o(e()).nullable(),new_lines:n().nullable(),new_start:n().nullable(),old_lines:n().nullable(),old_start:n().nullable()})])}),t({type:a("tool_search_tool_result"),tool_use_id:e(),content:p([t({type:a("tool_search_tool_search_result"),tool_references:o(t({type:a("tool_reference"),tool_name:e()}))}),t({type:a("tool_search_tool_result_error"),error_code:e()})])}),t({type:a("advisor_tool_result"),tool_use_id:e(),content:w("type",[t({type:a("advisor_result"),text:e(),stop_reason:e().nullish()}),t({type:a("advisor_redacted_result"),encrypted_content:e(),stop_reason:e().nullish()}),t({type:a("advisor_tool_result_error"),error_code:e()})])}),nt()])}),t({type:a("content_block_delta"),index:n(),delta:w("type",[t({type:a("input_json_delta"),partial_json:e()}),t({type:a("text_delta"),text:e()}),t({type:a("thinking_delta"),thinking:e()}),t({type:a("signature_delta"),signature:e()}),t({type:a("compaction_delta"),content:e().nullish()}),t({type:a("citations_delta"),citation:St()})])}),t({type:a("content_block_stop"),index:n()}),t({type:a("error"),error:t({type:e(),message:e(),code:p([e(),n()]).nullish(),statusCode:n().nullish(),isRetryable:r().nullish(),data:m().nullish()})}),t({type:a("message_delta"),delta:t({stop_reason:e().nullish(),stop_sequence:e().nullish(),stop_details:Tt().nullish(),safeguard_results:o(Ct()).nullish(),container:t({expires_at:e(),id:e(),skills:o(t({type:p([a("anthropic"),a("custom")]),skill_id:e(),version:e()})).nullish()}).nullish()}),usage:ae({input_tokens:n().nullish(),output_tokens:n(),output_tokens_details:t({thinking_tokens:n().nullish()}).nullish(),cache_creation_input_tokens:n().nullish(),cache_read_input_tokens:n().nullish(),iterations:o(t({type:p([a("compaction"),a("message"),a("advisor_message"),a("fallback_message")]),model:e().nullish(),input_tokens:n(),output_tokens:n(),cache_creation_input_tokens:n().nullish(),cache_read_input_tokens:n().nullish()})).nullish()}),input_transformations:o(ot()).nullish(),context_management:t({applied_edits:o(p([t({type:a("clear_tool_uses_20250919"),cleared_tool_uses:n(),cleared_input_tokens:n()}),t({type:a("clear_thinking_20251015"),cleared_thinking_turns:n(),cleared_input_tokens:n()}),t({type:a("compact_20260112")})]))}).nullish()}),t({type:a("message_stop")}),t({type:a("ping")})]))),Zt=u(()=>l(t({signature:e().optional(),redactedData:e().optional()}))),Ye=u(()=>l(t({containerUpload:r().optional(),citations:t({enabled:r()}).optional(),title:e().optional(),context:e().optional()}))),Yt=u(()=>l(t({clearAt:a("next_user_message").optional(),effort:s(["low","medium","high","xhigh","max"]).optional(),toolChanges:o(w("type",[t({type:a("tool_addition"),toolName:e()}),t({type:a("tool_removal"),toolName:e()})])).optional()}))),pt=u(()=>l(t({sendReasoning:r().optional(),structuredOutputMode:s(["outputFormat","jsonTool","auto"]).optional(),thinking:p([w("type",[t({type:a("adaptive"),display:s(["omitted","summarized","updates"]).optional(),blockBinding:t({prefixMismatchBehavior:s(["error","drop_block"])}).optional()}),t({type:a("enabled"),budgetTokens:n().optional()}),t({type:a("disabled")}),t({type:a("between_tools")})]),t({type:le().optional(),blockBinding:t({prefixMismatchBehavior:s(["error","drop_block"])})})]).optional(),disableParallelToolUse:r().optional(),cacheControl:t({type:a("ephemeral"),ttl:p([a("5m"),a("1h")]).optional()}).optional(),metadata:t({userId:e().optional()}).optional(),mcpServers:o(t({type:a("url"),name:e(),url:e(),authorizationToken:e().nullish(),toolConfiguration:t({enabled:r().nullish(),allowedTools:o(e()).nullish()}).nullish()})).optional(),container:t({id:e().optional(),skills:o(w("type",[t({type:a("anthropic"),skillId:e(),version:e().optional()}),t({type:a("custom"),providerReference:d(e(),e()),version:e().optional()})])).optional()}).optional(),toolStreaming:r().optional(),effort:s(["low","medium","high","xhigh","max"]).optional(),taskBudget:t({type:a("tokens"),total:n().int().min(20000),remaining:n().int().min(0).optional()}).optional(),speed:s(["fast","standard"]).optional(),serviceTier:s(["auto","standard_only"]).optional(),inferenceGeo:s(["us","global"]).optional(),fallbacks:p([a("default"),o(t({model:e(),max_tokens:n().int().optional(),thinking:d(e(),m()).optional(),output_config:d(e(),m()).optional(),speed:s(["fast","standard"]).optional()}))]).optional(),anthropicBeta:o(e()).optional(),safeguards:o(t({type:a("dangerous_tool_use"),classifierContext:d(e(),m()).optional()})).optional(),compaction:t({type:a("summarize"),instructions:e().optional()}).optional(),contextManagement:t({edits:o(w("type",[t({type:a("clear_tool_uses_20250919"),trigger:w("type",[t({type:a("input_tokens"),value:n()}),t({type:a("tool_uses"),value:n()})]).optional(),keep:t({type:a("tool_uses"),value:n()}).optional(),clearAtLeast:t({type:a("input_tokens"),value:n()}).optional(),clearToolInputs:r().optional(),excludeTools:o(e()).optional()}),t({type:a("clear_thinking_20251015"),keep:p([a("all"),t({type:a("thinking_turns"),value:n()})]).optional()}),t({type:a("compact_20260112"),trigger:t({type:a("input_tokens"),value:n()}).optional(),pauseAfterCompaction:r().optional(),instructions:e().optional()})]))}).optional()}))),dt=4;function Qt(i,h){let g=i?.[h],D=i?.anthropic;return g?.cacheControl??g?.cache_control??D?.cacheControl??D?.cache_control}var rt=class{constructor(i="anthropic"){this.providerOptionsName=i,this.breakpointCount=0,this.warnings=[]}getCacheControl(i,h){let g=Qt(i,this.providerOptionsName);if(!g)return;if(!h.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${h.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>dt){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${dt} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return g}getWarnings(){return this.warnings}},eo=u(()=>l(t({model:e(),maxUses:n().optional(),maxTokens:n().int().min(1024).optional(),caching:t({type:a("ephemeral"),ttl:p([a("5m"),a("1h")])}).optional()}))),Ot=u(()=>l(w("type",[t({type:a("advisor_result"),text:e(),stopReason:e().optional()}),t({type:a("advisor_redacted_result"),encryptedContent:e(),stopReason:e().optional()}),t({type:a("advisor_tool_result_error"),errorCode:e()})]))),to=u(()=>l(t({}).strict())),oo=G({id:"anthropic.advisor_20260301",inputSchema:to,outputSchema:Ot,supportsDeferredResults:!0}),no=(i)=>oo(i),It=["screenshot","zoom","left_click","right_click","middle_click","double_click","triple_click","left_click_drag","mouse_move","left_mouse_down","left_mouse_up","cursor_position","scroll","type","key","hold_key","wait"],ro=u(()=>l(t({action:s(It),coordinate:M([n().int(),n().int()]).optional(),duration:n().optional(),region:M([n().int(),n().int(),n().int(),n().int()]).optional(),repeat:n().int().optional(),scroll_amount:n().optional(),scroll_direction:s(["up","down","left","right"]).optional(),start_coordinate:M([n().int(),n().int()]).optional(),text:e().optional()}))),io=u(()=>l(t({configs:on(s(It),t({enabled:r().optional(),deferLoading:r().optional()})).optional()}))),ao=Re({id:"anthropic.computer_toolset_20260801",inputSchema:ro}),so=u(()=>l(t({maxCharacters:n().optional()}))),lo=u(()=>l(t({command:s(["view","create","str_replace","insert"]),path:e(),file_text:e().optional(),insert_line:n().int().optional(),new_str:e().optional(),insert_text:e().optional(),old_str:e().optional(),view_range:o(n().int()).optional()}))),co=Re({id:"anthropic.text_editor_20250728",inputSchema:lo}),uo=(i={})=>co(i),po=u(()=>l(t({maxUses:n().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),userLocation:t({type:a("approximate"),city:e().optional(),region:e().optional(),country:e().optional(),timezone:e().optional()}).optional(),responseInclusion:s(["full","excluded"]).optional()}))),_o=u(()=>l(o(t({url:e(),title:e().nullable(),pageAge:e().nullable(),encryptedContent:e(),type:a("web_search_result")})))),ho=u(()=>l(t({query:e()}))),mo=G({id:"anthropic.web_search_20260318",inputSchema:ho,outputSchema:_o,supportsDeferredResults:!0}),go=(i={})=>mo(i),fo=u(()=>l(t({maxUses:n().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),userLocation:t({type:a("approximate"),city:e().optional(),region:e().optional(),country:e().optional(),timezone:e().optional()}).optional()}))),yo=u(()=>l(o(t({url:e(),title:e().nullable(),pageAge:e().nullable(),encryptedContent:e(),type:a("web_search_result")})))),bo=u(()=>l(t({query:e()}))),xo=G({id:"anthropic.web_search_20260209",inputSchema:bo,outputSchema:yo,supportsDeferredResults:!0}),ko=(i={})=>xo(i),vo=u(()=>l(t({maxUses:n().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),userLocation:t({type:a("approximate"),city:e().optional(),region:e().optional(),country:e().optional(),timezone:e().optional()}).optional()}))),At=u(()=>l(o(t({url:e(),title:e().nullable(),pageAge:e().nullable(),encryptedContent:e(),type:a("web_search_result")})))),wo=u(()=>l(t({query:e()}))),jo=G({id:"anthropic.web_search_20250305",inputSchema:wo,outputSchema:At,supportsDeferredResults:!0}),To=(i={})=>jo(i),So=u(()=>l(t({maxUses:n().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),citations:t({enabled:r()}).optional(),maxContentTokens:n().optional(),useCache:r().optional(),responseInclusion:s(["full","excluded"]).optional()}))),No=u(()=>l(t({type:a("web_fetch_result"),url:e(),content:t({type:a("document"),title:e().nullable(),citations:t({enabled:r()}).optional(),source:p([t({type:a("base64"),mediaType:a("application/pdf"),data:e()}),t({type:a("text"),mediaType:a("text/plain"),data:e()})])}),retrievedAt:e().nullable()}))),Oo=u(()=>l(t({url:e()}))),Io=G({id:"anthropic.web_fetch_20260318",inputSchema:Oo,outputSchema:No,supportsDeferredResults:!0}),Ao=(i={})=>Io(i),Eo=u(()=>l(t({maxUses:n().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),citations:t({enabled:r()}).optional(),maxContentTokens:n().optional()}))),Ro=u(()=>l(t({type:a("web_fetch_result"),url:e(),content:t({type:a("document"),title:e().nullable(),citations:t({enabled:r()}).optional(),source:p([t({type:a("base64"),mediaType:a("application/pdf"),data:e()}),t({type:a("text"),mediaType:a("text/plain"),data:e()})])}),retrievedAt:e().nullable()}))),Mo=u(()=>l(t({url:e()}))),$o=G({id:"anthropic.web_fetch_20260209",inputSchema:Mo,outputSchema:Ro,supportsDeferredResults:!0}),Uo=(i={})=>$o(i),qo=u(()=>l(t({maxUses:n().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),citations:t({enabled:r()}).optional(),maxContentTokens:n().optional()}))),Et=u(()=>l(t({type:a("web_fetch_result"),url:e(),content:t({type:a("document"),title:e().nullable(),citations:t({enabled:r()}).optional(),source:p([t({type:a("base64"),mediaType:a("application/pdf"),data:e()}),t({type:a("text"),mediaType:a("text/plain"),data:e()})])}),retrievedAt:e().nullable()}))),Bo=u(()=>l(t({url:e()}))),Po=G({id:"anthropic.web_fetch_20250910",inputSchema:Bo,outputSchema:Et,supportsDeferredResults:!0}),Fo=(i={})=>Po(i);async function by({tools:i,toolChoice:h,disableParallelToolUse:g,cacheControlValidator:D,supportsStructuredOutput:L,supportsStrictTools:se,defaultEagerInputStreaming:q=!1,rejectsForcedToolUse:ue=!1}){i=i?.length?i:void 0;let ce=[],K=new Set,je=D||new rt;if(i==null)return{tools:void 0,toolChoice:void 0,toolWarnings:ce,betas:K};let X=[];for(let Z of i)switch(Z.type){case"function":{let v=je.getCacheControl(Z.providerOptions,{type:"tool definition",canCache:!0}),de=Z.providerOptions?.anthropic,fe=de?.eagerInputStreaming??q,ke=de?.deferLoading,he=de?.allowedCallers;if(!se&&Z.strict===!0)ce.push({type:"unsupported",feature:"strict",details:`Tool '${Z.name}' has strict: ${Z.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`});if(X.push({name:Z.name,description:Z.description,input_schema:Z.inputSchema,cache_control:v,...fe?{eager_input_streaming:!0}:{},...se===!0&&Z.strict!=null?{strict:Z.strict}:{},...ke!=null?{defer_loading:ke}:{},...he!=null?{allowed_callers:he}:{},...Z.inputExamples!=null?{input_examples:Z.inputExamples.map((c)=>c.input)}:{}}),L===!0)K.add("structured-outputs-2025-11-13");if(Z.inputExamples!=null||he!=null)K.add("advanced-tool-use-2025-11-20");break}case"provider":switch(Z.id){case"anthropic.code_execution_20250522":K.add("code-execution-2025-05-22"),X.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break;case"anthropic.code_execution_20250825":K.add("code-execution-2025-08-25"),X.push({type:"code_execution_20250825",name:"code_execution"});break;case"anthropic.code_execution_20260120":X.push({type:"code_execution_20260120",name:"code_execution"});break;case"anthropic.computer_20250124":K.add("computer-use-2025-01-24"),X.push({name:"computer",type:"computer_20250124",display_width_px:Z.args.displayWidthPx,display_height_px:Z.args.displayHeightPx,display_number:Z.args.displayNumber,cache_control:void 0});break;case"anthropic.computer_20251124":K.add("computer-use-2025-11-24"),X.push({name:"computer",type:"computer_20251124",display_width_px:Z.args.displayWidthPx,display_height_px:Z.args.displayHeightPx,display_number:Z.args.displayNumber,enable_zoom:Z.args.enableZoom,cache_control:void 0});break;case"anthropic.computer_toolset_20260801":{let v=await z({value:Z.args,schema:io}),de=v.configs!=null?Object.fromEntries(Object.entries(v.configs).map(([fe,ke])=>[fe,{...ke?.enabled!=null&&{enabled:ke.enabled},...ke?.deferLoading!=null&&{defer_loading:ke.deferLoading}}])):void 0;X.push({type:"computer_toolset_20260801",...de!=null&&{configs:de},cache_control:void 0});break}case"anthropic.computer_20241022":K.add("computer-use-2024-10-22"),X.push({name:"computer",type:"computer_20241022",display_width_px:Z.args.displayWidthPx,display_height_px:Z.args.displayHeightPx,display_number:Z.args.displayNumber,cache_control:void 0});break;case"anthropic.text_editor_20250124":K.add("computer-use-2025-01-24"),X.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break;case"anthropic.text_editor_20241022":K.add("computer-use-2024-10-22"),X.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break;case"anthropic.text_editor_20250429":K.add("computer-use-2025-01-24"),X.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break;case"anthropic.text_editor_20250728":{let v=await z({value:Z.args,schema:so});X.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:v.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":K.add("computer-use-2025-01-24"),X.push({name:"bash",type:"bash_20250124",cache_control:void 0});break;case"anthropic.bash_20241022":K.add("computer-use-2024-10-22"),X.push({name:"bash",type:"bash_20241022",cache_control:void 0});break;case"anthropic.memory_20250818":K.add("context-management-2025-06-27"),X.push({name:"memory",type:"memory_20250818"});break;case"anthropic.web_fetch_20250910":{K.add("web-fetch-2025-09-10");let v=await z({value:Z.args,schema:qo});X.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:v.maxUses,allowed_domains:v.allowedDomains,blocked_domains:v.blockedDomains,citations:v.citations,max_content_tokens:v.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{K.add("code-execution-web-tools-2026-02-09");let v=await z({value:Z.args,schema:Eo});X.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:v.maxUses,allowed_domains:v.allowedDomains,blocked_domains:v.blockedDomains,citations:v.citations,max_content_tokens:v.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260318":{let v=await z({value:Z.args,schema:So});X.push({type:"web_fetch_20260318",name:"web_fetch",max_uses:v.maxUses,allowed_domains:v.allowedDomains,blocked_domains:v.blockedDomains,citations:v.citations,max_content_tokens:v.maxContentTokens,use_cache:v.useCache,response_inclusion:v.responseInclusion,cache_control:void 0});break}case"anthropic.web_search_20250305":{let v=await z({value:Z.args,schema:vo});X.push({type:"web_search_20250305",name:"web_search",max_uses:v.maxUses,allowed_domains:v.allowedDomains,blocked_domains:v.blockedDomains,user_location:v.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{K.add("code-execution-web-tools-2026-02-09");let v=await z({value:Z.args,schema:fo});X.push({type:"web_search_20260209",name:"web_search",max_uses:v.maxUses,allowed_domains:v.allowedDomains,blocked_domains:v.blockedDomains,user_location:v.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260318":{let v=await z({value:Z.args,schema:po});X.push({type:"web_search_20260318",name:"web_search",max_uses:v.maxUses,allowed_domains:v.allowedDomains,blocked_domains:v.blockedDomains,user_location:v.userLocation,response_inclusion:v.responseInclusion,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":X.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break;case"anthropic.tool_search_bm25_20251119":X.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break;case"anthropic.advisor_20260301":{K.add("advisor-tool-2026-03-01");let v=await z({value:Z.args,schema:eo});X.push({type:"advisor_20260301",name:"advisor",model:v.model,...v.maxUses!==void 0&&{max_uses:v.maxUses},...v.maxTokens!==void 0&&{max_tokens:v.maxTokens},...v.caching!==void 0&&{caching:v.caching}});break}default:ce.push({type:"unsupported",feature:`provider-defined tool ${Z.id}`})}break;default:ce.push({type:"unsupported",feature:`tool ${Z}`})}if(h==null)return{tools:X,toolChoice:g?{type:"auto",disable_parallel_tool_use:g}:void 0,toolWarnings:ce,betas:K};let ne=h.type;switch(ne){case"auto":return{tools:X,toolChoice:{type:"auto",disable_parallel_tool_use:g},toolWarnings:ce,betas:K};case"required":if(ue)return ce.push({type:"unsupported",feature:"toolChoice",details:"toolChoice 'required' is not supported with this model or thinking configuration. Using 'auto' instead. Instruct the model to use a tool in the prompt and verify that a tool call was made."}),{tools:X,toolChoice:{type:"auto",disable_parallel_tool_use:g},toolWarnings:ce,betas:K};return{tools:X,toolChoice:{type:"any",disable_parallel_tool_use:g},toolWarnings:ce,betas:K};case"none":return{tools:X,toolChoice:{type:"none"},toolWarnings:ce,betas:K};case"tool":if(ue)return ce.push({type:"unsupported",feature:"toolChoice",details:`toolChoice 'tool' is not supported with this model or thinking configuration. Only the '${h.toolName}' tool is sent with 'auto' tool choice. Instruct the model to use the tool in the prompt and verify that a tool call was made.`}),{tools:X.filter((Z)=>("name"in Z)&&Z.name===h.toolName),toolChoice:{type:"auto",disable_parallel_tool_use:g},toolWarnings:ce,betas:K};return{tools:X,toolChoice:{type:"tool",name:h.toolName,disable_parallel_tool_use:g},toolWarnings:ce,betas:K};default:throw new b({functionality:`tool choice type: ${ne}`})}}function _t({usage:i,rawUsage:h}){let g=i.cache_creation_input_tokens??0,D=i.cache_read_input_tokens??0,L=i.output_tokens_details?.thinking_tokens??void 0,se,q,ue=i.iterations?.some((ce)=>ce.type==="fallback_message");if(i.iterations&&i.iterations.length>0&&!ue){let ce=i.iterations.filter((K)=>K.type==="compaction"||K.type==="message");if(ce.length>0){let K=ce.reduce((je,X)=>({input:je.input+X.input_tokens,output:je.output+X.output_tokens}),{input:0,output:0});se=K.input,q=K.output}else se=i.input_tokens,q=i.output_tokens}else se=i.input_tokens,q=i.output_tokens;return{inputTokens:{total:se+g+D,noCache:se,cacheRead:D,cacheWrite:g},outputTokens:{total:q,text:L==null?void 0:q-L,reasoning:L},raw:h??i}}var Rt=u(()=>l(t({type:a("code_execution_result"),stdout:e(),stderr:e(),return_code:n(),content:o(t({type:a("code_execution_output"),file_id:e()})).optional().default([])}))),Ho=u(()=>l(t({code:e()}))),Lo=G({id:"anthropic.code_execution_20250522",inputSchema:Ho,outputSchema:Rt}),Jo=(i={})=>Lo(i),Mt=u(()=>l(w("type",[t({type:a("code_execution_result"),stdout:e(),stderr:e(),return_code:n(),content:o(t({type:a("code_execution_output"),file_id:e()})).optional().default([])}),t({type:a("bash_code_execution_result"),content:o(t({type:a("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:n()}),t({type:a("bash_code_execution_tool_result_error"),error_code:e()}),t({type:a("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:a("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:n().nullable(),start_line:n().nullable(),total_lines:n().nullable()}),t({type:a("text_editor_code_execution_create_result"),is_file_update:r()}),t({type:a("text_editor_code_execution_str_replace_result"),lines:o(e()).nullable(),new_lines:n().nullable(),new_start:n().nullable(),old_lines:n().nullable(),old_start:n().nullable()})]))),zo=u(()=>l(w("type",[t({type:a("programmatic-tool-call"),code:e()}),t({type:a("bash_code_execution"),command:e()}),w("command",[t({type:a("text_editor_code_execution"),command:a("view"),path:e()}),t({type:a("text_editor_code_execution"),command:a("create"),path:e(),file_text:e().nullish()}),t({type:a("text_editor_code_execution"),command:a("str_replace"),path:e(),old_str:e(),new_str:e()})])]))),Wo=G({id:"anthropic.code_execution_20250825",inputSchema:zo,outputSchema:Mt,supportsDeferredResults:!0}),Ko=(i={})=>Do(Wo(i),{type:"provider",prepareProviderOptions:(h)=>{let g=h?.anthropic;return{...h,anthropic:{...g,allowedCallers:[...new Set([...g?.allowedCallers??[],"code_execution_20250825"])]}}}}),Dt=u(()=>l(w("type",[t({type:a("code_execution_result"),stdout:e(),stderr:e(),return_code:n(),content:o(t({type:a("code_execution_output"),file_id:e()})).optional().default([])}),t({type:a("encrypted_code_execution_result"),encrypted_stdout:e(),stderr:e(),return_code:n(),content:o(t({type:a("code_execution_output"),file_id:e()})).optional().default([])}),t({type:a("bash_code_execution_result"),content:o(t({type:a("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:n()}),t({type:a("bash_code_execution_tool_result_error"),error_code:e()}),t({type:a("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:a("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:n().nullable(),start_line:n().nullable(),total_lines:n().nullable()}),t({type:a("text_editor_code_execution_create_result"),is_file_update:r()}),t({type:a("text_editor_code_execution_str_replace_result"),lines:o(e()).nullable(),new_lines:n().nullable(),new_start:n().nullable(),old_lines:n().nullable(),old_start:n().nullable()})]))),Vo=u(()=>l(w("type",[t({type:a("programmatic-tool-call"),code:e()}),t({type:a("bash_code_execution"),command:e()}),w("command",[t({type:a("text_editor_code_execution"),command:a("view"),path:e()}),t({type:a("text_editor_code_execution"),command:a("create"),path:e(),file_text:e().nullish()}),t({type:a("text_editor_code_execution"),command:a("str_replace"),path:e(),old_str:e(),new_str:e()})])]))),Xo=G({id:"anthropic.code_execution_20260120",inputSchema:Vo,outputSchema:Dt,supportsDeferredResults:!0}),Go=(i={})=>Do(Xo(i),{type:"provider",prepareProviderOptions:(h)=>{let g=h?.anthropic;return{...h,anthropic:{...g,allowedCallers:[...new Set([...g?.allowedCallers??[],"code_execution_20260120"])]}}}}),$t=u(()=>l(o(t({type:a("tool_reference"),toolName:e()})))),Zo=u(()=>l(t({pattern:e(),limit:n().optional()}))),Yo=G({id:"anthropic.tool_search_regex_20251119",inputSchema:Zo,outputSchema:$t,supportsDeferredResults:!0}),Qo=(i={})=>Yo(i);function tn(i){if(typeof i==="string")return new TextDecoder().decode(Te(i));return new TextDecoder().decode(i)}function Qe(i){try{if(typeof i==="string")return Ke(i);else if(typeof i==="object"&&i!==null)return i}catch{let h=i?.errorCode;return{errorCode:typeof h==="string"?h:"unavailable"}}return{}}async function nn({prompt:i,sendReasoning:h,warnings:g,cacheControlValidator:D,toolNameMapping:L,toolsetNames:se={},convertMediaPart:q}){let ue=new Set,ce=rn(i),K=D||new rt,je=void 0,X=[],ne=-1;async function Z(he){return(await k({provider:"anthropic",providerOptions:he,schema:Ye}))?.citations?.enabled??!1}async function v(he){return(await k({provider:"anthropic",providerOptions:he,schema:Ye}))?.containerUpload??!1}async function de(he){let c=await k({provider:"anthropic",providerOptions:he,schema:Ye});return{title:c?.title,context:c?.context}}for(let he=0;he<ce.length;he++){let c=ce[he],V=he===ce.length-1,ye=c.type;switch(ye){case"system":{let O=[];for(let{content:ie,providerOptions:f}of c.messages){let B=await k({provider:"anthropic",providerOptions:f,schema:Yt}),me=B?.toolChanges??[],y=[];if(ie!==""||me.length===0&&B?.clearAt==null&&B?.effort==null)y.push({type:"text",text:ie,cache_control:K.getCacheControl(f,{type:"system message",canCache:!0})});for(let Se of me)y.push({type:Se.type,tool:{type:"tool_reference",name:L.toProviderToolName(Se.toolName)}});O.push({content:y,clearAt:B?.clearAt,effort:B?.effort,toolChangeCount:me.length})}let Ne=O.reduce((ie,f)=>ie+f.toolChangeCount,0),Oe=O.some((ie)=>ie.clearAt!=null||ie.effort!=null);if(he===0||je==null&&Ne===0&&!Oe){if(Ne>0)g.push({type:"other",message:"tool changes on the initial system message are not supported by Anthropic. Configure the initial tool set via the tools option instead. The tool changes have been ignored."});for(let ie of O)if(ie.content.length===0&&ie.clearAt==null&&ie.effort!=null)X.push({role:"system",content:[],output_config:{effort:ie.effort}}),ue.add("mid-conversation-output-config-2026-07-01");else if(ie.clearAt!=null||ie.effort!=null)g.push({type:"other",message:"clearAt and effort on this initial system message are not supported by Anthropic. Use a separate effort-only system message with empty content to set effort. These options have been ignored."});je=O.flatMap((ie)=>ie.content.filter((f)=>f.type==="text"))}else{ue.add("mid-conversation-system-2026-04-07");for(let ie of O){if(X.push({role:"system",content:ie.content,...ie.clearAt!=null&&{clear_at:ie.clearAt},...ie.effort!=null&&{output_config:{effort:ie.effort}}}),ie.toolChangeCount>0)ue.add("mid-conversation-tool-changes-2026-07-01");if(ie.clearAt!=null)ue.add("mid-conversation-system-clear-at-2026-08-21");if(ie.effort!=null)ue.add("mid-conversation-output-config-2026-07-01")}}break}case"user":{let O=[];for(let Ne of c.messages){let{role:Oe,content:ie}=Ne;switch(Oe){case"user":if(ie.length>0)ne=X.length;for(let f=0;f<ie.length;f++){let B=ie[f],me=f===ie.length-1,y=K.getCacheControl(B.providerOptions,{type:"user message part",canCache:!0})??(me?K.getCacheControl(Ne.providerOptions,{type:"user message",canCache:!0}):void 0);switch(B.type){case"text":O.push({type:"text",text:B.text,cache_control:y});break;case"file":{let Se=await q?.(B);if(Se!=null){O.push({...Se,cache_control:y});break}switch(B.data.type){case"reference":{let re=$e({reference:B.data.reference,provider:"anthropic"});if(ue.add("files-api-2025-04-14"),await v(B.providerOptions))O.push({type:"container_upload",file_id:re});else if(ge(B.mediaType)==="image")O.push({type:"image",source:{type:"file",file_id:re},cache_control:y});else O.push({type:"document",source:{type:"file",file_id:re},cache_control:y});break}case"text":{let re=await Z(B.providerOptions),P=await de(B.providerOptions);O.push({type:"document",source:{type:"text",media_type:"text/plain",data:B.data.text},title:P.title??B.filename,...P.context&&{context:P.context},...re&&{citations:{enabled:!0}},cache_control:y});break}case"url":case"data":{let re=ge(B.mediaType);if(re==="image")O.push({type:"image",source:B.data.type==="url"?{type:"url",url:B.data.url.toString()}:{type:"base64",media_type:ee({part:B}),data:j(B.data.data)},cache_control:y});else if(re==="application"&&(B.data.type==="url"?B.mediaType==="application/pdf":ee({part:B})==="application/pdf")){ue.add("pdfs-2024-09-25");let P=await Z(B.providerOptions),_e=await de(B.providerOptions);O.push({type:"document",source:B.data.type==="url"?{type:"url",url:B.data.url.toString()}:{type:"base64",media_type:"application/pdf",data:j(B.data.data)},title:_e.title??B.filename,..._e.context&&{context:_e.context},...P&&{citations:{enabled:!0}},cache_control:y})}else if(B.mediaType==="text/plain"){let P=await Z(B.providerOptions),_e=await de(B.providerOptions);O.push({type:"document",source:B.data.type==="url"?{type:"url",url:B.data.url.toString()}:{type:"text",media_type:"text/plain",data:tn(B.data.data)},title:_e.title??B.filename,..._e.context&&{context:_e.context},...P&&{citations:{enabled:!0}},cache_control:y})}else throw new b({functionality:`media type: ${B.mediaType}`});break}}break}}}break;case"tool":for(let f=0;f<ie.length;f++){let B=ie[f];if(B.type==="tool-approval-response")continue;let me=B.output,y="providerOptions"in me?me.providerOptions:me.type==="content"?me.value.find((T)=>T.providerOptions!=null)?.providerOptions:void 0,Se=f===ie.length-1,re=K.getCacheControl(B.providerOptions,{type:"tool result part",canCache:!0})??K.getCacheControl(y,{type:"tool result output",canCache:!0})??(Se?K.getCacheControl(Ne.providerOptions,{type:"tool result message",canCache:!0}):void 0),P;switch(me.type){case"content":P=me.value.map((T)=>{switch(T.type){case"text":return{type:"text",text:T.text};case"file":{let S=ge(T.mediaType);if(T.data.type==="reference"){let xe=$e({reference:T.data.reference,provider:"anthropic"});if(ue.add("files-api-2025-04-14"),S==="image")return{type:"image",source:{type:"file",file_id:xe}};return{type:"document",source:{type:"file",file_id:xe}}}if(T.data.type==="url"){if(S==="image")return{type:"image",source:{type:"url",url:T.data.url.toString()}};return{type:"document",source:{type:"url",url:T.data.url.toString()}}}if(T.data.type==="data"){if(S==="image")return{type:"image",source:{type:"base64",media_type:ee({part:T}),data:j(T.data.data)}};if(ee({part:T})==="application/pdf")return ue.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:"application/pdf",data:j(T.data.data)}};g.push({type:"other",message:`unsupported tool content part type: ${T.type} with media type: ${T.mediaType}`});return}g.push({type:"other",message:`unsupported tool content part type: ${T.type} with data type: ${T.data.type}`});return}case"custom":{let S=T.providerOptions?.anthropic;if(S?.type==="tool-reference")return{type:"tool_reference",tool_name:S.toolName};g.push({type:"other",message:"unsupported custom tool content part"});return}default:g.push({type:"other",message:`unsupported tool content part type: ${T.type}`});return}}).filter(Co);break;case"text":case"error-text":P=me.value;break;case"execution-denied":P=me.reason??"Tool call execution denied.";break;default:P=JSON.stringify(me.value)}let _e=ht({toolName:B.toolName,providerOptions:B.providerOptions,toolsetNames:se});O.push({type:"tool_result",tool_use_id:B.toolCallId,..._e!=null&&{toolset_name:_e},content:P,is_error:me.type==="error-text"||me.type==="error-json"?!0:void 0,cache_control:re})}break;default:throw Error(`Unsupported role: ${Oe}`)}}X.push({role:"user",content:O});break}case"assistant":{let O=[],Ne=new Set;for(let Oe=0;Oe<c.messages.length;Oe++){let ie=c.messages[Oe],f=Oe===c.messages.length-1,{content:B}=ie;for(let me=0;me<B.length;me++){let y=B[me],Se=me===B.length-1,re=K.getCacheControl(y.providerOptions,{type:"assistant message part",canCache:!0})??(Se?K.getCacheControl(ie.providerOptions,{type:"assistant message",canCache:!0}):void 0);switch(y.type){case"text":{let P=y.providerOptions?.anthropic;if(P?.type==="compaction"){if(y.text==="")break;if(typeof P.signature==="string")ue.add("compact-2026-09-04");O.push({type:"compaction",content:y.text,...typeof P.signature==="string"&&{signature:P.signature},cache_control:re})}else O.push({type:"text",text:V&&f&&Se?y.text.trim():y.text,...P?.citations!=null&&{citations:P.citations},cache_control:re});break}case"reasoning":if(h){let P=await k({provider:"anthropic",providerOptions:y.providerOptions,schema:Zt});if(P!=null)if(P.signature!=null)K.getCacheControl(y.providerOptions,{type:"thinking block",canCache:!1}),O.push({type:"thinking",thinking:y.text,signature:P.signature});else if(P.redactedData!=null)K.getCacheControl(y.providerOptions,{type:"redacted thinking block",canCache:!1}),O.push({type:"redacted_thinking",data:P.redactedData});else g.push({type:"other",message:"unsupported reasoning metadata"});else g.push({type:"other",message:"unsupported reasoning metadata"})}else g.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"custom":{if(y.kind!=="anthropic.fallback")break;let P=await Pe({value:y.providerOptions?.anthropic,schema:Vt});if(!P.success){g.push({type:"other",message:"anthropic fallback metadata must include from.model and to.model"});break}ue.add("server-side-fallback-2026-06-01"),O.push({type:"fallback",from:P.value.from,to:P.value.to});break}case"tool-call":{let P=mt(y.providerOptions);if(y.providerExecuted){let T=L.toProviderToolName(y.toolName);if(y.providerOptions?.anthropic?.type==="mcp-tool-use"){Ne.add(y.toolCallId);let S=y.providerOptions?.anthropic?.serverName;if(S==null||typeof S!=="string"){g.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}O.push({type:"mcp_tool_use",id:y.toolCallId,name:y.toolName,input:y.input,server_name:S,cache_control:re})}else if(T==="code_execution"&&y.input!=null&&typeof y.input==="object"&&"type"in y.input&&typeof y.input.type==="string"&&(y.input.type==="bash_code_execution"||y.input.type==="text_editor_code_execution")){let{type:S,...xe}=y.input;O.push({type:"server_tool_use",id:y.toolCallId,name:S,input:xe,...P&&{caller:P},cache_control:re})}else if(T==="code_execution"&&y.input!=null&&typeof y.input==="object"&&"type"in y.input&&y.input.type==="programmatic-tool-call"){let{type:S,...xe}=y.input;O.push({type:"server_tool_use",id:y.toolCallId,name:"code_execution",input:xe,...P&&{caller:P},cache_control:re})}else if(T==="code_execution"||T==="web_fetch"||T==="web_search")O.push({type:"server_tool_use",id:y.toolCallId,name:T,input:y.input,...P&&{caller:P},cache_control:re});else if(T==="tool_search_tool_regex"||T==="tool_search_tool_bm25")O.push({type:"server_tool_use",id:y.toolCallId,name:T,input:y.input,...P&&{caller:P},cache_control:re});else if(T==="advisor")O.push({type:"server_tool_use",id:y.toolCallId,name:"advisor",input:{},...P&&{caller:P},cache_control:re});else g.push({type:"other",message:`provider executed tool call for tool ${y.toolName} is not supported`});break}let _e=ht({toolName:y.toolName,providerOptions:y.providerOptions,toolsetNames:se});if(_e!=null){let T=gt(y.input),{action:S}=T,xe=typeof S==="string";if(!xe)g.push({type:"other",message:`toolset tool call for tool ${y.toolName} is missing the action`});O.push({type:"tool_use",id:y.toolCallId,name:xe?S:_e,toolset_name:_e,input:T,...P&&{caller:P},cache_control:re});break}O.push({type:"tool_use",id:y.toolCallId,name:y.toolName,input:gt(y.input),...P&&{caller:P},cache_control:re});break}case"tool-result":{let P=L.toProviderToolName(y.toolName),_e=mt(y.providerOptions);if(Ne.has(y.toolCallId)){let T=y.output;if(T.type!=="json"&&T.type!=="error-json"){g.push({type:"other",message:`provider executed tool result output type ${T.type} for tool ${y.toolName} is not supported`});break}O.push({type:"mcp_tool_result",tool_use_id:y.toolCallId,is_error:T.type==="error-json",content:T.value,cache_control:re})}else if(P==="code_execution"){let T=y.output;if(T.type==="error-text"||T.type==="error-json"){let S={};try{if(typeof T.value==="string")S=Ke(T.value);else if(typeof T.value==="object"&&T.value!==null)S=T.value}catch{}if(S.type==="code_execution_tool_result_error")O.push({type:"code_execution_tool_result",tool_use_id:y.toolCallId,content:{type:"code_execution_tool_result_error",error_code:S.errorCode??"unknown"},cache_control:re});else O.push({type:"bash_code_execution_tool_result",tool_use_id:y.toolCallId,cache_control:re,content:{type:"bash_code_execution_tool_result_error",error_code:S.errorCode??"unknown"}});break}if(T.type!=="json"){g.push({type:"other",message:`provider executed tool result output type ${T.type} for tool ${y.toolName} is not supported`});break}if(T.value==null||typeof T.value!=="object"||!("type"in T.value)||typeof T.value.type!=="string"){g.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${y.toolName}`});break}if(T.value.type==="code_execution_result"){let S=await z({value:T.value,schema:Rt});O.push({type:"code_execution_tool_result",tool_use_id:y.toolCallId,content:{type:S.type,stdout:S.stdout,stderr:S.stderr,return_code:S.return_code,content:S.content??[]},cache_control:re})}else if(T.value.type==="encrypted_code_execution_result"){let S=await z({value:T.value,schema:Dt});if(S.type==="encrypted_code_execution_result")O.push({type:"code_execution_tool_result",tool_use_id:y.toolCallId,content:{type:S.type,encrypted_stdout:S.encrypted_stdout,stderr:S.stderr,return_code:S.return_code,content:S.content??[]},cache_control:re})}else{let S=await z({value:T.value,schema:Mt});if(S.type==="code_execution_result")O.push({type:"code_execution_tool_result",tool_use_id:y.toolCallId,content:{type:S.type,stdout:S.stdout,stderr:S.stderr,return_code:S.return_code,content:S.content??[]},cache_control:re});else if(S.type==="bash_code_execution_result"||S.type==="bash_code_execution_tool_result_error")O.push({type:"bash_code_execution_tool_result",tool_use_id:y.toolCallId,cache_control:re,content:S.type==="bash_code_execution_result"?{type:S.type,stdout:S.stdout,stderr:S.stderr,return_code:S.return_code,content:S.content}:S});else O.push({type:"text_editor_code_execution_tool_result",tool_use_id:y.toolCallId,cache_control:re,content:S})}break}if(P==="web_fetch"){let T=y.output;if(T.type==="error-json"){O.push({type:"web_fetch_tool_result",tool_use_id:y.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:Qe(T.value).errorCode??"unavailable"},..._e&&{caller:_e},cache_control:re});break}if(T.type!=="json"){g.push({type:"other",message:`provider executed tool result output type ${T.type} for tool ${y.toolName} is not supported`});break}let S=await z({value:T.value,schema:Et});O.push({type:"web_fetch_tool_result",tool_use_id:y.toolCallId,content:{type:"web_fetch_result",url:S.url,retrieved_at:S.retrievedAt,content:{type:"document",title:S.content.title,citations:S.content.citations,source:{type:S.content.source.type,media_type:S.content.source.mediaType,data:S.content.source.data}}},..._e&&{caller:_e},cache_control:re});break}if(P==="web_search"){let T=y.output;if(T.type==="error-json"){O.push({type:"web_search_tool_result",tool_use_id:y.toolCallId,content:{type:"web_search_tool_result_error",error_code:Qe(T.value).errorCode??"unavailable"},..._e&&{caller:_e},cache_control:re});break}if(T.type!=="json"){g.push({type:"other",message:`provider executed tool result output type ${T.type} for tool ${y.toolName} is not supported`});break}let S=await z({value:T.value,schema:At});O.push({type:"web_search_tool_result",tool_use_id:y.toolCallId,content:S.map((xe)=>({url:xe.url,title:xe.title,page_age:xe.pageAge,encrypted_content:xe.encryptedContent,type:xe.type})),..._e&&{caller:_e},cache_control:re});break}if(P==="tool_search_tool_regex"||P==="tool_search_tool_bm25"){let T=y.output;if(T.type==="error-json"||T.type==="json"&&T.value!=null&&typeof T.value==="object"&&!Array.isArray(T.value)&&"type"in T.value&&T.value.type==="tool_search_tool_result_error"){O.push({type:"tool_search_tool_result",tool_use_id:y.toolCallId,content:{type:"tool_search_tool_result_error",error_code:Qe(T.value).errorCode??"unavailable"},cache_control:re});break}if(T.type!=="json"){g.push({type:"other",message:`provider executed tool result output type ${T.type} for tool ${y.toolName} is not supported`});break}let S=(await z({value:T.value,schema:$t})).map((xe)=>({type:"tool_reference",tool_name:xe.toolName}));O.push({type:"tool_search_tool_result",tool_use_id:y.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:S},cache_control:re});break}if(P==="advisor"){let T=y.output;if(T.type!=="json"&&T.type!=="error-json"){g.push({type:"other",message:`provider executed tool result output type ${T.type} for tool ${y.toolName} is not supported`});break}let S=await z({value:T.value,schema:Ot});if(S.type==="advisor_result")O.push({type:"advisor_tool_result",tool_use_id:y.toolCallId,content:{type:"advisor_result",text:S.text,...S.stopReason!==void 0&&{stop_reason:S.stopReason}},cache_control:re});else if(S.type==="advisor_redacted_result")O.push({type:"advisor_tool_result",tool_use_id:y.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:S.encryptedContent,...S.stopReason!==void 0&&{stop_reason:S.stopReason}},cache_control:re});else O.push({type:"advisor_tool_result",tool_use_id:y.toolCallId,content:{type:"advisor_tool_result_error",error_code:S.errorCode},cache_control:re});break}g.push({type:"other",message:`provider executed tool result for tool ${y.toolName} is not supported`});break}}}}if(O.length>0)X.push({role:"assistant",content:an(O)});break}default:throw Error(`content type: ${ye}`)}}let fe=new Set;for(let he of X){if(he.role!=="assistant")continue;for(let c of he.content)if(c.type==="server_tool_use"&&c.name==="code_execution")fe.add(c.id)}let ke=new Set;for(let he=0;he<ne;he++){let c=X[he];if(c.role!=="assistant")continue;for(let V of c.content){if(!("caller"in V))continue;let ye=V.caller;if(ye==null||ye.type==="direct"||fe.has(ye.tool_id))continue;let O="id"in V?V.id:V.tool_use_id;if(delete V.caller,!ke.has(O))ke.add(O),g.push({type:"other",message:`Omitted caller metadata for tool ${O} because source code execution tool ${ye.tool_id} is missing from the conversation history.`})}}return{prompt:{system:je,messages:X},betas:ue}}function rn(i){let h=[],g=void 0;for(let D of i){let{role:L}=D;switch(L){case"system":if(g?.type!=="system")g={type:"system",messages:[]},h.push(g);g.messages.push(D);break;case"assistant":if(g?.type!=="assistant")g={type:"assistant",messages:[]},h.push(g);g.messages.push(D);break;case"user":if(g?.type!=="user")g={type:"user",messages:[]},h.push(g);g.messages.push(D);break;case"tool":if(g?.type!=="user")g={type:"user",messages:[]},h.push(g);g.messages.push(D);break;default:throw Error(`Unsupported role: ${L}`)}}return h}function an(i){let h=[],g=[];function D(){h.push(...g.filter((L)=>L.type!=="tool_use"),...g.filter((L)=>L.type==="tool_use")),g=[]}for(let L of i)if(L.type==="thinking"||L.type==="redacted_thinking"||L.type==="fallback")D(),h.push(L);else g.push(L);return D(),h}function ht({toolName:i,providerOptions:h,toolsetNames:g}){let D=g[i];if(D!=null)return D;let L=h?.anthropic?.toolsetName;return typeof L==="string"?L:void 0}function mt(i){let h=i?.anthropic?.caller;if((h?.type==="code_execution_20250825"||h?.type==="code_execution_20260120")&&h.toolId)return{type:h.type,tool_id:h.toolId};return h?.type==="direct"?{type:"direct"}:void 0}function gt(i){return typeof i==="object"&&i!==null&&!Array.isArray(i)?i:{rawInvalidInput:i}}function et({finishReason:i,isJsonResponseFromTool:h}){switch(i){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return h?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}var Ut=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),sn=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function vy(i){return qt(i)}function He(i){if(typeof i==="boolean"||!Ce(i))return i;return qt(i)}function qt(i){let h={},g=i;if(i.$ref!=null)return{$ref:i.$ref};if(i.$schema!=null)h.$schema=i.$schema;if(i.$id!=null)h.$id=i.$id;if(i.title!=null)h.title=i.title;if(i.description!=null)h.description=i.description;if(i.default!==void 0)h.default=i.default;if(i.const!==void 0)h.const=i.const;if(i.enum!=null)h.enum=i.enum;if(i.type!=null)h.type=i.type;if(i.anyOf!=null)h.anyOf=i.anyOf.map(He);else if(i.oneOf!=null)h.anyOf=i.oneOf.map(He);if(i.allOf!=null)h.allOf=i.allOf.map(He);if(i.definitions!=null)h.definitions=Object.fromEntries(Object.entries(i.definitions).map(([L,se])=>[L,He(se)]));if(g.$defs!=null){let L=h;L.$defs=Object.fromEntries(Object.entries(g.$defs).map(([se,q])=>[se,He(q)]))}if(i.type==="object"||i.properties!=null){if(i.properties!=null)h.properties=Object.fromEntries(Object.entries(i.properties).map(([L,se])=>[L,He(se)]));if(h.additionalProperties=!1,i.required!=null)h.required=i.required}if(i.items!=null)h.items=Array.isArray(i.items)?i.items.map(He):He(i.items);if(typeof i.format==="string"&&Ut.has(i.format))h.format=i.format;let D=ln(i);if(D!=null)h.description=h.description==null?D:`${h.description}
2
+ ${D}`;return h}function ln(i){let h=sn.flatMap((g)=>{let D=i[g];if(D==null||D===!1)return[];return`${cn(g)}: ${un(D)}`});if(typeof i.format==="string"&&!Ut.has(i.format))h.push(`format: ${i.format}`);return h.length===0?void 0:`${h.join("; ")}.`}function cn(i){return i.replace(/[A-Z]/g,(h)=>` ${h.toLowerCase()}`)}function un(i){if(typeof i==="string")return i;return JSON.stringify(i)}function pn(i){let h=dn(i.type);return Ht({message:i.message,type:i.type,code:i.code??void 0,statusCode:i.statusCode??h.statusCode,isRetryable:i.isRetryable??h.isRetryable,data:"data"in i?i.data:i})}function dn(i){switch(i){case"api_error":return{statusCode:500,isRetryable:!0};case"overloaded_error":return{statusCode:529,isRetryable:!0};case"rate_limit_error":return{statusCode:429,isRetryable:!0};case"request_too_large":return{statusCode:413,isRetryable:!1};case"authentication_error":return{statusCode:401,isRetryable:!1};case"permission_error":return{statusCode:403,isRetryable:!1};case"not_found_error":return{statusCode:404,isRetryable:!1};case"billing_error":case"invalid_request_error":return{statusCode:400,isRetryable:!1};default:return{}}}function tt(i,h,g){if(i.type==="web_search_result_location")return{type:"source",sourceType:"url",id:g(),url:i.url,title:i.title??void 0,providerMetadata:{anthropic:{citedText:i.cited_text,encryptedIndex:i.encrypted_index}}};if(i.type!=="page_location"&&i.type!=="char_location")return;let D=h[i.document_index];if(!D)return;return{type:"source",sourceType:"document",id:g(),mediaType:D.mediaType,title:i.document_title??D.title,filename:D.filename,providerMetadata:{anthropic:i.type==="page_location"?{citedText:i.cited_text,startPageNumber:i.start_page_number,endPageNumber:i.end_page_number}:{citedText:i.cited_text,startCharIndex:i.start_char_index,endCharIndex:i.end_char_index}}}}function Ve(i){return i==null?void 0:{type:i.type,toolId:"tool_id"in i?i.tool_id:void 0}}function Ie(i){let h=Ve(i);return h==null?{}:{providerMetadata:{anthropic:{caller:h}}}}function _n(i){let h={};for(let g of i??[])if(g.type==="provider"&&g.id==="anthropic.computer_toolset_20260801")h[g.name]="computer";return h}function yt({memberName:i,input:h}){return{action:i,...typeof h==="object"&&h!==null&&!Array.isArray(h)?h:{}}}function bt(i){let h=i.indexOf(".");return h===-1?i:i.substring(0,h)}var Lw=class i{static[H](h){return te({modelId:h.modelId,config:h.config})}static[Q](h){return new i(h.modelId,h.config)}constructor(h,g){this.specificationVersion="v4",this.modelId=h,this.config=g,this.generateId=g.generateId??C}supportsUrl(h){return h.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:h,config:g,options:{userSuppliedBetas:D,prompt:L,maxOutputTokens:se,temperature:q,topP:ue,topK:ce,frequencyPenalty:K,presencePenalty:je,stopSequences:X,responseFormat:ne,seed:Z,tools:v,toolChoice:de,reasoning:fe,providerOptions:ke,stream:he}}){let c=[];if(K!=null)c.push({type:"unsupported",feature:"frequencyPenalty"});if(je!=null)c.push({type:"unsupported",feature:"presencePenalty"});if(Z!=null)c.push({type:"unsupported",feature:"seed"});let V=g.maxTemperature??1,ye=g.maxTemperature==null?"anthropic":bt(g.provider);if(q!=null&&q>V)c.push({type:"unsupported",feature:"temperature",details:`${q} exceeds ${ye} maximum of ${V.toFixed(1)}. clamped to ${V.toFixed(1)}`}),q=V;else if(q!=null&&q<0)c.push({type:"unsupported",feature:"temperature",details:`${q} is below ${ye} minimum of 0. clamped to 0`}),q=0;if(ne?.type==="json"){if(ne.schema==null)c.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."})}let O=bt(g.provider),Ne=await k({provider:"anthropic",providerOptions:ke,schema:pt}),Oe=O!=="anthropic"?await k({provider:O,providerOptions:ke,schema:pt}):null,ie=Oe!=null,f=Object.assign({},Ne??{},Oe??{}),{maxOutputTokens:B,supportsStructuredOutput:me,supportsAdaptiveThinking:y,rejectsSamplingParameters:Se,supportsXhighEffort:re,rejectsThinkingDisabledAboveHighEffort:P,rejectsThinkingDisabled:_e,rejectsBudgetThinking:T,rejectsForcedToolUse:S,supportsBetweenToolsThinking:xe,isKnownModel:Ue}=qm(h);if(!Ue&&se==null)c.push({type:"compatibility",feature:"maxOutputTokens",details:`The model "${h}" is unknown. The max output tokens have been limited to ${B}. Set maxOutputTokens explicitly to override this limit.`});if(Se){if(q!=null)c.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${h} and will be ignored`}),q=void 0;if(ce!=null)c.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${h} and will be ignored`}),ce=void 0;if(ue!=null)c.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${h} and will be ignored`}),ue=void 0}let Ge=Ue||h.includes("claude-"),Je=(g.supportsNativeStructuredOutput??!0)&&me,Be=(g.supportsStrictTools??!0)&&me,ve=f?.structuredOutputMode??"auto",U=ve==="outputFormat"||ve==="auto"&&Je;if(!U&&S&&Je&&ne?.type==="json"&&ne.schema!=null)c.push({type:"unsupported",feature:"providerOptions.anthropic.structuredOutputMode",details:`structuredOutputMode 'jsonTool' is not supported by ${h} because it rejects forced tool use. Using 'outputFormat' instead.`}),U=!0;let x=ne?.type==="json"&&ne.schema!=null&&!U?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:ne.schema}:void 0;if(x!=null&&f?.disableParallelToolUse===!1)c.push({type:"unsupported",feature:"providerOptions.anthropic.disableParallelToolUse",details:"`disableParallelToolUse: false` is ignored when using the JSON response tool. Parallel tool use is disabled to ensure a single coherent JSON tool call."});let _=f?.contextManagement,Y=f?.compaction;if(_!=null&&Y!=null)throw new F({argument:"providerOptions",message:"Anthropic provider options `compaction` and `contextManagement` cannot be used together."});let R=new rt(g.cacheControlProviderOptionsName),pe=Kt({tools:v,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.computer_20251124":"computer","anthropic.computer_toolset_20260801":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_search_20260318":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.web_fetch_20260318":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25","anthropic.advisor_20260301":"advisor"}}),Le=_n(v),{prompt:ze,betas:we}=await nn({prompt:L,sendReasoning:f?.sendReasoning??!0,warnings:c,cacheControlValidator:R,toolNameMapping:pe,toolsetNames:Le,convertMediaPart:g.convertMediaPart});if(Ee(fe)&&f?.effort==null){let J=hn({reasoning:fe,modelId:h,supportsAdaptiveThinking:y,supportsXhighEffort:re,rejectsThinkingDisabled:_e,supportsBetweenToolsThinking:xe,maxOutputTokensForModel:B,warnings:c});if(J!=null){if(f.thinking==null)f.thinking=J.thinking;if(J.effort!=null&&f.thinking?.type!=="disabled")f.effort=J.effort}}if(_e&&f?.thinking!=null){let J=f.thinking;if(J.type==="disabled"&&xe)c.push({type:"unsupported",feature:"providerOptions.anthropic.thinking",details:`thinking cannot be disabled for ${h}. Using 'between_tools' thinking, the lowest thinking setting, instead.`}),f.thinking={type:"between_tools"};else if(J.type==="disabled")c.push({type:"unsupported",feature:"providerOptions.anthropic.thinking",details:`thinking cannot be disabled for ${h}; it always uses adaptive thinking. The thinking setting has been removed. Lower 'effort' to reduce thinking.`}),f.thinking=void 0}if(T&&f?.thinking?.type==="enabled")c.push({type:"unsupported",feature:"providerOptions.anthropic.thinking",details:_e?`budget-based thinking is not supported by ${h}; it always uses adaptive thinking. Using adaptive thinking instead. Use 'effort' to control how much the model thinks.`:`budget-based thinking is not supported by ${h}. Using adaptive thinking instead. Use 'effort' to control how much the model thinks.`}),f.thinking={type:"adaptive"};if(P&&f?.thinking?.type==="disabled"&&(f.effort==="xhigh"||f.effort==="max"))c.push({type:"unsupported",feature:"providerOptions.anthropic.effort",details:`effort '${f.effort}' is not supported by ${h} when thinking is disabled. The effort has been lowered to 'high'.`}),f.effort="high";if(f?.thinking?.type==="between_tools"&&(f.effort==="xhigh"||f.effort==="max"))c.push({type:"unsupported",feature:"providerOptions.anthropic.effort",details:`effort '${f.effort}' is not supported with 'between_tools' thinking. The effort has been lowered to 'high'.`}),f.effort="high";let Ae=f?.thinking?.type,it=Ae==="enabled"||Ae==="adaptive"||Ae==="between_tools",Xe=f?.thinking!=null&&"blockBinding"in f.thinking?f.thinking.blockBinding:void 0,Bt=it||Ae==="disabled"||Xe!=null,We=Ae==="enabled"?f?.thinking?.budgetTokens:void 0,Ze=Ae==="adaptive"?f?.thinking?.display:void 0,at=se??B,Me={model:h,max_tokens:at,temperature:q,top_k:ce,top_p:ue,stop_sequences:X,...Bt&&{thinking:{...Ae!=null&&{type:Ae},...We!=null&&{budget_tokens:We},...Ze!=null&&{display:Ze},...Xe!=null&&{block_binding:{prefix_mismatch_behavior:Xe.prefixMismatchBehavior}}}},...(f?.effort||f?.taskBudget||U&&ne?.type==="json"&&ne.schema!=null)&&{output_config:{...f?.effort&&{effort:f.effort},...f?.taskBudget&&{task_budget:{type:f.taskBudget.type,total:f.taskBudget.total,...f.taskBudget.remaining!=null&&{remaining:f.taskBudget.remaining}}},...U&&ne?.type==="json"&&ne.schema!=null&&{format:{type:"json_schema",schema:vy(ne.schema)}}}},...f?.speed&&{speed:f.speed},...f?.serviceTier&&{service_tier:f.serviceTier},...f?.inferenceGeo&&{inference_geo:f.inferenceGeo},...f?.fallbacks!=null&&(f.fallbacks==="default"||f.fallbacks.length>0)&&{fallbacks:f.fallbacks},...f?.cacheControl&&{cache_control:f.cacheControl},...f?.metadata?.userId!=null&&{metadata:{user_id:f.metadata.userId}},...f?.mcpServers&&f.mcpServers.length>0&&{mcp_servers:f.mcpServers.map((J)=>({type:J.type,name:J.name,url:J.url,authorization_token:J.authorizationToken,tool_configuration:J.toolConfiguration?{allowed_tools:J.toolConfiguration.allowedTools,enabled:J.toolConfiguration.enabled}:void 0}))},...f?.container&&{container:f.container.skills&&f.container.skills.length>0?{id:f.container.id,skills:f.container.skills.map((J)=>({type:J.type,skill_id:J.type==="custom"?$e({reference:J.providerReference,provider:"anthropic"}):J.skillId,version:J.version}))}:f.container.id},system:ze.system,messages:ze.messages,...f?.safeguards&&f.safeguards.length>0&&{safeguards:f.safeguards.map((J)=>({type:J.type,...J.classifierContext!==void 0&&{classifier_context:J.classifierContext}}))},...Y&&{compaction:{type:Y.type,...Y.instructions!==void 0&&{instructions:Y.instructions}}},..._&&{context_management:{edits:_.edits.map((J)=>{let lt=J.type;switch(lt){case"clear_tool_uses_20250919":return{type:J.type,...J.trigger!==void 0&&{trigger:J.trigger},...J.keep!==void 0&&{keep:J.keep},...J.clearAtLeast!==void 0&&{clear_at_least:J.clearAtLeast},...J.clearToolInputs!==void 0&&{clear_tool_inputs:J.clearToolInputs},...J.excludeTools!==void 0&&{exclude_tools:J.excludeTools}};case"clear_thinking_20251015":return{type:J.type,...J.keep!==void 0&&{keep:J.keep}};case"compact_20260112":return{type:J.type,...J.trigger!==void 0&&{trigger:J.trigger},...J.pauseAfterCompaction!==void 0&&{pause_after_compaction:J.pauseAfterCompaction},...J.instructions!==void 0&&{instructions:J.instructions}};default:c.push({type:"other",message:`Unknown context management strategy: ${lt}`});return}}).filter((J)=>J!==void 0)}}};if(it){if(Ae==="enabled"&&We==null)c.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),Me.thinking={type:"enabled",budget_tokens:1024},We=1024;if(Me.temperature!=null&&!g.supportsTemperatureAndTopPWithThinking)Me.temperature=void 0,c.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"});if(ce!=null)Me.top_k=void 0,c.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"});if(ue!=null&&!g.supportsTemperatureAndTopPWithThinking)Me.top_p=void 0,c.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"});Me.max_tokens=at+(We??0)}else if(Ge&&ue!=null&&q!=null)c.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),Me.top_p=void 0;if(Ue&&Me.max_tokens>B){if(se!=null)c.push({type:"unsupported",feature:"maxOutputTokens",details:`${Me.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${h} ${B} max output tokens. The max output tokens have been limited to ${B}.`});Me.max_tokens=B}if(f?.mcpServers&&f.mcpServers.length>0)we.add("mcp-client-2025-04-04");if(f?.safeguards&&f.safeguards.length>0)we.add("dangerous-tool-use-2026-09-03");if(Y)we.add("compact-2026-09-04");if(_){if(we.add("context-management-2025-06-27"),_.edits.some((J)=>J.type==="compact_20260112"))we.add("compact-2026-01-12")}if(f?.container&&f.container.skills&&f.container.skills.length>0){if(we.add("code-execution-2025-08-25"),we.add("skills-2025-10-02"),we.add("files-api-2025-04-14"),!v?.some((J)=>J.type==="provider"&&(J.id==="anthropic.code_execution_20250825"||J.id==="anthropic.code_execution_20260120")))c.push({type:"other",message:"code execution tool is required when using skills"})}if(f?.taskBudget)we.add("task-budgets-2026-03-13");if(f?.speed==="fast")we.add("fast-mode-2026-02-01");if(Ze==="updates")we.add("thinking-display-updates-2026-08-18");if(Xe!=null)we.add("thinking-binding-controls-2026-08-01");if(f?.fallbacks==="default")we.add("server-side-fallback-2026-07-01");else if(f?.fallbacks&&f.fallbacks.length>0)we.add("server-side-fallback-2026-06-01");let st=he&&(f?.toolStreaming??!0),{tools:Pt,toolChoice:Ft,toolWarnings:Lt,betas:Jt}=await by(x!=null?{tools:[...v??[],x],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:R,supportsStructuredOutput:!1,supportsStrictTools:Be,defaultEagerInputStreaming:st,rejectsForcedToolUse:S||Ae==="enabled"}:{tools:v??[],toolChoice:de,disableParallelToolUse:f?.disableParallelToolUse,cacheControlValidator:R,supportsStructuredOutput:Je,supportsStrictTools:Be,defaultEagerInputStreaming:st,rejectsForcedToolUse:S||Ae==="enabled"}),zt=R.getWarnings();return{args:{...Me,tools:Pt,tool_choice:Ft,stream:he===!0?!0:void 0},warnings:[...c,...Lt,...zt],betas:new Set([...we,...Jt,...D,...f?.anthropicBeta??[]]),usesJsonResponseTool:x!=null,toolNameMapping:pe,providerOptionsName:O,usedCustomProviderKey:ie}}getArgs(h){return i.prepareRequest({modelId:this.modelId,config:this.config,options:h})}async getHeaders({betas:h,headers:g,providerOptions:D}){let L=I(this.config.headers?await W(this.config.headers):void 0,g,h.size>0?{"anthropic-beta":Array.from(h).join(",")}:{});return this.config.transformRequestHeaders?this.config.transformRequestHeaders(L,D):L}async getBetasFromHeaders(h){let g=(this.config.headers?await W(this.config.headers):void 0)?.["anthropic-beta"]??"",D=h?.["anthropic-beta"]??"";return new Set([...g.toLowerCase().split(","),...D.toLowerCase().split(",")].map((L)=>L.trim()).filter((L)=>L!==""))}buildRequestUrl(h){return this.config.buildRequestUrl?.(this.config.baseURL,h)??`${this.config.baseURL}/messages`}transformRequestBody(h,g){return this.config.transformRequestBody?.(h,g)??h}extractCitationDocuments(h){let g=(D)=>{if(D.type!=="file")return!1;if(D.mediaType!=="application/pdf"&&D.mediaType!=="text/plain")return!1;return D.providerOptions?.anthropic?.citations?.enabled??!1};return h.filter((D)=>D.role==="user").flatMap((D)=>D.content).filter(g).map((D)=>{let L=D;return{title:L.filename??"Untitled Document",filename:L.filename,mediaType:L.mediaType}})}async doGenerate(h){let{args:g,warnings:D,betas:L,usesJsonResponseTool:se,toolNameMapping:q,providerOptionsName:ue,usedCustomProviderKey:ce}=await this.getArgs({...h,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(h.headers)}),K=[...this.extractCitationDocuments(h.prompt)],je=xt(g.tools),{responseHeaders:X,value:ne,rawValue:Z}=await A({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:L,headers:h.headers,providerOptions:h.providerOptions}),body:this.transformRequestBody(g,L),failedResponseHandler:ct,successfulResponseHandler:E(Xt),abortSignal:h.abortSignal,fetch:this.config.fetch}),v=[],de={},fe={},ke=!1,he=ne.content.some((c)=>c.type==="web_search_tool_result"&&Array.isArray(c.content)&&c.content.length>0);for(let c of ne.content)switch(c.type){case"text":if(!se){let V=c.citations??[];if(v.push({type:"text",text:c.text,...V.length>0&&{citations:V.map((ye)=>ut(ye,K))},...V.length>0&&{providerMetadata:{anthropic:{citations:V}}}}),c.citations)for(let ye of c.citations){if(ye.type==="web_search_result_location"&&he)continue;let O=tt(ye,K,this.generateId);if(O)v.push(O)}}break;case"thinking":v.push({type:"reasoning",text:c.thinking,providerMetadata:{anthropic:{signature:c.signature}}});break;case"redacted_thinking":v.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:c.data}}});break;case"container_upload":v.push({type:"custom",kind:"anthropic.container_upload",providerMetadata:{anthropic:{fileId:c.file_id}}});break;case"compaction":if(!c.content)break;v.push({type:"text",text:c.content,providerMetadata:{anthropic:{type:"compaction",...c.signature!=null&&{signature:c.signature}}}});break;case"tool_use":if(se&&c.name==="json")ke=!0,v.push({type:"text",text:JSON.stringify(c.input)});else if(c.toolset_name!=null)v.push({type:"tool-call",toolCallId:c.id,toolName:q.toCustomToolName(c.toolset_name),input:JSON.stringify(yt({memberName:c.name,input:c.input})),providerMetadata:{anthropic:{toolsetName:c.toolset_name,...Ie(c.caller).providerMetadata?.anthropic}}});else v.push({type:"tool-call",toolCallId:c.id,toolName:c.name,input:JSON.stringify(c.input),...Ie(c.caller)});break;case"server_tool_use":if(c.name==="text_editor_code_execution"||c.name==="bash_code_execution")v.push({type:"tool-call",toolCallId:c.id,toolName:q.toCustomToolName("code_execution"),input:JSON.stringify({type:c.name,...c.input}),providerExecuted:!0,...je?{dynamic:!0}:{},...Ie(c.caller)});else if(c.name==="web_search"||c.name==="code_execution"||c.name==="web_fetch"){let V=c.name==="code_execution"&&c.input!=null&&typeof c.input==="object"&&"code"in c.input&&!("type"in c.input)?{type:"programmatic-tool-call",...c.input}:c.input;v.push({type:"tool-call",toolCallId:c.id,toolName:q.toCustomToolName(c.name),input:JSON.stringify(V),providerExecuted:!0,...je&&c.name==="code_execution"?{dynamic:!0}:{},...Ie(c.caller)})}else if(c.name==="tool_search_tool_regex"||c.name==="tool_search_tool_bm25")fe[c.id]=c.name,v.push({type:"tool-call",toolCallId:c.id,toolName:q.toCustomToolName(c.name),input:JSON.stringify(c.input),providerExecuted:!0,...Ie(c.caller)});else if(c.name==="advisor")v.push({type:"tool-call",toolCallId:c.id,toolName:q.toCustomToolName("advisor"),input:JSON.stringify(c.input),providerExecuted:!0,...Ie(c.caller)});break;case"mcp_tool_use":de[c.id]={type:"tool-call",toolCallId:c.id,toolName:c.name,input:JSON.stringify(c.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:c.server_name}}},v.push(de[c.id]);break;case"mcp_tool_result":v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:de[c.tool_use_id].toolName,isError:c.is_error,result:c.content,dynamic:!0,providerMetadata:de[c.tool_use_id].providerMetadata});break;case"web_fetch_tool_result":if(c.content.type==="web_fetch_result")K.push({title:c.content.content.title??c.content.url,mediaType:c.content.content.source.media_type}),v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:c.content.url,retrievedAt:c.content.retrieved_at,content:{type:c.content.content.type,title:c.content.content.title,citations:c.content.content.citations,source:{type:c.content.content.source.type,mediaType:c.content.content.source.media_type,data:c.content.content.source.data}}},...Ie(c.caller)});else if(c.content.type==="web_fetch_tool_result_error")v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:c.content.error_code},...Ie(c.caller)});break;case"web_search_tool_result":if(Array.isArray(c.content)){v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName("web_search"),result:c.content.map((V)=>({url:V.url,...V.title!=null?{title:V.title}:{},pageAge:V.page_age??null,encryptedContent:V.encrypted_content,type:V.type})),...Ie(c.caller)});for(let V of c.content)v.push({type:"source",sourceType:"url",id:this.generateId(),url:V.url,...V.title!=null?{title:V.title}:{},providerMetadata:{anthropic:{pageAge:V.page_age??null}}})}else v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:c.content.error_code},...Ie(c.caller)});break;case"code_execution_tool_result":if(c.content.type==="code_execution_result")v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName("code_execution"),result:{type:c.content.type,stdout:c.content.stdout,stderr:c.content.stderr,return_code:c.content.return_code,content:c.content.content??[]}});else if(c.content.type==="encrypted_code_execution_result")v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName("code_execution"),result:{type:c.content.type,encrypted_stdout:c.content.encrypted_stdout,stderr:c.content.stderr,return_code:c.content.return_code,content:c.content.content??[]}});else if(c.content.type==="code_execution_tool_result_error")v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:c.content.error_code}});break;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName("code_execution"),result:c.content});break;case"tool_search_tool_result":{let V=fe[c.tool_use_id];if(V==null){let ye=q.toCustomToolName("tool_search_tool_bm25"),O=q.toCustomToolName("tool_search_tool_regex");if(ye!=="tool_search_tool_bm25")V="tool_search_tool_bm25";else if(O!=="tool_search_tool_regex")V="tool_search_tool_regex";else V="tool_search_tool_regex"}if(c.content.type==="tool_search_tool_search_result")v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName(V),result:c.content.tool_references.map((ye)=>({type:ye.type,toolName:ye.tool_name}))});else v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:q.toCustomToolName(V),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:c.content.error_code}});break}case"advisor_tool_result":{let V=q.toCustomToolName("advisor");if(c.content.type==="advisor_result")v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:V,result:{type:"advisor_result",text:c.content.text,...c.content.stop_reason!=null&&{stopReason:c.content.stop_reason}}});else if(c.content.type==="advisor_redacted_result")v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:V,result:{type:"advisor_redacted_result",encryptedContent:c.content.encrypted_content,...c.content.stop_reason!=null&&{stopReason:c.content.stop_reason}}});else v.push({type:"tool-result",toolCallId:c.tool_use_id,toolName:V,isError:!0,result:{type:"advisor_tool_result_error",errorCode:c.content.error_code}});break}case"fallback":v.push({type:"custom",kind:"anthropic.fallback",providerMetadata:{anthropic:{type:"fallback",from:c.from,to:c.to}}})}return{content:v,finishReason:{unified:et({finishReason:ne.stop_reason,isJsonResponseFromTool:ke}),raw:ne.stop_reason??void 0},usage:_t({usage:ne.usage}),request:{body:g},response:{id:ne.id??void 0,modelId:ne.model??void 0,headers:X,body:Z},warnings:D,providerMetadata:(()=>{let c=vt(ne.stop_details),V={usage:ne.usage,stopSequence:ne.stop_sequence??null,...c!=null?{stopDetails:c}:{},...ne.input_transformations!=null?{inputTransformations:ne.input_transformations}:{},...ne.safeguard_results!=null?{safeguardResults:ne.safeguard_results}:{},iterations:ne.usage.iterations?ne.usage.iterations.map((O)=>({type:O.type,...O.model!=null?{model:O.model}:{},inputTokens:O.input_tokens,outputTokens:O.output_tokens,...O.cache_creation_input_tokens?{cacheCreationInputTokens:O.cache_creation_input_tokens}:{},...O.cache_read_input_tokens?{cacheReadInputTokens:O.cache_read_input_tokens}:{}})):null,container:ne.container?{expiresAt:ne.container.expires_at,id:ne.container.id,skills:ne.container.skills?.map((O)=>({type:O.type,skillId:O.skill_id,version:O.version}))??null}:null,contextManagement:kt(ne.context_management)??null},ye={anthropic:V};if(ce&&ue!=="anthropic")ye[ue]=V;return ye})()}}async doStream(h){let{args:g,warnings:D,betas:L,usesJsonResponseTool:se,toolNameMapping:q,providerOptionsName:ue,usedCustomProviderKey:ce}=await this.getArgs({...h,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(h.headers)}),K=[...this.extractCitationDocuments(h.prompt)],je=xt(g.tools),X=this.buildRequestUrl(!0),{responseHeaders:ne,value:Z}=await A({url:X,headers:await this.getHeaders({betas:L,headers:h.headers,providerOptions:h.providerOptions}),body:this.transformRequestBody(g,L),failedResponseHandler:ct,successfulResponseHandler:qe(Gt),abortSignal:h.abortSignal,fetch:this.config.fetch}),v={unified:"other",raw:void 0},de={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},fe={},ke={},he={},c=null,V=void 0,ye=null,O=void 0,Ne,Oe,ie=null,f=!1,B=!1,me=[],y=!1,Se,re=!1,P=void 0,_e=this.generateId,T=Z.pipeThrough(new TransformStream({start(ve){ve.enqueue({type:"stream-start",warnings:D})},transform(ve,U){if(re)return;if(h.includeRawChunks)U.enqueue({type:"raw",rawValue:ve.rawValue});if(!ve.success){U.enqueue({type:"error",error:ve.error});return}let x=ve.value;switch(x.type){case"ping":return;case"content_block_start":{let _=x.content_block,Y=_.type;if(Y==="fallback"){U.enqueue({type:"custom",kind:"anthropic.fallback",providerMetadata:{anthropic:{type:"fallback",from:_.from,to:_.to}}});return}switch(P=Y,Y){case"text":if(se)return;fe[x.index]={type:"text",citations:[]},U.enqueue({type:"text-start",id:String(x.index)});return;case"thinking":fe[x.index]={type:"reasoning"},U.enqueue({type:"reasoning-start",id:String(x.index)});return;case"redacted_thinking":fe[x.index]={type:"reasoning"},U.enqueue({type:"reasoning-start",id:String(x.index),providerMetadata:{anthropic:{redactedData:_.data}}});return;case"compaction":if(fe[x.index]={type:"text",citations:[]},U.enqueue({type:"text-start",id:String(x.index),providerMetadata:{anthropic:{type:"compaction",..._.signature!=null&&{signature:_.signature}}}}),_.signature!=null&&_.content!=null&&_.content!=="")U.enqueue({type:"text-delta",id:String(x.index),delta:_.content});return;case"tool_use":if(se&&_.name==="json")f=!0,fe[x.index]={type:"text",citations:[]},U.enqueue({type:"text-start",id:String(x.index)});else if(_.toolset_name!=null){let R=Ve(_.caller),pe=q.toCustomToolName(_.toolset_name),Le=_.input&&Object.keys(_.input).length>0;fe[x.index]={type:"tool-call",toolCallId:_.id,toolName:pe,input:Le?JSON.stringify(_.input):"",firstDelta:!0,toolset:{name:_.toolset_name,memberName:_.name},...R&&{caller:R}},U.enqueue({type:"tool-input-start",id:_.id,toolName:pe})}else{let R=Ve(_.caller),pe=_.input&&Object.keys(_.input).length>0?JSON.stringify(_.input):"";fe[x.index]={type:"tool-call",toolCallId:_.id,toolName:_.name,input:pe,firstDelta:pe.length===0,...R&&{caller:R}},U.enqueue({type:"tool-input-start",id:_.id,toolName:_.name})}return;case"server_tool_use":{let R=Ve(_.caller);if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(_.name)){let pe=_.name==="text_editor_code_execution"||_.name==="bash_code_execution"?"code_execution":_.name,Le=_.name==="text_editor_code_execution"||_.name==="bash_code_execution"?_.name:_.name==="code_execution"?"programmatic-tool-call":void 0,ze=q.toCustomToolName(pe),we=_.input!=null&&typeof _.input==="object"&&Object.keys(_.input).length>0?JSON.stringify(_.input):"";fe[x.index]={type:"tool-call",toolCallId:_.id,toolName:ze,input:we,providerExecuted:!0,...je&&pe==="code_execution"?{dynamic:!0}:{},firstDelta:we.length===0,providerToolName:pe,providerToolInputType:Le,...R&&{caller:R}},U.enqueue({type:"tool-input-start",id:_.id,toolName:ze,providerExecuted:!0,...je&&pe==="code_execution"?{dynamic:!0}:{}})}else if(_.name==="tool_search_tool_regex"||_.name==="tool_search_tool_bm25"){he[_.id]=_.name;let pe=q.toCustomToolName(_.name);fe[x.index]={type:"tool-call",toolCallId:_.id,toolName:pe,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:_.name,...R&&{caller:R}},U.enqueue({type:"tool-input-start",id:_.id,toolName:pe,providerExecuted:!0})}else if(_.name==="advisor"){let pe=q.toCustomToolName("advisor");fe[x.index]={type:"tool-call",toolCallId:_.id,toolName:pe,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:_.name,...R&&{caller:R}},U.enqueue({type:"tool-input-start",id:_.id,toolName:pe,providerExecuted:!0})}return}case"web_fetch_tool_result":if(_.content.type==="web_fetch_result")K.push({title:_.content.content.title??_.content.url,mediaType:_.content.content.source.media_type}),U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:_.content.url,retrievedAt:_.content.retrieved_at,content:{type:_.content.content.type,title:_.content.content.title,citations:_.content.content.citations,source:{type:_.content.content.source.type,mediaType:_.content.content.source.media_type,data:_.content.content.source.data}}},...Ie(_.caller)});else if(_.content.type==="web_fetch_tool_result_error")U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:_.content.error_code},...Ie(_.caller)});return;case"web_search_tool_result":if(Array.isArray(_.content)){U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName("web_search"),result:_.content.map((R)=>({url:R.url,...R.title!=null?{title:R.title}:{},pageAge:R.page_age??null,encryptedContent:R.encrypted_content,type:R.type})),...Ie(_.caller)});for(let R of _.content)B=!0,U.enqueue({type:"source",sourceType:"url",id:_e(),url:R.url,...R.title!=null?{title:R.title}:{},providerMetadata:{anthropic:{pageAge:R.page_age??null}}})}else U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:_.content.error_code},...Ie(_.caller)});return;case"code_execution_tool_result":if(_.content.type==="code_execution_result")U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName("code_execution"),result:{type:_.content.type,stdout:_.content.stdout,stderr:_.content.stderr,return_code:_.content.return_code,content:_.content.content??[]}});else if(_.content.type==="encrypted_code_execution_result")U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName("code_execution"),result:{type:_.content.type,encrypted_stdout:_.content.encrypted_stdout,stderr:_.content.stderr,return_code:_.content.return_code,content:_.content.content??[]}});else if(_.content.type==="code_execution_tool_result_error")U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:_.content.error_code}});return;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName("code_execution"),result:_.content});return;case"tool_search_tool_result":{let R=he[_.tool_use_id];if(R==null){let pe=q.toCustomToolName("tool_search_tool_bm25"),Le=q.toCustomToolName("tool_search_tool_regex");if(pe!=="tool_search_tool_bm25")R="tool_search_tool_bm25";else if(Le!=="tool_search_tool_regex")R="tool_search_tool_regex";else R="tool_search_tool_regex"}if(_.content.type==="tool_search_tool_search_result")U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName(R),result:_.content.tool_references.map((pe)=>({type:pe.type,toolName:pe.tool_name}))});else U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:q.toCustomToolName(R),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:_.content.error_code}});return}case"advisor_tool_result":{let R=q.toCustomToolName("advisor");if(_.content.type==="advisor_result")U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:R,result:{type:"advisor_result",text:_.content.text,..._.content.stop_reason!=null&&{stopReason:_.content.stop_reason}}});else if(_.content.type==="advisor_redacted_result")U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:R,result:{type:"advisor_redacted_result",encryptedContent:_.content.encrypted_content,..._.content.stop_reason!=null&&{stopReason:_.content.stop_reason}}});else U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:R,isError:!0,result:{type:"advisor_tool_result_error",errorCode:_.content.error_code}});return}case"mcp_tool_use":ke[_.id]={type:"tool-call",toolCallId:_.id,toolName:_.name,input:JSON.stringify(_.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:_.server_name}}},U.enqueue(ke[_.id]);return;case"mcp_tool_result":U.enqueue({type:"tool-result",toolCallId:_.tool_use_id,toolName:ke[_.tool_use_id].toolName,isError:_.is_error,result:_.content,dynamic:!0,providerMetadata:ke[_.tool_use_id].providerMetadata});return;default:throw Error(`Unsupported content block type: ${Y}`)}}case"content_block_stop":if(fe[x.index]!=null){let _=fe[x.index];switch(_.type){case"text":U.enqueue({type:"text-end",id:String(x.index),..._.citations.length>0&&{citations:_.citations.map((Y)=>ut(Y,K)),providerMetadata:{anthropic:{citations:_.citations}}}});break;case"reasoning":U.enqueue({type:"reasoning-end",id:String(x.index)});break;case"tool-call":if(!(se&&_.toolName==="json")){if(_.toolset!=null){let R={};try{R=_.input===""?{}:Ke(_.input)}catch{R=void 0}_.input=R===void 0?_.input:JSON.stringify(yt({memberName:_.toolset.memberName,input:R})),U.enqueue({type:"tool-input-delta",id:_.toolCallId,delta:_.input})}U.enqueue({type:"tool-input-end",id:_.toolCallId});let Y=_.input===""?"{}":_.input;if(_.providerToolName==="code_execution")try{let R=Ke(Y);if(R!=null&&typeof R==="object"&&"code"in R&&!("type"in R))Y=JSON.stringify({type:"programmatic-tool-call",...R})}catch{}U.enqueue({type:"tool-call",toolCallId:_.toolCallId,toolName:_.toolName,input:Y,providerExecuted:_.providerExecuted,...je&&_.providerToolName==="code_execution"?{dynamic:!0}:{},...(_.caller||_.toolset)&&{providerMetadata:{anthropic:{..._.toolset&&{toolsetName:_.toolset.name},..._.caller&&{caller:_.caller}}}}})}}delete fe[x.index]}P=void 0;return;case"content_block_delta":{let _=x.delta.type;switch(_){case"text_delta":if(se)return;U.enqueue({type:"text-delta",id:String(x.index),delta:x.delta.text});return;case"thinking_delta":U.enqueue({type:"reasoning-delta",id:String(x.index),delta:x.delta.thinking});return;case"signature_delta":if(P==="thinking")U.enqueue({type:"reasoning-delta",id:String(x.index),delta:"",providerMetadata:{anthropic:{signature:x.delta.signature}}});return;case"compaction_delta":if(x.delta.content!=null)U.enqueue({type:"text-delta",id:String(x.index),delta:x.delta.content});return;case"input_json_delta":{let Y=fe[x.index],R=x.delta.partial_json;if(R.length===0)return;if(f){if(Y?.type!=="text")return;U.enqueue({type:"text-delta",id:String(x.index),delta:R})}else{if(Y?.type!=="tool-call")return;if(Y.toolset!=null){Y.input+=R;return}if(Y.firstDelta&&Y.providerToolInputType!=null)R=`{"type": "${Y.providerToolInputType}",${R.substring(1)}`;U.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:R}),Y.input+=R,Y.firstDelta=!1}return}case"citations_delta":{let Y=x.delta.citation,R=fe[x.index];if(R?.type==="text")R.citations.push(Y);if(Y.type==="web_search_result_location")me.push(Y);else{let pe=tt(Y,K,_e);if(pe)U.enqueue(pe)}return}default:throw Error(`Unsupported delta type: ${_}`)}}case"message_start":if(y){if(Se===x.message.id)return;re=!0,U.enqueue({type:"error",error:new be({data:x,message:`Received message_start for message ${JSON.stringify(x.message.id)} while message ${JSON.stringify(Se)} is still open.`})});return}if(y=!0,Se=x.message.id,de.input_tokens=x.message.usage.input_tokens,de.cache_read_input_tokens=x.message.usage.cache_read_input_tokens??0,de.cache_creation_input_tokens=x.message.usage.cache_creation_input_tokens??0,V={...x.message.usage},x.message.input_transformations!=null)Ne=x.message.input_transformations;if(x.message.container!=null)ie={expiresAt:x.message.container.expires_at,id:x.message.container.id,skills:null};if(x.message.stop_reason!=null)v={unified:et({finishReason:x.message.stop_reason,isJsonResponseFromTool:f}),raw:x.message.stop_reason};if(U.enqueue({type:"response-metadata",id:x.message.id??void 0,modelId:x.message.model??void 0}),U.enqueue({type:"custom",kind:"anthropic.message_start",providerMetadata:{anthropic:{id:x.message.id??null,model:x.message.model??null,usage:V}}}),x.message.content!=null)for(let _=0;_<x.message.content.length;_++){let Y=x.message.content[_];if(Y.type==="tool_use"){let R=Ve(Y.caller);U.enqueue({type:"tool-input-start",id:Y.id,toolName:Y.name});let pe=JSON.stringify(Y.input??{});U.enqueue({type:"tool-input-delta",id:Y.id,delta:pe}),U.enqueue({type:"tool-input-end",id:Y.id}),U.enqueue({type:"tool-call",toolCallId:Y.id,toolName:Y.name,input:pe,...R&&{providerMetadata:{anthropic:{caller:R}}}})}}return;case"message_delta":if(x.usage.input_tokens!=null&&de.input_tokens!==x.usage.input_tokens)de.input_tokens=x.usage.input_tokens;if(de.output_tokens=x.usage.output_tokens,x.usage.output_tokens_details!=null)de.output_tokens_details=x.usage.output_tokens_details;if(x.usage.cache_read_input_tokens!=null)de.cache_read_input_tokens=x.usage.cache_read_input_tokens;if(x.usage.cache_creation_input_tokens!=null)de.cache_creation_input_tokens=x.usage.cache_creation_input_tokens;if(x.usage.iterations!=null)de.iterations=x.usage.iterations;if(v={unified:et({finishReason:x.delta.stop_reason,isJsonResponseFromTool:f}),raw:x.delta.stop_reason??void 0},ye=x.delta.stop_sequence??null,O=vt(x.delta.stop_details),ie=x.delta.container!=null?{expiresAt:x.delta.container.expires_at,id:x.delta.container.id,skills:x.delta.container.skills?.map((_)=>({type:_.type,skillId:_.skill_id,version:_.version}))??null}:null,x.context_management)c=kt(x.context_management);if(x.input_transformations!=null)Ne=x.input_transformations;if(x.delta.safeguard_results!=null)Oe=x.delta.safeguard_results;V={...V,...x.usage};return;case"message_stop":{y=!1,Se=void 0;let _={usage:V??null,stopSequence:ye,...O!=null?{stopDetails:O}:{},...Ne!=null?{inputTransformations:Ne}:{},...Oe!=null?{safeguardResults:Oe}:{},iterations:de.iterations?de.iterations.map((R)=>({type:R.type,...R.model!=null?{model:R.model}:{},inputTokens:R.input_tokens,outputTokens:R.output_tokens,...R.cache_creation_input_tokens?{cacheCreationInputTokens:R.cache_creation_input_tokens}:{},...R.cache_read_input_tokens?{cacheReadInputTokens:R.cache_read_input_tokens}:{}})):null,container:ie,contextManagement:c},Y={anthropic:_};if(ce&&ue!=="anthropic")Y[ue]=_;if(!B)for(let R of me){let pe=tt(R,K,_e);if(pe)U.enqueue(pe)}me.length=0,U.enqueue({type:"finish",finishReason:v,usage:_t({usage:de,rawUsage:V}),providerMetadata:Y});return}case"error":U.enqueue({type:"error",error:pn(x.error)});return;default:throw Error(`Unsupported chunk type: ${x}`)}}})),S=!1,xe=!1,Ue,[Ge,Je]=T.pipeThrough(new TransformStream({transform(ve,U){switch(ve.type){case"response-metadata":S=!1;break;case"finish":S=!1,Ue=ve;break;case"error":xe=!0;break;case"text-delta":case"reasoning-delta":case"tool-input-delta":S||=ve.delta.length>0;break;case"tool-call":S=!0}U.enqueue(ve)},flush(ve){if(S&&!xe)ve.enqueue({type:"finish",finishReason:{unified:"interrupted",raw:void 0},usage:Ue?.usage??{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}},...Ue?.providerMetadata!=null?{providerMetadata:Ue.providerMetadata}:{}})}})).tee(),Be=Ge.getReader();try{await Be.read();let ve=await Be.read();if(ve.value?.type==="raw")ve=await Be.read();if(ve.value?.type==="error"){let U=ve.value.error;if(!fc(U))throw Error("Expected a normalized Anthropic stream error");throw new N({message:U.message,url:X,requestBodyValues:g,statusCode:U.statusCode??500,responseHeaders:ne,responseBody:JSON.stringify(U.data),isRetryable:U.isRetryable??!1})}}finally{Be.cancel().catch(()=>{}),Be.releaseLock()}return{stream:Je,request:{body:g},response:{headers:ne}}}};function qm(i){if(i.includes("claude-sonnet-5-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!0,rejectsBudgetThinking:!0,rejectsForcedToolUse:!0,supportsBetweenToolsThinking:!0,isKnownModel:!0};else if(i.includes("claude-opus-5-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!0,rejectsBudgetThinking:!0,rejectsForcedToolUse:!0,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(i.includes("claude-haiku-5-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!0,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(i.includes("claude-opus-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(i.includes("claude-fable-5-1"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!0,rejectsBudgetThinking:!0,rejectsForcedToolUse:!0,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(i.includes("claude-fable-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!0,rejectsBudgetThinking:!0,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(i.includes("claude-opus-4-8")||i.includes("claude-opus-4-7")||i.includes("claude-sonnet-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(i.includes("claude-sonnet-4-6")||i.includes("claude-opus-4-6"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(i.includes("claude-sonnet-4-5")||i.includes("claude-opus-4-5")||i.includes("claude-haiku-4-5"))return{maxOutputTokens:64000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(i.includes("claude-opus-4-1"))return{maxOutputTokens:32000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(/claude-sonnet-4(?:-|@)/.test(i))return{maxOutputTokens:64000,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(/claude-opus-4(?:-|@)/.test(i))return{maxOutputTokens:32000,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(i.includes("claude-3-haiku"))return{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(/claude-(?:instant(?:-|$)|v?2(?=$|[-.:])|3(?=$|[-.]))/.test(i))return{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!1};else if(i.includes("claude-"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!1};else return{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!1}}function xt(i){if(!i)return!1;let h=!1,g=!1;for(let D of i){if("type"in D&&(D.type==="web_fetch_20260209"||D.type==="web_fetch_20260318"||D.type==="web_search_20260209"||D.type==="web_search_20260318")){h=!0;continue}if("type"in D&&(D.type==="code_execution_20250522"||D.type==="code_execution_20250825"||D.type==="code_execution_20260120")){g=!0;break}}return h&&!g}function hn({reasoning:i,modelId:h,supportsAdaptiveThinking:g,supportsXhighEffort:D,rejectsThinkingDisabled:L,supportsBetweenToolsThinking:se,maxOutputTokensForModel:q,warnings:ue}){if(!Ee(i))return;if(i==="none"){if(se)return{thinking:{type:"between_tools"}};if(L)return ue.push({type:"compatibility",feature:"reasoning",details:`reasoning 'none' is not supported by ${h}; it always uses adaptive thinking. Using effort 'low' to minimize thinking instead.`}),{effort:"low"};return{thinking:{type:"disabled"}}}if(g)return{thinking:{type:"adaptive",display:"summarized"},effort:ft({reasoning:i,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:D?"xhigh":"max",max:"max"},warnings:ue})};let ce=en({reasoning:i,maxOutputTokens:q,maxReasoningBudget:q,warnings:ue});if(ce==null)return;return{thinking:{type:"enabled",budgetTokens:ce}}}function kt(i){return i?{appliedEdits:i.applied_edits.map((h)=>{switch(h.type){case"clear_tool_uses_20250919":return{type:h.type,clearedToolUses:h.cleared_tool_uses,clearedInputTokens:h.cleared_input_tokens};case"clear_thinking_20251015":return{type:h.type,clearedThinkingTurns:h.cleared_thinking_turns,clearedInputTokens:h.cleared_input_tokens};case"compact_20260112":return{type:h.type}}}).filter((h)=>h!==void 0)}:null}function vt(i){if(i==null)return;return{type:i.type,...i.category!=null?{category:i.category}:{},...i.explanation!=null?{explanation:i.explanation}:{},...i.recommended_model!=null?{recommendedModel:i.recommended_model}:{}}}var mn=u(()=>l(t({command:e(),restart:r().optional()}))),wt=Re({id:"anthropic.bash_20241022",inputSchema:mn});function gn(i={}){let{execute:h,...g}=i;if(h===void 0)return wt({...g,execute:async({command:D},{abortSignal:L,experimental_sandbox:se})=>{if(!se)throw Error("Sandbox session is not available");return await se.run({command:D,abortSignal:L})}});return wt({...g,...h===null?{}:{execute:h}})}var fn=u(()=>l(t({command:e(),restart:r().optional()}))),jt=Re({id:"anthropic.bash_20250124",inputSchema:fn});function yn(i={}){let{execute:h,...g}=i;if(h===void 0)return jt({...g,execute:async({command:D},{abortSignal:L,experimental_sandbox:se})=>{if(!se)throw Error("Sandbox session is not available");return await se.run({command:D,abortSignal:L})}});return jt({...g,...h===null?{}:{execute:h}})}var bn=u(()=>l(t({action:s(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:o(n().int()).optional(),text:e().optional()}))),xn=Re({id:"anthropic.computer_20241022",inputSchema:bn}),kn=u(()=>l(t({action:s(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:M([n().int(),n().int()]).optional(),duration:n().optional(),scroll_amount:n().optional(),scroll_direction:s(["up","down","left","right"]).optional(),start_coordinate:M([n().int(),n().int()]).optional(),text:e().optional()}))),vn=Re({id:"anthropic.computer_20250124",inputSchema:kn}),wn=u(()=>l(t({action:s(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:M([n().int(),n().int()]).optional(),duration:n().optional(),region:M([n().int(),n().int(),n().int(),n().int()]).optional(),scroll_amount:n().optional(),scroll_direction:s(["up","down","left","right"]).optional(),start_coordinate:M([n().int(),n().int()]).optional(),text:e().optional()}))),jn=Re({id:"anthropic.computer_20251124",inputSchema:wn}),Tn=u(()=>l(w("command",[t({command:a("view"),path:e(),view_range:M([n(),n()]).optional()}),t({command:a("create"),path:e(),file_text:e()}),t({command:a("str_replace"),path:e(),old_str:e(),new_str:e()}),t({command:a("insert"),path:e(),insert_line:n(),insert_text:e()}),t({command:a("delete"),path:e()}),t({command:a("rename"),old_path:e(),new_path:e()})]))),Cn=Re({id:"anthropic.memory_20250818",inputSchema:Tn}),Sn=u(()=>l(t({command:s(["view","create","str_replace","insert","undo_edit"]),path:e(),file_text:e().optional(),insert_line:n().int().optional(),new_str:e().optional(),insert_text:e().optional(),old_str:e().optional(),view_range:o(n().int()).optional()}))),Nn=Re({id:"anthropic.text_editor_20241022",inputSchema:Sn}),On=u(()=>l(t({command:s(["view","create","str_replace","insert","undo_edit"]),path:e(),file_text:e().optional(),insert_line:n().int().optional(),new_str:e().optional(),insert_text:e().optional(),old_str:e().optional(),view_range:o(n().int()).optional()}))),In=Re({id:"anthropic.text_editor_20250124",inputSchema:On}),An=u(()=>l(t({command:s(["view","create","str_replace","insert"]),path:e(),file_text:e().optional(),insert_line:n().int().optional(),new_str:e().optional(),insert_text:e().optional(),old_str:e().optional(),view_range:o(n().int()).optional()}))),En=Re({id:"anthropic.text_editor_20250429",inputSchema:An}),Rn=u(()=>l(o(t({type:a("tool_reference"),toolName:e()})))),Mn=u(()=>l(t({query:e(),limit:n().optional()}))),Dn=G({id:"anthropic.tool_search_bm25_20251119",inputSchema:Mn,outputSchema:Rn,supportsDeferredResults:!0}),$n=(i={})=>Dn(i),Ri={advisor_20260301:no,bash_20241022:gn,bash_20250124:yn,codeExecution_20250522:Jo,codeExecution_20250825:Ko,codeExecution_20260120:Go,computer_20241022:xn,computer_20250124:vn,computer_20251124:jn,computerToolset_20260801:ao,memory_20250818:Cn,textEditor_20241022:Nn,textEditor_20250124:In,textEditor_20250429:En,textEditor_20250728:uo,webFetch_20250910:Fo,webFetch_20260209:Uo,webFetch_20260318:Ao,webSearch_20250305:To,webSearch_20260209:ko,webSearch_20260318:go,toolSearchRegex_20251119:Qo,toolSearchBm25_20251119:$n},Wn=u(()=>l(t({id:e(),display_title:e().nullish(),name:e().nullish(),description:e().nullish(),latest_version:e().nullish(),source:e(),created_at:e(),updated_at:e()})));u(()=>l(t({data:o(t({version:e()}))})));var Kn=u(()=>l(t({type:e(),skill_id:e(),name:e().nullish(),description:e().nullish()})));
3
+ export{by,vy,Lw,qm,Ri};
@@ -0,0 +1,6 @@
1
+ import{webcrypto as x}from"node:crypto";var T="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var q=128,c,d;function C(e){if(e<0)throw RangeError("Wrong ID size");try{if(!c||c.length<e)c=Buffer.allocUnsafe(e*q),x.getRandomValues(c),d=0;else if(d+e>c.length)x.getRandomValues(c),d=0}catch(t){throw c=void 0,t}d+=e}function M(e){return C(e|=0),c.subarray(d-e,d)}function U(e,t,s){let a=256-256%e.length;if(a===256){let i=e.length-1;return(r=t)=>{if(!r)return"";let o="";while(!0){let l=s(r),f=r;while(f--)if(o+=e[l[f]&i],o.length>=r)return o}}}let n=Math.ceil(409.6*t/a);return(i=t)=>{if(!i)return"";let r="";while(!0){let o=s(n),l=n;while(l--)if(o[l]<a){if(r+=e[o[l]%e.length],r.length>=i)return r}}}}function qw(e,t=21){return U(e,t,M)}function R(e=21){C(e|=0);let t="";for(let s=d-e;s<d;s++)t+=T[c[s]&63];return t}var y=new TextEncoder,W={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},K=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);class Jm{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:s,service:a,region:n,cache:i,retries:r,initRetryMs:o}){if(e==null)throw TypeError("accessKeyId is a required option");if(t==null)throw TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=s,this.service=a,this.region=n,this.cache=i||new Map,this.retries=r!=null?r:10,this.initRetryMs=o||50}async sign(e,t){if(e instanceof Request){let{method:n,url:i,headers:r,body:o}=e;if(t=Object.assign({method:n,url:i,headers:r},t),t.body==null&&r.has("Content-Type"))t.body=o!=null&&r.has("X-Amz-Content-Sha256")?o:await e.clone().arrayBuffer();e=i}let s=new Ym(Object.assign({url:e.toString()},t,this,t&&t.aws)),a=Object.assign({},t,await s.sign());delete a.aws;try{return new Request(a.url.toString(),a)}catch(n){if(n instanceof TypeError)return new Request(a.url.toString(),Object.assign({duplex:"half"},a));throw n}}async fetch(e,t){for(let s=0;s<=this.retries;s++){let a=fetch(await this.sign(e,t));if(s===this.retries)return a;let n=await a;if(n.status<500&&n.status!==429)return n;await new Promise((i)=>setTimeout(i,Math.random()*this.initRetryMs*Math.pow(2,s)))}throw Error("An unknown error occurred, ensure retries is not negative")}}class Ym{constructor({method:e,url:t,headers:s,body:a,accessKeyId:n,secretAccessKey:i,sessionToken:r,service:o,region:l,cache:f,datetime:k,signQuery:z,appendSessionToken:I,allHeaders:X,singleEncode:j}){if(t==null)throw TypeError("url is a required option");if(n==null)throw TypeError("accessKeyId is a required option");if(i==null)throw TypeError("secretAccessKey is a required option");this.method=e||(a?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(s||{}),this.body=a,this.accessKeyId=n,this.secretAccessKey=i,this.sessionToken=r;let w,S;if(!o||!l)[w,S]=O(this.url,this.headers);if(this.service=o||w||"",this.region=l||S||"us-east-1",this.cache=f||new Map,this.datetime=k||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=z,this.appendSessionToken=I||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256"))this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let u=this.signQuery?this.url.searchParams:this.headers;if(u.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)u.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((h)=>X||!K.has(h)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((h)=>h+":"+(h==="host"?this.url.host:(this.headers.get(h)||"").replace(/\s+/g," "))).join(`
2
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!u.has("X-Amz-Expires"))u.set("X-Amz-Expires","86400");u.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),u.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),u.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(h){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!j)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=P(this.encodedPath);let A=new Set;this.encodedSearch=[...this.url.searchParams].filter(([h])=>{if(!h)return!1;if(this.service==="s3"){if(A.has(h))return!1;A.add(h)}return!0}).map((h)=>h.map((m)=>P(encodeURIComponent(m)))).sort(([h,m],[b,H])=>h<b?-1:h>b?1:m<H?-1:m>H?1:0).map((h)=>h.join("=")).join("&")}async sign(){if(this.signQuery){if(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken)this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)}else this.headers.set("Authorization",await this.authHeader());return{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),s=this.cache.get(t);if(!s){let a=await g("AWS4"+this.secretAccessKey,e),n=await g(a,this.region),i=await g(n,this.service);s=await g(i,"aws4_request"),this.cache.set(t,s)}return p(await g(s,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,p(await E(await this.canonicalString()))].join(`
3
+ `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
4
+ `,this.signedHeaders,await this.hexBodyHash()].join(`
5
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(e==null){if(this.body&&typeof this.body!=="string"&&!("byteLength"in this.body))throw Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=p(await E(this.body||""))}return e}}async function g(e,t){let s=await crypto.subtle.importKey("raw",typeof e==="string"?y.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",s,y.encode(t))}async function E(e){return crypto.subtle.digest("SHA-256",typeof e==="string"?y.encode(e):e)}var v=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function p(e){let t=new Uint8Array(e),s="";for(let a=0;a<t.length;a++){let n=t[a];s+=v[n>>>4&15],s+=v[n&15]}return s}function P(e){return e.replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function O(e,t){let{hostname:s,pathname:a}=e;if(s.endsWith(".on.aws")){let o=s.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return o!=null?["lambda",o[1]||""]:["",""]}if(s.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(s.endsWith(".backblazeb2.com")){let o=s.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return o!=null?["s3",o[1]||""]:["",""]}let n=s.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),i=n&&n[1]||"",r=n&&n[2];if(r==="us-gov")r="us-gov-west-1";else if(r==="s3"||r==="s3-accelerate")r="us-east-1",i="s3";else if(i==="iot")if(s.startsWith("iot."))i="execute-api";else if(s.startsWith("data.jobs.iot."))i="iot-jobs-data";else i=a==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let o=(t.get("X-Amz-Target")||"").split(".")[0];if(o==="AnyScaleFrontendService")i="application-autoscaling";else if(o==="AnyScaleScalingPlannerFrontendService")i="autoscaling-plans"}else if(r==null&&i.startsWith("s3-"))r=i.slice(3).replace(/^fips-|^external-1/,""),i="s3";else if(i.endsWith("-fips"))i=i.slice(0,-5);else if(r&&/-\d$/.test(i)&&!/-\d$/.test(r))[i,r]=[r,i];return[W[i]||i,r||""]}
6
+ export{Jm,Ym,qw,R};
@@ -0,0 +1,2 @@
1
+ import{so,Ks,Hs,Gr,V2}from"./index-0f8xrhgt.js";import{Ph,F2,j2,Yp,$2,zr,Xp,Dh,q2,Ec,Wh}from"./index-yrnwqsdt.js";import{createRequire as B}from"module";var Q=B(import.meta.url),W=class{generateResponseId(){return crypto.randomUUID()}generateTextBlockId(){return crypto.randomUUID()}generateToolCallId(){return crypto.randomUUID()}};function S(a){let t=Error("The operation was aborted.",{cause:a});return t.name="AbortError",t}function H(){return{activeText:!1,finishReason:{raw:void 0,unified:"other"},isFirstChunk:!0,usage:{inputTokens:{cacheRead:void 0,cacheWrite:void 0,noCache:void 0,total:void 0},outputTokens:{reasoning:void 0,text:void 0,total:void 0}}}}function z(a){let{cancel:t,convertToAISDKError:e,extractChunkMetadata:s,idGenerator:n,includeRawChunks:o,modelId:d,options:i,providerName:p,requestId:I,responseMetadata:R,sdkStream:q,streamResponseGetCitations:N,streamResponseGetFinishReason:D,streamResponseGetIntermediateFailures:F,url:M,version:O,warnings:U}=a,h=null,u=H(),w=new Map,y={...R},T=I,v,_;function b(r){if(!r?.length)return;_??=new Map;for(let l of r)_.set(String(l.ref_id??l.url),l)}function G(r){if(!r)return;let l=v?.prompt_tokens_details,c=r.prompt_tokens_details,m=v?.completion_tokens_details,f=r.completion_tokens_details,g=l?.cache_creation_token_details,C=c?.cache_creation_token_details;v={...v,...r,...l||c?{prompt_tokens_details:{...l,...c,...g||C?{cache_creation_token_details:{...g,...C}}:{}}}:{},...m||f?{completion_tokens_details:{...m,...f}}:{}}}function P(r,l){if(r.didEmitInputStart||r.id==null)return;if(r.didEmitInputStart=!0,l.enqueue({id:r.id,toolName:r.toolName??"",type:"tool-input-start"}),r.arguments.length>0)l.enqueue({delta:r.arguments,id:r.id,type:"tool-input-delta"})}let x=J(q,i.abortSignal)[Symbol.asyncIterator](),E=!1;return new ReadableStream({async cancel(){E=!0,t(),await x.return(void 0)},async pull(r){let{done:l,value:c}=await x.next();if(E)return;if(l)r.close();else r.enqueue(c)}}).pipeThrough(new TransformStream({flush(r){if(i.abortSignal?.aborted){A(S(i.abortSignal.reason),r,e,i,d,M);return}let l=k(r,w,n,P);if(u.activeText&&h)r.enqueue({id:h,type:"text-end"});let c=D();if(c)u.finishReason=Xp(c);else if(l)u.finishReason={raw:void 0,unified:"tool-calls"};if(u.usage=Dh(v),b(N?.()),_)for(let f of _.values())r.enqueue({id:String(f.ref_id??f.url),sourceType:"url",title:f.title,type:"source",url:f.url});let m=F?.();r.enqueue({finishReason:u.finishReason,providerMetadata:{[p]:{...Ph(v),finishReason:u.finishReason.raw??"unknown",finishReasonMapped:u.finishReason,...m?.length?{intermediateFailures:Wh(m)}:{},...T?{requestId:T}:{},responseId:y.id,version:O}},type:"finish",usage:u.usage})},start(r){r.enqueue({type:"stream-start",warnings:[...U]})},transform(r,l){if(i.abortSignal?.aborted&&!(r instanceof Error))r=S(i.abortSignal.reason);if(r instanceof Error){A(r,l,e,i,d,M);return}if(o)l.enqueue({rawValue:r._data??r,type:"raw"});let c=s(r);if(c.requestId)T=c.requestId;let m=c.responseMetadata,f=m.id!==void 0&&m.id!==y.id||m.modelId!==void 0&&m.modelId!==y.modelId||m.timestamp!==void 0&&m.timestamp.getTime()!==y.timestamp?.getTime();if(Object.assign(y,m),G(r.getTokenUsage?.()),b(r.getCitations?.()),u.isFirstChunk||f)u.isFirstChunk=!1,l.enqueue({...y,type:"response-metadata"});let g=r.getDeltaToolCalls();if(Array.isArray(g)&&g.length>0)u.finishReason={raw:void 0,unified:"tool-calls"};let C=r.getDeltaContent();if(typeof C==="string"&&C.length>0)h=V(C,l,u,h,n);if(Array.isArray(g)&&g.length>0)j(g,l,w,P);let K=r.getFinishReason();if(K){if(u.finishReason=Xp(K),u.finishReason.unified==="tool-calls"){if(k(l,w,n,P),u.activeText&&h)l.enqueue({id:h,type:"text-end"}),u.activeText=!1}}}}))}function k(a,t,e,s){let n=!1;for(let o of t.values()){if(o.didEmitCall)continue;o.id??=e.generateToolCallId(),s(o,a),n=!0,o.didEmitCall=!0,a.enqueue({id:o.id,type:"tool-input-end"}),a.enqueue({input:o.arguments,toolCallId:o.id,toolName:o.toolName??"",type:"tool-call"})}return n}function A(a,t,e,s,n,o){let d=e(a,{modelId:n,modelType:"languageModel",operation:"doStream",requestBody:Yp(s),url:o});t.enqueue({error:d instanceof Error?d:Error(String(d)),type:"error"}),t.terminate()}function V(a,t,e,s,n){let o=s;if(!e.activeText)o=n.generateTextBlockId(),t.enqueue({id:o,type:"text-start"}),e.activeText=!0;if(o)return t.enqueue({delta:a,id:o,type:"text-delta"}),o;return s??n.generateTextBlockId()}function j(a,t,e,s){for(let n of a){let o=n.index;if(typeof o!=="number"||!Number.isFinite(o))continue;if(!e.has(o))e.set(o,{arguments:"",didEmitCall:!1,didEmitInputStart:!1,id:typeof n.id==="string"&&n.id.length>0?n.id:void 0,toolName:n.function?.name});let d=e.get(o);if(!d)continue;if(typeof n.id==="string"&&n.id.length>0&&d.id===void 0)d.id=n.id;let i=n.function?.name;if(typeof i==="string"&&i.length>0)d.toolName=i;if(!d.didEmitInputStart&&d.toolName!=null&&d.id!=null)s(d,t);let p=n.function?.arguments;if(typeof p==="string"&&p.length>0){if(d.arguments+=p,d.didEmitInputStart&&d.id!=null)t.enqueue({delta:p,id:d.id,type:"tool-input-delta"})}}}async function*J(a,t){try{for await(let e of a)t?.throwIfAborted(),yield e;t?.throwIfAborted()}catch(e){if(t?.aborted)yield S(t.reason);else yield e instanceof Error?e:Error(String(e))}}var Gs=class{static COMMON_PARAM_MAPPINGS=[{camelCaseKey:"maxTokens",optionKey:"maxOutputTokens",outputKey:"max_completion_tokens"},{camelCaseKey:"temperature",optionKey:"temperature",outputKey:"temperature"},{camelCaseKey:"topP",optionKey:"topP",outputKey:"top_p"},{camelCaseKey:"frequencyPenalty",optionKey:"frequencyPenalty",outputKey:"frequency_penalty"},{camelCaseKey:"presencePenalty",optionKey:"presencePenalty",outputKey:"presence_penalty"},{camelCaseKey:"seed",optionKey:"seed",outputKey:"seed"},{optionKey:"reasoning",outputKey:"reasoning_effort"},{camelCaseKey:"parallel_tool_calls",outputKey:"parallel_tool_calls"}];async doGenerate(a,t,e){try{if(e.abortSignal?.aborted)throw S(e.abortSignal.reason);let s=this.buildCommonParts(a,t,e),{request:n,warnings:o}=this.buildRequest(a,t,e,s),d=this.createClient(a,t,s),i=await this.executeApiCall(d,n,Ec(a.requestConfig,e.abortSignal,e.headers));return F2({providerName:s.providerName,requestBody:n,requestId:i.requestId,response:i,responseHeaders:Hs(i.rawResponse.headers),version:Gr,warnings:[...s.warnings,...o]})}catch(s){throw Ks(s,{modelId:a.modelId,modelType:"languageModel",operation:"doGenerate",requestBody:Yp(e),url:this.getUrl()})}}async doStream(a,t,e){try{if(e.abortSignal?.aborted)throw S(e.abortSignal.reason);let s=this.buildCommonParts(a,t,e),{request:n,warnings:o}=this.buildRequest(a,t,e,s),d=this.createClient(a,t,s),i=await this.executeStreamCall(d,n,e.abortSignal??void 0,t,Ec(a.requestConfig,void 0,e.headers),s),p=new W,I=this.collectStreamWarnings(t,s.sapOptions),R=z({cancel:i.cancel,convertToAISDKError:Ks,extractChunkMetadata:(q)=>this.extractMetadata(q),idGenerator:p,includeRawChunks:e.includeRawChunks??!1,modelId:a.modelId,options:e,providerName:s.providerName,requestId:i.requestId,responseMetadata:{...i.responseMetadata,id:i.responseMetadata?.id??p.generateResponseId()},sdkStream:i.stream,streamResponseGetCitations:i.getCitations,streamResponseGetFinishReason:i.getFinishReason,streamResponseGetIntermediateFailures:i.getIntermediateFailures,url:this.getUrl(),version:Gr,warnings:[...s.warnings,...o,...I]});return{request:{body:n},response:{headers:i.responseHeaders},stream:R}}catch(s){throw Ks(s,{modelId:a.modelId,modelType:"languageModel",operation:"doStream",requestBody:Yp(e),url:this.getUrl()})}}buildCommonParts(a,t,e){let s=so(a.provider),n=a.parsedProviderOptions,o=[],d=this.resolveAdditionalState(a,t,n,e,o),i=V2(e.prompt,{escapeTemplatePlaceholders:this.getEscapeTemplatePlaceholders(n,t),includeReasoning:this.getIncludeReasoning(n,t),parsePartProviderOptions:this.getPartProviderOptionsParser(),warnings:o}),{modelParams:p,warnings:I}=j2({options:e,paramMappings:this.getParamMappings(),providerModelParams:n?.modelParams,settingsModelParams:t.modelParams});o.push(...I);let R=q2(e.toolChoice);return{messages:i,modelParams:p,providerName:s,resolvedState:d,sapOptions:n,toolChoice:R,warnings:o}}collectStreamWarnings(a,t){return[]}extractMetadata(a){let t=$2(a,this.getCompletionDataPath()),{headers:e,requestId:s}=zr(a,"rawResponse");return{requestId:s,responseHeaders:e,responseMetadata:t}}getEscapeTemplatePlaceholders(a,t){return!1}getIncludeReasoning(a,t){return a?.includeReasoning??t.includeReasoning??!1}getPartProviderOptionsParser(){return}resolveAdditionalState(a,t,e,s,n){return}};
2
+ export{Gs};
@@ -0,0 +1,3 @@
1
+ import{jo,eu,Vr,H2,iu,dd}from"./index-h7s1a560.js";import{bt}from"./index-mcnngj50.js";function Fe(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,"");let r=e.indexOf(",");if(r===-1||r<=4)throw TypeError("malformed data: URI");let t=e.substring(5,r).split(";"),n="",o=!1,s=t[0]||"text/plain",f=s;for(let T=1;T<t.length;T++)if(t[T]==="base64")o=!0;else if(t[T]){if(f+=`;${t[T]}`,t[T].indexOf("charset=")===0)n=t[T].substring(8)}if(!t[0]&&!n.length)f+=";charset=US-ASCII",n="US-ASCII";let c=o?"base64":"ascii",l=unescape(e.substring(r+1)),i=Buffer.from(l,c);return i.type=s,i.typeFull=f,i.charset=n,i}var se;var ie=bt(()=>{se=Fe});var L;var D=bt(()=>{L=class L extends Error{constructor(e,r){super(e);Error.captureStackTrace(this,this.constructor),this.type=r}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var y;var Q=bt(()=>{D();y=class y extends L{constructor(e,r,t){super(e,r);if(t)this.code=this.errno=t.code,this.erroredSysCall=t.syscall}}});var M,X=(e)=>typeof e==="object"&&typeof e.append==="function"&&typeof e.delete==="function"&&typeof e.get==="function"&&typeof e.getAll==="function"&&typeof e.has==="function"&&typeof e.set==="function"&&typeof e.sort==="function"&&e[M]==="URLSearchParams",I=(e)=>e&&typeof e==="object"&&typeof e.arrayBuffer==="function"&&typeof e.type==="string"&&typeof e.stream==="function"&&typeof e.constructor==="function"&&/^(Blob|File)$/.test(e[M]),ae=(e)=>typeof e==="object"&&(e[M]==="AbortSignal"||e[M]==="EventTarget"),fe=(e,r)=>{let t=new URL(r).hostname,n=new URL(e).hostname;return t===n||t.endsWith(`.${n}`)},ce=(e,r)=>{let t=new URL(r).protocol,n=new URL(e).protocol;return t===n};var W=bt(()=>{M=Symbol.toStringTag});import U,{PassThrough as le}from"node:stream";import{types as ue,deprecate as q,promisify as ke}from"node:util";import{Buffer as b}from"node:buffer";class P{constructor(e,{size:r=0}={}){let t=null;if(e===null)e=null;else if(X(e))e=b.from(e.toString());else if(I(e));else if(b.isBuffer(e));else if(ue.isAnyArrayBuffer(e))e=b.from(e);else if(ArrayBuffer.isView(e))e=b.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof U);else if(e instanceof Vr)e=H2(e),t=e.type.split("=")[1];else e=b.from(String(e));let n=e;if(b.isBuffer(e))n=U.Readable.from(e);else if(I(e))n=U.Readable.from(e.stream());if(this[m]={body:e,stream:n,boundary:t,disturbed:!1,error:null},this.size=r,e instanceof U)e.on("error",(o)=>{let s=o instanceof L?o:new y(`Invalid response body while trying to fetch ${this.url}: ${o.message}`,"system",o);this[m].error=s})}get body(){return this[m].stream}get bodyUsed(){return this[m].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:r,byteLength:t}=await j(this);return e.slice(r,r+t)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let t=new Vr,n=new URLSearchParams(await this.text());for(let[o,s]of n)t.append(o,s);return t}let{toFormData:r}=await import("./multipart-parser-qkjjf8mm.js");return r(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[m].body&&this[m].body.type||"",r=await this.arrayBuffer();return new jo([r],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await j(this);return new TextDecoder().decode(e)}buffer(){return j(this)}}async function j(e){if(e[m].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[m].disturbed=!0,e[m].error)throw e[m].error;let{body:r}=e;if(r===null)return b.alloc(0);if(!(r instanceof U))return b.alloc(0);let t=[],n=0;try{for await(let o of r){if(e.size>0&&n+o.length>e.size){let s=new y(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw r.destroy(s),s}n+=o.length,t.push(o)}}catch(o){throw o instanceof L?o:new y(`Invalid response body while trying to fetch ${e.url}: ${o.message}`,"system",o)}if(r.readableEnded===!0||r._readableState.ended===!0)try{if(t.every((o)=>typeof o==="string"))return b.from(t.join(""));return b.concat(t,n)}catch(o){throw new y(`Could not create Buffer from response body for ${e.url}: ${o.message}`,"system",o)}else throw new y(`Premature close of server response while trying to fetch ${e.url}`)}var Oe,m,F=(e,r)=>{let t,n,{body:o}=e[m];if(e.bodyUsed)throw Error("cannot clone body after it is used");if(o instanceof U&&typeof o.getBoundary!=="function")t=new le({highWaterMark:r}),n=new le({highWaterMark:r}),o.pipe(t),o.pipe(n),e[m].stream=t,o=n;return o},He,V=(e,r)=>{if(e===null)return null;if(typeof e==="string")return"text/plain;charset=UTF-8";if(X(e))return"application/x-www-form-urlencoded;charset=UTF-8";if(I(e))return e.type||null;if(b.isBuffer(e)||ue.isAnyArrayBuffer(e)||ArrayBuffer.isView(e))return null;if(e instanceof Vr)return`multipart/form-data; boundary=${r[m].boundary}`;if(e&&typeof e.getBoundary==="function")return`multipart/form-data;boundary=${He(e)}`;if(e instanceof U)return null;return"text/plain;charset=UTF-8"},he=(e)=>{let{body:r}=e[m];if(r===null)return 0;if(I(r))return r.size;if(b.isBuffer(r))return r.length;if(r&&typeof r.getLengthSync==="function")return r.hasKnownLength&&r.hasKnownLength()?r.getLengthSync():null;return null},de=async(e,{body:r})=>{if(r===null)e.end();else await Oe(r,e)};var _=bt(()=>{eu();iu();Q();D();W();Oe=ke(U.pipeline),m=Symbol("Body internals");P.prototype.buffer=q(P.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(P.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:q(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});He=q((e)=>e.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167")});import{types as pe}from"node:util";import K from"node:http";function me(e=[]){return new g(e.reduce((r,t,n,o)=>{if(n%2===0)r.push(o.slice(n,n+2));return r},[]).filter(([r,t])=>{try{return G(r),ee(r,String(t)),!0}catch{return!1}}))}var G,ee,g;var Y=bt(()=>{G=typeof K.validateHeaderName==="function"?K.validateHeaderName:(e)=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let r=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),r}},ee=typeof K.validateHeaderValue==="function"?K.validateHeaderValue:(e,r)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(r)){let t=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}};g=class g extends URLSearchParams{constructor(e){let r=[];if(e instanceof g){let t=e.raw();for(let[n,o]of Object.entries(t))r.push(...o.map((s)=>[n,s]))}else if(e==null);else if(typeof e==="object"&&!pe.isBoxedPrimitive(e)){let t=e[Symbol.iterator];if(t==null)r.push(...Object.entries(e));else{if(typeof t!=="function")throw TypeError("Header pairs must be iterable");r=[...e].map((n)=>{if(typeof n!=="object"||pe.isBoxedPrimitive(n))throw TypeError("Each header pair must be an iterable object");return[...n]}).map((n)=>{if(n.length!==2)throw TypeError("Each header pair must be a name/value tuple");return[...n]})}}else throw TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");r=r.length>0?r.map(([t,n])=>(G(t),ee(t,String(n)),[String(t).toLowerCase(),String(n)])):void 0;super(r);return new Proxy(this,{get(t,n,o){switch(n){case"append":case"set":return(s,f)=>(G(s),ee(s,String(f)),URLSearchParams.prototype[n].call(t,String(s).toLowerCase(),String(f)));case"delete":case"has":case"getAll":return(s)=>(G(s),URLSearchParams.prototype[n].call(t,String(s).toLowerCase()));case"keys":return()=>(t.sort(),new Set(URLSearchParams.prototype.keys.call(t)).keys());default:return Reflect.get(t,n,o)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let r=this.getAll(e);if(r.length===0)return null;let t=r.join(", ");if(/^content-encoding$/i.test(e))t=t.toLowerCase();return t}forEach(e,r=void 0){for(let t of this.keys())Reflect.apply(e,r,[this.get(t),t,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,r)=>(e[r]=this.getAll(r),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,r)=>{let t=this.getAll(r);if(r==="host")e[r]=t[0];else e[r]=t.length>1?t:t[0];return e},{})}};Object.defineProperties(g.prototype,["get","entries","forEach","values"].reduce((e,r)=>(e[r]={enumerable:!0},e),{}))});var Ie,J=(e)=>Ie.has(e);var re=bt(()=>{Ie=new Set([301,302,303,307,308])});var S,p;var ye=bt(()=>{Y();_();re();S=Symbol("Response internals");p=class p extends P{constructor(e=null,r={}){super(e,r);let t=r.status!=null?r.status:200,n=new g(r.headers);if(e!==null&&!n.has("Content-Type")){let o=V(e,this);if(o)n.append("Content-Type",o)}this[S]={type:"default",url:r.url,status:t,statusText:r.statusText||"",headers:n,counter:r.counter,highWaterMark:r.highWaterMark}}get type(){return this[S].type}get url(){return this[S].url||""}get status(){return this[S].status}get ok(){return this[S].status>=200&&this[S].status<300}get redirected(){return this[S].counter>0}get statusText(){return this[S].statusText}get headers(){return this[S].headers}get highWaterMark(){return this[S].highWaterMark}clone(){return new p(F(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,r=302){if(!J(r))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');return new p(null,{headers:{location:new URL(e).toString()},status:r})}static error(){let e=new p(null,{status:0,statusText:""});return e[S].type="error",e}static json(e=void 0,r={}){let t=JSON.stringify(e);if(t===void 0)throw TypeError("data is not JSON serializable");let n=new g(r&&r.headers);if(!n.has("content-type"))n.set("content-type","application/json");return new p(t,{...r,headers:n})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(p.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})});var ge=(e)=>{if(e.search)return e.search;let r=e.href.length-1,t=e.hash||(e.href[r]==="#"?"#":"");return e.href[r-t.length]==="?"?"?":""};var we=()=>{};import{isIP as ze}from"node:net";function be(e,r=!1){if(e==null)return"no-referrer";if(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))return"no-referrer";if(e.username="",e.password="",e.hash="",r)e.pathname="",e.search="";return e}function Re(e){if(!Se.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function Ne(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let r=e.host.replace(/(^\[)|(]$)/g,""),t=ze(r);if(t===4&&/^127\./.test(r))return!0;if(t===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(r))return!0;if(e.host==="localhost"||e.host.endsWith(".localhost"))return!1;if(e.protocol==="file:")return!0;return!1}function k(e){if(/^about:(blank|srcdoc)$/.test(e))return!0;if(e.protocol==="data:")return!0;if(/^(blob|filesystem):$/.test(e.protocol))return!0;return Ne(e)}function Ee(e,{referrerURLCallback:r,referrerOriginCallback:t}={}){if(e.referrer==="no-referrer"||e.referrerPolicy==="")return null;let n=e.referrerPolicy;if(e.referrer==="about:client")return"no-referrer";let o=e.referrer,s=be(o),f=be(o,!0);if(s.toString().length>4096)s=f;if(r)s=r(s);if(t)f=t(f);let c=new URL(e.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return f;case"unsafe-url":return s;case"strict-origin":if(k(s)&&!k(c))return"no-referrer";return f.toString();case"strict-origin-when-cross-origin":if(s.origin===c.origin)return s;if(k(s)&&!k(c))return"no-referrer";return f;case"same-origin":if(s.origin===c.origin)return s;return"no-referrer";case"origin-when-cross-origin":if(s.origin===c.origin)return s;return f;case"no-referrer-when-downgrade":if(k(s)&&!k(c))return"no-referrer";return s;default:throw TypeError(`Invalid referrerPolicy: ${n}`)}}function xe(e){let r=(e.get("referrer-policy")||"").split(/[,\s]+/),t="";for(let n of r)if(n&&Se.has(n))t=n;return t}var Se,Te="strict-origin-when-cross-origin";var te=bt(()=>{Se=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"])});import{format as De}from"node:url";import{deprecate as Me}from"node:util";var u,z=(e)=>typeof e==="object"&&typeof e[u]==="object",We,A,Pe=(e)=>{let{parsedURL:r}=e[u],t=new g(e[u].headers);if(!t.has("Accept"))t.set("Accept","*/*");let n=null;if(e.body===null&&/^(post|put)$/i.test(e.method))n="0";if(e.body!==null){let c=he(e);if(typeof c==="number"&&!Number.isNaN(c))n=String(c)}if(n)t.set("Content-Length",n);if(e.referrerPolicy==="")e.referrerPolicy=Te;if(e.referrer&&e.referrer!=="no-referrer")e[u].referrer=Ee(e);else e[u].referrer="no-referrer";if(e[u].referrer instanceof URL)t.set("Referer",e.referrer);if(!t.has("User-Agent"))t.set("User-Agent","node-fetch");if(e.compress&&!t.has("Accept-Encoding"))t.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=e;if(typeof o==="function")o=o(r);let s=ge(r),f={path:r.pathname+s,method:e.method,headers:t[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:o};return{parsedURL:r,options:f}};var Le=bt(()=>{Y();_();W();we();te();u=Symbol("Request internals"),We=Me(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)");A=class A extends P{constructor(e,r={}){let t;if(z(e))t=new URL(e.url);else t=new URL(e),e={};if(t.username!==""||t.password!=="")throw TypeError(`${t} is an url with embedded credentials.`);let n=r.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(n))n=n.toUpperCase();if(!z(r)&&"data"in r)We();if((r.body!=null||z(e)&&e.body!==null)&&(n==="GET"||n==="HEAD"))throw TypeError("Request with GET/HEAD method cannot have body");let o=r.body?r.body:z(e)&&e.body!==null?F(e):null;super(o,{size:r.size||e.size||0});let s=new g(r.headers||e.headers||{});if(o!==null&&!s.has("Content-Type")){let l=V(o,this);if(l)s.set("Content-Type",l)}let f=z(e)?e.signal:null;if("signal"in r)f=r.signal;if(f!=null&&!ae(f))throw TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let c=r.referrer==null?e.referrer:r.referrer;if(c==="")c="no-referrer";else if(c){let l=new URL(c);c=/^about:(\/\/)?client$/.test(l)?"client":l}else c=void 0;this[u]={method:n,redirect:r.redirect||e.redirect||"follow",headers:s,parsedURL:t,signal:f,referrer:c},this.follow=r.follow===void 0?e.follow===void 0?20:e.follow:r.follow,this.compress=r.compress===void 0?e.compress===void 0?!0:e.compress:r.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent,this.highWaterMark=r.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=r.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=r.referrerPolicy||e.referrerPolicy||""}get method(){return this[u].method}get url(){return De(this[u].parsedURL)}get headers(){return this[u].headers}get redirect(){return this[u].redirect}get signal(){return this[u].signal}get referrer(){if(this[u].referrer==="no-referrer")return"";if(this[u].referrer==="client")return"about:client";if(this[u].referrer)return this[u].referrer.toString();return}get referrerPolicy(){return this[u].referrerPolicy}set referrerPolicy(e){this[u].referrerPolicy=Re(e)}clone(){return new A(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(A.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}})});var oe;var Ue=bt(()=>{D();oe=class oe extends L{constructor(e,r="aborted"){super(e,r)}}});import Ve from"node:http";import _e from"node:https";import O from"node:zlib";import ve,{PassThrough as Be,pipeline as H}from"node:stream";import{Buffer as Z}from"node:buffer";async function Ae(e,r){return new Promise((t,n)=>{let o=new A(e,r),{parsedURL:s,options:f}=Pe(o);if(!Ge.has(s.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let a=se(o.url),E=new p(a,{headers:{"Content-Type":a.typeFull}});t(E);return}let c=(s.protocol==="https:"?_e:Ve).request,{signal:l}=o,i=null,T=()=>{let a=new oe("The operation was aborted.");if(n(a),o.body&&o.body instanceof ve.Readable)o.body.destroy(a);if(!i||!i.body)return;i.body.emit("error",a)};if(l&&l.aborted){T();return}let N=()=>{T(),B()},v=c(s.toString(),f);if(l)l.addEventListener("abort",N);let B=()=>{if(v.abort(),l)l.removeEventListener("abort",N)};if(v.on("error",(a)=>{n(new y(`request to ${o.url} failed, reason: ${a.message}`,"system",a)),B()}),Ke(v,(a)=>{if(i&&i.body)i.body.destroy(a)}),process.version<"v14")v.on("socket",(a)=>{let E;a.prependListener("end",()=>{E=a._eventsCount}),a.prependListener("close",(h)=>{if(i&&E<a._eventsCount&&!h){let x=Error("Premature close");x.code="ERR_STREAM_PREMATURE_CLOSE",i.body.emit("error",x)}})});v.on("response",(a)=>{v.setTimeout(0);let E=me(a.rawHeaders);if(J(a.statusCode)){let d=E.get("Location"),R=null;try{R=d===null?null:new URL(d,o.url)}catch{if(o.redirect!=="manual"){n(new y(`uri requested responds with an invalid redirect URL: ${d}`,"invalid-redirect")),B();return}}switch(o.redirect){case"error":n(new y(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),B();return;case"manual":break;case"follow":{if(R===null)break;if(o.counter>=o.follow){n(new y(`maximum redirect reached at: ${o.url}`,"max-redirect")),B();return}let w={headers:new g(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:F(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!fe(o.url,R)||!ce(o.url,R))for(let $e of["authorization","www-authenticate","cookie","cookie2"])w.headers.delete($e);if(a.statusCode!==303&&o.body&&r.body instanceof ve.Readable){n(new y("Cannot follow redirect with body being a readable stream","unsupported-redirect")),B();return}if(a.statusCode===303||(a.statusCode===301||a.statusCode===302)&&o.method==="POST")w.method="GET",w.body=void 0,w.headers.delete("content-length");let ne=xe(E);if(ne)w.referrerPolicy=ne;t(Ae(new A(R,w))),B();return}default:return n(TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}if(l)a.once("end",()=>{l.removeEventListener("abort",N)});let h=H(a,new Be,(d)=>{if(d)n(d)});if(process.version<"v12.10")a.on("aborted",N);let x={url:o.url,status:a.statusCode,statusText:a.statusMessage,headers:E,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},C=E.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||C===null||a.statusCode===204||a.statusCode===304){i=new p(h,x),t(i);return}let Ce={flush:O.Z_SYNC_FLUSH,finishFlush:O.Z_SYNC_FLUSH};if(C==="gzip"||C==="x-gzip"){h=H(h,O.createGunzip(Ce),(d)=>{if(d)n(d)}),i=new p(h,x),t(i);return}if(C==="deflate"||C==="x-deflate"){let d=H(a,new Be,(R)=>{if(R)n(R)});d.once("data",(R)=>{if((R[0]&15)===8)h=H(h,O.createInflate(),(w)=>{if(w)n(w)});else h=H(h,O.createInflateRaw(),(w)=>{if(w)n(w)});i=new p(h,x),t(i)}),d.once("end",()=>{if(!i)i=new p(h,x),t(i)});return}if(C==="br"){h=H(h,O.createBrotliDecompress(),(d)=>{if(d)n(d)}),i=new p(h,x),t(i);return}i=new p(h,x),t(i)}),de(v,o).catch(n)})}function Ke(e,r){let t=Z.from(`0\r
2
+ \r
3
+ `),n=!1,o=!1,s;e.on("response",(f)=>{let{headers:c}=f;n=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),e.on("socket",(f)=>{let c=()=>{if(n&&!o){let i=Error("Premature close");i.code="ERR_STREAM_PREMATURE_CLOSE",r(i)}},l=(i)=>{if(o=Z.compare(i.slice(-5),t)===0,!o&&s)o=Z.compare(s.slice(-3),t.slice(0,3))===0&&Z.compare(i.slice(-2),t.slice(3))===0;s=i};f.prependListener("close",c),f.on("data",l),e.on("close",()=>{f.removeListener("close",c),f.removeListener("data",l)})})}var Ge;var Ye=bt(()=>{ie();_();ye();Y();Le();Q();Ue();re();iu();W();te();dd();Ge=new Set(["data:","http:","https:"])});Ye();export{Ae as default};
@@ -0,0 +1 @@
1
+ import{se,sa,Fo,Zl,sd}from"./index-0f8xrhgt.js";import{v}from"./index-mcnngj50.js";var _=v(se(),1);class l{rawResponse;_data;constructor(e){this.rawResponse=e,this._data=e.data}getRequestId(){return _.pickValueIgnoreCase(this.rawResponse.headers,"x-aicore-request-id")}getTokenUsage(){return this._data.usage}getFinishReason(e=0){return this.findChoiceByIndex(e)?.finish_reason}getContent(e=0){return this.findChoiceByIndex(e)?.message?.content}getToolCalls(e=0){return this.findChoiceByIndex(e)?.message?.tool_calls}getRefusal(e=0){return this.findChoiceByIndex(e)?.message?.refusal}getAssistantMessage(e=0){return this.findChoiceByIndex(e)?.message}findChoiceByIndex(e){return this.getChoices().find((t)=>t.index===e)}getChoices(){return this._data.choices}}var u=v(se(),1);function x(e){return typeof e.id==="string"&&typeof e.function.name==="string"&&typeof e.function.arguments==="string"}function w(e,t){let o=t?{...t}:{type:"function",function:{}};if(e.id)o.id=e.id;for(let s of Object.keys(e))if(!["index","id","type","function"].includes(s))o[s]=e[s];if(e.function){if(e.function.name)o.function.name=e.function.name;if(e.function.arguments)o.function.arguments=(o.function.arguments||"")+e.function.arguments;for(let s of Object.keys(e.function))if(!["name","arguments"].includes(s))o.function[s]=e.function[s]}return o}var I=u.createLogger({package:"foundation-models",messageContext:"azure-openai-chat-completion-stream-response"});class p{_usage;_finishReasons=new Map;_toolCallsAccumulators=new Map;_toolCalls=new Map;_stream;_rawResponse;constructor(e){if(!e){I.warn("Constructing AzureOpenAiChatCompletionStreamResponse without raw HTTP response is deprecated and can lead to runtime errors when accessing `rawResponse`.");return}this._rawResponse=e}get rawResponse(){if(!this._rawResponse)throw Error("The raw response is not available. Please provide the raw response when constructing `AzureOpenAiChatCompletionStreamResponse`.");return this._rawResponse}getRequestId(){return u.pickValueIgnoreCase(this._rawResponse?.headers,"x-aicore-request-id")}getTokenUsage(){return this._usage}_setTokenUsage(e){this._usage=e}getFinishReason(e=0){return this._finishReasons.get(e)}_getFinishReasons(){return this._finishReasons}_setFinishReasons(e){this._finishReasons=e}getToolCalls(e=0){return this._toolCalls.get(e)}_setToolCalls(e,t){this._toolCalls.set(e,t)}_getToolCallsAccumulators(){return this._toolCallsAccumulators}get stream(){if(!this._stream)throw Error("Response stream is undefined.");return this._stream}set stream(e){this._stream=e}}var y=v(se(),1);class m{_data;constructor(e){this._data=e}getTokenUsage(){return this._data.usage}getFinishReason(e=0){return this.findChoiceByIndex(e)?.finish_reason}getDeltaContent(e=0){return this.findChoiceByIndex(e)?.delta.content}getDeltaToolCalls(e=0){return this.findChoiceByIndex(e)?.delta.tool_calls}findChoiceByIndex(e){return this.getChoices()?.find((t)=>t.index===e)}getChoices(){return this._data.choices}}var c=y.createLogger({package:"foundation-models",messageContext:"azure-openai-chat-completion-stream"});class r extends Fo{static _create(e,t){let o=Fo.transformToSseStream(e,t);return new r(o.iterator,t)}static async*_processChunk(e){for await(let t of e)yield new m(t)}static async*_processToolCalls(e,t){if(!t)throw Error("Response is required to process tool calls.");for await(let o of e)o._data.choices.forEach((s)=>{let n=s.index,i=o.getDeltaToolCalls(n);if(i){let a=t._getToolCallsAccumulators().get(n);if(!a)a=new Map,t._getToolCallsAccumulators().set(n,a);i.forEach((g)=>{let C=g.index,T=w(g,a.get(C));a.set(C,T)})}}),yield o;for(let[o,s]of t._getToolCallsAccumulators()){let n=[];for(let[i,a]of s.entries())if(x(a))n.push(a);else c.error(`Error while parsing tool calls for choice index ${o}: Tool call with id ${i} was incomplete.`);t._setToolCalls(o,n)}}static async*_processFinishReason(e,t){for await(let o of e)o._data.choices.forEach((s)=>{let n=s.index;if(n>=0){let i=o.getFinishReason(n);if(i){if(t)t._getFinishReasons().set(n,i);switch(i){case"content_filter":c.error(`Choice ${n}: Stream finished with content filter hit.`);break;case"length":c.error(`Choice ${n}: Stream finished with token length exceeded.`);break;case"stop":case"tool_calls":case"function_call":c.debug(`Choice ${n}: Stream finished.`);break;default:c.error(`Choice ${n}: Stream finished with unknown reason '${String(i)}'.`)}}}}),yield o}static async*_processTokenUsage(e,t){for await(let o of e){let s=o.getTokenUsage();if(s){if(t)t._setTokenUsage(s);c.debug(`Token usage: ${JSON.stringify(s)}`)}yield o}}static async*_processContentStream(e,t=0){for await(let o of e){let s=o.getDeltaContent(t);if(!s)continue;yield s}}constructor(e,t){super(e,t)}_pipe(e,t){if(t)return new r(()=>e(this,t),this.controller);return new r(()=>e(this),this.controller)}toContentStream(e){return new r(()=>r._processContentStream(this,e),this.controller)}}var h="2024-10-21";class R{modelDeployment;destination;constructor(e,t){this.modelDeployment=e,this.destination=t}async run(e,t){let o=await this.executeRequest(e,t);return new l(o)}async stream(e,t,o){let s=new AbortController;if(t)t.addEventListener("abort",()=>{s.abort()});return this.createStreamResponse(e,s,o)}async executeRequest(e,t){let o=await sd(this.modelDeployment,"azure-openai",this.destination),s=Zl(this.modelDeployment);return sa({url:`/inference/deployments/${o}/chat/completions`,apiVersion:h,resourceGroup:s},e,t,this.destination)}async createStreamResponse(e,t,o){let s=await this.executeRequest({...e,stream:!0,stream_options:{include_usage:!0}},{...o,responseType:"stream",signal:t.signal}),n=new p(s);return n.stream=r._create(s,t)._pipe(r._processChunk)._pipe(r._processToolCalls,n)._pipe(r._processFinishReason,n)._pipe(r._processTokenUsage,n),n}}var f=v(se(),1),k=f.createLogger({package:"foundation-models",messageContext:"azure-openai-embedding-response"});class d{rawResponse;_data;constructor(e){this.rawResponse=e,this._data=e.data}getRequestId(){return f.pickValueIgnoreCase(this.rawResponse.headers,"x-aicore-request-id")}getEmbedding(e=0){return this.logInvalidDataIndex(e),this._data.data[e]?.embedding}getEmbeddings(){return this._data.data.map(({embedding:e})=>e)}logInvalidDataIndex(e){if(e<0||e>=this._data.data.length)k.error(`Data index ${e} is out of bounds.`)}}class A{modelDeployment;destination;constructor(e,t){this.modelDeployment=e,this.destination=t}async run(e,t){let o=await sd(this.modelDeployment,"azure-openai",this.destination),s=Zl(this.modelDeployment),n=await sa({url:`/inference/deployments/${o}/embeddings`,apiVersion:h,resourceGroup:s},e,t,this.destination);return new d(n)}}export{R as AzureOpenAiChatClient,A as AzureOpenAiEmbeddingClient};