blink 1.1.9 → 1.1.11

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 (112) hide show
  1. package/dist/browser/agent/client/index.cjs +8 -8
  2. package/dist/browser/agent/client/index.js +8 -8
  3. package/dist/browser/control/index.d.cts +16 -16
  4. package/dist/browser/control/index.d.ts +16 -16
  5. package/dist/cli/auth-BXRoCHFw.js +31 -0
  6. package/dist/cli/{chat-BjvV7d0R.js → chat-Jjsxhu91.js} +1 -1
  7. package/dist/cli/{chat-manager-DaAkYjGP.js → chat-manager-DYZXp8bu.js} +4 -4
  8. package/dist/cli/{connect-CVCoC2zM.js → connect-BpfPzXxZ.js} +1 -1
  9. package/dist/cli/connect-O43Nkqhm.js +1 -0
  10. package/dist/cli/{dev-CcLkrDGj.js → dev-8UEn9f59.js} +128 -121
  11. package/dist/cli/devhook-C-VKp2Vf.js +1 -0
  12. package/dist/cli/index.js +9 -6
  13. package/dist/cli/{init-BKs1grB-.js → init-lHUh7gYE.js} +1 -1
  14. package/dist/cli/login-BaxIl8sF.js +1 -0
  15. package/dist/cli/{run-oo-G0Nba.js → run-DtICLjeJ.js} +1 -1
  16. package/dist/cli/{token-DWOyWoV8.js → token-CwpupgJv.js} +1 -1
  17. package/dist/cli/{token-util-UKYhGiq1.js → token-util-BGsva5RI.js} +1 -1
  18. package/dist/cli/token-util-DsmDyKzB.js +1 -0
  19. package/dist/cli/undici-Cyjf_ODA.js +1 -0
  20. package/dist/cli/{util-kaMG7TI_.js → util-sYfoyux0.js} +1 -1
  21. package/dist/node/agent/index.node.cjs +1 -1
  22. package/dist/node/agent/index.node.d.ts +1 -1
  23. package/dist/node/agent/index.node.js +1 -1
  24. package/dist/node/build/index.cjs +1 -1
  25. package/dist/node/build/index.d.ts +1 -1
  26. package/dist/node/build/index.js +1 -1
  27. package/dist/node/{build-D_L0gFGa.js → build-M5Q2ZTGh.js} +5 -5
  28. package/dist/node/{build-BzoNpizh.cjs → build-lx6plR19.cjs} +4 -4
  29. package/dist/node/{getMachineId-bsd-B84ixt26.cjs → getMachineId-bsd-CUUgtcEk.cjs} +1 -1
  30. package/dist/node/{getMachineId-bsd-BxqlJcyA.js → getMachineId-bsd-CpiyZ31n.js} +1 -1
  31. package/dist/node/{getMachineId-bsd-C10eVJgT.js → getMachineId-bsd-DKc3Wh2z.js} +1 -1
  32. package/dist/node/{getMachineId-bsd-BudRe7J9.cjs → getMachineId-bsd-YA-Qh955.cjs} +1 -1
  33. package/dist/node/{getMachineId-darwin-Bf4P0U5b.js → getMachineId-darwin-BBDIi9K5.js} +1 -1
  34. package/dist/node/{getMachineId-darwin-JB29MQsG.js → getMachineId-darwin-CQ9-5u-a.js} +1 -1
  35. package/dist/node/{getMachineId-darwin-BsTWxMfp.cjs → getMachineId-darwin-CcM48gLI.cjs} +1 -1
  36. package/dist/node/{getMachineId-darwin-Cyng5kFG.cjs → getMachineId-darwin-IcDjLpqm.cjs} +1 -1
  37. package/dist/node/{getMachineId-linux-B-CtXK0L.cjs → getMachineId-linux-BzwdWZoB.cjs} +1 -1
  38. package/dist/{cli/getMachineId-linux-ClPhWquQ.js → node/getMachineId-linux-Cc8c4coA.js} +1 -1
  39. package/dist/node/{getMachineId-linux-CJXPQ8U5.cjs → getMachineId-linux-DMvLmvRp.cjs} +1 -1
  40. package/dist/{cli/getMachineId-linux-Dbj9U4yu.js → node/getMachineId-linux-TNXyQsBB.js} +1 -1
  41. package/dist/node/{getMachineId-unsupported--0R36RP6.cjs → getMachineId-unsupported-ApoW5rxx.cjs} +1 -1
  42. package/dist/{cli/getMachineId-unsupported-Bs1SnM_0.js → node/getMachineId-unsupported-CRrpolgF.js} +1 -1
  43. package/dist/{cli/getMachineId-unsupported-CHR_usqt.js → node/getMachineId-unsupported-DGhOj3l0.js} +1 -1
  44. package/dist/node/{getMachineId-unsupported-DM7fz1pP.cjs → getMachineId-unsupported-DYGwqELh.cjs} +1 -1
  45. package/dist/node/{getMachineId-win-CjJkZMZe.cjs → getMachineId-win-B-bRjIv0.cjs} +1 -1
  46. package/dist/node/{getMachineId-win-D1szVnqR.js → getMachineId-win-CSKzOPIT.js} +1 -1
  47. package/dist/node/{getMachineId-win-DDz2FyEp.cjs → getMachineId-win-CoAu5xDr.cjs} +1 -1
  48. package/dist/node/{getMachineId-win-C4G-fkEF.js → getMachineId-win-Dfq5UG8G.js} +1 -1
  49. package/dist/node/index.node-Bpfi4MhM.cjs +55 -0
  50. package/dist/node/index.node-CKuelGPD.js +55 -0
  51. package/dist/node/react/index.node.cjs +138 -133
  52. package/dist/node/react/index.node.d.cts +3 -1
  53. package/dist/node/react/index.node.d.ts +5 -3
  54. package/dist/node/react/index.node.js +75 -70
  55. package/dist/node/{token-DY8sflMu.js → token-B0ivJQut.js} +1 -1
  56. package/dist/node/{token-Bcs36BIo.cjs → token-C10csUbV.cjs} +1 -1
  57. package/dist/node/{token-util-Czyk5fmW.js → token-util-1r_uDcp7.js} +1 -1
  58. package/dist/node/{token-util-B9ankBb5.cjs → token-util-BwRq8n40.cjs} +1 -1
  59. package/dist/node/token-util-CSWJ2yfA.js +1 -0
  60. package/dist/node/token-util-beB2LRJ9.cjs +1 -0
  61. package/package.json +2 -4
  62. package/dist/cli/auth-H6rzjAi5.js +0 -31
  63. package/dist/cli/connect-CtqmowwG.js +0 -1
  64. package/dist/cli/execAsync-B6G0LK2C.js +0 -1
  65. package/dist/cli/execAsync-Ctllx3d6.js +0 -1
  66. package/dist/cli/execAsync-DHcx5IrU.js +0 -1
  67. package/dist/cli/getMachineId-bsd-BYLNHO9x.js +0 -1
  68. package/dist/cli/getMachineId-bsd-Bg_YijfN.js +0 -1
  69. package/dist/cli/getMachineId-bsd-Bxa9lNXK.js +0 -1
  70. package/dist/cli/getMachineId-darwin-BrUGbJv8.js +0 -2
  71. package/dist/cli/getMachineId-darwin-CtvOW9mQ.js +0 -2
  72. package/dist/cli/getMachineId-darwin-liMTOj7C.js +0 -2
  73. package/dist/cli/getMachineId-linux-CiDK6aCK.js +0 -1
  74. package/dist/cli/getMachineId-unsupported-Bi2KfeL-.js +0 -1
  75. package/dist/cli/getMachineId-win-Bulv8Srt.js +0 -1
  76. package/dist/cli/getMachineId-win-C2CDdXPL.js +0 -1
  77. package/dist/cli/getMachineId-win-tGnHJTQN.js +0 -1
  78. package/dist/cli/ignore-NA4V6Pjc.js +0 -1
  79. package/dist/cli/login-DZMx8lNz.js +0 -1
  80. package/dist/cli/token-util-5SlAL-E7.js +0 -1
  81. package/dist/cli/undici-DnqlJkTO.js +0 -1
  82. package/dist/node/execAsync-DDSV4gfK.cjs +0 -1
  83. package/dist/node/execAsync-DQysi_u6.js +0 -1
  84. package/dist/node/getMachineId-bsd-D2W6fhXU.js +0 -1
  85. package/dist/node/getMachineId-bsd-DM9BAly2.cjs +0 -1
  86. package/dist/node/getMachineId-darwin-Dk0tjVME.js +0 -2
  87. package/dist/node/getMachineId-darwin-ZVi3EKE3.cjs +0 -2
  88. package/dist/node/getMachineId-linux-BPnkHJah.js +0 -1
  89. package/dist/node/getMachineId-linux-CmMSYp7C.js +0 -1
  90. package/dist/node/getMachineId-linux-DZ7RMAHq.js +0 -1
  91. package/dist/node/getMachineId-linux-DmWhhrp6.cjs +0 -1
  92. package/dist/node/getMachineId-unsupported-C_4fnT4Z.js +0 -1
  93. package/dist/node/getMachineId-unsupported-CiZad6mc.js +0 -1
  94. package/dist/node/getMachineId-unsupported-Dtt3HTNZ.js +0 -1
  95. package/dist/node/getMachineId-unsupported-y6X1AHF8.cjs +0 -1
  96. package/dist/node/getMachineId-win-_P_0Nv15.js +0 -1
  97. package/dist/node/getMachineId-win-e1UzWB2B.cjs +0 -1
  98. package/dist/node/index.node-CERnwYbK.js +0 -55
  99. package/dist/node/index.node-sb6fILn2.cjs +0 -55
  100. package/dist/node/token-util-BIiR16HV.js +0 -1
  101. package/dist/node/token-util-BrE-Vihm.cjs +0 -1
  102. /package/dist/cli/{devtools-CmKJ6wJc.js → devtools-aLFrISVw.js} +0 -0
  103. /package/dist/cli/{init-BDulGjOS.js → init-DYOLPWi7.js} +0 -0
  104. /package/dist/cli/{server-C8plsU0X-C-2SFw7d.js → server-C8plsU0X-BmosAKXr.js} +0 -0
  105. /package/dist/cli/{token-error-CFvhLJ_l.js → token-error-C6TSmqWz.js} +0 -0
  106. /package/dist/cli/{undici-DpMlUpXi.js → undici-v5uUkaRO.js} +0 -0
  107. /package/dist/node/{esm-0UNjvroT.cjs → esm-C-vSI1Ww.cjs} +0 -0
  108. /package/dist/node/{esm-CbZfjZBn.js → esm-D1GEQyaY.js} +0 -0
  109. /package/dist/node/{index-Q90WjL1a.d.ts → index-C28Wm0bG.d.ts} +0 -0
  110. /package/dist/node/{index.node-BN_MeTbR.d.ts → index.node-CiqENj_g.d.ts} +0 -0
  111. /package/dist/node/{token-error-BoNG8ooW.cjs → token-error-l6zIbPbZ.cjs} +0 -0
  112. /package/dist/node/{token-error-488npYdU.js → token-error-wsvzy87W.js} +0 -0
@@ -2,9 +2,9 @@ import*as e from"node:path";import*as t from"node:fs";import n,{z as r}from"zod/
2
2
  `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new bt(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new bt(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
3
3
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Ct(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
4
4
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
5
- `&&r++}}return[t,n]}var wt=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=St({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}},Tt=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),Et=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},Dt=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t},Ot=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},kt=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function At(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jt(e,t){if(!At(e)&&!At(t))return t;let n={...e};for(let e in t){let r=t[e];At(n[e])&&At(r)?n[e]=jt(n[e],r):n[e]=r}return n}var Mt=(e,t)=>new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return Mt(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}}),Nt=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(e,t)=>{if(e){if(e.query&&(this.queryParams=Dt(e.query)),e.form){let t=new FormData;for(let[n,r]of Object.entries(e.form))if(Array.isArray(r))for(let e of r)t.append(n,e);else t.append(n,r);this.rBody=t}e.json&&(this.rBody=JSON.stringify(e.json),this.cType=`application/json`),e.param&&(this.pathParams=e.param)}let n=this.method.toUpperCase(),r={...e?.header,...typeof t?.headers==`function`?await t.headers():t?.headers};if(e?.cookie){let t=[];for(let[n,r]of Object.entries(e.cookie))t.push(Je(n,r,{path:`/`}));r.Cookie=t.join(`,`)}this.cType&&(r[`Content-Type`]=this.cType);let i=new Headers(r??void 0),a=this.url;a=kt(a),a=Et(a,this.pathParams),this.queryParams&&(a=a+`?`+this.queryParams.toString()),n=this.method.toUpperCase();let o=!(n===`GET`||n===`HEAD`);return(t?.fetch||fetch)(a,{body:o?this.rBody:void 0,method:n,headers:i,...t?.init})}},Pt=(e,t)=>Mt(function n(r){let i=[...r.path],a=i.slice(-3).reverse();if(a[0]===`toString`)return a[1]===`name`?a[2]||``:n.toString();if(a[0]===`valueOf`)return a[1]===`name`?a[2]||``:n;let o=``;if(/^\$/.test(a[0])){let e=i.pop();e&&(o=e.replace(/^\$/,``))}let s=i.join(`/`),c=Tt(e,s);if(o===`url`){let e=c;return r.args[0]&&(r.args[0].param&&(e=Et(c,r.args[0].param)),r.args[0].query&&(e=e+`?`+Dt(r.args[0].query).toString())),e=kt(e),new URL(e)}if(o===`ws`){let e=Ot(r.args[0]&&r.args[0].param?Et(c,r.args[0].param):c,`ws`),n=new URL(e),i=r.args[0]?.query;return i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)}),((...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e))(n.toString())}let l=new Nt(c,o);if(o){t??={};let e=jt(t,{...r.args[1]});return l.fetch(r.args[0],e)}return l},[]),Ft=`vercel.ai.error`,It=Symbol.for(Ft),Lt,Rt=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Lt]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Ft)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Lt=It;var O=Rt,zt=`AI_APICallError`,Bt=`vercel.ai.error.${zt}`,Vt=Symbol.for(Bt),Ht,k=class extends O{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:a,cause:o,isRetryable:s=r!=null&&(r===408||r===409||r===429||r>=500),data:c}){super({name:zt,message:e,cause:o}),this[Ht]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=a,this.isRetryable=s,this.data=c}static isInstance(e){return O.hasMarker(e,Bt)}};Ht=Vt;var Ut=`AI_EmptyResponseBodyError`,Wt=`vercel.ai.error.${Ut}`,Gt=Symbol.for(Wt),Kt,qt=class extends O{constructor({message:e=`Empty response body`}={}){super({name:Ut,message:e}),this[Kt]=!0}static isInstance(e){return O.hasMarker(e,Wt)}};Kt=Gt;function Jt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var Yt=`AI_InvalidArgumentError`,Xt=`vercel.ai.error.${Yt}`,Zt=Symbol.for(Xt),Qt,$t=class extends O{constructor({message:e,cause:t,argument:n}){super({name:Yt,message:e,cause:t}),this[Qt]=!0,this.argument=n}static isInstance(e){return O.hasMarker(e,Xt)}};Qt=Zt;var en=`AI_InvalidPromptError`,tn=`vercel.ai.error.${en}`,nn=Symbol.for(tn),rn,an=class extends O{constructor({prompt:e,message:t,cause:n}){super({name:en,message:`Invalid prompt: ${t}`,cause:n}),this[rn]=!0,this.prompt=e}static isInstance(e){return O.hasMarker(e,tn)}};rn=nn;var on=`AI_InvalidResponseDataError`,sn=`vercel.ai.error.${on}`,cn=Symbol.for(sn),ln,un=class extends O{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:on,message:t}),this[ln]=!0,this.data=e}static isInstance(e){return O.hasMarker(e,sn)}};ln=cn;var dn=`AI_JSONParseError`,fn=`vercel.ai.error.${dn}`,pn=Symbol.for(fn),mn,A=class extends O{constructor({text:e,cause:t}){super({name:dn,message:`JSON parsing failed: Text: ${e}.
6
- Error message: ${Jt(t)}`,cause:t}),this[mn]=!0,this.text=e}static isInstance(e){return O.hasMarker(e,fn)}};mn=pn;var hn=`AI_LoadAPIKeyError`,gn=`vercel.ai.error.${hn}`,_n=Symbol.for(gn),vn,j=class extends O{constructor({message:e}){super({name:hn,message:e}),this[vn]=!0}static isInstance(e){return O.hasMarker(e,gn)}};vn=_n;var yn=`AI_NoSuchModelError`,bn=`vercel.ai.error.${yn}`,xn=Symbol.for(bn),Sn,Cn=class extends O{constructor({errorName:e=yn,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[Sn]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return O.hasMarker(e,bn)}};Sn=xn;var wn=`AI_TooManyEmbeddingValuesForCallError`,Tn=`vercel.ai.error.${wn}`,En=Symbol.for(Tn),Dn,On=class extends O{constructor(e){super({name:wn,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[Dn]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return O.hasMarker(e,Tn)}};Dn=En;var kn=`AI_TypeValidationError`,An=`vercel.ai.error.${kn}`,jn=Symbol.for(An),Mn,Nn=class e extends O{constructor({value:e,cause:t}){super({name:kn,message:`Type validation failed: Value: ${JSON.stringify(e)}.
7
- Error message: ${Jt(t)}`,cause:t}),this[Mn]=!0,this.value=e}static isInstance(e){return O.hasMarker(e,An)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};Mn=jn;var M=Nn,Pn=`AI_UnsupportedFunctionalityError`,Fn=`vercel.ai.error.${Pn}`,In=Symbol.for(Fn),Ln,N=class extends O{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Pn,message:t}),this[Ln]=!0,this.functionality=e}static isInstance(e){return O.hasMarker(e,Fn)}};Ln=In;function P(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function F(e){return Object.fromEntries([...e.headers])}function Rn(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function zn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function I(e,...t){let n=zn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var L=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new $t({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function R(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Bn=[`fetch failed`,`failed to fetch`];function Vn({error:e,url:t,requestBodyValues:n}){if(R(e))return e;if(e instanceof TypeError&&Bn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new k({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Hn=`3.0.10`,Un=()=>globalThis.fetch,Wn=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:i,fetch:a=Un()})=>{try{let o=await a(e,{method:`GET`,headers:I(t,`ai-sdk/provider-utils/${Hn}`,Rn()),signal:i}),s=F(o);if(!o.ok){let t;try{t=await r({response:o,url:e,requestBodyValues:{}})}catch(t){throw R(t)||k.isInstance(t)?t:new k({message:`Failed to process error response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw t.value}try{return await n({response:o,url:e,requestBodyValues:{}})}catch(t){throw t instanceof Error&&(R(t)||k.isInstance(t))?t:new k({message:`Failed to process successful response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(t){throw Vn({error:t,url:e,requestBodyValues:{}})}};function Gn({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new j({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new j({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new j({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new j({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Kn({settingValue:e,environmentVariableName:t}){if(typeof e==`string`||!(e!=null||typeof process>`u`)&&(e=process.env[t],!(e==null||typeof e!=`string`)))return e}function qn(e){let[t,n=``]=e.toLowerCase().split(`/`);return{mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[n]??n}var Jn=/"__proto__"\s*:/,Yn=/"constructor"\s*:/;function Xn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Jn.test(e)===!1&&Yn.test(e)===!1?t:Zn(t)}function Zn(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Qn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Xn(e)}finally{Error.stackTraceLimit=t}}var $n=Symbol.for(`vercel.ai.validator`);function er(e){return{[$n]:!0,validate:e}}function tr(e){return typeof e==`object`&&!!e&&$n in e&&e[$n]===!0&&`validate`in e}function nr(e){return tr(e)?e:rr(e)}function rr(e){return er(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new M({value:t,cause:n.issues})}})}async function ir({value:e,schema:t}){let n=await ar({value:e,schema:t});if(!n.success)throw M.wrap({value:e,cause:n.error});return n.value}async function ar({value:e,schema:t}){let n=nr(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:M.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:M.wrap({value:e,cause:t}),rawValue:e}}}async function or({text:e,schema:t}){try{let n=Qn(e);return t==null?n:ir({value:n,schema:t})}catch(t){throw A.isInstance(t)||M.isInstance(t)?t:new A({text:e,cause:t})}}async function sr({text:e,schema:t}){try{let n=Qn(e);return t==null?{success:!0,value:n,rawValue:n}:await ar({value:n,schema:t})}catch(t){return{success:!1,error:A.isInstance(t)?t:new A({text:e,cause:t}),rawValue:void 0}}}function cr(e){try{return Qn(e),!0}catch{return!1}}function lr({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new wt).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await sr({text:e,schema:t}))}}))}async function z({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await ar({value:t[e],schema:n});if(!r.success)throw new $t({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var ur=()=>globalThis.fetch,B=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>fr({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),dr=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>fr({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),fr=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=ur()})=>{try{let s=await o(e,{method:`POST`,headers:I(t,`ai-sdk/provider-utils/${Hn}`,Rn()),body:n.content,signal:a}),c=F(s);if(!s.ok){let t;try{t=await i({response:s,url:e,requestBodyValues:n.values})}catch(t){throw R(t)||k.isInstance(t)?t:new k({message:`Failed to process error response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(R(t)||k.isInstance(t))?t:new k({message:`Failed to process successful response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(t){throw Vn({error:t,url:e,requestBodyValues:n.values})}};function pr(e){return e}function V({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>pr({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function H({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>pr({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function U(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var W=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),s=F(r);if(o.trim()===``)return{responseHeaders:s,value:new k({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})};try{let c=await or({text:o,schema:e});return{responseHeaders:s,value:new k({message:t(c),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,data:c,isRetryable:n?.(r,c)})}}catch{return{responseHeaders:s,value:new k({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})}}},G=e=>async({response:t})=>{let n=F(t);if(t.body==null)throw new qt({});return{responseHeaders:n,value:lr({stream:t.body,schema:e})}},K=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await sr({text:i,schema:e}),o=F(t);if(!a.success)throw new k({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},mr=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=F(e);if(!e.body)throw new k({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new k({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},{btoa:hr,atob:gr}=globalThis;function _r(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=gr(t);return Uint8Array.from(n,e=>e.codePointAt(0))}function vr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return hr(t)}function q(e){return e instanceof Uint8Array?vr(e):e}function J(e){return e?.replace(/\/$/,``)}var yr=`2.0.23`,br=r.object({type:r.literal(`error`),error:r.object({type:r.string(),message:r.string()})}),xr=W({errorSchema:br,errorToMessage:e=>e.error.message}),Sr=r.object({citations:r.object({enabled:r.boolean()}).optional(),title:r.string().optional(),context:r.string().optional()}),Cr=r.object({sendReasoning:r.boolean().optional(),thinking:r.object({type:r.union([r.literal(`enabled`),r.literal(`disabled`)]),budgetTokens:r.number().optional()}).optional(),disableParallelToolUse:r.boolean().optional(),cacheControl:r.object({type:r.literal(`ephemeral`),ttl:r.union([r.literal(`5m`),r.literal(`1h`)]).optional()}).optional()});function Y(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var wr=r.object({maxCharacters:r.number().optional()}),Tr=V({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),Er=(e={})=>Tr(e),Dr=r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),userLocation:r.object({type:r.literal(`approximate`),city:r.string().optional(),region:r.string().optional(),country:r.string().optional(),timezone:r.string().optional()}).optional()}),Or=r.array(r.object({url:r.string(),title:r.string(),pageAge:r.string().nullable(),encryptedContent:r.string(),type:r.literal(`web_search_result`)})),kr=H({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.object({query:r.string()}),outputSchema:Or}),Ar=(e={})=>kr(e),jr=r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),citations:r.object({enabled:r.boolean()}).optional(),maxContentTokens:r.number().optional()}),Mr=r.object({type:r.literal(`web_fetch_result`),url:r.string(),content:r.object({type:r.literal(`document`),title:r.string(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal(`base64`),mediaType:r.literal(`application/pdf`),data:r.string()}),r.object({type:r.literal(`text`),mediaType:r.literal(`text/plain`),data:r.string()})])}),retrievedAt:r.string().nullable()}),Nr=H({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.object({url:r.string()}),outputSchema:Mr}),Pr=(e={})=>Nr(e);function Fr({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Y(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=wr.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=jr.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Dr.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new N({functionality:`tool choice type: ${o}`})}}var Ir=r.object({type:r.literal(`code_execution_result`),stdout:r.string(),stderr:r.string(),return_code:r.number()}),Lr=H({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.object({code:r.string()}),outputSchema:Ir}),Rr=(e={})=>Lr(e);function zr(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new N({functionality:`URL-based text documents are not supported for citations`}):new N({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Br({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Vr(e),a,o=[];async function s(e){return(await z({provider:`anthropic`,providerOptions:e,schema:Sr}))?.citations?.enabled??!1}async function c(e){let t=await z({provider:`anthropic`,providerOptions:e,schema:Sr});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new N({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Y(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Y(a.providerOptions)??(o?Y(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:q(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:q(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:zr(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new N({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Y(r.providerOptions)??(a?Y(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new N({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Y(s.providerOptions)??(c?Y(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await z({provider:`anthropic`,providerOptions:s.providerOptions,schema:Yr});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ir.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Mr.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Or.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Vr(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function Hr({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var X={webSearchResult:r.object({type:r.literal(`web_search_result_location`),cited_text:r.string(),url:r.string(),title:r.string(),encrypted_index:r.string()}),pageLocation:r.object({type:r.literal(`page_location`),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_page_number:r.number(),end_page_number:r.number()}),charLocation:r.object({type:r.literal(`char_location`),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_char_index:r.number(),end_char_index:r.number()})},Ur=r.discriminatedUnion(`type`,[X.webSearchResult,X.pageLocation,X.charLocation]);r.discriminatedUnion(`type`,[X.pageLocation,X.charLocation]);function Wr(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=Gr(e,t,n);i&&r(i)}}function Gr(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var Kr=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??L}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await z({provider:`anthropic`,providerOptions:f,schema:Cr}),{prompt:g,betas:_}=await Br({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new N({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:S,toolWarnings:C,betas:w}=Fr(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:S},warnings:[...p,...C],betas:new Set([..._,...w]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return P(await U(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await B({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:xr,successfulResponseHandler:K(qr),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)Wr(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:Hr({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await B({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:xr,successfulResponseHandler:G(Jr),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;Wr(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=Hr({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},qr=r.object({type:r.literal(`message`),id:r.string().nullish(),model:r.string().nullish(),content:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`text`),text:r.string(),citations:r.array(Ur).optional()}),r.object({type:r.literal(`thinking`),thinking:r.string(),signature:r.string()}),r.object({type:r.literal(`redacted_thinking`),data:r.string()}),r.object({type:r.literal(`tool_use`),id:r.string(),name:r.string(),input:r.unknown()}),r.object({type:r.literal(`server_tool_use`),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish()}),r.object({type:r.literal(`web_fetch_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`web_fetch_result`),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal(`document`),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.object({type:r.literal(`text`),media_type:r.string(),data:r.string()})})}),r.object({type:r.literal(`web_fetch_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`web_search_tool_result`),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal(`web_search_result`),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal(`web_search_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`code_execution_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`code_execution_result`),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal(`code_execution_tool_result_error`),error_code:r.string()})])})])),stop_reason:r.string().nullish(),stop_sequence:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()})}),Jr=r.discriminatedUnion(`type`,[r.object({type:r.literal(`message_start`),message:r.object({id:r.string().nullish(),model:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()})})}),r.object({type:r.literal(`content_block_start`),index:r.number(),content_block:r.discriminatedUnion(`type`,[r.object({type:r.literal(`text`),text:r.string()}),r.object({type:r.literal(`thinking`),thinking:r.string()}),r.object({type:r.literal(`tool_use`),id:r.string(),name:r.string()}),r.object({type:r.literal(`redacted_thinking`),data:r.string()}),r.object({type:r.literal(`server_tool_use`),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish()}),r.object({type:r.literal(`web_fetch_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`web_fetch_result`),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal(`document`),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.object({type:r.literal(`text`),media_type:r.string(),data:r.string()})})}),r.object({type:r.literal(`web_fetch_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`web_search_tool_result`),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal(`web_search_result`),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal(`web_search_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`code_execution_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`code_execution_result`),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal(`code_execution_tool_result_error`),error_code:r.string()})])})])}),r.object({type:r.literal(`content_block_delta`),index:r.number(),delta:r.discriminatedUnion(`type`,[r.object({type:r.literal(`input_json_delta`),partial_json:r.string()}),r.object({type:r.literal(`text_delta`),text:r.string()}),r.object({type:r.literal(`thinking_delta`),thinking:r.string()}),r.object({type:r.literal(`signature_delta`),signature:r.string()}),r.object({type:r.literal(`citations_delta`),citation:Ur})])}),r.object({type:r.literal(`content_block_stop`),index:r.number()}),r.object({type:r.literal(`error`),error:r.object({type:r.string(),message:r.string()})}),r.object({type:r.literal(`message_delta`),delta:r.object({stop_reason:r.string().nullish(),stop_sequence:r.string().nullish()}),usage:r.looseObject({output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish()})}),r.object({type:r.literal(`message_stop`)}),r.object({type:r.literal(`ping`)})]),Yr=r.object({signature:r.string().optional(),redactedData:r.string().optional()}),Xr=V({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:n.object({command:n.string(),restart:n.boolean().optional()})}),Zr=V({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:n.object({command:n.string(),restart:n.boolean().optional()})}),Qr=V({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.object({action:r.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.array(r.number().int()).optional(),text:r.string().optional()})}),$r=V({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.object({action:r.enum([`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:r.tuple([r.number().int(),r.number().int()]).optional(),duration:r.number().optional(),scroll_amount:r.number().optional(),scroll_direction:r.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),text:r.string().optional()})}),ei=V({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),ti=V({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),ni=V({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),ri={bash_20241022:Xr,bash_20250124:Zr,codeExecution_20250522:Rr,computer_20241022:Qr,computer_20250124:$r,textEditor_20241022:ei,textEditor_20250124:ti,textEditor_20250429:ni,textEditor_20250728:Er,webFetch_20250910:Pr,webSearch_20250305:Ar};function ii(e={}){let t=J(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>I({"anthropic-version":`2023-06-01`,"x-api-key":Gn({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${yr}`),r=r=>new Kr(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??L,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new Cn({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new Cn({modelId:e,modelType:`imageModel`})},i.tools=ri,i}ii();var ai=`2.0.17`,oi=r.object({error:r.object({code:r.number().nullable(),message:r.string(),status:r.string()})}),Z=W({errorSchema:oi,errorToMessage:e=>e.error.message}),si=r.object({outputDimensionality:r.number().optional(),taskType:r.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),ci=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await z({provider:`google`,providerOptions:r,schema:si});if(e.length>this.maxEmbeddingsPerCall)throw new On({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=P(await U(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await B({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:Z,successfulResponseHandler:K(ui),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await B({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:Z,successfulResponseHandler:K(li),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},li=r.object({embeddings:r.array(r.object({values:r.array(r.number())}))}),ui=r.object({embedding:r.object({values:r.array(r.number())})});function Q(e){if(e==null||di(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=Q(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(Q):Q(a)),o&&(p.allOf=o.map(Q)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=Q(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(Q),p.nullable=!0}else p.anyOf=s.map(Q);return c&&(p.oneOf=c.map(Q)),d!==void 0&&(p.minLength=d),p}function di(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function fi(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new N({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:q(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new N({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new N({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:q(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
5
+ `&&r++}}return[t,n]}var wt=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=St({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}},Tt=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),Et=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},Dt=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t},Ot=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},kt=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function At(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jt(e,t){if(!At(e)&&!At(t))return t;let n={...e};for(let e in t){let r=t[e];At(n[e])&&At(r)?n[e]=jt(n[e],r):n[e]=r}return n}var Mt=(e,t)=>new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return Mt(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}}),Nt=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(e,t)=>{if(e){if(e.query&&(this.queryParams=Dt(e.query)),e.form){let t=new FormData;for(let[n,r]of Object.entries(e.form))if(Array.isArray(r))for(let e of r)t.append(n,e);else t.append(n,r);this.rBody=t}e.json&&(this.rBody=JSON.stringify(e.json),this.cType=`application/json`),e.param&&(this.pathParams=e.param)}let n=this.method.toUpperCase(),r={...e?.header,...typeof t?.headers==`function`?await t.headers():t?.headers};if(e?.cookie){let t=[];for(let[n,r]of Object.entries(e.cookie))t.push(Je(n,r,{path:`/`}));r.Cookie=t.join(`,`)}this.cType&&(r[`Content-Type`]=this.cType);let i=new Headers(r??void 0),a=this.url;a=kt(a),a=Et(a,this.pathParams),this.queryParams&&(a=a+`?`+this.queryParams.toString()),n=this.method.toUpperCase();let o=!(n===`GET`||n===`HEAD`);return(t?.fetch||fetch)(a,{body:o?this.rBody:void 0,method:n,headers:i,...t?.init})}},Pt=(e,t)=>Mt(function n(r){let i=[...r.path],a=i.slice(-3).reverse();if(a[0]===`toString`)return a[1]===`name`?a[2]||``:n.toString();if(a[0]===`valueOf`)return a[1]===`name`?a[2]||``:n;let o=``;if(/^\$/.test(a[0])){let e=i.pop();e&&(o=e.replace(/^\$/,``))}let s=i.join(`/`),c=Tt(e,s);if(o===`url`){let e=c;return r.args[0]&&(r.args[0].param&&(e=Et(c,r.args[0].param)),r.args[0].query&&(e=e+`?`+Dt(r.args[0].query).toString())),e=kt(e),new URL(e)}if(o===`ws`){let e=Ot(r.args[0]&&r.args[0].param?Et(c,r.args[0].param):c,`ws`),n=new URL(e),i=r.args[0]?.query;return i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)}),((...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e))(n.toString())}let l=new Nt(c,o);if(o){t??={};let e=jt(t,{...r.args[1]});return l.fetch(r.args[0],e)}return l},[]),Ft=`vercel.ai.error`,It=Symbol.for(Ft),Lt,Rt=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Lt]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Ft)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Lt=It;var O=Rt,zt=`AI_APICallError`,Bt=`vercel.ai.error.${zt}`,Vt=Symbol.for(Bt),Ht,k=class extends O{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:a,cause:o,isRetryable:s=r!=null&&(r===408||r===409||r===429||r>=500),data:c}){super({name:zt,message:e,cause:o}),this[Ht]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=a,this.isRetryable=s,this.data=c}static isInstance(e){return O.hasMarker(e,Bt)}};Ht=Vt;var Ut=`AI_EmptyResponseBodyError`,Wt=`vercel.ai.error.${Ut}`,Gt=Symbol.for(Wt),Kt,qt=class extends O{constructor({message:e=`Empty response body`}={}){super({name:Ut,message:e}),this[Kt]=!0}static isInstance(e){return O.hasMarker(e,Wt)}};Kt=Gt;function Jt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var Yt=`AI_InvalidArgumentError`,Xt=`vercel.ai.error.${Yt}`,Zt=Symbol.for(Xt),Qt,$t=class extends O{constructor({message:e,cause:t,argument:n}){super({name:Yt,message:e,cause:t}),this[Qt]=!0,this.argument=n}static isInstance(e){return O.hasMarker(e,Xt)}};Qt=Zt;var en=`AI_InvalidPromptError`,tn=`vercel.ai.error.${en}`,nn=Symbol.for(tn),rn,an=class extends O{constructor({prompt:e,message:t,cause:n}){super({name:en,message:`Invalid prompt: ${t}`,cause:n}),this[rn]=!0,this.prompt=e}static isInstance(e){return O.hasMarker(e,tn)}};rn=nn;var on=`AI_InvalidResponseDataError`,sn=`vercel.ai.error.${on}`,cn=Symbol.for(sn),ln,un=class extends O{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:on,message:t}),this[ln]=!0,this.data=e}static isInstance(e){return O.hasMarker(e,sn)}};ln=cn;var dn=`AI_JSONParseError`,fn=`vercel.ai.error.${dn}`,pn=Symbol.for(fn),mn,hn=class extends O{constructor({text:e,cause:t}){super({name:dn,message:`JSON parsing failed: Text: ${e}.
6
+ Error message: ${Jt(t)}`,cause:t}),this[mn]=!0,this.text=e}static isInstance(e){return O.hasMarker(e,fn)}};mn=pn;var gn=`AI_LoadAPIKeyError`,_n=`vercel.ai.error.${gn}`,vn=Symbol.for(_n),yn,A=class extends O{constructor({message:e}){super({name:gn,message:e}),this[yn]=!0}static isInstance(e){return O.hasMarker(e,_n)}};yn=vn;var bn=`AI_NoSuchModelError`,xn=`vercel.ai.error.${bn}`,Sn=Symbol.for(xn),Cn,j=class extends O{constructor({errorName:e=bn,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[Cn]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return O.hasMarker(e,xn)}};Cn=Sn;var wn=`AI_TooManyEmbeddingValuesForCallError`,Tn=`vercel.ai.error.${wn}`,En=Symbol.for(Tn),Dn,On=class extends O{constructor(e){super({name:wn,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[Dn]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return O.hasMarker(e,Tn)}};Dn=En;var kn=`AI_TypeValidationError`,An=`vercel.ai.error.${kn}`,jn=Symbol.for(An),Mn,Nn=class e extends O{constructor({value:e,cause:t}){super({name:kn,message:`Type validation failed: Value: ${JSON.stringify(e)}.
7
+ Error message: ${Jt(t)}`,cause:t}),this[Mn]=!0,this.value=e}static isInstance(e){return O.hasMarker(e,An)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};Mn=jn;var M=Nn,Pn=`AI_UnsupportedFunctionalityError`,Fn=`vercel.ai.error.${Pn}`,In=Symbol.for(Fn),Ln,N=class extends O{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Pn,message:t}),this[Ln]=!0,this.functionality=e}static isInstance(e){return O.hasMarker(e,Fn)}};Ln=In;function P(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function F(e){return Object.fromEntries([...e.headers])}function Rn(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function zn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function I(e,...t){let n=zn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var L=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new $t({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function R(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Bn=[`fetch failed`,`failed to fetch`];function Vn({error:e,url:t,requestBodyValues:n}){if(R(e))return e;if(e instanceof TypeError&&Bn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new k({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Hn=`3.0.10`,Un=()=>globalThis.fetch,Wn=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:i,fetch:a=Un()})=>{try{let o=await a(e,{method:`GET`,headers:I(t,`ai-sdk/provider-utils/${Hn}`,Rn()),signal:i}),s=F(o);if(!o.ok){let t;try{t=await r({response:o,url:e,requestBodyValues:{}})}catch(t){throw R(t)||k.isInstance(t)?t:new k({message:`Failed to process error response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw t.value}try{return await n({response:o,url:e,requestBodyValues:{}})}catch(t){throw t instanceof Error&&(R(t)||k.isInstance(t))?t:new k({message:`Failed to process successful response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(t){throw Vn({error:t,url:e,requestBodyValues:{}})}};function Gn({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new A({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new A({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new A({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new A({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Kn({settingValue:e,environmentVariableName:t}){if(typeof e==`string`||!(e!=null||typeof process>`u`)&&(e=process.env[t],!(e==null||typeof e!=`string`)))return e}function qn(e){let[t,n=``]=e.toLowerCase().split(`/`);return{mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[n]??n}var Jn=/"__proto__"\s*:/,Yn=/"constructor"\s*:/;function Xn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Jn.test(e)===!1&&Yn.test(e)===!1?t:Zn(t)}function Zn(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Qn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Xn(e)}finally{Error.stackTraceLimit=t}}var $n=Symbol.for(`vercel.ai.validator`);function er(e){return{[$n]:!0,validate:e}}function tr(e){return typeof e==`object`&&!!e&&$n in e&&e[$n]===!0&&`validate`in e}function nr(e){return tr(e)?e:rr(e)}function rr(e){return er(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new M({value:t,cause:n.issues})}})}async function ir({value:e,schema:t}){let n=await ar({value:e,schema:t});if(!n.success)throw M.wrap({value:e,cause:n.error});return n.value}async function ar({value:e,schema:t}){let n=nr(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:M.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:M.wrap({value:e,cause:t}),rawValue:e}}}async function or({text:e,schema:t}){try{let n=Qn(e);return t==null?n:ir({value:n,schema:t})}catch(t){throw hn.isInstance(t)||M.isInstance(t)?t:new hn({text:e,cause:t})}}async function sr({text:e,schema:t}){try{let n=Qn(e);return t==null?{success:!0,value:n,rawValue:n}:await ar({value:n,schema:t})}catch(t){return{success:!1,error:hn.isInstance(t)?t:new hn({text:e,cause:t}),rawValue:void 0}}}function cr(e){try{return Qn(e),!0}catch{return!1}}function lr({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new wt).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await sr({text:e,schema:t}))}}))}async function z({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await ar({value:t[e],schema:n});if(!r.success)throw new $t({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var ur=()=>globalThis.fetch,B=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>fr({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),dr=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>fr({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),fr=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=ur()})=>{try{let s=await o(e,{method:`POST`,headers:I(t,`ai-sdk/provider-utils/${Hn}`,Rn()),body:n.content,signal:a}),c=F(s);if(!s.ok){let t;try{t=await i({response:s,url:e,requestBodyValues:n.values})}catch(t){throw R(t)||k.isInstance(t)?t:new k({message:`Failed to process error response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(R(t)||k.isInstance(t))?t:new k({message:`Failed to process successful response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(t){throw Vn({error:t,url:e,requestBodyValues:n.values})}};function pr(e){return e}function V({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>pr({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function H({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>pr({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function U(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var W=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),s=F(r);if(o.trim()===``)return{responseHeaders:s,value:new k({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})};try{let c=await or({text:o,schema:e});return{responseHeaders:s,value:new k({message:t(c),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,data:c,isRetryable:n?.(r,c)})}}catch{return{responseHeaders:s,value:new k({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})}}},G=e=>async({response:t})=>{let n=F(t);if(t.body==null)throw new qt({});return{responseHeaders:n,value:lr({stream:t.body,schema:e})}},K=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await sr({text:i,schema:e}),o=F(t);if(!a.success)throw new k({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},mr=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=F(e);if(!e.body)throw new k({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new k({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},{btoa:hr,atob:gr}=globalThis;function _r(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=gr(t);return Uint8Array.from(n,e=>e.codePointAt(0))}function vr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return hr(t)}function q(e){return e instanceof Uint8Array?vr(e):e}function J(e){return e?.replace(/\/$/,``)}var yr=`2.0.23`,br=r.object({type:r.literal(`error`),error:r.object({type:r.string(),message:r.string()})}),xr=W({errorSchema:br,errorToMessage:e=>e.error.message}),Sr=r.object({citations:r.object({enabled:r.boolean()}).optional(),title:r.string().optional(),context:r.string().optional()}),Cr=r.object({sendReasoning:r.boolean().optional(),thinking:r.object({type:r.union([r.literal(`enabled`),r.literal(`disabled`)]),budgetTokens:r.number().optional()}).optional(),disableParallelToolUse:r.boolean().optional(),cacheControl:r.object({type:r.literal(`ephemeral`),ttl:r.union([r.literal(`5m`),r.literal(`1h`)]).optional()}).optional()});function Y(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var wr=r.object({maxCharacters:r.number().optional()}),Tr=V({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),Er=(e={})=>Tr(e),Dr=r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),userLocation:r.object({type:r.literal(`approximate`),city:r.string().optional(),region:r.string().optional(),country:r.string().optional(),timezone:r.string().optional()}).optional()}),Or=r.array(r.object({url:r.string(),title:r.string(),pageAge:r.string().nullable(),encryptedContent:r.string(),type:r.literal(`web_search_result`)})),kr=H({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.object({query:r.string()}),outputSchema:Or}),Ar=(e={})=>kr(e),jr=r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),citations:r.object({enabled:r.boolean()}).optional(),maxContentTokens:r.number().optional()}),Mr=r.object({type:r.literal(`web_fetch_result`),url:r.string(),content:r.object({type:r.literal(`document`),title:r.string(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal(`base64`),mediaType:r.literal(`application/pdf`),data:r.string()}),r.object({type:r.literal(`text`),mediaType:r.literal(`text/plain`),data:r.string()})])}),retrievedAt:r.string().nullable()}),Nr=H({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.object({url:r.string()}),outputSchema:Mr}),Pr=(e={})=>Nr(e);function Fr({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Y(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=wr.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=jr.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Dr.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new N({functionality:`tool choice type: ${o}`})}}var Ir=r.object({type:r.literal(`code_execution_result`),stdout:r.string(),stderr:r.string(),return_code:r.number()}),Lr=H({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.object({code:r.string()}),outputSchema:Ir}),Rr=(e={})=>Lr(e);function zr(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new N({functionality:`URL-based text documents are not supported for citations`}):new N({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Br({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Vr(e),a,o=[];async function s(e){return(await z({provider:`anthropic`,providerOptions:e,schema:Sr}))?.citations?.enabled??!1}async function c(e){let t=await z({provider:`anthropic`,providerOptions:e,schema:Sr});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new N({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Y(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Y(a.providerOptions)??(o?Y(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:q(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:q(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:zr(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new N({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Y(r.providerOptions)??(a?Y(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new N({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Y(s.providerOptions)??(c?Y(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await z({provider:`anthropic`,providerOptions:s.providerOptions,schema:Yr});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ir.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Mr.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Or.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Vr(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function Hr({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var X={webSearchResult:r.object({type:r.literal(`web_search_result_location`),cited_text:r.string(),url:r.string(),title:r.string(),encrypted_index:r.string()}),pageLocation:r.object({type:r.literal(`page_location`),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_page_number:r.number(),end_page_number:r.number()}),charLocation:r.object({type:r.literal(`char_location`),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_char_index:r.number(),end_char_index:r.number()})},Ur=r.discriminatedUnion(`type`,[X.webSearchResult,X.pageLocation,X.charLocation]);r.discriminatedUnion(`type`,[X.pageLocation,X.charLocation]);function Wr(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=Gr(e,t,n);i&&r(i)}}function Gr(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var Kr=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??L}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await z({provider:`anthropic`,providerOptions:f,schema:Cr}),{prompt:g,betas:_}=await Br({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new N({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:S,toolWarnings:C,betas:w}=Fr(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:S},warnings:[...p,...C],betas:new Set([..._,...w]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return P(await U(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await B({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:xr,successfulResponseHandler:K(qr),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)Wr(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:Hr({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await B({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:xr,successfulResponseHandler:G(Jr),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;Wr(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=Hr({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},qr=r.object({type:r.literal(`message`),id:r.string().nullish(),model:r.string().nullish(),content:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`text`),text:r.string(),citations:r.array(Ur).optional()}),r.object({type:r.literal(`thinking`),thinking:r.string(),signature:r.string()}),r.object({type:r.literal(`redacted_thinking`),data:r.string()}),r.object({type:r.literal(`tool_use`),id:r.string(),name:r.string(),input:r.unknown()}),r.object({type:r.literal(`server_tool_use`),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish()}),r.object({type:r.literal(`web_fetch_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`web_fetch_result`),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal(`document`),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.object({type:r.literal(`text`),media_type:r.string(),data:r.string()})})}),r.object({type:r.literal(`web_fetch_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`web_search_tool_result`),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal(`web_search_result`),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal(`web_search_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`code_execution_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`code_execution_result`),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal(`code_execution_tool_result_error`),error_code:r.string()})])})])),stop_reason:r.string().nullish(),stop_sequence:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()})}),Jr=r.discriminatedUnion(`type`,[r.object({type:r.literal(`message_start`),message:r.object({id:r.string().nullish(),model:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()})})}),r.object({type:r.literal(`content_block_start`),index:r.number(),content_block:r.discriminatedUnion(`type`,[r.object({type:r.literal(`text`),text:r.string()}),r.object({type:r.literal(`thinking`),thinking:r.string()}),r.object({type:r.literal(`tool_use`),id:r.string(),name:r.string()}),r.object({type:r.literal(`redacted_thinking`),data:r.string()}),r.object({type:r.literal(`server_tool_use`),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish()}),r.object({type:r.literal(`web_fetch_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`web_fetch_result`),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal(`document`),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.object({type:r.literal(`text`),media_type:r.string(),data:r.string()})})}),r.object({type:r.literal(`web_fetch_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`web_search_tool_result`),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal(`web_search_result`),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal(`web_search_tool_result_error`),error_code:r.string()})])}),r.object({type:r.literal(`code_execution_tool_result`),tool_use_id:r.string(),content:r.union([r.object({type:r.literal(`code_execution_result`),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal(`code_execution_tool_result_error`),error_code:r.string()})])})])}),r.object({type:r.literal(`content_block_delta`),index:r.number(),delta:r.discriminatedUnion(`type`,[r.object({type:r.literal(`input_json_delta`),partial_json:r.string()}),r.object({type:r.literal(`text_delta`),text:r.string()}),r.object({type:r.literal(`thinking_delta`),thinking:r.string()}),r.object({type:r.literal(`signature_delta`),signature:r.string()}),r.object({type:r.literal(`citations_delta`),citation:Ur})])}),r.object({type:r.literal(`content_block_stop`),index:r.number()}),r.object({type:r.literal(`error`),error:r.object({type:r.string(),message:r.string()})}),r.object({type:r.literal(`message_delta`),delta:r.object({stop_reason:r.string().nullish(),stop_sequence:r.string().nullish()}),usage:r.looseObject({output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish()})}),r.object({type:r.literal(`message_stop`)}),r.object({type:r.literal(`ping`)})]),Yr=r.object({signature:r.string().optional(),redactedData:r.string().optional()}),Xr=V({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:n.object({command:n.string(),restart:n.boolean().optional()})}),Zr=V({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:n.object({command:n.string(),restart:n.boolean().optional()})}),Qr=V({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.object({action:r.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.array(r.number().int()).optional(),text:r.string().optional()})}),$r=V({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.object({action:r.enum([`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:r.tuple([r.number().int(),r.number().int()]).optional(),duration:r.number().optional(),scroll_amount:r.number().optional(),scroll_direction:r.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),text:r.string().optional()})}),ei=V({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),ti=V({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),ni=V({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.object({command:r.enum([`view`,`create`,`str_replace`,`insert`]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()})}),ri={bash_20241022:Xr,bash_20250124:Zr,codeExecution_20250522:Rr,computer_20241022:Qr,computer_20250124:$r,textEditor_20241022:ei,textEditor_20250124:ti,textEditor_20250429:ni,textEditor_20250728:Er,webFetch_20250910:Pr,webSearch_20250305:Ar};function ii(e={}){let t=J(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>I({"anthropic-version":`2023-06-01`,"x-api-key":Gn({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${yr}`),r=r=>new Kr(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??L,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new j({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new j({modelId:e,modelType:`imageModel`})},i.tools=ri,i}ii();var ai=`2.0.17`,oi=r.object({error:r.object({code:r.number().nullable(),message:r.string(),status:r.string()})}),Z=W({errorSchema:oi,errorToMessage:e=>e.error.message}),si=r.object({outputDimensionality:r.number().optional(),taskType:r.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),ci=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await z({provider:`google`,providerOptions:r,schema:si});if(e.length>this.maxEmbeddingsPerCall)throw new On({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=P(await U(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await B({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:Z,successfulResponseHandler:K(ui),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await B({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:Z,successfulResponseHandler:K(li),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},li=r.object({embeddings:r.array(r.object({values:r.array(r.number())}))}),ui=r.object({embedding:r.object({values:r.array(r.number())})});function Q(e){if(e==null||di(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=Q(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(Q):Q(a)),o&&(p.allOf=o.map(Q)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=Q(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(Q),p.nullable=!0}else p.anyOf=s.map(Q);return c&&(p.oneOf=c.map(Q)),d!==void 0&&(p.minLength=d),p}function di(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function fi(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new N({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:q(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new N({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new N({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:q(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
8
8
 
9
9
  `);r[0].parts.unshift({text:e+`
10
10
 
@@ -18,4 +18,4 @@ ${e}
18
18
 
19
19
  `;break}case`tool`:throw new N({functionality:`tool messages`});default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return r+=`${n}:
20
20
  `,{prompt:r,stopSequences:[`
21
- ${t}:`]}}function ea({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function ta(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var na=r.object({echo:r.boolean().optional(),logitBias:r.record(r.string(),r.number()).optional(),suffix:r.string().optional(),user:r.string().optional(),logprobs:r.union([r.boolean(),r.number()]).optional()}),ra=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await z({provider:`openai`,providerOptions:f,schema:na}),...await z({provider:this.providerOptionsName,providerOptions:f,schema:na})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=$i({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await B({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:t,failedResponseHandler:$,successfulResponseHandler:K(aa),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s={openai:{}};return o.logprobs!=null&&(s.openai.logprobs=o.logprobs),{content:[{type:`text`,text:o.text}],usage:{inputTokens:i.usage?.prompt_tokens,outputTokens:i.usage?.completion_tokens,totalTokens:i.usage?.total_tokens},finishReason:ta(o.finish_reason),request:{body:t},response:{...ea(i),headers:r,body:a},providerMetadata:s,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await B({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:$,successfulResponseHandler:G(oa),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...ea(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=ta(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},ia=r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()}),aa=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullish()}).nullish()})),usage:ia.nullish()}),oa=r.union([r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string().nullish(),index:r.number(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullish()}).nullish()})),usage:ia.nullish()}),Ri]),sa=r.object({dimensions:r.number().optional(),user:r.string().optional()}),ca=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){if(e.length>this.maxEmbeddingsPerCall)throw new On({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let i=await z({provider:`openai`,providerOptions:r,schema:sa})??{},{responseHeaders:a,value:o,rawValue:s}=await B({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:P(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:i.dimensions,user:i.user},failedResponseHandler:$,successfulResponseHandler:K(la),abortSignal:n,fetch:this.config.fetch});return{embeddings:o.data.map(e=>e.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,response:{headers:a,body:s}}}},la=r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish()}),ua={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},da=new Set([`gpt-image-1`]),fa=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return ua[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await B({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:P(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...da.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:$,successfulResponseHandler:K(pa),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:d.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},pa=r.object({data:r.array(r.object({b64_json:r.string(),revised_prompt:r.string().optional()}))}),ma=r.object({code:r.string().nullish(),containerId:r.string()}),ha=r.object({outputs:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`logs`),logs:r.string()}),r.object({type:r.literal(`image`),url:r.string()})])).nullish()}),ga=r.object({container:r.union([r.string(),r.object({fileIds:r.array(r.string()).optional()})]).optional()}),_a=H({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:ma,outputSchema:ha}),va=(e={})=>_a(e),ya=r.object({key:r.string(),type:r.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:r.union([r.string(),r.number(),r.boolean()])}),ba=r.object({type:r.enum([`and`,`or`]),filters:r.array(r.union([ya,r.lazy(()=>ba)]))}),xa=r.object({vectorStoreIds:r.array(r.string()),maxNumResults:r.number().optional(),ranking:r.object({ranker:r.string().optional(),scoreThreshold:r.number().optional()}).optional(),filters:r.union([ya,ba]).optional()}),Sa=r.object({queries:r.array(r.string()),results:r.array(r.object({attributes:r.record(r.string(),r.unknown()),fileId:r.string(),filename:r.string(),score:r.number(),text:r.string()})).nullable()}),Ca=H({id:`openai.file_search`,name:`file_search`,inputSchema:r.object({}),outputSchema:Sa}),wa=r.object({background:r.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:r.enum([`low`,`high`]).optional(),inputImageMask:r.object({fileId:r.string().optional(),imageUrl:r.string().optional()}).optional(),model:r.string().optional(),moderation:r.enum([`auto`]).optional(),outputCompression:r.number().int().min(0).max(100).optional(),outputFormat:r.enum([`png`,`jpeg`,`webp`]).optional(),quality:r.enum([`auto`,`low`,`medium`,`high`]).optional(),size:r.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),Ta=r.object({result:r.string()}),Ea=H({id:`openai.image_generation`,name:`image_generation`,inputSchema:r.object({}),outputSchema:Ta}),Da=(e={})=>Ea(e),Oa=r.object({action:r.object({type:r.literal(`exec`),command:r.array(r.string()),timeoutMs:r.number().optional(),user:r.string().optional(),workingDirectory:r.string().optional(),env:r.record(r.string(),r.string()).optional()})}),ka=r.object({output:r.string()}),Aa=H({id:`openai.local_shell`,name:`local_shell`,inputSchema:Oa,outputSchema:ka}),ja=r.object({filters:r.object({allowedDomains:r.array(r.string()).optional()}).optional(),searchContextSize:r.enum([`low`,`medium`,`high`]).optional(),userLocation:r.object({type:r.literal(`approximate`),country:r.string().optional(),city:r.string().optional(),region:r.string().optional(),timezone:r.string().optional()}).optional()}),Ma=V({id:`openai.web_search`,name:`web_search`,inputSchema:r.object({action:r.discriminatedUnion(`type`,[r.object({type:r.literal(`search`),query:r.string().nullish()}),r.object({type:r.literal(`open_page`),url:r.string()}),r.object({type:r.literal(`find`),url:r.string(),pattern:r.string()})]).nullish()})}),Na=(e={})=>Ma(e),Pa=r.object({searchContextSize:r.enum([`low`,`medium`,`high`]).optional(),userLocation:r.object({type:r.literal(`approximate`),country:r.string().optional(),city:r.string().optional(),region:r.string().optional(),timezone:r.string().optional()}).optional()}),Fa=V({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:r.object({action:r.discriminatedUnion(`type`,[r.object({type:r.literal(`search`),query:r.string().nullish()}),r.object({type:r.literal(`open_page`),url:r.string()}),r.object({type:r.literal(`find`),url:r.string(),pattern:r.string()})]).nullish()})}),Ia={codeInterpreter:va,fileSearch:Ca,imageGeneration:Da,localShell:Aa,webSearchPreview:Fa,webSearch:Na};function La(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Ra({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:i=!1}){let a=[],o=[];for(let{role:s,content:c}of e)switch(s){case`system`:switch(t){case`system`:a.push({role:`system`,content:c});break;case`developer`:a.push({role:`developer`,content:c});break;case`remove`:o.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:a.push({role:`user`,content:c.map((e,t)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&La(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${q(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&La(e.data,n)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${q(e.data)}`}};else throw new N({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of c)switch(n.type){case`text`:a.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(t[n.toolCallId]=n,n.providerExecuted)break;if(i&&n.toolName===`local_shell`){let e=Oa.parse(n.input);a.push({type:`local_shell_call`,call_id:n.toolCallId,id:n.providerOptions?.openai?.itemId??void 0,action:{type:`exec`,command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}a.push({type:`function_call`,call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:r?a.push({type:`item_reference`,id:n.toolCallId}):o.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await z({provider:`openai`,providerOptions:n.providerOptions,schema:za}),i=t?.itemId;if(i!=null){let s=e[i];if(r)s===void 0&&(a.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let r=[];n.text.length>0?r.push({type:`summary_text`,text:n.text}):s!==void 0&&o.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),s===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:r},a.push(e[i])):s.summary.push(...r)}}else o.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of c){let t=e.output;if(i&&e.toolName===`local_shell`&&t.type===`json`){a.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:ka.parse(t.value).output});break}let n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}a.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=s;throw Error(`Unsupported role: ${e}`)}}return{input:a,warnings:o}}var za=r.object({itemId:r.string().nullish(),reasoningEncryptedContent:r.string().nullish()});function Ba({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function Va({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=xa.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:i.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=Pa.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=ja.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=ga.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=wa.parse(t.args);i.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:throw new N({functionality:`tool choice type: ${a}`})}}var Ha=r.object({type:r.literal(`web_search_call`),id:r.string(),status:r.string(),action:r.discriminatedUnion(`type`,[r.object({type:r.literal(`search`),query:r.string().nullish()}),r.object({type:r.literal(`open_page`),url:r.string()}),r.object({type:r.literal(`find`),url:r.string(),pattern:r.string()})]).nullish()}),Ua=r.object({type:r.literal(`file_search_call`),id:r.string(),queries:r.array(r.string()),results:r.array(r.object({attributes:r.record(r.string(),r.unknown()),file_id:r.string(),filename:r.string(),score:r.number(),text:r.string()})).nullish()}),Wa=r.object({type:r.literal(`code_interpreter_call`),id:r.string(),code:r.string().nullable(),container_id:r.string(),outputs:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`logs`),logs:r.string()}),r.object({type:r.literal(`image`),url:r.string()})])).nullable()}),Ga=r.object({type:r.literal(`local_shell_call`),id:r.string(),call_id:r.string(),action:r.object({type:r.literal(`exec`),command:r.array(r.string()),timeout_ms:r.number().optional(),user:r.string().optional(),working_directory:r.string().optional(),env:r.record(r.string(),r.string()).optional()})}),Ka=r.object({type:r.literal(`image_generation_call`),id:r.string(),result:r.string()}),qa=20,Ja=r.array(r.object({token:r.string(),logprob:r.number(),top_logprobs:r.array(r.object({token:r.string(),logprob:r.number()}))})),Ya=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let p=[],m=To(this.modelId);i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`});let h=await z({provider:`openai`,providerOptions:l,schema:Eo}),{input:g,warnings:_}=await Ra({prompt:c,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:h?.store??!0,hasLocalShellTool:x(`openai.local_shell`)});p.push(..._);let v=h?.strictJsonSchema??!1,y=h?.include;function b(e){y=y==null?[e]:[...y,e]}function x(e){return u?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let S=typeof h?.logprobs==`number`?h?.logprobs:h?.logprobs===!0?qa:void 0;S&&b(`message.output_text.logprobs`);let C=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;C&&b(`web_search_call.action.sources`),x(`openai.code_interpreter`)&&b(`code_interpreter_call.outputs`);let w={model:this.modelId,input:g,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||h?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:v,name:f.name??`response`,description:f.description,schema:f.schema}},...h?.textVerbosity&&{verbosity:h.textVerbosity}}},max_tool_calls:h?.maxToolCalls,metadata:h?.metadata,parallel_tool_calls:h?.parallelToolCalls,previous_response_id:h?.previousResponseId,store:h?.store,user:h?.user,instructions:h?.instructions,service_tier:h?.serviceTier,include:y,prompt_cache_key:h?.promptCacheKey,safety_identifier:h?.safetyIdentifier,top_logprobs:S,...m.isReasoningModel&&(h?.reasoningEffort!=null||h?.reasoningSummary!=null)&&{reasoning:{...h?.reasoningEffort!=null&&{effort:h.reasoningEffort},...h?.reasoningSummary!=null&&{summary:h.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:`auto`}};m.isReasoningModel?(w.temperature!=null&&(w.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),w.top_p!=null&&(w.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(h?.reasoningEffort!=null&&p.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),h?.reasoningSummary!=null&&p.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),h?.serviceTier===`flex`&&!m.supportsFlexProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete w.service_tier),h?.serviceTier===`priority`&&!m.supportsPriorityProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete w.service_tier);let{tools:ee,toolChoice:te,toolWarnings:ne}=Va({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:ee,tool_choice:te},warnings:[...p,...ne]}}async doGenerate(e){var t,n;let{args:i,warnings:a,webSearchToolName:o}=await this.getArgs(e),s=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:c,value:l,rawValue:u}=await B({url:s,headers:P(this.config.headers(),e.headers),body:i,failedResponseHandler:$,successfulResponseHandler:K(r.object({id:r.string(),created_at:r.number(),error:r.object({code:r.string(),message:r.string()}).nullish(),model:r.string(),output:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`message`),role:r.literal(`assistant`),id:r.string(),content:r.array(r.object({type:r.literal(`output_text`),text:r.string(),logprobs:Ja.nullish(),annotations:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`url_citation`),start_index:r.number(),end_index:r.number(),url:r.string(),title:r.string()}),r.object({type:r.literal(`file_citation`),file_id:r.string(),filename:r.string().nullish(),index:r.number().nullish(),start_index:r.number().nullish(),end_index:r.number().nullish(),quote:r.string().nullish()}),r.object({type:r.literal(`container_file_citation`)})]))}))}),Ha,Ua,Wa,Ka,Ga,r.object({type:r.literal(`function_call`),call_id:r.string(),name:r.string(),arguments:r.string(),id:r.string()}),r.object({type:r.literal(`computer_call`),id:r.string(),status:r.string().optional()}),r.object({type:r.literal(`reasoning`),id:r.string(),encrypted_content:r.string().nullish(),summary:r.array(r.object({type:r.literal(`summary_text`),text:r.string()}))})])),service_tier:r.string().nullish(),incomplete_details:r.object({reason:r.string()}).nullish(),usage:Xa})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(l.error)throw new k({message:l.error.message,url:s,requestBodyValues:i,statusCode:400,responseHeaders:c,responseBody:u,isRetryable:!1});let d=[],f=[],p=!1;for(let r of l.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)d.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:d.push({type:`tool-call`,toolCallId:r.call_id,toolName:`local_shell`,input:JSON.stringify({action:r.action}),providerMetadata:{openai:{itemId:r.id}}});break;case`message`:for(let i of r.content){e.providerOptions?.openai?.logprobs&&i.logprobs&&f.push(i.logprobs),d.push({type:`text`,text:i.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of i.annotations)e.type===`url_citation`?d.push({type:`source`,sourceType:`url`,id:(t=this.config).generateId?.call(t)??L(),url:e.url,title:e.title}):e.type===`file_citation`&&d.push({type:`source`,sourceType:`document`,id:(n=this.config).generateId?.call(n)??L(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:p=!0,d.push({type:`tool-call`,toolCallId:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:o??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:o??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:r.status||`completed`},providerExecuted:!0});break;case`file_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`file_search`,result:{queries:r.queries,results:r.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});break;case`code_interpreter_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.outputs},providerExecuted:!0});break}let m={openai:{responseId:l.id}};return f.length>0&&(m.openai.logprobs=f),typeof l.service_tier==`string`&&(m.openai.serviceTier=l.service_tier),{content:d,finishReason:Ba({finishReason:l.incomplete_details?.reason,hasFunctionCall:p}),usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,reasoningTokens:l.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:l.usage.input_tokens_details?.cached_tokens??void 0},request:{body:i},response:{id:l.id,timestamp:new Date(l.created_at*1e3),modelId:l.model,headers:c,body:u},providerMetadata:m,warnings:a}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await B({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:$,successfulResponseHandler:G(lo),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let g=t.value;if(yo(g))g.item.type===`function_call`?(d[g.output_index]={toolName:g.item.name,toolCallId:g.item.call_id},n.enqueue({type:`tool-input-start`,id:g.item.call_id,toolName:g.item.name})):g.item.type===`web_search_call`?(d[g.output_index]={toolName:r??`web_search`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:r??`web_search`})):g.item.type===`computer_call`?(d[g.output_index]={toolName:`computer_use`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`computer_use`})):g.item.type===`code_interpreter_call`?(d[g.output_index]={toolName:`code_interpreter`,toolCallId:g.item.id,codeInterpreter:{containerId:g.item.container_id}},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`code_interpreter`}),n.enqueue({type:`tool-input-delta`,id:g.item.id,delta:`{"containerId":"${g.item.container_id}","code":"`})):g.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):g.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):g.item.type===`message`?n.enqueue({type:`text-start`,id:g.item.id,providerMetadata:{openai:{itemId:g.item.id}}}):bo(g)&&(p[g.item.id]={encryptedContent:g.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${g.item.id}:0`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}}));else if(fo(g)){if(g.item.type===`function_call`)d[g.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:g.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:g.item.name,input:g.item.arguments,providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`web_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`web_search`,input:JSON.stringify({action:g.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`web_search`,result:{status:g.item.status},providerExecuted:!0});else if(g.item.type===`computer_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:g.item.status||`completed`},providerExecuted:!0});else if(g.item.type===`file_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`file_search`,result:{queries:g.item.queries,results:g.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});else if(g.item.type===`code_interpreter_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`code_interpreter`,result:{outputs:g.item.outputs},providerExecuted:!0});else if(g.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`image_generation`,result:{result:g.item.result},providerExecuted:!0});else if(g.item.type===`local_shell_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:g.item.action.command,timeoutMs:g.item.action.timeout_ms,user:g.item.action.user,workingDirectory:g.item.action.working_directory,env:g.item.action.env}}),providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`message`)n.enqueue({type:`text-end`,id:g.item.id});else if(po(g)){let e=p[g.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${g.item.id}:${t}`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}});delete p[g.item.id]}}else if(go(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(_o(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(g.delta).slice(1,-1)})}else if(vo(g)){let e=d[g.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:g.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else ho(g)?(u=g.response.id,n.enqueue({type:`response-metadata`,id:g.response.id,timestamp:new Date(g.response.created_at*1e3),modelId:g.response.model})):uo(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):So(g)?g.summary_index>0&&((i=p[g.item_id])==null||i.summaryParts.push(g.summary_index),n.enqueue({type:`reasoning-start`,id:`${g.item_id}:${g.summary_index}`,providerMetadata:{openai:{itemId:g.item_id,reasoningEncryptedContent:p[g.item_id]?.encryptedContent??null}}})):Co(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):mo(g)?(s=Ba({finishReason:g.response.incomplete_details?.reason,hasFunctionCall:f}),c.inputTokens=g.response.usage.input_tokens,c.outputTokens=g.response.usage.output_tokens,c.totalTokens=g.response.usage.input_tokens+g.response.usage.output_tokens,c.reasoningTokens=g.response.usage.output_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=g.response.usage.input_tokens_details?.cached_tokens??void 0,typeof g.response.service_tier==`string`&&(m=g.response.service_tier)):xo(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??L(),url:g.annotation.url,title:g.annotation.title}):g.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(h=o.config).generateId?.call(h)??L(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):wo(g)&&n.enqueue({type:`error`,error:g})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},Xa=r.object({input_tokens:r.number(),input_tokens_details:r.object({cached_tokens:r.number().nullish()}).nullish(),output_tokens:r.number(),output_tokens_details:r.object({reasoning_tokens:r.number().nullish()}).nullish()}),Za=r.object({type:r.literal(`response.output_text.delta`),item_id:r.string(),delta:r.string(),logprobs:Ja.nullish()}),Qa=r.object({type:r.literal(`error`),code:r.string(),message:r.string(),param:r.string().nullish(),sequence_number:r.number()}),$a=r.object({type:r.enum([`response.completed`,`response.incomplete`]),response:r.object({incomplete_details:r.object({reason:r.string()}).nullish(),usage:Xa,service_tier:r.string().nullish()})}),eo=r.object({type:r.literal(`response.created`),response:r.object({id:r.string(),created_at:r.number(),model:r.string(),service_tier:r.string().nullish()})}),to=r.object({type:r.literal(`response.output_item.added`),output_index:r.number(),item:r.discriminatedUnion(`type`,[r.object({type:r.literal(`message`),id:r.string()}),r.object({type:r.literal(`reasoning`),id:r.string(),encrypted_content:r.string().nullish()}),r.object({type:r.literal(`function_call`),id:r.string(),call_id:r.string(),name:r.string(),arguments:r.string()}),r.object({type:r.literal(`web_search_call`),id:r.string(),status:r.string(),action:r.object({type:r.literal(`search`),query:r.string().optional()}).nullish()}),r.object({type:r.literal(`computer_call`),id:r.string(),status:r.string()}),r.object({type:r.literal(`file_search_call`),id:r.string()}),r.object({type:r.literal(`image_generation_call`),id:r.string()}),r.object({type:r.literal(`code_interpreter_call`),id:r.string(),container_id:r.string(),code:r.string().nullable(),outputs:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`logs`),logs:r.string()}),r.object({type:r.literal(`image`),url:r.string()})])).nullable(),status:r.string()})])}),no=r.object({type:r.literal(`response.output_item.done`),output_index:r.number(),item:r.discriminatedUnion(`type`,[r.object({type:r.literal(`message`),id:r.string()}),r.object({type:r.literal(`reasoning`),id:r.string(),encrypted_content:r.string().nullish()}),r.object({type:r.literal(`function_call`),id:r.string(),call_id:r.string(),name:r.string(),arguments:r.string(),status:r.literal(`completed`)}),Wa,Ka,Ha,Ua,Ga,r.object({type:r.literal(`computer_call`),id:r.string(),status:r.literal(`completed`)})])}),ro=r.object({type:r.literal(`response.function_call_arguments.delta`),item_id:r.string(),output_index:r.number(),delta:r.string()}),io=r.object({type:r.literal(`response.code_interpreter_call_code.delta`),item_id:r.string(),output_index:r.number(),delta:r.string()}),ao=r.object({type:r.literal(`response.code_interpreter_call_code.done`),item_id:r.string(),output_index:r.number(),code:r.string()}),oo=r.object({type:r.literal(`response.output_text.annotation.added`),annotation:r.discriminatedUnion(`type`,[r.object({type:r.literal(`url_citation`),url:r.string(),title:r.string()}),r.object({type:r.literal(`file_citation`),file_id:r.string(),filename:r.string().nullish(),index:r.number().nullish(),start_index:r.number().nullish(),end_index:r.number().nullish(),quote:r.string().nullish()})])}),so=r.object({type:r.literal(`response.reasoning_summary_part.added`),item_id:r.string(),summary_index:r.number()}),co=r.object({type:r.literal(`response.reasoning_summary_text.delta`),item_id:r.string(),summary_index:r.number(),delta:r.string()}),lo=r.union([Za,$a,eo,to,no,ro,io,ao,oo,so,co,Qa,r.object({type:r.string()}).loose()]);function uo(e){return e.type===`response.output_text.delta`}function fo(e){return e.type===`response.output_item.done`}function po(e){return fo(e)&&e.item.type===`reasoning`}function mo(e){return e.type===`response.completed`||e.type===`response.incomplete`}function ho(e){return e.type===`response.created`}function go(e){return e.type===`response.function_call_arguments.delta`}function _o(e){return e.type===`response.code_interpreter_call_code.delta`}function vo(e){return e.type===`response.code_interpreter_call_code.done`}function yo(e){return e.type===`response.output_item.added`}function bo(e){return yo(e)&&e.item.type===`reasoning`}function xo(e){return e.type===`response.output_text.annotation.added`}function So(e){return e.type===`response.reasoning_summary_part.added`}function Co(e){return e.type===`response.reasoning_summary_text.delta`}function wo(e){return e.type===`error`}function To(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var Eo=r.object({include:r.array(r.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:r.string().nullish(),logprobs:r.union([r.boolean(),r.number().min(1).max(qa)]).optional(),maxToolCalls:r.number().nullish(),metadata:r.any().nullish(),parallelToolCalls:r.boolean().nullish(),previousResponseId:r.string().nullish(),promptCacheKey:r.string().nullish(),reasoningEffort:r.string().nullish(),reasoningSummary:r.string().nullish(),safetyIdentifier:r.string().nullish(),serviceTier:r.enum([`auto`,`flex`,`priority`]).nullish(),store:r.boolean().nullish(),strictJsonSchema:r.boolean().nullish(),textVerbosity:r.enum([`low`,`medium`,`high`]).nullish(),user:r.string().nullish()}),Do=r.object({instructions:r.string().nullish(),speed:r.number().min(.25).max(4).default(1).nullish()}),Oo=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await z({provider:`openai`,providerOptions:o,schema:Do}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await B({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:$,successfulResponseHandler:mr(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},ko=r.object({include:r.array(r.string()).optional(),language:r.string().optional(),prompt:r.string().optional(),temperature:r.number().min(0).max(1).default(0).optional(),timestampGranularities:r.array(r.enum([`word`,`segment`])).default([`segment`]).optional()}),Ao={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},jo=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await z({provider:`openai`,providerOptions:n,schema:ko}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([_r(e)]);a.append(`model`,this.modelId);let s=qn(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await dr({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),formData:r,failedResponseHandler:$,successfulResponseHandler:K(Mo),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Ao?Ao[a.language]:void 0;return{text:a.text,segments:a.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??a.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:c,durationInSeconds:a.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Mo=r.object({text:r.string(),language:r.string().nullish(),duration:r.number().nullish(),words:r.array(r.object({word:r.string(),start:r.number(),end:r.number()})).nullish(),segments:r.array(r.object({id:r.number(),seek:r.number(),start:r.number(),end:r.number(),text:r.string(),tokens:r.array(r.number()),temperature:r.number(),avg_logprob:r.number(),compression_ratio:r.number(),no_speech_prob:r.number()})).nullish()}),No=`2.0.42`;function Po(e={}){let t=J(Kn({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>I({Authorization:`Bearer ${Gn({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${No}`),i=i=>new Wi(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new ra(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new ca(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new fa(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new jo(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new Oo(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new Ya(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.textEmbedding=o,f.textEmbeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=Ia,f}Po();function Fo(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function Io(e){return Object.fromEntries([...e.headers])}function Lo(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function Ro(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function zo(e,...t){let n=Ro(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new $t({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function Bo(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Vo=[`fetch failed`,`failed to fetch`];function Ho({error:e,url:t,requestBodyValues:n}){if(Bo(e))return e;if(e instanceof TypeError&&Vo.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new k({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Uo=`3.0.10`,Wo=/"__proto__"\s*:/,Go=/"constructor"\s*:/;function Ko(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Wo.test(e)===!1&&Go.test(e)===!1?t:qo(t)}function qo(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Jo(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Ko(e)}finally{Error.stackTraceLimit=t}}var Yo=Symbol.for(`vercel.ai.validator`);function Xo(e){return{[Yo]:!0,validate:e}}function Zo(e){return typeof e==`object`&&!!e&&Yo in e&&e[Yo]===!0&&`validate`in e}function Qo(e){return Zo(e)?e:$o(e)}function $o(e){return Xo(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new M({value:t,cause:n.issues})}})}async function es({value:e,schema:t}){let n=await ts({value:e,schema:t});if(!n.success)throw M.wrap({value:e,cause:n.error});return n.value}async function ts({value:e,schema:t}){let n=Qo(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:M.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:M.wrap({value:e,cause:t}),rawValue:e}}}async function ns({text:e,schema:t}){try{let n=Jo(e);return t==null?n:es({value:n,schema:t})}catch(t){throw A.isInstance(t)||M.isInstance(t)?t:new A({text:e,cause:t})}}async function rs({text:e,schema:t}){try{let n=Jo(e);return t==null?{success:!0,value:n,rawValue:n}:await ts({value:n,schema:t})}catch(t){return{success:!1,error:A.isInstance(t)?t:new A({text:e,cause:t}),rawValue:void 0}}}var os=()=>globalThis.fetch,ss=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>cs({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),cs=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=os()})=>{try{let s=await o(e,{method:`POST`,headers:zo(t,`ai-sdk/provider-utils/${Uo}`,Lo()),body:n.content,signal:a}),c=Io(s);if(!s.ok){let t;try{t=await i({response:s,url:e,requestBodyValues:n.values})}catch(t){throw Bo(t)||k.isInstance(t)?t:new k({message:`Failed to process error response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Bo(t)||k.isInstance(t))?t:new k({message:`Failed to process successful response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(t){throw Ho({error:t,url:e,requestBodyValues:n.values})}},ls=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),s=Io(r);if(o.trim()===``)return{responseHeaders:s,value:new k({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})};try{let c=await ns({text:o,schema:e});return{responseHeaders:s,value:new k({message:t(c),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,data:c,isRetryable:n?.(r,c)})}}catch{return{responseHeaders:s,value:new k({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})}}},us=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await rs({text:i,schema:e}),o=Io(t);if(!a.success)throw new k({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:ds,atob:fs}=globalThis;r.object({user:r.string().optional(),reasoningEffort:r.string().optional()});var ps={errorSchema:r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.any().nullish(),code:r.union([r.string(),r.number()]).nullish()})}),errorToMessage:e=>e.error.message},ms=r.object({prompt_tokens:r.number().nullish(),completion_tokens:r.number().nullish(),total_tokens:r.number().nullish(),prompt_tokens_details:r.object({cached_tokens:r.number().nullish()}).nullish(),completion_tokens_details:r.object({reasoning_tokens:r.number().nullish(),accepted_prediction_tokens:r.number().nullish(),rejected_prediction_tokens:r.number().nullish()}).nullish()}).nullish();r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({message:r.object({role:r.literal(`assistant`).nullish(),content:r.string().nullish(),reasoning_content:r.string().nullish(),reasoning:r.string().nullish(),tool_calls:r.array(r.object({id:r.string().nullish(),function:r.object({name:r.string(),arguments:r.string()})})).nullish()}),finish_reason:r.string().nullish()})),usage:ms}),r.object({echo:r.boolean().optional(),logitBias:r.record(r.string(),r.number()).optional(),suffix:r.string().optional(),user:r.string().optional()});var hs=r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()});r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string()})),usage:hs.nullish()}),r.object({dimensions:r.number().optional(),user:r.string().optional()}),r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish(),providerMetadata:r.record(r.string(),r.record(r.string(),r.any())).optional()});var gs=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await ss({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Fo(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:ls(this.config.errorStructure??ps),successfulResponseHandler:us(_s),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f}}}},_s=r.object({data:r.array(r.object({b64_json:r.string()}))});function vs(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${q(e.data)}`}}}else throw new N({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function ys({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function bs(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var xs=r.object({type:r.literal(`web`),country:r.string().length(2).optional(),excludedWebsites:r.array(r.string()).max(5).optional(),allowedWebsites:r.array(r.string()).max(5).optional(),safeSearch:r.boolean().optional()}),Ss=r.object({type:r.literal(`x`),excludedXHandles:r.array(r.string()).optional(),includedXHandles:r.array(r.string()).optional(),postFavoriteCount:r.number().int().optional(),postViewCount:r.number().int().optional(),xHandles:r.array(r.string()).optional()}),Cs=r.object({type:r.literal(`news`),country:r.string().length(2).optional(),excludedWebsites:r.array(r.string()).max(5).optional(),safeSearch:r.boolean().optional()}),ws=r.object({type:r.literal(`rss`),links:r.array(r.string().url()).max(1)}),Ts=r.discriminatedUnion(`type`,[xs,Ss,Cs,ws]),Es=r.object({reasoningEffort:r.enum([`low`,`high`]).optional(),searchParameters:r.object({mode:r.enum([`off`,`auto`,`on`]),returnCitations:r.boolean().optional(),fromDate:r.string().optional(),toDate:r.string().optional(),maxSearchResults:r.number().min(1).max(50).optional(),sources:r.array(Ts).optional()}).optional()}),Ds=r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.any().nullish(),code:r.union([r.string(),r.number()]).nullish()})}),Os=W({errorSchema:Ds,errorToMessage:e=>e.error.message});function ks({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new N({functionality:`tool choice type: ${i}`})}}var As=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){let p=[],m=await z({provider:`xai`,providerOptions:u,schema:Es})??{};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:h,warnings:g}=vs(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=ks({tools:d,toolChoice:f});return p.push(...y),{args:{model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:m.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:l.name??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:m.searchParameters?{mode:m.searchParameters.mode,return_citations:m.searchParameters.returnCitations,from_date:m.searchParameters.fromDate,to_date:m.searchParameters.toDate,max_search_results:m.searchParameters.maxSearchResults,sources:m.searchParameters.sources?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{excluded_x_handles:e.excludedXHandles,included_x_handles:e.includedXHandles??e.xHandles,post_favorite_count:e.postFavoriteCount,post_view_count:e.postViewCount},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:h,tools:_,tool_choice:v},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await B({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:P(this.config.headers(),e.headers),body:t,failedResponseHandler:Os,successfulResponseHandler:K(Ms),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[];if(o.message.content!=null&&o.message.content.length>0){let e=o.message.content,n=t.messages[t.messages.length-1];n?.role===`assistant`&&e===n.content&&(e=``),e.length>0&&s.push({type:`text`,text:e})}if(o.message.reasoning_content!=null&&o.message.reasoning_content.length>0&&s.push({type:`reasoning`,text:o.message.reasoning_content}),o.message.tool_calls!=null)for(let e of o.message.tool_calls)s.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(i.citations!=null)for(let e of i.citations)s.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:s,finishReason:bs(o.finish_reason),usage:{inputTokens:i.usage.prompt_tokens,outputTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens,reasoningTokens:i.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:t},response:{...ys(i),headers:r,body:a},warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await B({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:Os,successfulResponseHandler:G(Ns),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},c=!0,l={},u={},d=this;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let i=t.value;if(c&&=(n.enqueue({type:`response-metadata`,...ys(i)}),!1),i.citations!=null)for(let e of i.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});i.usage!=null&&(s.inputTokens=i.usage.prompt_tokens,s.outputTokens=i.usage.completion_tokens,s.totalTokens=i.usage.total_tokens,s.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=i.choices[0];if(a?.finish_reason!=null&&(o=bs(a.finish_reason)),a?.delta==null)return;let f=a.delta,p=a.index;if(f.content!=null&&f.content.length>0){let e=f.content,t=r.messages[r.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${i.id||p}`;l[a]??(l[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(f.reasoning_content!=null&&f.reasoning_content.length>0){let e=`reasoning-${i.id||p}`;if(u[e]===f.reasoning_content)return;u[e]=f.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:f.reasoning_content})}if(f.tool_calls!=null)for(let e of f.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:o,usage:s})}})),request:{body:r},response:{headers:i}}}},js=r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number(),completion_tokens_details:r.object({reasoning_tokens:r.number().nullish()}).nullish()}),Ms=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({message:r.object({role:r.literal(`assistant`),content:r.string().nullish(),reasoning_content:r.string().nullish(),tool_calls:r.array(r.object({id:r.string(),type:r.literal(`function`),function:r.object({name:r.string(),arguments:r.string()})})).nullish()}),index:r.number(),finish_reason:r.string().nullish()})),object:r.literal(`chat.completion`),usage:js,citations:r.array(r.string().url()).nullish()}),Ns=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({delta:r.object({role:r.enum([`assistant`]).optional(),content:r.string().nullish(),reasoning_content:r.string().nullish(),tool_calls:r.array(r.object({id:r.string(),type:r.literal(`function`),function:r.object({name:r.string(),arguments:r.string()})})).nullish()}),finish_reason:r.string().nullish(),index:r.number()})),usage:js.nullish(),citations:r.array(r.string().url()).nullish()}),Ps=`2.0.23`,Fs={errorSchema:Ds,errorToMessage:e=>e.error.message};function Is(e={}){let t=J(e.baseURL??`https://api.x.ai/v1`),n=()=>I({Authorization:`Bearer ${Gn({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${Ps}`),r=r=>new As(r,{provider:`xai.chat`,baseURL:t,headers:n,generateId:L,fetch:e.fetch}),i=r=>new gs(r,{provider:`xai.image`,url:({path:e})=>`${t}${e}`,headers:n,fetch:e.fetch,errorStructure:Fs}),a=e=>r(e);return a.languageModel=r,a.chat=r,a.textEmbeddingModel=e=>{throw new Cn({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=i,a.image=i,a}Is();function Ls(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function Rs(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(`x-blink-stream-response-format`);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new wt).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let n=e=>u({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(Po({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(Po({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(ii({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(Li({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(Is({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}const zs=`BLINK_API_URL`;var Bs=class{baseUrl;client;constructor(e){this.client=Pt(e.baseUrl),this.baseUrl=e.baseUrl}async chat(e,t){let n=await this.client._agent.chat.$post({json:e},{headers:t?.headers,init:{signal:t?.signal}});return n.ok||await this.handleError(n),Rs(n)}async capabilities(){let e=await this.client._agent.capabilities.$get();return e.ok||await this.handleError(e),e.json()}async ui(e,t){let n=await this.client._agent.ui.$get({query:e.selectedOptions?{selected_options:JSON.stringify(e.selectedOptions)}:{}},{init:{signal:t?.signal}});if(!n.ok||n.status!==200){if(n.status===404)return;await this.handleError(n)}return n.json()}async health(){let e=await this.client._agent.health.$get();e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed (${e.status}): ${t}`)}throw Error(`Failed (${e.status}): ${e.statusText}`)}};async function Vs({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Hs}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),u=l({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of u)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Hs=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(s);return n.length===0||n.some(e=>Ee(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Us=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Ws(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Gs=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=vt(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=yt(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Ws(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!s(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await Vs({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),c=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},l=o.getReader();n.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||n.signal.aborted)break;u||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};export{k as APICallError,zs as APIServerURLEnvironmentVariable,Gs as ChatManager,Bs as Client,we as CustomChatResponseError,wt as EventSourceParserStream,Cn as NoSuchModelError,Re as checkOptionalParameter,P as combineHeaders,me as completeAssign,Us as convertMessage,ii as createAnthropic,Ce as createCustomAbortControllerSignal,vt as createDiskStore,G as createEventSourceResponseHandler,W as createJsonErrorResponseHandler,K as createJsonResponseHandler,Po as createOpenAI,St as createParser,Ue as decodeURIComponent_,xe as ensureDisposableStackRegisteredForTerminateEvents,h as fakePromise,Wn as getFromApi,Fe as getPath,Ie as getPathNoStrict,Me as getPattern,Ve as getQueryParam,He as getQueryParams,_e as handleAbortSignalAndPromiseResponse,he as handleErrorFromRequestHandler,m as handleMaybePromise,Pt as hc,ce as isFetchEvent,ae as isNodeRequest,f as isPromise,pe as isRequestInit,oe as isServerResponse,Ws as isStoredMessageMetadata,Ee as isToolApprovalOutput,ge as isolateObject,_ as iterateAsync,Ls as lastUIOptions,Kn as loadOptionalSetting,Le as mergePath,re as normalizeNodeRequest,Ke as parse,B as postJsonToApi,U as resolve,de as sendNodeResponse,De as splitPath,Oe as splitRoutingPath,Te as tools,Ne as tryDecode,S as unfakePromise,I as withUserAgentSuffix,J as withoutTrailingSlash};
21
+ ${t}:`]}}function ea({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function ta(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var na=r.object({echo:r.boolean().optional(),logitBias:r.record(r.string(),r.number()).optional(),suffix:r.string().optional(),user:r.string().optional(),logprobs:r.union([r.boolean(),r.number()]).optional()}),ra=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await z({provider:`openai`,providerOptions:f,schema:na}),...await z({provider:this.providerOptionsName,providerOptions:f,schema:na})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=$i({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await B({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:t,failedResponseHandler:$,successfulResponseHandler:K(aa),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s={openai:{}};return o.logprobs!=null&&(s.openai.logprobs=o.logprobs),{content:[{type:`text`,text:o.text}],usage:{inputTokens:i.usage?.prompt_tokens,outputTokens:i.usage?.completion_tokens,totalTokens:i.usage?.total_tokens},finishReason:ta(o.finish_reason),request:{body:t},response:{...ea(i),headers:r,body:a},providerMetadata:s,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await B({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:$,successfulResponseHandler:G(oa),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...ea(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=ta(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},ia=r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()}),aa=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullish()}).nullish()})),usage:ia.nullish()}),oa=r.union([r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string().nullish(),index:r.number(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullish()}).nullish()})),usage:ia.nullish()}),Ri]),sa=r.object({dimensions:r.number().optional(),user:r.string().optional()}),ca=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){if(e.length>this.maxEmbeddingsPerCall)throw new On({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let i=await z({provider:`openai`,providerOptions:r,schema:sa})??{},{responseHeaders:a,value:o,rawValue:s}=await B({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:P(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:i.dimensions,user:i.user},failedResponseHandler:$,successfulResponseHandler:K(la),abortSignal:n,fetch:this.config.fetch});return{embeddings:o.data.map(e=>e.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,response:{headers:a,body:s}}}},la=r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish()}),ua={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},da=new Set([`gpt-image-1`]),fa=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return ua[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await B({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:P(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...da.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:$,successfulResponseHandler:K(pa),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:d.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},pa=r.object({data:r.array(r.object({b64_json:r.string(),revised_prompt:r.string().optional()}))}),ma=r.object({code:r.string().nullish(),containerId:r.string()}),ha=r.object({outputs:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`logs`),logs:r.string()}),r.object({type:r.literal(`image`),url:r.string()})])).nullish()}),ga=r.object({container:r.union([r.string(),r.object({fileIds:r.array(r.string()).optional()})]).optional()}),_a=H({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:ma,outputSchema:ha}),va=(e={})=>_a(e),ya=r.object({key:r.string(),type:r.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:r.union([r.string(),r.number(),r.boolean()])}),ba=r.object({type:r.enum([`and`,`or`]),filters:r.array(r.union([ya,r.lazy(()=>ba)]))}),xa=r.object({vectorStoreIds:r.array(r.string()),maxNumResults:r.number().optional(),ranking:r.object({ranker:r.string().optional(),scoreThreshold:r.number().optional()}).optional(),filters:r.union([ya,ba]).optional()}),Sa=r.object({queries:r.array(r.string()),results:r.array(r.object({attributes:r.record(r.string(),r.unknown()),fileId:r.string(),filename:r.string(),score:r.number(),text:r.string()})).nullable()}),Ca=H({id:`openai.file_search`,name:`file_search`,inputSchema:r.object({}),outputSchema:Sa}),wa=r.object({background:r.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:r.enum([`low`,`high`]).optional(),inputImageMask:r.object({fileId:r.string().optional(),imageUrl:r.string().optional()}).optional(),model:r.string().optional(),moderation:r.enum([`auto`]).optional(),outputCompression:r.number().int().min(0).max(100).optional(),outputFormat:r.enum([`png`,`jpeg`,`webp`]).optional(),quality:r.enum([`auto`,`low`,`medium`,`high`]).optional(),size:r.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),Ta=r.object({result:r.string()}),Ea=H({id:`openai.image_generation`,name:`image_generation`,inputSchema:r.object({}),outputSchema:Ta}),Da=(e={})=>Ea(e),Oa=r.object({action:r.object({type:r.literal(`exec`),command:r.array(r.string()),timeoutMs:r.number().optional(),user:r.string().optional(),workingDirectory:r.string().optional(),env:r.record(r.string(),r.string()).optional()})}),ka=r.object({output:r.string()}),Aa=H({id:`openai.local_shell`,name:`local_shell`,inputSchema:Oa,outputSchema:ka}),ja=r.object({filters:r.object({allowedDomains:r.array(r.string()).optional()}).optional(),searchContextSize:r.enum([`low`,`medium`,`high`]).optional(),userLocation:r.object({type:r.literal(`approximate`),country:r.string().optional(),city:r.string().optional(),region:r.string().optional(),timezone:r.string().optional()}).optional()}),Ma=V({id:`openai.web_search`,name:`web_search`,inputSchema:r.object({action:r.discriminatedUnion(`type`,[r.object({type:r.literal(`search`),query:r.string().nullish()}),r.object({type:r.literal(`open_page`),url:r.string()}),r.object({type:r.literal(`find`),url:r.string(),pattern:r.string()})]).nullish()})}),Na=(e={})=>Ma(e),Pa=r.object({searchContextSize:r.enum([`low`,`medium`,`high`]).optional(),userLocation:r.object({type:r.literal(`approximate`),country:r.string().optional(),city:r.string().optional(),region:r.string().optional(),timezone:r.string().optional()}).optional()}),Fa=V({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:r.object({action:r.discriminatedUnion(`type`,[r.object({type:r.literal(`search`),query:r.string().nullish()}),r.object({type:r.literal(`open_page`),url:r.string()}),r.object({type:r.literal(`find`),url:r.string(),pattern:r.string()})]).nullish()})}),Ia={codeInterpreter:va,fileSearch:Ca,imageGeneration:Da,localShell:Aa,webSearchPreview:Fa,webSearch:Na};function La(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Ra({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:i=!1}){let a=[],o=[];for(let{role:s,content:c}of e)switch(s){case`system`:switch(t){case`system`:a.push({role:`system`,content:c});break;case`developer`:a.push({role:`developer`,content:c});break;case`remove`:o.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:a.push({role:`user`,content:c.map((e,t)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&La(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${q(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&La(e.data,n)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${q(e.data)}`}};else throw new N({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of c)switch(n.type){case`text`:a.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(t[n.toolCallId]=n,n.providerExecuted)break;if(i&&n.toolName===`local_shell`){let e=Oa.parse(n.input);a.push({type:`local_shell_call`,call_id:n.toolCallId,id:n.providerOptions?.openai?.itemId??void 0,action:{type:`exec`,command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}a.push({type:`function_call`,call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:r?a.push({type:`item_reference`,id:n.toolCallId}):o.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await z({provider:`openai`,providerOptions:n.providerOptions,schema:za}),i=t?.itemId;if(i!=null){let s=e[i];if(r)s===void 0&&(a.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let r=[];n.text.length>0?r.push({type:`summary_text`,text:n.text}):s!==void 0&&o.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),s===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:r},a.push(e[i])):s.summary.push(...r)}}else o.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of c){let t=e.output;if(i&&e.toolName===`local_shell`&&t.type===`json`){a.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:ka.parse(t.value).output});break}let n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}a.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=s;throw Error(`Unsupported role: ${e}`)}}return{input:a,warnings:o}}var za=r.object({itemId:r.string().nullish(),reasoningEncryptedContent:r.string().nullish()});function Ba({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function Va({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=xa.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:i.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=Pa.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=ja.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=ga.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=wa.parse(t.args);i.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:throw new N({functionality:`tool choice type: ${a}`})}}var Ha=r.object({type:r.literal(`web_search_call`),id:r.string(),status:r.string(),action:r.discriminatedUnion(`type`,[r.object({type:r.literal(`search`),query:r.string().nullish()}),r.object({type:r.literal(`open_page`),url:r.string()}),r.object({type:r.literal(`find`),url:r.string(),pattern:r.string()})]).nullish()}),Ua=r.object({type:r.literal(`file_search_call`),id:r.string(),queries:r.array(r.string()),results:r.array(r.object({attributes:r.record(r.string(),r.unknown()),file_id:r.string(),filename:r.string(),score:r.number(),text:r.string()})).nullish()}),Wa=r.object({type:r.literal(`code_interpreter_call`),id:r.string(),code:r.string().nullable(),container_id:r.string(),outputs:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`logs`),logs:r.string()}),r.object({type:r.literal(`image`),url:r.string()})])).nullable()}),Ga=r.object({type:r.literal(`local_shell_call`),id:r.string(),call_id:r.string(),action:r.object({type:r.literal(`exec`),command:r.array(r.string()),timeout_ms:r.number().optional(),user:r.string().optional(),working_directory:r.string().optional(),env:r.record(r.string(),r.string()).optional()})}),Ka=r.object({type:r.literal(`image_generation_call`),id:r.string(),result:r.string()}),qa=20,Ja=r.array(r.object({token:r.string(),logprob:r.number(),top_logprobs:r.array(r.object({token:r.string(),logprob:r.number()}))})),Ya=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let p=[],m=To(this.modelId);i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`});let h=await z({provider:`openai`,providerOptions:l,schema:Eo}),{input:g,warnings:_}=await Ra({prompt:c,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:h?.store??!0,hasLocalShellTool:x(`openai.local_shell`)});p.push(..._);let v=h?.strictJsonSchema??!1,y=h?.include;function b(e){y=y==null?[e]:[...y,e]}function x(e){return u?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let S=typeof h?.logprobs==`number`?h?.logprobs:h?.logprobs===!0?qa:void 0;S&&b(`message.output_text.logprobs`);let C=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;C&&b(`web_search_call.action.sources`),x(`openai.code_interpreter`)&&b(`code_interpreter_call.outputs`);let w={model:this.modelId,input:g,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||h?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:v,name:f.name??`response`,description:f.description,schema:f.schema}},...h?.textVerbosity&&{verbosity:h.textVerbosity}}},max_tool_calls:h?.maxToolCalls,metadata:h?.metadata,parallel_tool_calls:h?.parallelToolCalls,previous_response_id:h?.previousResponseId,store:h?.store,user:h?.user,instructions:h?.instructions,service_tier:h?.serviceTier,include:y,prompt_cache_key:h?.promptCacheKey,safety_identifier:h?.safetyIdentifier,top_logprobs:S,...m.isReasoningModel&&(h?.reasoningEffort!=null||h?.reasoningSummary!=null)&&{reasoning:{...h?.reasoningEffort!=null&&{effort:h.reasoningEffort},...h?.reasoningSummary!=null&&{summary:h.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:`auto`}};m.isReasoningModel?(w.temperature!=null&&(w.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),w.top_p!=null&&(w.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(h?.reasoningEffort!=null&&p.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),h?.reasoningSummary!=null&&p.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),h?.serviceTier===`flex`&&!m.supportsFlexProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete w.service_tier),h?.serviceTier===`priority`&&!m.supportsPriorityProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete w.service_tier);let{tools:ee,toolChoice:te,toolWarnings:ne}=Va({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:ee,tool_choice:te},warnings:[...p,...ne]}}async doGenerate(e){var t,n;let{args:i,warnings:a,webSearchToolName:o}=await this.getArgs(e),s=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:c,value:l,rawValue:u}=await B({url:s,headers:P(this.config.headers(),e.headers),body:i,failedResponseHandler:$,successfulResponseHandler:K(r.object({id:r.string(),created_at:r.number(),error:r.object({code:r.string(),message:r.string()}).nullish(),model:r.string(),output:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`message`),role:r.literal(`assistant`),id:r.string(),content:r.array(r.object({type:r.literal(`output_text`),text:r.string(),logprobs:Ja.nullish(),annotations:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`url_citation`),start_index:r.number(),end_index:r.number(),url:r.string(),title:r.string()}),r.object({type:r.literal(`file_citation`),file_id:r.string(),filename:r.string().nullish(),index:r.number().nullish(),start_index:r.number().nullish(),end_index:r.number().nullish(),quote:r.string().nullish()}),r.object({type:r.literal(`container_file_citation`)})]))}))}),Ha,Ua,Wa,Ka,Ga,r.object({type:r.literal(`function_call`),call_id:r.string(),name:r.string(),arguments:r.string(),id:r.string()}),r.object({type:r.literal(`computer_call`),id:r.string(),status:r.string().optional()}),r.object({type:r.literal(`reasoning`),id:r.string(),encrypted_content:r.string().nullish(),summary:r.array(r.object({type:r.literal(`summary_text`),text:r.string()}))})])),service_tier:r.string().nullish(),incomplete_details:r.object({reason:r.string()}).nullish(),usage:Xa})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(l.error)throw new k({message:l.error.message,url:s,requestBodyValues:i,statusCode:400,responseHeaders:c,responseBody:u,isRetryable:!1});let d=[],f=[],p=!1;for(let r of l.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)d.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:d.push({type:`tool-call`,toolCallId:r.call_id,toolName:`local_shell`,input:JSON.stringify({action:r.action}),providerMetadata:{openai:{itemId:r.id}}});break;case`message`:for(let i of r.content){e.providerOptions?.openai?.logprobs&&i.logprobs&&f.push(i.logprobs),d.push({type:`text`,text:i.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of i.annotations)e.type===`url_citation`?d.push({type:`source`,sourceType:`url`,id:(t=this.config).generateId?.call(t)??L(),url:e.url,title:e.title}):e.type===`file_citation`&&d.push({type:`source`,sourceType:`document`,id:(n=this.config).generateId?.call(n)??L(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:p=!0,d.push({type:`tool-call`,toolCallId:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:o??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:o??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:r.status||`completed`},providerExecuted:!0});break;case`file_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`file_search`,result:{queries:r.queries,results:r.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});break;case`code_interpreter_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.outputs},providerExecuted:!0});break}let m={openai:{responseId:l.id}};return f.length>0&&(m.openai.logprobs=f),typeof l.service_tier==`string`&&(m.openai.serviceTier=l.service_tier),{content:d,finishReason:Ba({finishReason:l.incomplete_details?.reason,hasFunctionCall:p}),usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,reasoningTokens:l.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:l.usage.input_tokens_details?.cached_tokens??void 0},request:{body:i},response:{id:l.id,timestamp:new Date(l.created_at*1e3),modelId:l.model,headers:c,body:u},providerMetadata:m,warnings:a}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await B({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:$,successfulResponseHandler:G(lo),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let g=t.value;if(yo(g))g.item.type===`function_call`?(d[g.output_index]={toolName:g.item.name,toolCallId:g.item.call_id},n.enqueue({type:`tool-input-start`,id:g.item.call_id,toolName:g.item.name})):g.item.type===`web_search_call`?(d[g.output_index]={toolName:r??`web_search`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:r??`web_search`})):g.item.type===`computer_call`?(d[g.output_index]={toolName:`computer_use`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`computer_use`})):g.item.type===`code_interpreter_call`?(d[g.output_index]={toolName:`code_interpreter`,toolCallId:g.item.id,codeInterpreter:{containerId:g.item.container_id}},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`code_interpreter`}),n.enqueue({type:`tool-input-delta`,id:g.item.id,delta:`{"containerId":"${g.item.container_id}","code":"`})):g.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):g.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):g.item.type===`message`?n.enqueue({type:`text-start`,id:g.item.id,providerMetadata:{openai:{itemId:g.item.id}}}):bo(g)&&(p[g.item.id]={encryptedContent:g.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${g.item.id}:0`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}}));else if(fo(g)){if(g.item.type===`function_call`)d[g.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:g.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:g.item.name,input:g.item.arguments,providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`web_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`web_search`,input:JSON.stringify({action:g.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`web_search`,result:{status:g.item.status},providerExecuted:!0});else if(g.item.type===`computer_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:g.item.status||`completed`},providerExecuted:!0});else if(g.item.type===`file_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`file_search`,result:{queries:g.item.queries,results:g.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});else if(g.item.type===`code_interpreter_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`code_interpreter`,result:{outputs:g.item.outputs},providerExecuted:!0});else if(g.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`image_generation`,result:{result:g.item.result},providerExecuted:!0});else if(g.item.type===`local_shell_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:g.item.action.command,timeoutMs:g.item.action.timeout_ms,user:g.item.action.user,workingDirectory:g.item.action.working_directory,env:g.item.action.env}}),providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`message`)n.enqueue({type:`text-end`,id:g.item.id});else if(po(g)){let e=p[g.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${g.item.id}:${t}`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}});delete p[g.item.id]}}else if(go(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(_o(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(g.delta).slice(1,-1)})}else if(vo(g)){let e=d[g.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:g.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else ho(g)?(u=g.response.id,n.enqueue({type:`response-metadata`,id:g.response.id,timestamp:new Date(g.response.created_at*1e3),modelId:g.response.model})):uo(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):So(g)?g.summary_index>0&&((i=p[g.item_id])==null||i.summaryParts.push(g.summary_index),n.enqueue({type:`reasoning-start`,id:`${g.item_id}:${g.summary_index}`,providerMetadata:{openai:{itemId:g.item_id,reasoningEncryptedContent:p[g.item_id]?.encryptedContent??null}}})):Co(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):mo(g)?(s=Ba({finishReason:g.response.incomplete_details?.reason,hasFunctionCall:f}),c.inputTokens=g.response.usage.input_tokens,c.outputTokens=g.response.usage.output_tokens,c.totalTokens=g.response.usage.input_tokens+g.response.usage.output_tokens,c.reasoningTokens=g.response.usage.output_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=g.response.usage.input_tokens_details?.cached_tokens??void 0,typeof g.response.service_tier==`string`&&(m=g.response.service_tier)):xo(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??L(),url:g.annotation.url,title:g.annotation.title}):g.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(h=o.config).generateId?.call(h)??L(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):wo(g)&&n.enqueue({type:`error`,error:g})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},Xa=r.object({input_tokens:r.number(),input_tokens_details:r.object({cached_tokens:r.number().nullish()}).nullish(),output_tokens:r.number(),output_tokens_details:r.object({reasoning_tokens:r.number().nullish()}).nullish()}),Za=r.object({type:r.literal(`response.output_text.delta`),item_id:r.string(),delta:r.string(),logprobs:Ja.nullish()}),Qa=r.object({type:r.literal(`error`),code:r.string(),message:r.string(),param:r.string().nullish(),sequence_number:r.number()}),$a=r.object({type:r.enum([`response.completed`,`response.incomplete`]),response:r.object({incomplete_details:r.object({reason:r.string()}).nullish(),usage:Xa,service_tier:r.string().nullish()})}),eo=r.object({type:r.literal(`response.created`),response:r.object({id:r.string(),created_at:r.number(),model:r.string(),service_tier:r.string().nullish()})}),to=r.object({type:r.literal(`response.output_item.added`),output_index:r.number(),item:r.discriminatedUnion(`type`,[r.object({type:r.literal(`message`),id:r.string()}),r.object({type:r.literal(`reasoning`),id:r.string(),encrypted_content:r.string().nullish()}),r.object({type:r.literal(`function_call`),id:r.string(),call_id:r.string(),name:r.string(),arguments:r.string()}),r.object({type:r.literal(`web_search_call`),id:r.string(),status:r.string(),action:r.object({type:r.literal(`search`),query:r.string().optional()}).nullish()}),r.object({type:r.literal(`computer_call`),id:r.string(),status:r.string()}),r.object({type:r.literal(`file_search_call`),id:r.string()}),r.object({type:r.literal(`image_generation_call`),id:r.string()}),r.object({type:r.literal(`code_interpreter_call`),id:r.string(),container_id:r.string(),code:r.string().nullable(),outputs:r.array(r.discriminatedUnion(`type`,[r.object({type:r.literal(`logs`),logs:r.string()}),r.object({type:r.literal(`image`),url:r.string()})])).nullable(),status:r.string()})])}),no=r.object({type:r.literal(`response.output_item.done`),output_index:r.number(),item:r.discriminatedUnion(`type`,[r.object({type:r.literal(`message`),id:r.string()}),r.object({type:r.literal(`reasoning`),id:r.string(),encrypted_content:r.string().nullish()}),r.object({type:r.literal(`function_call`),id:r.string(),call_id:r.string(),name:r.string(),arguments:r.string(),status:r.literal(`completed`)}),Wa,Ka,Ha,Ua,Ga,r.object({type:r.literal(`computer_call`),id:r.string(),status:r.literal(`completed`)})])}),ro=r.object({type:r.literal(`response.function_call_arguments.delta`),item_id:r.string(),output_index:r.number(),delta:r.string()}),io=r.object({type:r.literal(`response.code_interpreter_call_code.delta`),item_id:r.string(),output_index:r.number(),delta:r.string()}),ao=r.object({type:r.literal(`response.code_interpreter_call_code.done`),item_id:r.string(),output_index:r.number(),code:r.string()}),oo=r.object({type:r.literal(`response.output_text.annotation.added`),annotation:r.discriminatedUnion(`type`,[r.object({type:r.literal(`url_citation`),url:r.string(),title:r.string()}),r.object({type:r.literal(`file_citation`),file_id:r.string(),filename:r.string().nullish(),index:r.number().nullish(),start_index:r.number().nullish(),end_index:r.number().nullish(),quote:r.string().nullish()})])}),so=r.object({type:r.literal(`response.reasoning_summary_part.added`),item_id:r.string(),summary_index:r.number()}),co=r.object({type:r.literal(`response.reasoning_summary_text.delta`),item_id:r.string(),summary_index:r.number(),delta:r.string()}),lo=r.union([Za,$a,eo,to,no,ro,io,ao,oo,so,co,Qa,r.object({type:r.string()}).loose()]);function uo(e){return e.type===`response.output_text.delta`}function fo(e){return e.type===`response.output_item.done`}function po(e){return fo(e)&&e.item.type===`reasoning`}function mo(e){return e.type===`response.completed`||e.type===`response.incomplete`}function ho(e){return e.type===`response.created`}function go(e){return e.type===`response.function_call_arguments.delta`}function _o(e){return e.type===`response.code_interpreter_call_code.delta`}function vo(e){return e.type===`response.code_interpreter_call_code.done`}function yo(e){return e.type===`response.output_item.added`}function bo(e){return yo(e)&&e.item.type===`reasoning`}function xo(e){return e.type===`response.output_text.annotation.added`}function So(e){return e.type===`response.reasoning_summary_part.added`}function Co(e){return e.type===`response.reasoning_summary_text.delta`}function wo(e){return e.type===`error`}function To(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var Eo=r.object({include:r.array(r.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:r.string().nullish(),logprobs:r.union([r.boolean(),r.number().min(1).max(qa)]).optional(),maxToolCalls:r.number().nullish(),metadata:r.any().nullish(),parallelToolCalls:r.boolean().nullish(),previousResponseId:r.string().nullish(),promptCacheKey:r.string().nullish(),reasoningEffort:r.string().nullish(),reasoningSummary:r.string().nullish(),safetyIdentifier:r.string().nullish(),serviceTier:r.enum([`auto`,`flex`,`priority`]).nullish(),store:r.boolean().nullish(),strictJsonSchema:r.boolean().nullish(),textVerbosity:r.enum([`low`,`medium`,`high`]).nullish(),user:r.string().nullish()}),Do=r.object({instructions:r.string().nullish(),speed:r.number().min(.25).max(4).default(1).nullish()}),Oo=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await z({provider:`openai`,providerOptions:o,schema:Do}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await B({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:$,successfulResponseHandler:mr(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},ko=r.object({include:r.array(r.string()).optional(),language:r.string().optional(),prompt:r.string().optional(),temperature:r.number().min(0).max(1).default(0).optional(),timestampGranularities:r.array(r.enum([`word`,`segment`])).default([`segment`]).optional()}),Ao={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},jo=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await z({provider:`openai`,providerOptions:n,schema:ko}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([_r(e)]);a.append(`model`,this.modelId);let s=qn(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await dr({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:P(this.config.headers(),e.headers),formData:r,failedResponseHandler:$,successfulResponseHandler:K(Mo),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Ao?Ao[a.language]:void 0;return{text:a.text,segments:a.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??a.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:c,durationInSeconds:a.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Mo=r.object({text:r.string(),language:r.string().nullish(),duration:r.number().nullish(),words:r.array(r.object({word:r.string(),start:r.number(),end:r.number()})).nullish(),segments:r.array(r.object({id:r.number(),seek:r.number(),start:r.number(),end:r.number(),text:r.string(),tokens:r.array(r.number()),temperature:r.number(),avg_logprob:r.number(),compression_ratio:r.number(),no_speech_prob:r.number()})).nullish()}),No=`2.0.42`;function Po(e={}){let t=J(Kn({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>I({Authorization:`Bearer ${Gn({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${No}`),i=i=>new Wi(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new ra(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new ca(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new fa(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new jo(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new Oo(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new Ya(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.textEmbedding=o,f.textEmbeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=Ia,f}Po(),r.object({user:r.string().optional(),reasoningEffort:r.string().optional()});var Fo={errorSchema:r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.any().nullish(),code:r.union([r.string(),r.number()]).nullish()})}),errorToMessage:e=>e.error.message},Io=r.object({prompt_tokens:r.number().nullish(),completion_tokens:r.number().nullish(),total_tokens:r.number().nullish(),prompt_tokens_details:r.object({cached_tokens:r.number().nullish()}).nullish(),completion_tokens_details:r.object({reasoning_tokens:r.number().nullish(),accepted_prediction_tokens:r.number().nullish(),rejected_prediction_tokens:r.number().nullish()}).nullish()}).nullish();r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({message:r.object({role:r.literal(`assistant`).nullish(),content:r.string().nullish(),reasoning_content:r.string().nullish(),reasoning:r.string().nullish(),tool_calls:r.array(r.object({id:r.string().nullish(),function:r.object({name:r.string(),arguments:r.string()})})).nullish()}),finish_reason:r.string().nullish()})),usage:Io}),r.object({echo:r.boolean().optional(),logitBias:r.record(r.string(),r.number()).optional(),suffix:r.string().optional(),user:r.string().optional()});var Lo=r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()});r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string()})),usage:Lo.nullish()}),r.object({dimensions:r.number().optional(),user:r.string().optional()}),r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish(),providerMetadata:r.record(r.string(),r.record(r.string(),r.any())).optional()});var Ro=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await B({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:P(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:W(this.config.errorStructure??Fo),successfulResponseHandler:K(zo),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f}}}},zo=r.object({data:r.array(r.object({b64_json:r.string()}))});function Bo(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${q(e.data)}`}}}else throw new N({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function Vo({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Ho(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var Uo=r.object({type:r.literal(`web`),country:r.string().length(2).optional(),excludedWebsites:r.array(r.string()).max(5).optional(),allowedWebsites:r.array(r.string()).max(5).optional(),safeSearch:r.boolean().optional()}),Wo=r.object({type:r.literal(`x`),excludedXHandles:r.array(r.string()).optional(),includedXHandles:r.array(r.string()).optional(),postFavoriteCount:r.number().int().optional(),postViewCount:r.number().int().optional(),xHandles:r.array(r.string()).optional()}),Go=r.object({type:r.literal(`news`),country:r.string().length(2).optional(),excludedWebsites:r.array(r.string()).max(5).optional(),safeSearch:r.boolean().optional()}),Ko=r.object({type:r.literal(`rss`),links:r.array(r.string().url()).max(1)}),qo=r.discriminatedUnion(`type`,[Uo,Wo,Go,Ko]),Jo=r.object({reasoningEffort:r.enum([`low`,`high`]).optional(),searchParameters:r.object({mode:r.enum([`off`,`auto`,`on`]),returnCitations:r.boolean().optional(),fromDate:r.string().optional(),toDate:r.string().optional(),maxSearchResults:r.number().min(1).max(50).optional(),sources:r.array(qo).optional()}).optional()}),Yo=r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.any().nullish(),code:r.union([r.string(),r.number()]).nullish()})}),Xo=W({errorSchema:Yo,errorToMessage:e=>e.error.message});function Zo({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new N({functionality:`tool choice type: ${i}`})}}var Qo=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){let p=[],m=await z({provider:`xai`,providerOptions:u,schema:Jo})??{};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:h,warnings:g}=Bo(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=Zo({tools:d,toolChoice:f});return p.push(...y),{args:{model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:m.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:l.name??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:m.searchParameters?{mode:m.searchParameters.mode,return_citations:m.searchParameters.returnCitations,from_date:m.searchParameters.fromDate,to_date:m.searchParameters.toDate,max_search_results:m.searchParameters.maxSearchResults,sources:m.searchParameters.sources?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{excluded_x_handles:e.excludedXHandles,included_x_handles:e.includedXHandles??e.xHandles,post_favorite_count:e.postFavoriteCount,post_view_count:e.postViewCount},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:h,tools:_,tool_choice:v},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await B({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:P(this.config.headers(),e.headers),body:t,failedResponseHandler:Xo,successfulResponseHandler:K(es),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[];if(o.message.content!=null&&o.message.content.length>0){let e=o.message.content,n=t.messages[t.messages.length-1];n?.role===`assistant`&&e===n.content&&(e=``),e.length>0&&s.push({type:`text`,text:e})}if(o.message.reasoning_content!=null&&o.message.reasoning_content.length>0&&s.push({type:`reasoning`,text:o.message.reasoning_content}),o.message.tool_calls!=null)for(let e of o.message.tool_calls)s.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(i.citations!=null)for(let e of i.citations)s.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:s,finishReason:Ho(o.finish_reason),usage:{inputTokens:i.usage.prompt_tokens,outputTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens,reasoningTokens:i.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:t},response:{...Vo(i),headers:r,body:a},warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await B({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:P(this.config.headers(),e.headers),body:r,failedResponseHandler:Xo,successfulResponseHandler:G(ts),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},c=!0,l={},u={},d=this;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let i=t.value;if(c&&=(n.enqueue({type:`response-metadata`,...Vo(i)}),!1),i.citations!=null)for(let e of i.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});i.usage!=null&&(s.inputTokens=i.usage.prompt_tokens,s.outputTokens=i.usage.completion_tokens,s.totalTokens=i.usage.total_tokens,s.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=i.choices[0];if(a?.finish_reason!=null&&(o=Ho(a.finish_reason)),a?.delta==null)return;let f=a.delta,p=a.index;if(f.content!=null&&f.content.length>0){let e=f.content,t=r.messages[r.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${i.id||p}`;l[a]??(l[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(f.reasoning_content!=null&&f.reasoning_content.length>0){let e=`reasoning-${i.id||p}`;if(u[e]===f.reasoning_content)return;u[e]=f.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:f.reasoning_content})}if(f.tool_calls!=null)for(let e of f.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:o,usage:s})}})),request:{body:r},response:{headers:i}}}},$o=r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number(),completion_tokens_details:r.object({reasoning_tokens:r.number().nullish()}).nullish()}),es=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({message:r.object({role:r.literal(`assistant`),content:r.string().nullish(),reasoning_content:r.string().nullish(),tool_calls:r.array(r.object({id:r.string(),type:r.literal(`function`),function:r.object({name:r.string(),arguments:r.string()})})).nullish()}),index:r.number(),finish_reason:r.string().nullish()})),object:r.literal(`chat.completion`),usage:$o,citations:r.array(r.string().url()).nullish()}),ts=r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({delta:r.object({role:r.enum([`assistant`]).optional(),content:r.string().nullish(),reasoning_content:r.string().nullish(),tool_calls:r.array(r.object({id:r.string(),type:r.literal(`function`),function:r.object({name:r.string(),arguments:r.string()})})).nullish()}),finish_reason:r.string().nullish(),index:r.number()})),usage:$o.nullish(),citations:r.array(r.string().url()).nullish()}),ns=`2.0.23`,rs={errorSchema:Yo,errorToMessage:e=>e.error.message};function os(e={}){let t=J(e.baseURL??`https://api.x.ai/v1`),n=()=>I({Authorization:`Bearer ${Gn({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${ns}`),r=r=>new Qo(r,{provider:`xai.chat`,baseURL:t,headers:n,generateId:L,fetch:e.fetch}),i=r=>new Ro(r,{provider:`xai.image`,url:({path:e})=>`${t}${e}`,headers:n,fetch:e.fetch,errorStructure:rs}),a=e=>r(e);return a.languageModel=r,a.chat=r,a.textEmbeddingModel=e=>{throw new j({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=i,a.image=i,a}os();function ss(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function cs(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(`x-blink-stream-response-format`);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new wt).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let n=e=>u({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(Po({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(Po({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(ii({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(Li({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(os({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}const ls=`BLINK_API_URL`;var us=class{baseUrl;client;constructor(e){this.client=Pt(e.baseUrl),this.baseUrl=e.baseUrl}async chat(e,t){let n=await this.client._agent.chat.$post({json:e},{headers:t?.headers,init:{signal:t?.signal}});return n.ok||await this.handleError(n),cs(n)}async capabilities(){let e=await this.client._agent.capabilities.$get();return e.ok||await this.handleError(e),e.json()}async ui(e,t){let n=await this.client._agent.ui.$get({query:e.selectedOptions?{selected_options:JSON.stringify(e.selectedOptions)}:{}},{init:{signal:t?.signal}});if(!n.ok||n.status!==200){if(n.status===404)return;await this.handleError(n)}return n.json()}async health(){let e=await this.client._agent.health.$get();e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed (${e.status}): ${t}`)}throw Error(`Failed (${e.status}): ${e.statusText}`)}};async function ds({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=fs}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),u=l({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of u)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const fs=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(s);return n.length===0||n.some(e=>Ee(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},ps=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function ms(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var hs=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=vt(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=yt(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!ms(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!s(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await ds({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),c=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},l=o.getReader();n.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||n.signal.aborted)break;u||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};export{k as APICallError,ls as APIServerURLEnvironmentVariable,hs as ChatManager,us as Client,we as CustomChatResponseError,wt as EventSourceParserStream,j as NoSuchModelError,Re as checkOptionalParameter,P as combineHeaders,me as completeAssign,ps as convertMessage,ii as createAnthropic,Ce as createCustomAbortControllerSignal,vt as createDiskStore,G as createEventSourceResponseHandler,W as createJsonErrorResponseHandler,K as createJsonResponseHandler,Po as createOpenAI,St as createParser,Ue as decodeURIComponent_,xe as ensureDisposableStackRegisteredForTerminateEvents,h as fakePromise,Wn as getFromApi,pt as getLockInfo,Fe as getPath,Ie as getPathNoStrict,Me as getPattern,Ve as getQueryParam,He as getQueryParams,_e as handleAbortSignalAndPromiseResponse,he as handleErrorFromRequestHandler,m as handleMaybePromise,Pt as hc,ce as isFetchEvent,ae as isNodeRequest,f as isPromise,pe as isRequestInit,oe as isServerResponse,ms as isStoredMessageMetadata,Ee as isToolApprovalOutput,ge as isolateObject,_ as iterateAsync,ss as lastUIOptions,Kn as loadOptionalSetting,dt as lock,Le as mergePath,re as normalizeNodeRequest,Ke as parse,B as postJsonToApi,U as resolve,de as sendNodeResponse,De as splitPath,Oe as splitRoutingPath,Te as tools,Ne as tryDecode,S as unfakePromise,I as withUserAgentSuffix,J as withoutTrailingSlash};