aicommits 2.0.0-develop.11 → 2.0.0-develop.12

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.
@@ -1,92 +1,92 @@
1
- var zm=Object.defineProperty;var i=(e,t)=>zm(e,"name",{value:t,configurable:!0});var gn,Kt,vn,yn,_n,Fn,Cn,bn,En,wn,Tt,An,In,Yt,Xt,xn,kn,$n,Tn,Bn,Sn,On,Rn,Nn,Pn,Mn,jn,zn,qn,Zn,Ln,Un,Vn,Gn,Wn,Hn,Jn,Kn,Yn,Xn,Qn,er,tr,nr,rr,or,ar,sr,ir;import qm from"tty";import Zm from"update-notifier";import{Buffer as Lm}from"node:buffer";import nn from"node:path";import ni,{ChildProcess as Um}from"node:child_process";import ke,{stdin as ri,stdout as oi}from"node:process";import Vm from"child_process";import at from"path";import Ro from"fs";import{fileURLToPath as ai}from"node:url";import Gm,{constants as si}from"node:os";import Wm from"assert";import Hm from"events";import{createWriteStream as Jm,createReadStream as Km}from"node:fs";import Ym from"buffer";import No from"stream";import Xm from"util";import{debuglog as Qm}from"node:util";import*as jr from"node:readline";import ii from"node:readline";import{Writable as ef}from"node:stream";import Ne from"fs/promises";import ui from"os";import tf from"crypto";import{fileURLToPath as nf,pathToFileURL as rf}from"url";var of=Object.defineProperty,$e=i((e,t)=>of(e,"name",{value:t,configurable:!0}),"a");const af="known-flag",sf="unknown-flag",uf="argument",lf=/\B([A-Z])/g,cf=$e(e=>e.replaceAll(lf,"-$1").toLowerCase(),"camelToKebab"),{hasOwnProperty:pf}=Object.prototype,dr=$e((e,t)=>pf.call(e,t),"hasOwn"),Po=$e(e=>typeof e=="function"?[e,!1]:Array.isArray(e)?[e[0],!0]:Po(e.type),"parseFlagType"),li=$e((e,t)=>e===Boolean?t!=="false":t,"normalizeBoolean"),ci=$e((e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),"applyParser"),df=/[\s.:=]/,mf=$e(e=>{const t=`Flag name "${e}"`;if(e.length===0)throw new Error(`${t} cannot be empty`);if(e.length===1)throw new Error(`${t} must be longer than a character`);const n=e.match(df);if(n)throw new Error(`${t} cannot contain "${n?.[0]}"`)},"validateFlagName"),Mo=$e((e,t,n)=>{if(dr(e,t))throw new Error(`Duplicate flags named "${t}"`);e[t]=n},"setFlag"),ff=$e(e=>{const t={};for(const n in e){if(!dr(e,n))continue;mf(n);const r=e[n],a=[[],...Po(r),r];Mo(t,n,a);const s=cf(n);if(n!==s&&Mo(t,s,a),"alias"in r&&typeof r.alias=="string"){const{alias:o}=r,u=`Flag alias "${o}" for flag "${n}"`;if(o.length===0)throw new Error(`${u} cannot be empty`);if(o.length>1)throw new Error(`${u} must be a single character`);Mo(t,o,a)}}return t},"createRegistry"),hf=$e((e,t)=>{const n={};for(const r in e){if(!dr(e,r))continue;const[a,,s,o]=t[r];if(a.length===0&&"default"in o){let{default:u}=o;typeof u=="function"&&(u=u()),n[r]=u}else n[r]=s?a:a.pop()}return n},"finalizeFlags"),zr="--",Df=3,gf=/^-{1,2}\w/,pi=$e(e=>{if(!gf.test(e))return;const t=!e.startsWith(zr);let n=e.slice(t?1:2),r,a=-1;for(const s of["=",":","."]){const o=n.indexOf(s);o!==-1&&(a===-1||o<a)&&(a=o)}return a!==-1&&(r=n.slice(a+1),n=n.slice(0,a)),[n,r,t]},"parseFlagArgv"),di=$e((e,{onFlag:t,onArgument:n})=>{let r;const a=$e((s,o)=>{if(typeof r!="function")return!0;r(s,o),r=void 0},"triggerValueCallback");for(let s=0;s<e.length;s+=1){const o=e[s];if(o===zr){a();const l=e.slice(s+1);n?.(l,[s],!0);break}const u=pi(o);if(u){if(a(),!t)continue;const[l,c,d]=u;if(d)for(let m=0;m<l.length;m+=1){a();const h=m===l.length-1;r=t(l[m],h?c:void 0,[s,m+1,h])}else r=t(l,c,[s])}else a(o,[s])&&n?.([o],[s])}a()},"argvIterator"),mi=$e((e,t)=>{for(let n=t.length-1;n>=0;n-=1){const[r,a,s]=t[n];if(a){const o=e[r];let u=o.slice(0,a);if(s||(u+=o.slice(a+1)),u!=="-"){e[r]=u;continue}}e.splice(r,1)}},"spliceFromArgv"),vf=$e((e,t=process.argv.slice(2),{ignore:n}={})=>{const r=[],a=ff(e),s={},o=[];return o[zr]=[],di(t,{onFlag(u,l,c){const d=(c.length===Df||u.length>1)&&dr(a,u);if(!n?.(d?af:sf,u,l)){if(d){const[m,h]=a[u],D=li(h,l),f=$e((v,y)=>{r.push(c),y&&r.push(y),m.push(ci(h,v||""))},"getFollowingValue");return D===void 0?f:f(D)}dr(s,u)||(s[u]=[]),s[u].push(l===void 0?!0:l),r.push(c)}},onArgument:$e((u,l,c)=>{n?.(uf,t[l[0]])||(o.push(...u),c?(o[zr]=u,t.splice(l[0])):r.push(l))},"onArgument")}),mi(t,r),{flags:hf(e,a),unknownFlags:s,_:o}},"typeFlag");$e((e,t,n=process.argv.slice(2))=>{const r=new Set(e.split(",").map(l=>pi(l)?.[0])),[a,s]=Po(t),o=[],u=[];return di(n,{onFlag:$e((l,c,d)=>{if(!r.has(l)||!s&&o.length>0)return;const m=li(a,c),h=$e((D,f)=>{u.push(d),f&&u.push(f),o.push(ci(a,D||""))},"getFollowingValue");return m===void 0?h:h(m)},"onFlag")}),mi(n,u),s?o:o[0]},"getFlag");var yf=Object.defineProperty,te=i((e,t)=>yf(e,"name",{value:t,configurable:!0}),"n");const _f=te(e=>{const t=process.stdout.columns??Number.POSITIVE_INFINITY;return typeof e=="function"&&(e=e(t)),e||(e={}),Array.isArray(e)?{columns:e,stdoutColumns:t}:{columns:e.columns??[],stdoutColumns:e.stdoutColumns??t}},"getOptions");function fi({onlyFirst:e=!1}={}){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}i(fi,"j$1"),te(fi,"ansiRegex");const Ff=fi();function jo(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Ff,"")}i(jo,"w$2"),te(jo,"stripAnsi");function hi(e){return e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109}i(hi,"P$2"),te(hi,"isAmbiguous");function Di(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}i(Di,"z$2"),te(Di,"isFullWidth");function gi(e){return e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9776&&e<=9783||e>=9800&&e<=9811||e===9855||e>=9866&&e<=9871||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101631&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e>=119552&&e<=119638||e>=119648&&e<=119670||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129673||e>=129679&&e<=129734||e>=129742&&e<=129756||e>=129759&&e<=129769||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141}i(gi,"G$3"),te(gi,"isWide");function vi(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}i(vi,"Z$1"),te(vi,"validate");function yi(e,{ambiguousAsWide:t=!1}={}){return vi(e),Di(e)||gi(e)||t&&hi(e)?2:1}i(yi,"V$3"),te(yi,"eastAsianWidth");var Cf=te(()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g,"emojiRegex");const bf=new Intl.Segmenter,Ef=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Et(e,t={}){if(typeof e!="string"||e.length===0)return 0;const{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=jo(e)),e.length===0)return 0;let a=0;const s={ambiguousAsWide:!n};for(const{segment:o}of bf.segment(e)){const u=o.codePointAt(0);if(!(u<=31||u>=127&&u<=159)&&!(u>=8203&&u<=8207||u===65279)&&!(u>=768&&u<=879||u>=6832&&u<=6911||u>=7616&&u<=7679||u>=8400&&u<=8447||u>=65056&&u<=65071)&&!(u>=55296&&u<=57343)&&!(u>=65024&&u<=65039)&&!Ef.test(o)){if(Cf().test(o)){a+=2;continue}a+=yi(u,s)}}return a}i(Et,"d$2"),te(Et,"stringWidth");const _i=te(e=>Math.max(...e.split(`
2
- `).map(t=>Et(t))),"getLongestLineWidth"),wf=te(e=>{const t=[];for(const n of e){const{length:r}=n,a=r-t.length;for(let s=0;s<a;s+=1)t.push(0);for(let s=0;s<r;s+=1){const o=_i(n[s]);o>t[s]&&(t[s]=o)}}return t},"getColumnContentWidths"),Fi=/^\d+%$/,Ci={width:"auto",align:"left",contentWidth:0,paddingLeft:0,paddingRight:0,paddingTop:0,paddingBottom:0,horizontalPadding:0,paddingLeftString:"",paddingRightString:""},Af=te((e,t)=>{const n=[];for(let r=0;r<e.length;r+=1){const a=t[r]??"auto";if(typeof a=="number"||a==="auto"||a==="content-width"||typeof a=="string"&&Fi.test(a)){n.push({...Ci,width:a,contentWidth:e[r]});continue}if(a&&typeof a=="object"){const s={...Ci,...a,contentWidth:e[r]};s.horizontalPadding=s.paddingLeft+s.paddingRight,n.push(s);continue}throw new Error(`Invalid column width: ${JSON.stringify(a)}`)}return n},"initColumns"),If=te((e,t)=>{for(const n of e){const{width:r}=n;if(r==="content-width"&&(n.width=n.contentWidth),r==="auto"){const l=Math.min(20,n.contentWidth);n.width=l,n.autoOverflow=n.contentWidth-l}if(typeof r=="string"&&Fi.test(r)){const l=Number.parseFloat(r.slice(0,-1))/100;n.width=Math.floor(t*l)-(n.paddingLeft+n.paddingRight)}const{horizontalPadding:a}=n,s=1,o=s+a;if(o>=t){const l=o-t,c=Math.ceil(n.paddingLeft/a*l),d=l-c;n.paddingLeft-=c,n.paddingRight-=d,n.horizontalPadding=n.paddingLeft+n.paddingRight}n.paddingLeftString=n.paddingLeft?" ".repeat(n.paddingLeft):"",n.paddingRightString=n.paddingRight?" ".repeat(n.paddingRight):"";const u=t-n.horizontalPadding;n.width=Math.max(Math.min(n.width,u),s)}},"resolveColumnWidths"),bi=te(()=>Object.assign([],{columns:0}),"makeRow"),xf=te((e,t)=>{const n=[bi()];let[r]=n;for(const a of e){const s=a.width+a.horizontalPadding;r.columns+s>t&&(r=bi(),n.push(r)),r.push(a),r.columns+=s}for(const a of n){const s=a.reduce((h,D)=>h+D.width+D.horizontalPadding,0);let o=t-s;if(o===0)continue;const u=a.filter(h=>"autoOverflow"in h),l=u.filter(h=>h.autoOverflow>0),c=l.reduce((h,D)=>h+D.autoOverflow,0),d=Math.min(c,o);for(const h of l){const D=Math.floor(h.autoOverflow/c*d);h.width+=D,o-=D}const m=Math.floor(o/u.length);for(let h=0;h<u.length;h+=1){const D=u[h];h===u.length-1?D.width+=o:D.width+=m,o-=m}}return n},"balanceAuto"),kf=te((e,t,n)=>{const r=Af(n,t);return If(r,e),xf(r,e)},"computeColumnWidths"),zo=10,Ei=te((e=0)=>t=>`\x1B[${t+e}m`,"wrapAnsi16"),wi=te((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"wrapAnsi256"),Ai=te((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"wrapAnsi16m"),_e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(_e.modifier);const $f=Object.keys(_e.color),Tf=Object.keys(_e.bgColor);[...$f,...Tf];function Ii(){const e=new Map;for(const[t,n]of Object.entries(_e)){for(const[r,a]of Object.entries(n))_e[r]={open:`\x1B[${a[0]}m`,close:`\x1B[${a[1]}m`},n[r]=_e[r],e.set(a[0],a[1]);Object.defineProperty(_e,t,{value:n,enumerable:!1})}return Object.defineProperty(_e,"codes",{value:e,enumerable:!1}),_e.color.close="\x1B[39m",_e.bgColor.close="\x1B[49m",_e.color.ansi=Ei(),_e.color.ansi256=wi(),_e.color.ansi16m=Ai(),_e.bgColor.ansi=Ei(zo),_e.bgColor.ansi256=wi(zo),_e.bgColor.ansi16m=Ai(zo),Object.defineProperties(_e,{rgbToAnsi256:{value:te((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:te(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,a&255]},"value"),enumerable:!1},hexToAnsi256:{value:te(t=>_e.rgbToAnsi256(..._e.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:te(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,a;if(t>=232)n=((t-232)*10+8)/255,r=n,a=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,a=u%6/5}const s=Math.max(n,r,a)*2;if(s===0)return 30;let o=30+(Math.round(a)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(o+=60),o},"value"),enumerable:!1},rgbToAnsi:{value:te((t,n,r)=>_e.ansi256ToAnsi(_e.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:te(t=>_e.ansi256ToAnsi(_e.hexToAnsi256(t)),"value"),enumerable:!1}}),_e}i(Ii,"FD$1"),te(Ii,"assembleStyles");const Bf=Ii(),qr=new Set(["\x1B","\x9B"]),Sf=39,qo="\x07",xi="[",Of="]",ki="m",Zr=`${Of}8;;`,$i=te(e=>`${qr.values().next().value}${xi}${e}${ki}`,"wrapAnsiCode"),Ti=te(e=>`${qr.values().next().value}${Zr}${e}${qo}`,"wrapAnsiHyperlink"),Rf=te(e=>e.split(" ").map(t=>Et(t)),"wordLengths"),Zo=te((e,t,n)=>{const r=[...t];let a=!1,s=!1,o=Et(jo(e.at(-1)));for(const[u,l]of r.entries()){const c=Et(l);if(o+c<=n?e[e.length-1]+=l:(e.push(l),o=0),qr.has(l)&&(a=!0,s=r.slice(u+1,u+1+Zr.length).join("")===Zr),a){s?l===qo&&(a=!1,s=!1):l===ki&&(a=!1);continue}o+=c,o===n&&u<r.length-1&&(e.push(""),o=0)}!o&&e.at(-1).length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"wrapWord"),Nf=te(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(Et(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"stringVisibleTrimSpacesRight"),Pf=te((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",a,s;const o=Rf(e);let u=[""];for(const[m,h]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u.at(-1).trimStart());let D=Et(u.at(-1));if(m!==0&&(D>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),D=0),(D>0||n.trim===!1)&&(u[u.length-1]+=" ",D++)),n.hard&&o[m]>t){const f=t-D,v=1+Math.floor((o[m]-f-1)/t);Math.floor((o[m]-1)/t)<v&&u.push(""),Zo(u,h,t);continue}if(D+o[m]>t&&D>0&&o[m]>0){if(n.wordWrap===!1&&D<t){Zo(u,h,t);continue}u.push("")}if(D+o[m]>t&&n.wordWrap===!1){Zo(u,h,t);continue}u[u.length-1]+=h}n.trim!==!1&&(u=u.map(m=>Nf(m)));const l=u.join(`
3
- `),c=[...l];let d=0;for(const[m,h]of c.entries()){if(r+=h,qr.has(h)){const{groups:f}=new RegExp(`(?:\\${xi}(?<code>\\d+)m|\\${Zr}(?<uri>.*)${qo})`).exec(l.slice(d))||{groups:{}};if(f.code!==void 0){const v=Number.parseFloat(f.code);a=v===Sf?void 0:v}else f.uri!==void 0&&(s=f.uri.length===0?void 0:f.uri)}const D=Bf.codes.get(Number(a));c[m+1]===`
4
- `?(s&&(r+=Ti("")),a&&D&&(r+=$i(D))):h===`
5
- `&&(a&&D&&(r+=$i(a)),s&&(r+=Ti(s))),d+=h.length}return r},"exec");function Bi(e,t,n){return String(e).normalize().replaceAll(`\r
1
+ var Zm=Object.defineProperty;var i=(e,t)=>Zm(e,"name",{value:t,configurable:!0});var gn,Kt,vn,yn,_n,Fn,Cn,bn,En,wn,Tt,An,In,Yt,Xt,xn,kn,$n,Tn,Bn,Sn,On,Rn,Nn,Pn,Mn,jn,zn,qn,Zn,Un,Ln,Vn,Gn,Wn,Hn,Jn,Kn,Yn,Xn,Qn,er,tr,nr,rr,or,ar,sr,ir;import Um from"tty";import ni from"update-notifier";import{Buffer as Lm}from"node:buffer";import nn from"node:path";import ri,{ChildProcess as Vm}from"node:child_process";import ke,{stdin as oi,stdout as ai}from"node:process";import Gm,{exec as si}from"child_process";import at from"path";import No from"fs";import{fileURLToPath as ii}from"node:url";import Wm,{constants as ui}from"node:os";import Hm from"assert";import Jm from"events";import{createWriteStream as Km,createReadStream as Ym}from"node:fs";import Xm from"buffer";import Po from"stream";import Qm,{promisify as ef}from"util";import{debuglog as tf}from"node:util";import*as zr from"node:readline";import li from"node:readline";import{Writable as nf}from"node:stream";import Ne from"fs/promises";import ci from"os";import rf from"crypto";import{fileURLToPath as of,pathToFileURL as af}from"url";var sf=Object.defineProperty,$e=i((e,t)=>sf(e,"name",{value:t,configurable:!0}),"a");const uf="known-flag",lf="unknown-flag",cf="argument",pf=/\B([A-Z])/g,df=$e(e=>e.replaceAll(pf,"-$1").toLowerCase(),"camelToKebab"),{hasOwnProperty:mf}=Object.prototype,dr=$e((e,t)=>mf.call(e,t),"hasOwn"),Mo=$e(e=>typeof e=="function"?[e,!1]:Array.isArray(e)?[e[0],!0]:Mo(e.type),"parseFlagType"),pi=$e((e,t)=>e===Boolean?t!=="false":t,"normalizeBoolean"),di=$e((e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),"applyParser"),ff=/[\s.:=]/,hf=$e(e=>{const t=`Flag name "${e}"`;if(e.length===0)throw new Error(`${t} cannot be empty`);if(e.length===1)throw new Error(`${t} must be longer than a character`);const n=e.match(ff);if(n)throw new Error(`${t} cannot contain "${n?.[0]}"`)},"validateFlagName"),jo=$e((e,t,n)=>{if(dr(e,t))throw new Error(`Duplicate flags named "${t}"`);e[t]=n},"setFlag"),Df=$e(e=>{const t={};for(const n in e){if(!dr(e,n))continue;hf(n);const r=e[n],a=[[],...Mo(r),r];jo(t,n,a);const s=df(n);if(n!==s&&jo(t,s,a),"alias"in r&&typeof r.alias=="string"){const{alias:o}=r,u=`Flag alias "${o}" for flag "${n}"`;if(o.length===0)throw new Error(`${u} cannot be empty`);if(o.length>1)throw new Error(`${u} must be a single character`);jo(t,o,a)}}return t},"createRegistry"),gf=$e((e,t)=>{const n={};for(const r in e){if(!dr(e,r))continue;const[a,,s,o]=t[r];if(a.length===0&&"default"in o){let{default:u}=o;typeof u=="function"&&(u=u()),n[r]=u}else n[r]=s?a:a.pop()}return n},"finalizeFlags"),qr="--",vf=3,yf=/^-{1,2}\w/,mi=$e(e=>{if(!yf.test(e))return;const t=!e.startsWith(qr);let n=e.slice(t?1:2),r,a=-1;for(const s of["=",":","."]){const o=n.indexOf(s);o!==-1&&(a===-1||o<a)&&(a=o)}return a!==-1&&(r=n.slice(a+1),n=n.slice(0,a)),[n,r,t]},"parseFlagArgv"),fi=$e((e,{onFlag:t,onArgument:n})=>{let r;const a=$e((s,o)=>{if(typeof r!="function")return!0;r(s,o),r=void 0},"triggerValueCallback");for(let s=0;s<e.length;s+=1){const o=e[s];if(o===qr){a();const l=e.slice(s+1);n?.(l,[s],!0);break}const u=mi(o);if(u){if(a(),!t)continue;const[l,c,d]=u;if(d)for(let m=0;m<l.length;m+=1){a();const h=m===l.length-1;r=t(l[m],h?c:void 0,[s,m+1,h])}else r=t(l,c,[s])}else a(o,[s])&&n?.([o],[s])}a()},"argvIterator"),hi=$e((e,t)=>{for(let n=t.length-1;n>=0;n-=1){const[r,a,s]=t[n];if(a){const o=e[r];let u=o.slice(0,a);if(s||(u+=o.slice(a+1)),u!=="-"){e[r]=u;continue}}e.splice(r,1)}},"spliceFromArgv"),_f=$e((e,t=process.argv.slice(2),{ignore:n}={})=>{const r=[],a=Df(e),s={},o=[];return o[qr]=[],fi(t,{onFlag(u,l,c){const d=(c.length===vf||u.length>1)&&dr(a,u);if(!n?.(d?uf:lf,u,l)){if(d){const[m,h]=a[u],D=pi(h,l),f=$e((v,y)=>{r.push(c),y&&r.push(y),m.push(di(h,v||""))},"getFollowingValue");return D===void 0?f:f(D)}dr(s,u)||(s[u]=[]),s[u].push(l===void 0?!0:l),r.push(c)}},onArgument:$e((u,l,c)=>{n?.(cf,t[l[0]])||(o.push(...u),c?(o[qr]=u,t.splice(l[0])):r.push(l))},"onArgument")}),hi(t,r),{flags:gf(e,a),unknownFlags:s,_:o}},"typeFlag");$e((e,t,n=process.argv.slice(2))=>{const r=new Set(e.split(",").map(l=>mi(l)?.[0])),[a,s]=Mo(t),o=[],u=[];return fi(n,{onFlag:$e((l,c,d)=>{if(!r.has(l)||!s&&o.length>0)return;const m=pi(a,c),h=$e((D,f)=>{u.push(d),f&&u.push(f),o.push(di(a,D||""))},"getFollowingValue");return m===void 0?h:h(m)},"onFlag")}),hi(n,u),s?o:o[0]},"getFlag");var Ff=Object.defineProperty,te=i((e,t)=>Ff(e,"name",{value:t,configurable:!0}),"n");const Cf=te(e=>{const t=process.stdout.columns??Number.POSITIVE_INFINITY;return typeof e=="function"&&(e=e(t)),e||(e={}),Array.isArray(e)?{columns:e,stdoutColumns:t}:{columns:e.columns??[],stdoutColumns:e.stdoutColumns??t}},"getOptions");function Di({onlyFirst:e=!1}={}){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}i(Di,"j$1"),te(Di,"ansiRegex");const bf=Di();function zo(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(bf,"")}i(zo,"w$2"),te(zo,"stripAnsi");function gi(e){return e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109}i(gi,"P$2"),te(gi,"isAmbiguous");function vi(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}i(vi,"z$2"),te(vi,"isFullWidth");function yi(e){return e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9776&&e<=9783||e>=9800&&e<=9811||e===9855||e>=9866&&e<=9871||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101631&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e>=119552&&e<=119638||e>=119648&&e<=119670||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129673||e>=129679&&e<=129734||e>=129742&&e<=129756||e>=129759&&e<=129769||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141}i(yi,"G$3"),te(yi,"isWide");function _i(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}i(_i,"Z$1"),te(_i,"validate");function Fi(e,{ambiguousAsWide:t=!1}={}){return _i(e),vi(e)||yi(e)||t&&gi(e)?2:1}i(Fi,"V$3"),te(Fi,"eastAsianWidth");var Ef=te(()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g,"emojiRegex");const wf=new Intl.Segmenter,Af=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Et(e,t={}){if(typeof e!="string"||e.length===0)return 0;const{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=zo(e)),e.length===0)return 0;let a=0;const s={ambiguousAsWide:!n};for(const{segment:o}of wf.segment(e)){const u=o.codePointAt(0);if(!(u<=31||u>=127&&u<=159)&&!(u>=8203&&u<=8207||u===65279)&&!(u>=768&&u<=879||u>=6832&&u<=6911||u>=7616&&u<=7679||u>=8400&&u<=8447||u>=65056&&u<=65071)&&!(u>=55296&&u<=57343)&&!(u>=65024&&u<=65039)&&!Af.test(o)){if(Ef().test(o)){a+=2;continue}a+=Fi(u,s)}}return a}i(Et,"d$2"),te(Et,"stringWidth");const Ci=te(e=>Math.max(...e.split(`
2
+ `).map(t=>Et(t))),"getLongestLineWidth"),If=te(e=>{const t=[];for(const n of e){const{length:r}=n,a=r-t.length;for(let s=0;s<a;s+=1)t.push(0);for(let s=0;s<r;s+=1){const o=Ci(n[s]);o>t[s]&&(t[s]=o)}}return t},"getColumnContentWidths"),bi=/^\d+%$/,Ei={width:"auto",align:"left",contentWidth:0,paddingLeft:0,paddingRight:0,paddingTop:0,paddingBottom:0,horizontalPadding:0,paddingLeftString:"",paddingRightString:""},xf=te((e,t)=>{const n=[];for(let r=0;r<e.length;r+=1){const a=t[r]??"auto";if(typeof a=="number"||a==="auto"||a==="content-width"||typeof a=="string"&&bi.test(a)){n.push({...Ei,width:a,contentWidth:e[r]});continue}if(a&&typeof a=="object"){const s={...Ei,...a,contentWidth:e[r]};s.horizontalPadding=s.paddingLeft+s.paddingRight,n.push(s);continue}throw new Error(`Invalid column width: ${JSON.stringify(a)}`)}return n},"initColumns"),kf=te((e,t)=>{for(const n of e){const{width:r}=n;if(r==="content-width"&&(n.width=n.contentWidth),r==="auto"){const l=Math.min(20,n.contentWidth);n.width=l,n.autoOverflow=n.contentWidth-l}if(typeof r=="string"&&bi.test(r)){const l=Number.parseFloat(r.slice(0,-1))/100;n.width=Math.floor(t*l)-(n.paddingLeft+n.paddingRight)}const{horizontalPadding:a}=n,s=1,o=s+a;if(o>=t){const l=o-t,c=Math.ceil(n.paddingLeft/a*l),d=l-c;n.paddingLeft-=c,n.paddingRight-=d,n.horizontalPadding=n.paddingLeft+n.paddingRight}n.paddingLeftString=n.paddingLeft?" ".repeat(n.paddingLeft):"",n.paddingRightString=n.paddingRight?" ".repeat(n.paddingRight):"";const u=t-n.horizontalPadding;n.width=Math.max(Math.min(n.width,u),s)}},"resolveColumnWidths"),wi=te(()=>Object.assign([],{columns:0}),"makeRow"),$f=te((e,t)=>{const n=[wi()];let[r]=n;for(const a of e){const s=a.width+a.horizontalPadding;r.columns+s>t&&(r=wi(),n.push(r)),r.push(a),r.columns+=s}for(const a of n){const s=a.reduce((h,D)=>h+D.width+D.horizontalPadding,0);let o=t-s;if(o===0)continue;const u=a.filter(h=>"autoOverflow"in h),l=u.filter(h=>h.autoOverflow>0),c=l.reduce((h,D)=>h+D.autoOverflow,0),d=Math.min(c,o);for(const h of l){const D=Math.floor(h.autoOverflow/c*d);h.width+=D,o-=D}const m=Math.floor(o/u.length);for(let h=0;h<u.length;h+=1){const D=u[h];h===u.length-1?D.width+=o:D.width+=m,o-=m}}return n},"balanceAuto"),Tf=te((e,t,n)=>{const r=xf(n,t);return kf(r,e),$f(r,e)},"computeColumnWidths"),qo=10,Ai=te((e=0)=>t=>`\x1B[${t+e}m`,"wrapAnsi16"),Ii=te((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"wrapAnsi256"),xi=te((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"wrapAnsi16m"),_e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(_e.modifier);const Bf=Object.keys(_e.color),Sf=Object.keys(_e.bgColor);[...Bf,...Sf];function ki(){const e=new Map;for(const[t,n]of Object.entries(_e)){for(const[r,a]of Object.entries(n))_e[r]={open:`\x1B[${a[0]}m`,close:`\x1B[${a[1]}m`},n[r]=_e[r],e.set(a[0],a[1]);Object.defineProperty(_e,t,{value:n,enumerable:!1})}return Object.defineProperty(_e,"codes",{value:e,enumerable:!1}),_e.color.close="\x1B[39m",_e.bgColor.close="\x1B[49m",_e.color.ansi=Ai(),_e.color.ansi256=Ii(),_e.color.ansi16m=xi(),_e.bgColor.ansi=Ai(qo),_e.bgColor.ansi256=Ii(qo),_e.bgColor.ansi16m=xi(qo),Object.defineProperties(_e,{rgbToAnsi256:{value:te((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:te(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,a&255]},"value"),enumerable:!1},hexToAnsi256:{value:te(t=>_e.rgbToAnsi256(..._e.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:te(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,a;if(t>=232)n=((t-232)*10+8)/255,r=n,a=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,a=u%6/5}const s=Math.max(n,r,a)*2;if(s===0)return 30;let o=30+(Math.round(a)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(o+=60),o},"value"),enumerable:!1},rgbToAnsi:{value:te((t,n,r)=>_e.ansi256ToAnsi(_e.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:te(t=>_e.ansi256ToAnsi(_e.hexToAnsi256(t)),"value"),enumerable:!1}}),_e}i(ki,"FD$1"),te(ki,"assembleStyles");const Of=ki(),Zr=new Set(["\x1B","\x9B"]),Rf=39,Zo="\x07",$i="[",Nf="]",Ti="m",Ur=`${Nf}8;;`,Bi=te(e=>`${Zr.values().next().value}${$i}${e}${Ti}`,"wrapAnsiCode"),Si=te(e=>`${Zr.values().next().value}${Ur}${e}${Zo}`,"wrapAnsiHyperlink"),Pf=te(e=>e.split(" ").map(t=>Et(t)),"wordLengths"),Uo=te((e,t,n)=>{const r=[...t];let a=!1,s=!1,o=Et(zo(e.at(-1)));for(const[u,l]of r.entries()){const c=Et(l);if(o+c<=n?e[e.length-1]+=l:(e.push(l),o=0),Zr.has(l)&&(a=!0,s=r.slice(u+1,u+1+Ur.length).join("")===Ur),a){s?l===Zo&&(a=!1,s=!1):l===Ti&&(a=!1);continue}o+=c,o===n&&u<r.length-1&&(e.push(""),o=0)}!o&&e.at(-1).length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"wrapWord"),Mf=te(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(Et(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"stringVisibleTrimSpacesRight"),jf=te((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",a,s;const o=Pf(e);let u=[""];for(const[m,h]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u.at(-1).trimStart());let D=Et(u.at(-1));if(m!==0&&(D>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),D=0),(D>0||n.trim===!1)&&(u[u.length-1]+=" ",D++)),n.hard&&o[m]>t){const f=t-D,v=1+Math.floor((o[m]-f-1)/t);Math.floor((o[m]-1)/t)<v&&u.push(""),Uo(u,h,t);continue}if(D+o[m]>t&&D>0&&o[m]>0){if(n.wordWrap===!1&&D<t){Uo(u,h,t);continue}u.push("")}if(D+o[m]>t&&n.wordWrap===!1){Uo(u,h,t);continue}u[u.length-1]+=h}n.trim!==!1&&(u=u.map(m=>Mf(m)));const l=u.join(`
3
+ `),c=[...l];let d=0;for(const[m,h]of c.entries()){if(r+=h,Zr.has(h)){const{groups:f}=new RegExp(`(?:\\${$i}(?<code>\\d+)m|\\${Ur}(?<uri>.*)${Zo})`).exec(l.slice(d))||{groups:{}};if(f.code!==void 0){const v=Number.parseFloat(f.code);a=v===Rf?void 0:v}else f.uri!==void 0&&(s=f.uri.length===0?void 0:f.uri)}const D=Of.codes.get(Number(a));c[m+1]===`
4
+ `?(s&&(r+=Si("")),a&&D&&(r+=Bi(D))):h===`
5
+ `&&(a&&D&&(r+=Bi(a)),s&&(r+=Si(s))),d+=h.length}return r},"exec");function Oi(e,t,n){return String(e).normalize().replaceAll(`\r
6
6
  `,`
7
7
  `).split(`
8
- `).map(r=>Pf(r,t,n)).join(`
9
- `)}i(Bi,"BD$1"),te(Bi,"wrapAnsi");const Si=te(e=>Array.from({length:e}).fill(""),"emptyLines"),Mf=te((e,t)=>{const n=[];let r=0;for(const a of e){let s=0;const o=a.map(l=>{let c=t[r]??"";r+=1,l.preprocess&&(c=l.preprocess(c)),_i(c)>l.width&&(c=Bi(c,l.width,{hard:!0}));let d=c.split(`
10
- `);if(l.postprocess){const{postprocess:m}=l;d=d.map((h,D)=>m.call(l,h,D))}return l.paddingTop&&d.unshift(...Si(l.paddingTop)),l.paddingBottom&&d.push(...Si(l.paddingBottom)),d.length>s&&(s=d.length),{...l,lines:d}}),u=[];for(let l=0;l<s;l+=1){const c=o.map(d=>{const m=d.lines[l]??"",h=Number.isFinite(d.width)?" ".repeat(d.width-Et(m)):"";let D=d.paddingLeftString;return d.align==="right"&&(D+=h),D+=m,d.align==="left"&&(D+=h),D+d.paddingRightString}).join("");u.push(c)}n.push(u.join(`
8
+ `).map(r=>jf(r,t,n)).join(`
9
+ `)}i(Oi,"BD$1"),te(Oi,"wrapAnsi");const Ri=te(e=>Array.from({length:e}).fill(""),"emptyLines"),zf=te((e,t)=>{const n=[];let r=0;for(const a of e){let s=0;const o=a.map(l=>{let c=t[r]??"";r+=1,l.preprocess&&(c=l.preprocess(c)),Ci(c)>l.width&&(c=Oi(c,l.width,{hard:!0}));let d=c.split(`
10
+ `);if(l.postprocess){const{postprocess:m}=l;d=d.map((h,D)=>m.call(l,h,D))}return l.paddingTop&&d.unshift(...Ri(l.paddingTop)),l.paddingBottom&&d.push(...Ri(l.paddingBottom)),d.length>s&&(s=d.length),{...l,lines:d}}),u=[];for(let l=0;l<s;l+=1){const c=o.map(d=>{const m=d.lines[l]??"",h=Number.isFinite(d.width)?" ".repeat(d.width-Et(m)):"";let D=d.paddingLeftString;return d.align==="right"&&(D+=h),D+=m,d.align==="left"&&(D+=h),D+d.paddingRightString}).join("");u.push(c)}n.push(u.join(`
11
11
  `))}return n.join(`
12
- `)},"renderRow"),jf=te((e,t)=>{if(!e||e.length===0)return"";const n=wf(e),r=n.length;if(r===0)return"";const{stdoutColumns:a,columns:s}=_f(t);if(s.length>r)throw new Error(`${s.length} columns defined, but only ${r} columns found`);const o=kf(a,s,n);return e.map(u=>Mf(o,u)).join(`
13
- `)},"terminalColumns"),zf=["<",">","=",">=","<="],qf=te(e=>{if(!zf.includes(e))throw new TypeError(`Invalid breakpoint operator: ${e}`)},"assertOperator"),Zf=te(e=>{const t=Object.keys(e).map(n=>{const[r,a]=n.split(" ");qf(r);const s=Number.parseInt(a,10);if(Number.isNaN(s))throw new TypeError(`Invalid breakpoint value: ${a}`);const o=e[n];return{operator:r,breakpoint:s,value:o}}).sort((n,r)=>r.breakpoint-n.breakpoint);return n=>t.find(({operator:r,breakpoint:a})=>r==="="&&n===a||r===">"&&n>a||r==="<"&&n<a||r===">="&&n>=a||r==="<="&&n<=a)?.value},"breakpoints");var Lf=Object.defineProperty,ge=i((e,t)=>Lf(e,"name",{value:t,configurable:!0}),"s");const Uf=ge(e=>e.replaceAll(/[\W_]([a-z\d])?/gi,(t,n)=>n?n.toUpperCase():""),"camelCase"),Vf=ge(e=>e.replaceAll(/\B([A-Z])/g,"-$1").toLowerCase(),"kebabCase"),Gf={"> 80":[{width:"content-width",paddingLeft:2,paddingRight:8},{width:"auto"}],"> 40":[{width:"auto",paddingLeft:2,paddingRight:8,preprocess:ge(e=>e.trim(),"preprocess")},{width:"100%",paddingLeft:2,paddingBottom:1}],"> 0":{stdoutColumns:1e3,columns:[{width:"content-width",paddingLeft:2,paddingRight:8},{width:"content-width"}]}};function Oi(e){let t=!1;return{type:"table",data:{tableData:Object.keys(e).sort((n,r)=>n.localeCompare(r)).map(n=>{const r=e[n],a="alias"in r;return a&&(t=!0),{name:n,flag:r,flagFormatted:`--${Vf(n)}`,aliasesEnabled:t,aliasFormatted:a?`-${r.alias}`:void 0}}).map(n=>(n.aliasesEnabled=t,[{type:"flagName",data:n},{type:"flagDescription",data:n}])),tableBreakpoints:Gf}}}i(Oi,"T"),ge(Oi,"renderFlags");const Ri=ge(e=>!e||(e.version??(e.help?e.help.version:void 0)),"getVersion"),Ni=ge(e=>{const t="parent"in e&&e.parent?.name;return(t?`${t} `:"")+e.name},"getName");function Pi(e){const t=[];e.name&&t.push(Ni(e));const n=Ri(e)??("parent"in e&&Ri(e.parent));if(n&&t.push(`v${n}`),t.length!==0)return{id:"name",type:"text",data:`${t.join(" ")}
14
- `}}i(Pi,"k$2"),ge(Pi,"getNameAndVersion");function Mi(e){const{help:t}=e;if(!(!t||!t.description))return{id:"description",type:"text",data:`${t.description}
15
- `}}i(Mi,"_$1"),ge(Mi,"getDescription");function ji(e){const t=e.help||{};if("usage"in t)return t.usage?{id:"usage",type:"section",data:{title:"Usage:",body:Array.isArray(t.usage)?t.usage.join(`
16
- `):t.usage}}:void 0;if(e.name){const n=[],r=[Ni(e)];if(e.flags&&Object.keys(e.flags).length>0&&r.push("[flags...]"),e.parameters&&e.parameters.length>0){const{parameters:a}=e,s=a.indexOf("--"),o=s!==-1&&a.slice(s+1).some(u=>u.startsWith("<"));r.push(a.map(u=>u!=="--"?u:o?"--":"[--]").join(" "))}if(r.length>1&&n.push(r.join(" ")),"commands"in e&&e.commands?.length&&n.push(`${e.name} <command>`),n.length>0)return{id:"usage",type:"section",data:{title:"Usage:",body:n.join(`
17
- `)}}}}i(ji,"F"),ge(ji,"getUsage");function zi(e){return!("commands"in e)||!e.commands?.length?void 0:{id:"commands",type:"section",data:{title:"Commands:",body:{type:"table",data:{tableData:e.commands.map(t=>[t.options.name,t.options.help?t.options.help.description:""]),tableOptions:[{width:"content-width",paddingLeft:2,paddingRight:8}]}},indentBody:0}}}i(zi,"H"),ge(zi,"getCommands");function qi(e){if(!(!e.flags||Object.keys(e.flags).length===0))return{id:"flags",type:"section",data:{title:"Flags:",body:Oi(e.flags),indentBody:0}}}i(qi,"U$1"),ge(qi,"getFlags");function Zi(e){const{help:t}=e;if(!t||!t.examples||t.examples.length===0)return;let{examples:n}=t;if(Array.isArray(n)&&(n=n.join(`
18
- `)),n)return{id:"examples",type:"section",data:{title:"Examples:",body:n}}}i(Zi,"V$2"),ge(Zi,"getExamples");function Li(e){if(!("alias"in e)||!e.alias)return;const{alias:t}=e;return{id:"aliases",type:"section",data:{title:"Aliases:",body:Array.isArray(t)?t.join(", "):t}}}i(Li,"J$1"),ge(Li,"getAliases");const Wf=ge(e=>[Pi,Mi,ji,zi,qi,Zi,Li].map(t=>t(e)).filter(Boolean),"generateHelp"),Hf=qm.WriteStream.prototype.hasColors(),Ui=(gn=class{text(t){return t}bold(t){return Hf?`\x1B[1m${t}\x1B[22m`:t.toLocaleUpperCase()}indentText({text:t,spaces:n}){return t.replaceAll(/^/gm," ".repeat(n))}heading(t){return this.bold(t)}section({title:t,body:n,indentBody:r=2}){return`${(t?`${this.heading(t)}
12
+ `)},"renderRow"),qf=te((e,t)=>{if(!e||e.length===0)return"";const n=If(e),r=n.length;if(r===0)return"";const{stdoutColumns:a,columns:s}=Cf(t);if(s.length>r)throw new Error(`${s.length} columns defined, but only ${r} columns found`);const o=Tf(a,s,n);return e.map(u=>zf(o,u)).join(`
13
+ `)},"terminalColumns"),Zf=["<",">","=",">=","<="],Uf=te(e=>{if(!Zf.includes(e))throw new TypeError(`Invalid breakpoint operator: ${e}`)},"assertOperator"),Lf=te(e=>{const t=Object.keys(e).map(n=>{const[r,a]=n.split(" ");Uf(r);const s=Number.parseInt(a,10);if(Number.isNaN(s))throw new TypeError(`Invalid breakpoint value: ${a}`);const o=e[n];return{operator:r,breakpoint:s,value:o}}).sort((n,r)=>r.breakpoint-n.breakpoint);return n=>t.find(({operator:r,breakpoint:a})=>r==="="&&n===a||r===">"&&n>a||r==="<"&&n<a||r===">="&&n>=a||r==="<="&&n<=a)?.value},"breakpoints");var Vf=Object.defineProperty,ge=i((e,t)=>Vf(e,"name",{value:t,configurable:!0}),"s");const Gf=ge(e=>e.replaceAll(/[\W_]([a-z\d])?/gi,(t,n)=>n?n.toUpperCase():""),"camelCase"),Wf=ge(e=>e.replaceAll(/\B([A-Z])/g,"-$1").toLowerCase(),"kebabCase"),Hf={"> 80":[{width:"content-width",paddingLeft:2,paddingRight:8},{width:"auto"}],"> 40":[{width:"auto",paddingLeft:2,paddingRight:8,preprocess:ge(e=>e.trim(),"preprocess")},{width:"100%",paddingLeft:2,paddingBottom:1}],"> 0":{stdoutColumns:1e3,columns:[{width:"content-width",paddingLeft:2,paddingRight:8},{width:"content-width"}]}};function Ni(e){let t=!1;return{type:"table",data:{tableData:Object.keys(e).sort((n,r)=>n.localeCompare(r)).map(n=>{const r=e[n],a="alias"in r;return a&&(t=!0),{name:n,flag:r,flagFormatted:`--${Wf(n)}`,aliasesEnabled:t,aliasFormatted:a?`-${r.alias}`:void 0}}).map(n=>(n.aliasesEnabled=t,[{type:"flagName",data:n},{type:"flagDescription",data:n}])),tableBreakpoints:Hf}}}i(Ni,"T"),ge(Ni,"renderFlags");const Pi=ge(e=>!e||(e.version??(e.help?e.help.version:void 0)),"getVersion"),Mi=ge(e=>{const t="parent"in e&&e.parent?.name;return(t?`${t} `:"")+e.name},"getName");function ji(e){const t=[];e.name&&t.push(Mi(e));const n=Pi(e)??("parent"in e&&Pi(e.parent));if(n&&t.push(`v${n}`),t.length!==0)return{id:"name",type:"text",data:`${t.join(" ")}
14
+ `}}i(ji,"k$2"),ge(ji,"getNameAndVersion");function zi(e){const{help:t}=e;if(!(!t||!t.description))return{id:"description",type:"text",data:`${t.description}
15
+ `}}i(zi,"_$1"),ge(zi,"getDescription");function qi(e){const t=e.help||{};if("usage"in t)return t.usage?{id:"usage",type:"section",data:{title:"Usage:",body:Array.isArray(t.usage)?t.usage.join(`
16
+ `):t.usage}}:void 0;if(e.name){const n=[],r=[Mi(e)];if(e.flags&&Object.keys(e.flags).length>0&&r.push("[flags...]"),e.parameters&&e.parameters.length>0){const{parameters:a}=e,s=a.indexOf("--"),o=s!==-1&&a.slice(s+1).some(u=>u.startsWith("<"));r.push(a.map(u=>u!=="--"?u:o?"--":"[--]").join(" "))}if(r.length>1&&n.push(r.join(" ")),"commands"in e&&e.commands?.length&&n.push(`${e.name} <command>`),n.length>0)return{id:"usage",type:"section",data:{title:"Usage:",body:n.join(`
17
+ `)}}}}i(qi,"F"),ge(qi,"getUsage");function Zi(e){return!("commands"in e)||!e.commands?.length?void 0:{id:"commands",type:"section",data:{title:"Commands:",body:{type:"table",data:{tableData:e.commands.map(t=>[t.options.name,t.options.help?t.options.help.description:""]),tableOptions:[{width:"content-width",paddingLeft:2,paddingRight:8}]}},indentBody:0}}}i(Zi,"H"),ge(Zi,"getCommands");function Ui(e){if(!(!e.flags||Object.keys(e.flags).length===0))return{id:"flags",type:"section",data:{title:"Flags:",body:Ni(e.flags),indentBody:0}}}i(Ui,"U$1"),ge(Ui,"getFlags");function Li(e){const{help:t}=e;if(!t||!t.examples||t.examples.length===0)return;let{examples:n}=t;if(Array.isArray(n)&&(n=n.join(`
18
+ `)),n)return{id:"examples",type:"section",data:{title:"Examples:",body:n}}}i(Li,"V$2"),ge(Li,"getExamples");function Vi(e){if(!("alias"in e)||!e.alias)return;const{alias:t}=e;return{id:"aliases",type:"section",data:{title:"Aliases:",body:Array.isArray(t)?t.join(", "):t}}}i(Vi,"J$1"),ge(Vi,"getAliases");const Jf=ge(e=>[ji,zi,qi,Zi,Ui,Li,Vi].map(t=>t(e)).filter(Boolean),"generateHelp"),Kf=Um.WriteStream.prototype.hasColors(),Gi=(gn=class{text(t){return t}bold(t){return Kf?`\x1B[1m${t}\x1B[22m`:t.toLocaleUpperCase()}indentText({text:t,spaces:n}){return t.replaceAll(/^/gm," ".repeat(n))}heading(t){return this.bold(t)}section({title:t,body:n,indentBody:r=2}){return`${(t?`${this.heading(t)}
19
19
  `:"")+(n?this.indentText({text:this.render(n),spaces:r}):"")}
20
- `}table({tableData:t,tableOptions:n,tableBreakpoints:r}){return jf(t.map(a=>a.map(s=>this.render(s))),r?Zf(r):n)}flagParameter(t){return t===Boolean?"":t===String?"<string>":t===Number?"<number>":Array.isArray(t)?this.flagParameter(t[0]):"<value>"}flagOperator(t){return" "}flagName(t){const{flag:n,flagFormatted:r,aliasesEnabled:a,aliasFormatted:s}=t;let o="";if(s?o+=`${s}, `:a&&(o+=" "),o+=r,"placeholder"in n&&typeof n.placeholder=="string")o+=`${this.flagOperator(t)}${n.placeholder}`;else{const u=this.flagParameter("type"in n?n.type:n);u&&(o+=`${this.flagOperator(t)}${u}`)}return o}flagDefault(t){return JSON.stringify(t)}flagDescription({flag:t}){let n="description"in t?t.description??"":"";if("default"in t){let{default:r}=t;typeof r=="function"&&(r=r()),r&&(n+=` (default: ${this.flagDefault(r)})`)}return n}render(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>this.render(n)).join(`
21
- `);if("type"in t&&this[t.type]){const n=this[t.type];if(typeof n=="function")return n.call(this,t.data)}throw new Error(`Invalid node type: ${JSON.stringify(t)}`)}},i(gn,"_z"),gn);ge(Ui,"Renderers");let Jf=Ui;const Lo=ge(e=>e.length>0&&!e.includes(" "),"isValidScriptName"),{stringify:mt}=JSON,Kf=/[|\\{}()[\]^$+*?.]/;function Lr(e){const t=[];let n,r;for(const a of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${mt(r)} must be last`);const s=a[0],o=a.at(-1);let u;if(s==="<"&&o===">"&&(u=!0,n))throw new Error(`Invalid parameter: Required parameter ${mt(a)} cannot come after optional parameter ${mt(n)}`);if(s==="["&&o==="]"&&(u=!1,n=a),u===void 0)throw new Error(`Invalid parameter: ${mt(a)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let l=a.slice(1,-1);const c=l.slice(-3)==="...";c&&(r=a,l=l.slice(0,-3));const d=l.match(Kf);if(d)throw new Error(`Invalid parameter: ${mt(a)}. Invalid character found ${mt(d[0])}`);t.push({name:l,required:u,spread:c})}return t}i(Lr,"b$1"),ge(Lr,"parseParameters");function Ur(e,t,n,r){for(let a=0;a<t.length;a+=1){const{name:s,required:o,spread:u}=t[a],l=Uf(s);if(l in e)throw new Error(`Invalid parameter: ${mt(s)} is used more than once.`);const c=u?n.slice(a):n[a];if(u&&(a=t.length),o&&(!c||u&&c.length===0))return console.error(`Error: Missing required parameter ${mt(s)}
22
- `),r(),process.exit(1);e[l]=c}}i(Ur,"v"),ge(Ur,"mapParametersToArguments");function Vi(e){return e===void 0||e!==!1}i(Vi,"G$2"),ge(Vi,"helpEnabled");function Uo(e,t,n,r){const a={...t.flags},s=t.version&&!("version"in a);s&&(a.version={type:Boolean,description:"Show version"});const{help:o}=t,u=Vi(o);u&&!("help"in a)&&(a.help={type:Boolean,alias:"h",description:"Show help"});const l=vf(a,r,{ignore:t.ignoreArgv}),c=ge(()=>{console.log(t.version)},"showVersion");if(s&&l.flags.version===!0)return c(),process.exit(0);const d=new Jf,m=u&&o?.render?o.render:v=>d.render(v),h=ge(v=>{const y=Wf({...t,...v?{help:v}:{},flags:a});console.log(m(y,d))},"showHelp");if(u&&l.flags.help===!0)return h(),process.exit(0);if(t.parameters){let{parameters:v}=t,y=l._;const F=v.indexOf("--"),E=v.slice(F+1),b=Object.create(null);if(F>-1&&E.length>0){v=v.slice(0,F);const w=l._["--"];y=y.slice(0,-w.length||void 0),Ur(b,Lr(v),y,h),Ur(b,Lr(E),w,h)}else Ur(b,Lr(v),y,h);Object.assign(l._,b)}const D={...l,showVersion:c,showHelp:h},f={command:e,...D};if(typeof n=="function"){const v=n(D);if(v&&"then"in v)return Object.assign(Promise.resolve(v),f)}return f}i(Uo,"j"),ge(Uo,"cliBase");function Gi(e,t){const n=new Map;for(const r of t){const a=[r.options.name],{alias:s}=r.options;s&&(Array.isArray(s)?a.push(...s):a.push(s));for(const o of a){if(n.has(o))throw new Error(`Duplicate command name found: ${mt(o)}`);n.set(o,r)}}return n.get(e)}i(Gi,"K$1"),ge(Gi,"getCommand");function Wi(e,t,n=process.argv.slice(2)){if(!e)throw new Error("Options is required");if("name"in e&&(!e.name||!Lo(e.name)))throw new Error(`Invalid script name: ${mt(e.name)}`);const r=n[0];if(e.commands&&r&&Lo(r)){const a=Gi(r,e.commands);if(a)return Uo(a.options.name,{...a.options,parent:e},a.callback,n.slice(1))}return Uo(void 0,e,t,n)}i(Wi,"Q"),ge(Wi,"cli");function rn(e,t){if(!e)throw new Error("Command options are required");const{name:n}=e;if(n===void 0)throw new Error("Command name is required");if(!Lo(n))throw new Error(`Invalid command name ${JSON.stringify(n)}. Command names must be one word.`);return{options:e,callback:t}}i(rn,"X"),ge(rn,"command");var Yf="aicommits",Xf="2.0.0-develop.11",Qf="Writes your git commit messages for you with AI",eh=["ai","git","commit","code changes"],th="MIT",nh={type:"git",url:"git+https://github.com/Nutlope/aicommits.git"},rh="Hassan El Mghari (@nutlope)",oh="module",ah=["dist"],sh={aicommits:"dist/cli.mjs",aic:"dist/cli.mjs"},ih={build:"pkgroll --minify",lint:"","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json"},uh={"@clack/prompts":"^0.11.0","@types/ini":"^1.3.31","@types/node":"^24.10.1","@types/update-notifier":"^6.0.8","clean-pkg-json":"^1.3.0",cleye:"^2.0.0",clipboardy:"^5.0.0",execa:"^7.0.0","fs-fixture":"^1.2.0",ini:"^3.0.1",kolorist:"^1.8.0",manten:"^0.7.0",ai:"^6.0.13","@ai-sdk/openai":"^3.0.5","@ai-sdk/openai-compatible":"^2.0.4",pkgroll:"^2.20.1",tsx:"^4.20.6",typescript:"^5.9.3"},lh={branches:["main",{name:"develop",prerelease:!0}]},ch={"update-notifier":"^7.3.1"},Vo={name:Yf,version:Xf,description:Qf,keywords:eh,license:th,repository:nh,author:rh,type:oh,files:ah,bin:sh,scripts:ih,devDependencies:uh,release:lh,dependencies:ch},wt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function St(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(St,"getDefaultExportFromCjs");var Ot={exports:{}},Go,Hi;function ph(){if(Hi)return Go;Hi=1,Go=r,r.sync=a;var e=Ro;function t(s,o){var u=o.pathExt!==void 0?o.pathExt:process.env.PATHEXT;if(!u||(u=u.split(";"),u.indexOf("")!==-1))return!0;for(var l=0;l<u.length;l++){var c=u[l].toLowerCase();if(c&&s.substr(-c.length).toLowerCase()===c)return!0}return!1}i(t,"checkPathExt");function n(s,o,u){return!s.isSymbolicLink()&&!s.isFile()?!1:t(o,u)}i(n,"checkStat");function r(s,o,u){e.stat(s,function(l,c){u(l,l?!1:n(c,s,o))})}i(r,"isexe");function a(s,o){return n(e.statSync(s),s,o)}return i(a,"sync"),Go}i(ph,"requireWindows");var Wo,Ji;function dh(){if(Ji)return Wo;Ji=1,Wo=t,t.sync=n;var e=Ro;function t(s,o,u){e.stat(s,function(l,c){u(l,l?!1:r(c,o))})}i(t,"isexe");function n(s,o){return r(e.statSync(s),o)}i(n,"sync");function r(s,o){return s.isFile()&&a(s,o)}i(r,"checkStat");function a(s,o){var u=s.mode,l=s.uid,c=s.gid,d=o.uid!==void 0?o.uid:process.getuid&&process.getuid(),m=o.gid!==void 0?o.gid:process.getgid&&process.getgid(),h=parseInt("100",8),D=parseInt("010",8),f=parseInt("001",8),v=h|D,y=u&f||u&D&&c===m||u&h&&l===d||u&v&&d===0;return y}return i(a,"checkMode"),Wo}i(dh,"requireMode");var Ho,Ki;function mh(){if(Ki)return Ho;Ki=1;var e;process.platform==="win32"||wt.TESTING_WINDOWS?e=ph():e=dh(),Ho=t,t.sync=n;function t(r,a,s){if(typeof a=="function"&&(s=a,a={}),!s){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,u){t(r,a||{},function(l,c){l?u(l):o(c)})})}e(r,a||{},function(o,u){o&&(o.code==="EACCES"||a&&a.ignoreErrors)&&(o=null,u=!1),s(o,u)})}i(t,"isexe");function n(r,a){try{return e.sync(r,a||{})}catch(s){if(a&&a.ignoreErrors||s.code==="EACCES")return!1;throw s}}return i(n,"sync"),Ho}i(mh,"requireIsexe");var Jo,Yi;function fh(){if(Yi)return Jo;Yi=1;const e=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",t=at,n=e?";":":",r=mh(),a=i(l=>Object.assign(new Error(`not found: ${l}`),{code:"ENOENT"}),"getNotFoundError"),s=i((l,c)=>{const d=c.colon||n,m=l.match(/\//)||e&&l.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(c.path||process.env.PATH||"").split(d)],h=e?c.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",D=e?h.split(d):[""];return e&&l.indexOf(".")!==-1&&D[0]!==""&&D.unshift(""),{pathEnv:m,pathExt:D,pathExtExe:h}},"getPathInfo"),o=i((l,c,d)=>{typeof c=="function"&&(d=c,c={}),c||(c={});const{pathEnv:m,pathExt:h,pathExtExe:D}=s(l,c),f=[],v=i(F=>new Promise((E,b)=>{if(F===m.length)return c.all&&f.length?E(f):b(a(l));const w=m[F],S=/^".*"$/.test(w)?w.slice(1,-1):w,k=t.join(S,l),C=!S&&/^\.[\\\/]/.test(l)?l.slice(0,2)+k:k;E(y(C,F,0))}),"step"),y=i((F,E,b)=>new Promise((w,S)=>{if(b===h.length)return w(v(E+1));const k=h[b];r(F+k,{pathExt:D},(C,z)=>{if(!C&&z)if(c.all)f.push(F+k);else return w(F+k);return w(y(F,E,b+1))})}),"subStep");return d?v(0).then(F=>d(null,F),d):v(0)},"which"),u=i((l,c)=>{c=c||{};const{pathEnv:d,pathExt:m,pathExtExe:h}=s(l,c),D=[];for(let f=0;f<d.length;f++){const v=d[f],y=/^".*"$/.test(v)?v.slice(1,-1):v,F=t.join(y,l),E=!y&&/^\.[\\\/]/.test(l)?l.slice(0,2)+F:F;for(let b=0;b<m.length;b++){const w=E+m[b];try{if(r.sync(w,{pathExt:h}))if(c.all)D.push(w);else return w}catch{}}}if(c.all&&D.length)return D;if(c.nothrow)return null;throw a(l)},"whichSync");return Jo=o,o.sync=u,Jo}i(fh,"requireWhich");var Vr={exports:{}},Xi;function hh(){if(Xi)return Vr.exports;Xi=1;const e=i((t={})=>{const n=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(n).reverse().find(a=>a.toUpperCase()==="PATH")||"Path"},"pathKey");return Vr.exports=e,Vr.exports.default=e,Vr.exports}i(hh,"requirePathKey");var Ko,Qi;function Dh(){if(Qi)return Ko;Qi=1;const e=at,t=fh(),n=hh();function r(s,o){const u=s.options.env||process.env,l=process.cwd(),c=s.options.cwd!=null,d=c&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(s.options.cwd)}catch{}let m;try{m=t.sync(s.command,{path:u[n({env:u})],pathExt:o?e.delimiter:void 0})}catch{}finally{d&&process.chdir(l)}return m&&(m=e.resolve(c?s.options.cwd:"",m)),m}i(r,"resolveCommandAttempt");function a(s){return r(s)||r(s,!0)}return i(a,"resolveCommand"),Ko=a,Ko}i(Dh,"requireResolveCommand");var Gr={},eu;function gh(){if(eu)return Gr;eu=1;const e=/([()\][%!^"`<>&|;, *?])/g;function t(r){return r=r.replace(e,"^$1"),r}i(t,"escapeCommand");function n(r,a){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(e,"^$1"),a&&(r=r.replace(e,"^$1")),r}return i(n,"escapeArgument"),Gr.command=t,Gr.argument=n,Gr}i(gh,"require_escape");var Yo,tu;function vh(){return tu||(tu=1,Yo=/^#!(.*)/),Yo}i(vh,"requireShebangRegex");var Xo,nu;function yh(){if(nu)return Xo;nu=1;const e=vh();return Xo=i((t="")=>{const n=t.match(e);if(!n)return null;const[r,a]=n[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?a:a?`${s} ${a}`:s},"shebangCommand"),Xo}i(yh,"requireShebangCommand");var Qo,ru;function _h(){if(ru)return Qo;ru=1;const e=Ro,t=yh();function n(r){const s=Buffer.alloc(150);let o;try{o=e.openSync(r,"r"),e.readSync(o,s,0,150,0),e.closeSync(o)}catch{}return t(s.toString())}return i(n,"readShebang"),Qo=n,Qo}i(_h,"requireReadShebang");var ea,ou;function Fh(){if(ou)return ea;ou=1;const e=at,t=Dh(),n=gh(),r=_h(),a=process.platform==="win32",s=/\.(?:com|exe)$/i,o=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(d){d.file=t(d);const m=d.file&&r(d.file);return m?(d.args.unshift(d.file),d.command=m,t(d)):d.file}i(u,"detectShebang");function l(d){if(!a)return d;const m=u(d),h=!s.test(m);if(d.options.forceShell||h){const D=o.test(m);d.command=e.normalize(d.command),d.command=n.command(d.command),d.args=d.args.map(v=>n.argument(v,D));const f=[d.command].concat(d.args).join(" ");d.args=["/d","/s","/c",`"${f}"`],d.command=process.env.comspec||"cmd.exe",d.options.windowsVerbatimArguments=!0}return d}i(l,"parseNonShell");function c(d,m,h){m&&!Array.isArray(m)&&(h=m,m=null),m=m?m.slice(0):[],h=Object.assign({},h);const D={command:d,args:m,options:h,file:void 0,original:{command:d,args:m}};return h.shell?D:l(D)}return i(c,"parse"),ea=c,ea}i(Fh,"requireParse");var ta,au;function Ch(){if(au)return ta;au=1;const e=process.platform==="win32";function t(s,o){return Object.assign(new Error(`${o} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${o} ${s.command}`,path:s.command,spawnargs:s.args})}i(t,"notFoundError");function n(s,o){if(!e)return;const u=s.emit;s.emit=function(l,c){if(l==="exit"){const d=r(c,o);if(d)return u.call(s,"error",d)}return u.apply(s,arguments)}}i(n,"hookChildProcess");function r(s,o){return e&&s===1&&!o.file?t(o.original,"spawn"):null}i(r,"verifyENOENT");function a(s,o){return e&&s===1&&!o.file?t(o.original,"spawnSync"):null}return i(a,"verifyENOENTSync"),ta={hookChildProcess:n,verifyENOENT:r,verifyENOENTSync:a,notFoundError:t},ta}i(Ch,"requireEnoent");var su;function bh(){if(su)return Ot.exports;su=1;const e=Vm,t=Fh(),n=Ch();function r(s,o,u){const l=t(s,o,u),c=e.spawn(l.command,l.args,l.options);return n.hookChildProcess(c,l),c}i(r,"spawn");function a(s,o,u){const l=t(s,o,u),c=e.spawnSync(l.command,l.args,l.options);return c.error=c.error||n.verifyENOENTSync(c.status,l),c}return i(a,"spawnSync"),Ot.exports=r,Ot.exports.spawn=r,Ot.exports.sync=a,Ot.exports._parse=t,Ot.exports._enoent=n,Ot.exports}i(bh,"requireCrossSpawn");var Eh=bh(),wh=St(Eh);function Ah(e){const t=typeof e=="string"?`
23
- `:10,n=typeof e=="string"?"\r":13;return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}i(Ah,"stripFinalNewline");function iu(e={}){const{env:t=process.env,platform:n=process.platform}=e;return n!=="win32"?"PATH":Object.keys(t).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}i(iu,"pathKey");const Ih=i(({cwd:e=ke.cwd(),path:t=ke.env[iu()],preferLocal:n=!0,execPath:r=ke.execPath,addExecPath:a=!0}={})=>{const s=e instanceof URL?ai(e):e,o=nn.resolve(s),u=[];return n&&xh(u,o),a&&kh(u,r,o),[...u,t].join(nn.delimiter)},"npmRunPath"),xh=i((e,t)=>{let n;for(;n!==t;)e.push(nn.join(t,"node_modules/.bin")),n=t,t=nn.resolve(t,"..")},"applyPreferLocal"),kh=i((e,t,n)=>{const r=t instanceof URL?ai(t):t;e.push(nn.resolve(n,r,".."))},"applyExecPath"),$h=i(({env:e=ke.env,...t}={})=>{e={...e};const n=iu({env:e});return t.path=e[n],e[n]=Ih(t),e},"npmRunPathEnv"),Th=i((e,t,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const a=Object.getOwnPropertyDescriptor(e,n),s=Object.getOwnPropertyDescriptor(t,n);!Bh(a,s)&&r||Object.defineProperty(e,n,s)},"copyProperty"),Bh=i(function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},"canCopyProperty"),Sh=i((e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},"changePrototype"),Oh=i((e,t)=>`/* Wrapped ${e}*/
24
- ${t}`,"wrappedToString"),Rh=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Nh=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Ph=i((e,t,n)=>{const r=n===""?"":`with ${n.trim()}() `,a=Oh.bind(null,r,t.toString());Object.defineProperty(a,"name",Nh),Object.defineProperty(e,"toString",{...Rh,value:a})},"changeToString");function Mh(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:r}=e;for(const a of Reflect.ownKeys(t))Th(e,t,a,n);return Sh(e,t),Ph(e,t,r),e}i(Mh,"mimicFunction");const Wr=new WeakMap,uu=i((e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,r=0;const a=e.displayName||e.name||"<anonymous>",s=i(function(...o){if(Wr.set(s,++r),r===1)n=e.apply(this,o),e=null;else if(t.throw===!0)throw new Error(`Function \`${a}\` can only be called once`);return n},"onetime2");return Mh(s,e),Wr.set(s,r),s},"onetime");uu.callCount=e=>{if(!Wr.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Wr.get(e)};const jh=i(()=>{const e=cu-lu+1;return Array.from({length:e},zh)},"getRealtimeSignals"),zh=i((e,t)=>({name:`SIGRT${t+1}`,number:lu+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),"getRealtimeSignal"),lu=34,cu=64,qh=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],pu=i(()=>{const e=jh();return[...qh,...e].map(Zh)},"getSignals"),Zh=i(({name:e,number:t,description:n,action:r,forced:a=!1,standard:s})=>{const{signals:{[e]:o}}=si,u=o!==void 0;return{name:e,number:u?o:t,description:n,supported:u,action:r,forced:a,standard:s}},"normalizeSignal"),Lh=i(()=>{const e=pu();return Object.fromEntries(e.map(Uh))},"getSignalsByName"),Uh=i(({name:e,number:t,description:n,supported:r,action:a,forced:s,standard:o})=>[e,{name:e,number:t,description:n,supported:r,action:a,forced:s,standard:o}],"getSignalByName"),Vh=Lh(),Gh=i(()=>{const e=pu(),t=cu+1,n=Array.from({length:t},(r,a)=>Wh(a,e));return Object.assign({},...n)},"getSignalsByNumber"),Wh=i((e,t)=>{const n=Hh(e,t);if(n===void 0)return{};const{name:r,description:a,supported:s,action:o,forced:u,standard:l}=n;return{[e]:{name:r,number:e,description:a,supported:s,action:o,forced:u,standard:l}}},"getSignalByNumber"),Hh=i((e,t)=>{const n=t.find(({name:r})=>si.signals[r]===e);return n!==void 0?n:t.find(r=>r.number===e)},"findSignalByNumber");Gh();const Jh=i(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:a,exitCode:s,isCanceled:o})=>e?`timed out after ${t} milliseconds`:o?"was canceled":n!==void 0?`failed with ${n}`:r!==void 0?`was killed with ${r} (${a})`:s!==void 0?`failed with exit code ${s}`:"failed","getErrorPrefix"),du=i(({stdout:e,stderr:t,all:n,error:r,signal:a,exitCode:s,command:o,escapedCommand:u,timedOut:l,isCanceled:c,killed:d,parsed:{options:{timeout:m,cwd:h=ke.cwd()}}})=>{s=s===null?void 0:s,a=a===null?void 0:a;const D=a===void 0?void 0:Vh[a].description,f=r&&r.code,y=`Command ${Jh({timedOut:l,timeout:m,errorCode:f,signal:a,signalDescription:D,exitCode:s,isCanceled:c})}: ${o}`,F=Object.prototype.toString.call(r)==="[object Error]",E=F?`${y}
20
+ `}table({tableData:t,tableOptions:n,tableBreakpoints:r}){return qf(t.map(a=>a.map(s=>this.render(s))),r?Lf(r):n)}flagParameter(t){return t===Boolean?"":t===String?"<string>":t===Number?"<number>":Array.isArray(t)?this.flagParameter(t[0]):"<value>"}flagOperator(t){return" "}flagName(t){const{flag:n,flagFormatted:r,aliasesEnabled:a,aliasFormatted:s}=t;let o="";if(s?o+=`${s}, `:a&&(o+=" "),o+=r,"placeholder"in n&&typeof n.placeholder=="string")o+=`${this.flagOperator(t)}${n.placeholder}`;else{const u=this.flagParameter("type"in n?n.type:n);u&&(o+=`${this.flagOperator(t)}${u}`)}return o}flagDefault(t){return JSON.stringify(t)}flagDescription({flag:t}){let n="description"in t?t.description??"":"";if("default"in t){let{default:r}=t;typeof r=="function"&&(r=r()),r&&(n+=` (default: ${this.flagDefault(r)})`)}return n}render(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>this.render(n)).join(`
21
+ `);if("type"in t&&this[t.type]){const n=this[t.type];if(typeof n=="function")return n.call(this,t.data)}throw new Error(`Invalid node type: ${JSON.stringify(t)}`)}},i(gn,"_z"),gn);ge(Gi,"Renderers");let Yf=Gi;const Lo=ge(e=>e.length>0&&!e.includes(" "),"isValidScriptName"),{stringify:mt}=JSON,Xf=/[|\\{}()[\]^$+*?.]/;function Lr(e){const t=[];let n,r;for(const a of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${mt(r)} must be last`);const s=a[0],o=a.at(-1);let u;if(s==="<"&&o===">"&&(u=!0,n))throw new Error(`Invalid parameter: Required parameter ${mt(a)} cannot come after optional parameter ${mt(n)}`);if(s==="["&&o==="]"&&(u=!1,n=a),u===void 0)throw new Error(`Invalid parameter: ${mt(a)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let l=a.slice(1,-1);const c=l.slice(-3)==="...";c&&(r=a,l=l.slice(0,-3));const d=l.match(Xf);if(d)throw new Error(`Invalid parameter: ${mt(a)}. Invalid character found ${mt(d[0])}`);t.push({name:l,required:u,spread:c})}return t}i(Lr,"b$1"),ge(Lr,"parseParameters");function Vr(e,t,n,r){for(let a=0;a<t.length;a+=1){const{name:s,required:o,spread:u}=t[a],l=Gf(s);if(l in e)throw new Error(`Invalid parameter: ${mt(s)} is used more than once.`);const c=u?n.slice(a):n[a];if(u&&(a=t.length),o&&(!c||u&&c.length===0))return console.error(`Error: Missing required parameter ${mt(s)}
22
+ `),r(),process.exit(1);e[l]=c}}i(Vr,"v"),ge(Vr,"mapParametersToArguments");function Wi(e){return e===void 0||e!==!1}i(Wi,"G$2"),ge(Wi,"helpEnabled");function Vo(e,t,n,r){const a={...t.flags},s=t.version&&!("version"in a);s&&(a.version={type:Boolean,description:"Show version"});const{help:o}=t,u=Wi(o);u&&!("help"in a)&&(a.help={type:Boolean,alias:"h",description:"Show help"});const l=_f(a,r,{ignore:t.ignoreArgv}),c=ge(()=>{console.log(t.version)},"showVersion");if(s&&l.flags.version===!0)return c(),process.exit(0);const d=new Yf,m=u&&o?.render?o.render:v=>d.render(v),h=ge(v=>{const y=Jf({...t,...v?{help:v}:{},flags:a});console.log(m(y,d))},"showHelp");if(u&&l.flags.help===!0)return h(),process.exit(0);if(t.parameters){let{parameters:v}=t,y=l._;const F=v.indexOf("--"),E=v.slice(F+1),b=Object.create(null);if(F>-1&&E.length>0){v=v.slice(0,F);const w=l._["--"];y=y.slice(0,-w.length||void 0),Vr(b,Lr(v),y,h),Vr(b,Lr(E),w,h)}else Vr(b,Lr(v),y,h);Object.assign(l._,b)}const D={...l,showVersion:c,showHelp:h},f={command:e,...D};if(typeof n=="function"){const v=n(D);if(v&&"then"in v)return Object.assign(Promise.resolve(v),f)}return f}i(Vo,"j"),ge(Vo,"cliBase");function Hi(e,t){const n=new Map;for(const r of t){const a=[r.options.name],{alias:s}=r.options;s&&(Array.isArray(s)?a.push(...s):a.push(s));for(const o of a){if(n.has(o))throw new Error(`Duplicate command name found: ${mt(o)}`);n.set(o,r)}}return n.get(e)}i(Hi,"K$1"),ge(Hi,"getCommand");function Ji(e,t,n=process.argv.slice(2)){if(!e)throw new Error("Options is required");if("name"in e&&(!e.name||!Lo(e.name)))throw new Error(`Invalid script name: ${mt(e.name)}`);const r=n[0];if(e.commands&&r&&Lo(r)){const a=Hi(r,e.commands);if(a)return Vo(a.options.name,{...a.options,parent:e},a.callback,n.slice(1))}return Vo(void 0,e,t,n)}i(Ji,"Q"),ge(Ji,"cli");function rn(e,t){if(!e)throw new Error("Command options are required");const{name:n}=e;if(n===void 0)throw new Error("Command name is required");if(!Lo(n))throw new Error(`Invalid command name ${JSON.stringify(n)}. Command names must be one word.`);return{options:e,callback:t}}i(rn,"X"),ge(rn,"command");var Qf="aicommits",eh="2.0.0-develop.12",th="Writes your git commit messages for you with AI",nh=["ai","git","commit","code changes"],rh="MIT",oh={type:"git",url:"git+https://github.com/Nutlope/aicommits.git"},ah="Hassan El Mghari (@nutlope)",sh="module",ih=["dist"],uh={aicommits:"dist/cli.mjs",aic:"dist/cli.mjs"},lh={build:"pkgroll --minify",lint:"","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json"},ch={"@clack/prompts":"^0.11.0","@types/ini":"^1.3.31","@types/node":"^24.10.1","@types/update-notifier":"^6.0.8","clean-pkg-json":"^1.3.0",cleye:"^2.0.0",clipboardy:"^5.0.0",execa:"^7.0.0","fs-fixture":"^1.2.0",ini:"^3.0.1",kolorist:"^1.8.0",manten:"^0.7.0",ai:"^6.0.13","@ai-sdk/openai":"^3.0.5","@ai-sdk/openai-compatible":"^2.0.4",pkgroll:"^2.20.1",tsx:"^4.20.6",typescript:"^5.9.3"},ph={branches:["main",{name:"develop",prerelease:!0}]},dh={"update-notifier":"^7.3.1"},Gr={name:Qf,version:eh,description:th,keywords:nh,license:rh,repository:oh,author:ah,type:sh,files:ih,bin:uh,scripts:lh,devDependencies:ch,release:ph,dependencies:dh},wt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function St(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(St,"getDefaultExportFromCjs");var Ot={exports:{}},Go,Ki;function mh(){if(Ki)return Go;Ki=1,Go=r,r.sync=a;var e=No;function t(s,o){var u=o.pathExt!==void 0?o.pathExt:process.env.PATHEXT;if(!u||(u=u.split(";"),u.indexOf("")!==-1))return!0;for(var l=0;l<u.length;l++){var c=u[l].toLowerCase();if(c&&s.substr(-c.length).toLowerCase()===c)return!0}return!1}i(t,"checkPathExt");function n(s,o,u){return!s.isSymbolicLink()&&!s.isFile()?!1:t(o,u)}i(n,"checkStat");function r(s,o,u){e.stat(s,function(l,c){u(l,l?!1:n(c,s,o))})}i(r,"isexe");function a(s,o){return n(e.statSync(s),s,o)}return i(a,"sync"),Go}i(mh,"requireWindows");var Wo,Yi;function fh(){if(Yi)return Wo;Yi=1,Wo=t,t.sync=n;var e=No;function t(s,o,u){e.stat(s,function(l,c){u(l,l?!1:r(c,o))})}i(t,"isexe");function n(s,o){return r(e.statSync(s),o)}i(n,"sync");function r(s,o){return s.isFile()&&a(s,o)}i(r,"checkStat");function a(s,o){var u=s.mode,l=s.uid,c=s.gid,d=o.uid!==void 0?o.uid:process.getuid&&process.getuid(),m=o.gid!==void 0?o.gid:process.getgid&&process.getgid(),h=parseInt("100",8),D=parseInt("010",8),f=parseInt("001",8),v=h|D,y=u&f||u&D&&c===m||u&h&&l===d||u&v&&d===0;return y}return i(a,"checkMode"),Wo}i(fh,"requireMode");var Ho,Xi;function hh(){if(Xi)return Ho;Xi=1;var e;process.platform==="win32"||wt.TESTING_WINDOWS?e=mh():e=fh(),Ho=t,t.sync=n;function t(r,a,s){if(typeof a=="function"&&(s=a,a={}),!s){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,u){t(r,a||{},function(l,c){l?u(l):o(c)})})}e(r,a||{},function(o,u){o&&(o.code==="EACCES"||a&&a.ignoreErrors)&&(o=null,u=!1),s(o,u)})}i(t,"isexe");function n(r,a){try{return e.sync(r,a||{})}catch(s){if(a&&a.ignoreErrors||s.code==="EACCES")return!1;throw s}}return i(n,"sync"),Ho}i(hh,"requireIsexe");var Jo,Qi;function Dh(){if(Qi)return Jo;Qi=1;const e=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",t=at,n=e?";":":",r=hh(),a=i(l=>Object.assign(new Error(`not found: ${l}`),{code:"ENOENT"}),"getNotFoundError"),s=i((l,c)=>{const d=c.colon||n,m=l.match(/\//)||e&&l.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(c.path||process.env.PATH||"").split(d)],h=e?c.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",D=e?h.split(d):[""];return e&&l.indexOf(".")!==-1&&D[0]!==""&&D.unshift(""),{pathEnv:m,pathExt:D,pathExtExe:h}},"getPathInfo"),o=i((l,c,d)=>{typeof c=="function"&&(d=c,c={}),c||(c={});const{pathEnv:m,pathExt:h,pathExtExe:D}=s(l,c),f=[],v=i(F=>new Promise((E,b)=>{if(F===m.length)return c.all&&f.length?E(f):b(a(l));const w=m[F],S=/^".*"$/.test(w)?w.slice(1,-1):w,k=t.join(S,l),C=!S&&/^\.[\\\/]/.test(l)?l.slice(0,2)+k:k;E(y(C,F,0))}),"step"),y=i((F,E,b)=>new Promise((w,S)=>{if(b===h.length)return w(v(E+1));const k=h[b];r(F+k,{pathExt:D},(C,z)=>{if(!C&&z)if(c.all)f.push(F+k);else return w(F+k);return w(y(F,E,b+1))})}),"subStep");return d?v(0).then(F=>d(null,F),d):v(0)},"which"),u=i((l,c)=>{c=c||{};const{pathEnv:d,pathExt:m,pathExtExe:h}=s(l,c),D=[];for(let f=0;f<d.length;f++){const v=d[f],y=/^".*"$/.test(v)?v.slice(1,-1):v,F=t.join(y,l),E=!y&&/^\.[\\\/]/.test(l)?l.slice(0,2)+F:F;for(let b=0;b<m.length;b++){const w=E+m[b];try{if(r.sync(w,{pathExt:h}))if(c.all)D.push(w);else return w}catch{}}}if(c.all&&D.length)return D;if(c.nothrow)return null;throw a(l)},"whichSync");return Jo=o,o.sync=u,Jo}i(Dh,"requireWhich");var Wr={exports:{}},eu;function gh(){if(eu)return Wr.exports;eu=1;const e=i((t={})=>{const n=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(n).reverse().find(a=>a.toUpperCase()==="PATH")||"Path"},"pathKey");return Wr.exports=e,Wr.exports.default=e,Wr.exports}i(gh,"requirePathKey");var Ko,tu;function vh(){if(tu)return Ko;tu=1;const e=at,t=Dh(),n=gh();function r(s,o){const u=s.options.env||process.env,l=process.cwd(),c=s.options.cwd!=null,d=c&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(s.options.cwd)}catch{}let m;try{m=t.sync(s.command,{path:u[n({env:u})],pathExt:o?e.delimiter:void 0})}catch{}finally{d&&process.chdir(l)}return m&&(m=e.resolve(c?s.options.cwd:"",m)),m}i(r,"resolveCommandAttempt");function a(s){return r(s)||r(s,!0)}return i(a,"resolveCommand"),Ko=a,Ko}i(vh,"requireResolveCommand");var Hr={},nu;function yh(){if(nu)return Hr;nu=1;const e=/([()\][%!^"`<>&|;, *?])/g;function t(r){return r=r.replace(e,"^$1"),r}i(t,"escapeCommand");function n(r,a){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(e,"^$1"),a&&(r=r.replace(e,"^$1")),r}return i(n,"escapeArgument"),Hr.command=t,Hr.argument=n,Hr}i(yh,"require_escape");var Yo,ru;function _h(){return ru||(ru=1,Yo=/^#!(.*)/),Yo}i(_h,"requireShebangRegex");var Xo,ou;function Fh(){if(ou)return Xo;ou=1;const e=_h();return Xo=i((t="")=>{const n=t.match(e);if(!n)return null;const[r,a]=n[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?a:a?`${s} ${a}`:s},"shebangCommand"),Xo}i(Fh,"requireShebangCommand");var Qo,au;function Ch(){if(au)return Qo;au=1;const e=No,t=Fh();function n(r){const s=Buffer.alloc(150);let o;try{o=e.openSync(r,"r"),e.readSync(o,s,0,150,0),e.closeSync(o)}catch{}return t(s.toString())}return i(n,"readShebang"),Qo=n,Qo}i(Ch,"requireReadShebang");var ea,su;function bh(){if(su)return ea;su=1;const e=at,t=vh(),n=yh(),r=Ch(),a=process.platform==="win32",s=/\.(?:com|exe)$/i,o=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(d){d.file=t(d);const m=d.file&&r(d.file);return m?(d.args.unshift(d.file),d.command=m,t(d)):d.file}i(u,"detectShebang");function l(d){if(!a)return d;const m=u(d),h=!s.test(m);if(d.options.forceShell||h){const D=o.test(m);d.command=e.normalize(d.command),d.command=n.command(d.command),d.args=d.args.map(v=>n.argument(v,D));const f=[d.command].concat(d.args).join(" ");d.args=["/d","/s","/c",`"${f}"`],d.command=process.env.comspec||"cmd.exe",d.options.windowsVerbatimArguments=!0}return d}i(l,"parseNonShell");function c(d,m,h){m&&!Array.isArray(m)&&(h=m,m=null),m=m?m.slice(0):[],h=Object.assign({},h);const D={command:d,args:m,options:h,file:void 0,original:{command:d,args:m}};return h.shell?D:l(D)}return i(c,"parse"),ea=c,ea}i(bh,"requireParse");var ta,iu;function Eh(){if(iu)return ta;iu=1;const e=process.platform==="win32";function t(s,o){return Object.assign(new Error(`${o} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${o} ${s.command}`,path:s.command,spawnargs:s.args})}i(t,"notFoundError");function n(s,o){if(!e)return;const u=s.emit;s.emit=function(l,c){if(l==="exit"){const d=r(c,o);if(d)return u.call(s,"error",d)}return u.apply(s,arguments)}}i(n,"hookChildProcess");function r(s,o){return e&&s===1&&!o.file?t(o.original,"spawn"):null}i(r,"verifyENOENT");function a(s,o){return e&&s===1&&!o.file?t(o.original,"spawnSync"):null}return i(a,"verifyENOENTSync"),ta={hookChildProcess:n,verifyENOENT:r,verifyENOENTSync:a,notFoundError:t},ta}i(Eh,"requireEnoent");var uu;function wh(){if(uu)return Ot.exports;uu=1;const e=Gm,t=bh(),n=Eh();function r(s,o,u){const l=t(s,o,u),c=e.spawn(l.command,l.args,l.options);return n.hookChildProcess(c,l),c}i(r,"spawn");function a(s,o,u){const l=t(s,o,u),c=e.spawnSync(l.command,l.args,l.options);return c.error=c.error||n.verifyENOENTSync(c.status,l),c}return i(a,"spawnSync"),Ot.exports=r,Ot.exports.spawn=r,Ot.exports.sync=a,Ot.exports._parse=t,Ot.exports._enoent=n,Ot.exports}i(wh,"requireCrossSpawn");var Ah=wh(),Ih=St(Ah);function xh(e){const t=typeof e=="string"?`
23
+ `:10,n=typeof e=="string"?"\r":13;return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}i(xh,"stripFinalNewline");function lu(e={}){const{env:t=process.env,platform:n=process.platform}=e;return n!=="win32"?"PATH":Object.keys(t).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}i(lu,"pathKey");const kh=i(({cwd:e=ke.cwd(),path:t=ke.env[lu()],preferLocal:n=!0,execPath:r=ke.execPath,addExecPath:a=!0}={})=>{const s=e instanceof URL?ii(e):e,o=nn.resolve(s),u=[];return n&&$h(u,o),a&&Th(u,r,o),[...u,t].join(nn.delimiter)},"npmRunPath"),$h=i((e,t)=>{let n;for(;n!==t;)e.push(nn.join(t,"node_modules/.bin")),n=t,t=nn.resolve(t,"..")},"applyPreferLocal"),Th=i((e,t,n)=>{const r=t instanceof URL?ii(t):t;e.push(nn.resolve(n,r,".."))},"applyExecPath"),Bh=i(({env:e=ke.env,...t}={})=>{e={...e};const n=lu({env:e});return t.path=e[n],e[n]=kh(t),e},"npmRunPathEnv"),Sh=i((e,t,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const a=Object.getOwnPropertyDescriptor(e,n),s=Object.getOwnPropertyDescriptor(t,n);!Oh(a,s)&&r||Object.defineProperty(e,n,s)},"copyProperty"),Oh=i(function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},"canCopyProperty"),Rh=i((e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},"changePrototype"),Nh=i((e,t)=>`/* Wrapped ${e}*/
24
+ ${t}`,"wrappedToString"),Ph=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Mh=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),jh=i((e,t,n)=>{const r=n===""?"":`with ${n.trim()}() `,a=Nh.bind(null,r,t.toString());Object.defineProperty(a,"name",Mh),Object.defineProperty(e,"toString",{...Ph,value:a})},"changeToString");function zh(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:r}=e;for(const a of Reflect.ownKeys(t))Sh(e,t,a,n);return Rh(e,t),jh(e,t,r),e}i(zh,"mimicFunction");const Jr=new WeakMap,cu=i((e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,r=0;const a=e.displayName||e.name||"<anonymous>",s=i(function(...o){if(Jr.set(s,++r),r===1)n=e.apply(this,o),e=null;else if(t.throw===!0)throw new Error(`Function \`${a}\` can only be called once`);return n},"onetime2");return zh(s,e),Jr.set(s,r),s},"onetime");cu.callCount=e=>{if(!Jr.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Jr.get(e)};const qh=i(()=>{const e=du-pu+1;return Array.from({length:e},Zh)},"getRealtimeSignals"),Zh=i((e,t)=>({name:`SIGRT${t+1}`,number:pu+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),"getRealtimeSignal"),pu=34,du=64,Uh=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],mu=i(()=>{const e=qh();return[...Uh,...e].map(Lh)},"getSignals"),Lh=i(({name:e,number:t,description:n,action:r,forced:a=!1,standard:s})=>{const{signals:{[e]:o}}=ui,u=o!==void 0;return{name:e,number:u?o:t,description:n,supported:u,action:r,forced:a,standard:s}},"normalizeSignal"),Vh=i(()=>{const e=mu();return Object.fromEntries(e.map(Gh))},"getSignalsByName"),Gh=i(({name:e,number:t,description:n,supported:r,action:a,forced:s,standard:o})=>[e,{name:e,number:t,description:n,supported:r,action:a,forced:s,standard:o}],"getSignalByName"),Wh=Vh(),Hh=i(()=>{const e=mu(),t=du+1,n=Array.from({length:t},(r,a)=>Jh(a,e));return Object.assign({},...n)},"getSignalsByNumber"),Jh=i((e,t)=>{const n=Kh(e,t);if(n===void 0)return{};const{name:r,description:a,supported:s,action:o,forced:u,standard:l}=n;return{[e]:{name:r,number:e,description:a,supported:s,action:o,forced:u,standard:l}}},"getSignalByNumber"),Kh=i((e,t)=>{const n=t.find(({name:r})=>ui.signals[r]===e);return n!==void 0?n:t.find(r=>r.number===e)},"findSignalByNumber");Hh();const Yh=i(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:a,exitCode:s,isCanceled:o})=>e?`timed out after ${t} milliseconds`:o?"was canceled":n!==void 0?`failed with ${n}`:r!==void 0?`was killed with ${r} (${a})`:s!==void 0?`failed with exit code ${s}`:"failed","getErrorPrefix"),fu=i(({stdout:e,stderr:t,all:n,error:r,signal:a,exitCode:s,command:o,escapedCommand:u,timedOut:l,isCanceled:c,killed:d,parsed:{options:{timeout:m,cwd:h=ke.cwd()}}})=>{s=s===null?void 0:s,a=a===null?void 0:a;const D=a===void 0?void 0:Wh[a].description,f=r&&r.code,y=`Command ${Yh({timedOut:l,timeout:m,errorCode:f,signal:a,signalDescription:D,exitCode:s,isCanceled:c})}: ${o}`,F=Object.prototype.toString.call(r)==="[object Error]",E=F?`${y}
25
25
  ${r.message}`:y,b=[E,t,e].filter(Boolean).join(`
26
- `);return F?(r.originalMessage=r.message,r.message=b):r=new Error(b),r.shortMessage=E,r.command=o,r.escapedCommand=u,r.exitCode=s,r.signal=a,r.signalDescription=D,r.stdout=e,r.stderr=t,r.cwd=h,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=c,r.killed=d&&!l,r},"makeError"),Hr=["stdin","stdout","stderr"],Kh=i(e=>Hr.some(t=>e[t]!==void 0),"hasAlias"),Yh=i(e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Hr.map(r=>e[r]);if(Kh(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Hr.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,Hr.length);return Array.from({length:n},(r,a)=>t[a])},"normalizeStdio");var Rt={exports:{}},na={exports:{}},mu;function Xh(){return mu||(mu=1,(function(e){e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")})(na)),na.exports}i(Xh,"requireSignals");var fu;function Qh(){if(fu)return Rt.exports;fu=1;var e=wt.process;const t=i(function(y){return y&&typeof y=="object"&&typeof y.removeListener=="function"&&typeof y.emit=="function"&&typeof y.reallyExit=="function"&&typeof y.listeners=="function"&&typeof y.kill=="function"&&typeof y.pid=="number"&&typeof y.on=="function"},"processOk");if(!t(e))Rt.exports=function(){return function(){}};else{var n=Wm,r=Xh(),a=/^win/i.test(e.platform),s=Hm;typeof s!="function"&&(s=s.EventEmitter);var o;e.__signal_exit_emitter__?o=e.__signal_exit_emitter__:(o=e.__signal_exit_emitter__=new s,o.count=0,o.emitted={}),o.infinite||(o.setMaxListeners(1/0),o.infinite=!0),Rt.exports=function(y,F){if(!t(wt.process))return function(){};n.equal(typeof y,"function","a callback must be provided for exit handler"),d===!1&&m();var E="exit";F&&F.alwaysLast&&(E="afterexit");var b=i(function(){o.removeListener(E,y),o.listeners("exit").length===0&&o.listeners("afterexit").length===0&&u()},"remove");return o.on(E,y),b};var u=i(function(){!d||!t(wt.process)||(d=!1,r.forEach(function(F){try{e.removeListener(F,c[F])}catch{}}),e.emit=f,e.reallyExit=h,o.count-=1)},"unload2");Rt.exports.unload=u;var l=i(function(F,E,b){o.emitted[F]||(o.emitted[F]=!0,o.emit(F,E,b))},"emit2"),c={};r.forEach(function(y){c[y]=i(function(){if(t(wt.process)){var E=e.listeners(y);E.length===o.count&&(u(),l("exit",null,y),l("afterexit",null,y),a&&y==="SIGHUP"&&(y="SIGINT"),e.kill(e.pid,y))}},"listener")}),Rt.exports.signals=function(){return r};var d=!1,m=i(function(){d||!t(wt.process)||(d=!0,o.count+=1,r=r.filter(function(F){try{return e.on(F,c[F]),!0}catch{return!1}}),e.emit=v,e.reallyExit=D)},"load2");Rt.exports.load=m;var h=e.reallyExit,D=i(function(F){t(wt.process)&&(e.exitCode=F||0,l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),h.call(e,e.exitCode))},"processReallyExit2"),f=e.emit,v=i(function(F,E){if(F==="exit"&&t(wt.process)){E!==void 0&&(e.exitCode=E);var b=f.apply(this,arguments);return l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),b}else return f.apply(this,arguments)},"processEmit2")}return Rt.exports}i(Qh,"requireSignalExit");var eD=Qh(),tD=St(eD);const nD=1e3*5,rD=i((e,t="SIGTERM",n={})=>{const r=e(t);return oD(e,t,n,r),r},"spawnedKill"),oD=i((e,t,n,r)=>{if(!aD(t,n,r))return;const a=iD(n),s=setTimeout(()=>{e("SIGKILL")},a);s.unref&&s.unref()},"setKillTimeout"),aD=i((e,{forceKillAfterTimeout:t},n)=>sD(e)&&t!==!1&&n,"shouldForceKill"),sD=i(e=>e===Gm.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM","isSigterm"),iD=i(({forceKillAfterTimeout:e=!0})=>{if(e===!0)return nD;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},"getForceKillAfterTimeout"),uD=i((e,t)=>{e.kill()&&(t.isCanceled=!0)},"spawnedCancel"),lD=i((e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},"timeoutKill"),cD=i((e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let a;const s=new Promise((u,l)=>{a=setTimeout(()=>{lD(e,n,l)},t)}),o=r.finally(()=>{clearTimeout(a)});return Promise.race([s,o])},"setupTimeout"),pD=i(({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},"validateTimeout"),dD=i(async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;const a=tD(()=>{e.kill()});return r.finally(()=>{a()})},"setExitHandler");function hu(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}i(hu,"isStream");function Du(e){return hu(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}i(Du,"isWritableStream");const mD=i(e=>e instanceof Um&&typeof e.then=="function","isExecaChildProcess"),ra=i((e,t,n)=>{if(typeof n=="string")return e[t].pipe(Jm(n)),e;if(Du(n))return e[t].pipe(n),e;if(!mD(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Du(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},"pipeToTarget"),fD=i(e=>{e.stdout!==null&&(e.pipeStdout=ra.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=ra.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=ra.bind(void 0,e,"all"))},"addPipeMethods");var on={exports:{}},oa,gu;function hD(){if(gu)return oa;gu=1;const{PassThrough:e}=No;return oa=i(t=>{t={...t};const{array:n}=t;let{encoding:r}=t;const a=r==="buffer";let s=!1;n?s=!(r||a):r=r||"utf8",a&&(r=null);const o=new e({objectMode:s});r&&o.setEncoding(r);let u=0;const l=[];return o.on("data",c=>{l.push(c),s?u=l.length:u+=c.length}),o.getBufferedValue=()=>n?l:a?Buffer.concat(l,u):l.join(""),o.getBufferedLength=()=>u,o},"bufferStream"),oa}i(hD,"requireBufferStream");var vu;function DD(){if(vu)return on.exports;vu=1;const{constants:e}=Ym,t=No,{promisify:n}=Xm,r=hD(),a=n(t.pipeline),u=class u extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};i(u,"MaxBufferError");let s=u;async function o(l,c){if(!l)throw new Error("Expected a stream");c={maxBuffer:1/0,...c};const{maxBuffer:d}=c,m=r(c);return await new Promise((h,D)=>{const f=i(v=>{v&&m.getBufferedLength()<=e.MAX_LENGTH&&(v.bufferedData=m.getBufferedValue()),D(v)},"rejectPromise");(async()=>{try{await a(l,m),h()}catch(v){f(v)}})(),m.on("data",()=>{m.getBufferedLength()>d&&f(new s)})}),m.getBufferedValue()}return i(o,"getStream"),on.exports=o,on.exports.buffer=(l,c)=>o(l,{...c,encoding:"buffer"}),on.exports.array=(l,c)=>o(l,{...c,array:!0}),on.exports.MaxBufferError=s,on.exports}i(DD,"requireGetStream");var gD=DD(),yu=St(gD),aa,_u;function vD(){if(_u)return aa;_u=1;const{PassThrough:e}=No;return aa=i(function(){var t=[],n=new e({objectMode:!0});return n.setMaxListeners(0),n.add=r,n.isEmpty=a,n.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),n;function r(o){return Array.isArray(o)?(o.forEach(r),this):(t.push(o),o.once("end",s.bind(null,o)),o.once("error",n.emit.bind(n,"error")),o.pipe(n,{end:!1}),this)}i(r,"add");function a(){return t.length==0}i(a,"isEmpty");function s(o){t=t.filter(function(u){return u!==o}),!t.length&&n.readable&&n.end()}i(s,"remove")},"mergeStream$1"),aa}i(vD,"requireMergeStream");var yD=vD(),_D=St(yD);const FD=i(e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},"validateInputOptions"),CD=i(({input:e,inputFile:t})=>typeof t!="string"?e:(FD(e),Km(t)),"getInput"),bD=i((e,t)=>{const n=CD(t);n!==void 0&&(hu(n)?n.pipe(e.stdin):e.stdin.end(n))},"handleInput"),ED=i((e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=_D();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},"makeAllStream"),sa=i(async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},"getBufferedData"),ia=i((e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?yu(e,{encoding:t,maxBuffer:r}):yu.buffer(e,{maxBuffer:r})},"getStreamPromise"),wD=i(async({stdout:e,stderr:t,all:n},{encoding:r,buffer:a,maxBuffer:s},o)=>{const u=ia(e,{encoding:r,buffer:a,maxBuffer:s}),l=ia(t,{encoding:r,buffer:a,maxBuffer:s}),c=ia(n,{encoding:r,buffer:a,maxBuffer:s*2});try{return await Promise.all([o,u,l,c])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},sa(e,u),sa(t,l),sa(n,c)])}},"getSpawnedResult"),AD=(async()=>{})().constructor.prototype,ID=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(AD,e)]),Fu=i((e,t)=>{for(const[n,r]of ID){const a=typeof t=="function"?(...s)=>Reflect.apply(r.value,t(),s):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:a})}},"mergePromise"),xD=i(e=>new Promise((t,n)=>{e.on("exit",(r,a)=>{t({exitCode:r,signal:a})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})}),"getSpawnedPromise"),Cu=i((e,t=[])=>Array.isArray(t)?[e,...t]:[e],"normalizeArgs"),kD=/^[\w.-]+$/,$D=/"/g,TD=i(e=>typeof e!="string"||kD.test(e)?e:`"${e.replace($D,'\\"')}"`,"escapeArg"),BD=i((e,t)=>Cu(e,t).join(" "),"joinCommand"),SD=i((e,t)=>Cu(e,t).map(n=>TD(n)).join(" "),"getEscapedCommand"),OD=Qm("execa").enabled,Jr=i((e,t)=>String(e).padStart(t,"0"),"padField"),RD=i(()=>{const e=new Date;return`${Jr(e.getHours(),2)}:${Jr(e.getMinutes(),2)}:${Jr(e.getSeconds(),2)}.${Jr(e.getMilliseconds(),3)}`},"getTimestamp"),ND=i((e,{verbose:t})=>{t&&ke.stderr.write(`[${RD()}] ${e}
27
- `)},"logCommand"),PD=1e3*1e3*100,MD=i(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:a})=>{const s=t?{...ke.env,...e}:e;return n?$h({env:s,cwd:r,execPath:a}):s},"getEnv"),jD=i((e,t,n={})=>{const r=wh._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:PD,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||ke.cwd(),execPath:ke.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:OD,...n},n.env=MD(n),n.stdio=Yh(n),ke.platform==="win32"&&nn.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},"handleArguments"),ua=i((e,t,n)=>typeof t!="string"&&!Lm.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?Ah(t):t,"handleOutput");function Ge(e,t,n){const r=jD(e,t,n),a=BD(e,t),s=SD(e,t);ND(s,r.options),pD(r.options);let o;try{o=ni.spawn(r.file,r.args,r.options)}catch(D){const f=new ni.ChildProcess,v=Promise.reject(du({error:D,stdout:"",stderr:"",all:"",command:a,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Fu(f,v),f}const u=xD(o),l=cD(o,r.options,u),c=dD(o,r.options,l),d={isCanceled:!1};o.kill=rD.bind(null,o.kill.bind(o)),o.cancel=uD.bind(null,o,d);const h=uu(i(async()=>{const[{error:D,exitCode:f,signal:v,timedOut:y},F,E,b]=await wD(o,r.options,c),w=ua(r.options,F),S=ua(r.options,E),k=ua(r.options,b);if(D||f!==0||v!==null){const C=du({error:D,exitCode:f,signal:v,stdout:w,stderr:S,all:k,command:a,escapedCommand:s,parsed:r,timedOut:y,isCanceled:d.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:o.killed});if(!r.options.reject)return C;throw C}return{command:a,escapedCommand:s,exitCode:0,stdout:w,stderr:S,all:k,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return bD(o,r.options),o.all=ED(o,r.options),fD(o),Fu(o,h),o}i(Ge,"execa");let Nt=!0;const an=typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{};let mr=0;if(an.process&&an.process.env&&an.process.stdout){const{FORCE_COLOR:e,NODE_DISABLE_COLORS:t,NO_COLOR:n,TERM:r,COLORTERM:a}=an.process.env;t||n||e==="0"?Nt=!1:e==="1"||e==="2"||e==="3"?Nt=!0:r==="dumb"?Nt=!1:"CI"in an.process.env&&["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(s=>s in an.process.env)?Nt=!0:Nt=process.stdout.isTTY,Nt&&(process.platform==="win32"||a&&(a==="truecolor"||a==="24bit")?mr=3:r&&(r.endsWith("-256color")||r.endsWith("256"))?mr=2:mr=1)}let la={enabled:Nt,supportLevel:mr};function sn(e,t,n=1){const r=`\x1B[${e}m`,a=`\x1B[${t}m`,s=new RegExp(`\\x1b\\[${t}m`,"g");return o=>la.enabled&&la.supportLevel>=n?r+(""+o).replace(s,r)+a:""+o}i(sn,"kolorist");const ca=sn(2,22),Kr=sn(30,39),pa=sn(31,39),ft=sn(32,39),da=sn(33,39),Yr=sn(46,49);var zD=Object.freeze({__proto__:null,bgCyan:Yr,black:Kr,dim:ca,green:ft,options:la,red:pa,yellow:da});const fr={};fr.write=async e=>{await navigator.clipboard.writeText(e)},fr.read=async()=>navigator.clipboard.readText(),fr.readSync=()=>{throw new Error("`.readSync()` is not supported in browsers!")},fr.writeSync=()=>{throw new Error("`.writeSync()` is not supported in browsers!")};async function bu(e){try{return process.platform==="darwin"?await Ge("pbcopy",{input:e}):await fr.write(e),!0}catch{return!1}}i(bu,"copyToClipboard");var ma,Eu;function qD(){if(Eu)return ma;Eu=1;const e="\x1B",t=`${e}[`,n="\x07",r={to(o,u){return u?`${t}${u+1};${o+1}H`:`${t}${o+1}G`},move(o,u){let l="";return o<0?l+=`${t}${-o}D`:o>0&&(l+=`${t}${o}C`),u<0?l+=`${t}${-u}A`:u>0&&(l+=`${t}${u}B`),l},up:i((o=1)=>`${t}${o}A`,"up"),down:i((o=1)=>`${t}${o}B`,"down"),forward:i((o=1)=>`${t}${o}C`,"forward"),backward:i((o=1)=>`${t}${o}D`,"backward"),nextLine:i((o=1)=>`${t}E`.repeat(o),"nextLine"),prevLine:i((o=1)=>`${t}F`.repeat(o),"prevLine"),left:`${t}G`,hide:`${t}?25l`,show:`${t}?25h`,save:`${e}7`,restore:`${e}8`},a={up:i((o=1)=>`${t}S`.repeat(o),"up"),down:i((o=1)=>`${t}T`.repeat(o),"down")},s={screen:`${t}2J`,up:i((o=1)=>`${t}1J`.repeat(o),"up"),down:i((o=1)=>`${t}J`.repeat(o),"down"),line:`${t}2K`,lineEnd:`${t}K`,lineStart:`${t}1K`,lines(o){let u="";for(let l=0;l<o;l++)u+=this.line+(l<o-1?r.up():"");return o&&(u+=r.left),u}};return ma={cursor:r,scroll:a,erase:s,beep:n},ma}i(qD,"requireSrc");var Me=qD(),Xr={exports:{}},wu;function ZD(){if(wu)return Xr.exports;wu=1;let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes("--no-color"))&&(!!n.FORCE_COLOR||t.includes("--color")||e.platform==="win32"||(e.stdout||{}).isTTY&&n.TERM!=="dumb"||!!n.CI),a=i((u,l,c=u)=>d=>{let m=""+d,h=m.indexOf(l,u.length);return~h?u+s(m,l,c,h)+l:u+m+l},"formatter"),s=i((u,l,c,d)=>{let m="",h=0;do m+=u.substring(h,d)+c,h=d+l.length,d=u.indexOf(l,h);while(~d);return m+u.substring(h)},"replaceClose"),o=i((u=r)=>{let l=u?a:()=>String;return{isColorSupported:u,reset:l("\x1B[0m","\x1B[0m"),bold:l("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:l("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:l("\x1B[3m","\x1B[23m"),underline:l("\x1B[4m","\x1B[24m"),inverse:l("\x1B[7m","\x1B[27m"),hidden:l("\x1B[8m","\x1B[28m"),strikethrough:l("\x1B[9m","\x1B[29m"),black:l("\x1B[30m","\x1B[39m"),red:l("\x1B[31m","\x1B[39m"),green:l("\x1B[32m","\x1B[39m"),yellow:l("\x1B[33m","\x1B[39m"),blue:l("\x1B[34m","\x1B[39m"),magenta:l("\x1B[35m","\x1B[39m"),cyan:l("\x1B[36m","\x1B[39m"),white:l("\x1B[37m","\x1B[39m"),gray:l("\x1B[90m","\x1B[39m"),bgBlack:l("\x1B[40m","\x1B[49m"),bgRed:l("\x1B[41m","\x1B[49m"),bgGreen:l("\x1B[42m","\x1B[49m"),bgYellow:l("\x1B[43m","\x1B[49m"),bgBlue:l("\x1B[44m","\x1B[49m"),bgMagenta:l("\x1B[45m","\x1B[49m"),bgCyan:l("\x1B[46m","\x1B[49m"),bgWhite:l("\x1B[47m","\x1B[49m"),blackBright:l("\x1B[90m","\x1B[39m"),redBright:l("\x1B[91m","\x1B[39m"),greenBright:l("\x1B[92m","\x1B[39m"),yellowBright:l("\x1B[93m","\x1B[39m"),blueBright:l("\x1B[94m","\x1B[39m"),magentaBright:l("\x1B[95m","\x1B[39m"),cyanBright:l("\x1B[96m","\x1B[39m"),whiteBright:l("\x1B[97m","\x1B[39m"),bgBlackBright:l("\x1B[100m","\x1B[49m"),bgRedBright:l("\x1B[101m","\x1B[49m"),bgGreenBright:l("\x1B[102m","\x1B[49m"),bgYellowBright:l("\x1B[103m","\x1B[49m"),bgBlueBright:l("\x1B[104m","\x1B[49m"),bgMagentaBright:l("\x1B[105m","\x1B[49m"),bgCyanBright:l("\x1B[106m","\x1B[49m"),bgWhiteBright:l("\x1B[107m","\x1B[49m")}},"createColors");return Xr.exports=o(),Xr.exports.createColors=o,Xr.exports}i(ZD,"requirePicocolors");var LD=ZD(),N=St(LD);function UD({onlyFirst:e=!1}={}){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}i(UD,"DD");const VD=UD();function Au(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(VD,"")}i(Au,"P$1");function Iu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(Iu,"L$1");var xu={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(r){var a=r.charCodeAt(0),s=r.length==2?r.charCodeAt(1):0,o=a;return 55296<=a&&a<=56319&&56320<=s&&s<=57343&&(a&=1023,s&=1023,o=a<<10|s,o+=65536),o==12288||65281<=o&&o<=65376||65504<=o&&o<=65510?"F":o==8361||65377<=o&&o<=65470||65474<=o&&o<=65479||65482<=o&&o<=65487||65490<=o&&o<=65495||65498<=o&&o<=65500||65512<=o&&o<=65518?"H":4352<=o&&o<=4447||4515<=o&&o<=4519||4602<=o&&o<=4607||9001<=o&&o<=9002||11904<=o&&o<=11929||11931<=o&&o<=12019||12032<=o&&o<=12245||12272<=o&&o<=12283||12289<=o&&o<=12350||12353<=o&&o<=12438||12441<=o&&o<=12543||12549<=o&&o<=12589||12593<=o&&o<=12686||12688<=o&&o<=12730||12736<=o&&o<=12771||12784<=o&&o<=12830||12832<=o&&o<=12871||12880<=o&&o<=13054||13056<=o&&o<=19903||19968<=o&&o<=42124||42128<=o&&o<=42182||43360<=o&&o<=43388||44032<=o&&o<=55203||55216<=o&&o<=55238||55243<=o&&o<=55291||63744<=o&&o<=64255||65040<=o&&o<=65049||65072<=o&&o<=65106||65108<=o&&o<=65126||65128<=o&&o<=65131||110592<=o&&o<=110593||127488<=o&&o<=127490||127504<=o&&o<=127546||127552<=o&&o<=127560||127568<=o&&o<=127569||131072<=o&&o<=194367||177984<=o&&o<=196605||196608<=o&&o<=262141?"W":32<=o&&o<=126||162<=o&&o<=163||165<=o&&o<=166||o==172||o==175||10214<=o&&o<=10221||10629<=o&&o<=10630?"Na":o==161||o==164||167<=o&&o<=168||o==170||173<=o&&o<=174||176<=o&&o<=180||182<=o&&o<=186||188<=o&&o<=191||o==198||o==208||215<=o&&o<=216||222<=o&&o<=225||o==230||232<=o&&o<=234||236<=o&&o<=237||o==240||242<=o&&o<=243||247<=o&&o<=250||o==252||o==254||o==257||o==273||o==275||o==283||294<=o&&o<=295||o==299||305<=o&&o<=307||o==312||319<=o&&o<=322||o==324||328<=o&&o<=331||o==333||338<=o&&o<=339||358<=o&&o<=359||o==363||o==462||o==464||o==466||o==468||o==470||o==472||o==474||o==476||o==593||o==609||o==708||o==711||713<=o&&o<=715||o==717||o==720||728<=o&&o<=731||o==733||o==735||768<=o&&o<=879||913<=o&&o<=929||931<=o&&o<=937||945<=o&&o<=961||963<=o&&o<=969||o==1025||1040<=o&&o<=1103||o==1105||o==8208||8211<=o&&o<=8214||8216<=o&&o<=8217||8220<=o&&o<=8221||8224<=o&&o<=8226||8228<=o&&o<=8231||o==8240||8242<=o&&o<=8243||o==8245||o==8251||o==8254||o==8308||o==8319||8321<=o&&o<=8324||o==8364||o==8451||o==8453||o==8457||o==8467||o==8470||8481<=o&&o<=8482||o==8486||o==8491||8531<=o&&o<=8532||8539<=o&&o<=8542||8544<=o&&o<=8555||8560<=o&&o<=8569||o==8585||8592<=o&&o<=8601||8632<=o&&o<=8633||o==8658||o==8660||o==8679||o==8704||8706<=o&&o<=8707||8711<=o&&o<=8712||o==8715||o==8719||o==8721||o==8725||o==8730||8733<=o&&o<=8736||o==8739||o==8741||8743<=o&&o<=8748||o==8750||8756<=o&&o<=8759||8764<=o&&o<=8765||o==8776||o==8780||o==8786||8800<=o&&o<=8801||8804<=o&&o<=8807||8810<=o&&o<=8811||8814<=o&&o<=8815||8834<=o&&o<=8835||8838<=o&&o<=8839||o==8853||o==8857||o==8869||o==8895||o==8978||9312<=o&&o<=9449||9451<=o&&o<=9547||9552<=o&&o<=9587||9600<=o&&o<=9615||9618<=o&&o<=9621||9632<=o&&o<=9633||9635<=o&&o<=9641||9650<=o&&o<=9651||9654<=o&&o<=9655||9660<=o&&o<=9661||9664<=o&&o<=9665||9670<=o&&o<=9672||o==9675||9678<=o&&o<=9681||9698<=o&&o<=9701||o==9711||9733<=o&&o<=9734||o==9737||9742<=o&&o<=9743||9748<=o&&o<=9749||o==9756||o==9758||o==9792||o==9794||9824<=o&&o<=9825||9827<=o&&o<=9829||9831<=o&&o<=9834||9836<=o&&o<=9837||o==9839||9886<=o&&o<=9887||9918<=o&&o<=9919||9924<=o&&o<=9933||9935<=o&&o<=9953||o==9955||9960<=o&&o<=9983||o==10045||o==10071||10102<=o&&o<=10111||11093<=o&&o<=11097||12872<=o&&o<=12879||57344<=o&&o<=63743||65024<=o&&o<=65039||o==65533||127232<=o&&o<=127242||127248<=o&&o<=127277||127280<=o&&o<=127337||127344<=o&&o<=127386||917760<=o&&o<=917999||983040<=o&&o<=1048573||1048576<=o&&o<=1114109?"A":"N"},t.characterLength=function(r){var a=this.eastAsianWidth(r);return a=="F"||a=="W"||a=="A"?2:1};function n(r){return r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}i(n,"t"),t.length=function(r){for(var a=n(r),s=0,o=0;o<a.length;o++)s=s+this.characterLength(a[o]);return s},t.slice=function(r,a,s){textLen=t.length(r),a=a||0,s=s||1,a<0&&(a=textLen+a),s<0&&(s=textLen+s);for(var o="",u=0,l=n(r),c=0;c<l.length;c++){var d=l[c],m=t.length(d);if(u>=a-(m==2?1:0))if(u+m<=s)o+=d;else break;u+=m}return o}})(xu);var GD=xu.exports;const WD=Iu(GD);var HD=i(function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},"FD");const JD=Iu(HD);function hr(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Au(e),e.length===0))return 0;e=e.replace(JD()," ");const n=t.ambiguousIsNarrow?1:2;let r=0;for(const a of e){const s=a.codePointAt(0);if(!(s<=31||s>=127&&s<=159||s>=768&&s<=879))switch(WD.eastAsianWidth(a)){case"F":case"W":r+=2;break;case"A":r+=n;break;default:r+=1}}return r}i(hr,"p");const fa=10,ku=i((e=0)=>t=>`\x1B[${t+e}m`,"N"),$u=i((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"I"),Tu=i((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"R"),Fe={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Fe.modifier);const KD=Object.keys(Fe.color),YD=Object.keys(Fe.bgColor);[...KD,...YD];function XD(){const e=new Map;for(const[t,n]of Object.entries(Fe)){for(const[r,a]of Object.entries(n))Fe[r]={open:`\x1B[${a[0]}m`,close:`\x1B[${a[1]}m`},n[r]=Fe[r],e.set(a[0],a[1]);Object.defineProperty(Fe,t,{value:n,enumerable:!1})}return Object.defineProperty(Fe,"codes",{value:e,enumerable:!1}),Fe.color.close="\x1B[39m",Fe.bgColor.close="\x1B[49m",Fe.color.ansi=ku(),Fe.color.ansi256=$u(),Fe.color.ansi16m=Tu(),Fe.bgColor.ansi=ku(fa),Fe.bgColor.ansi256=$u(fa),Fe.bgColor.ansi16m=Tu(fa),Object.defineProperties(Fe,{rgbToAnsi256:{value:i((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:i(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,a&255]},"value"),enumerable:!1},hexToAnsi256:{value:i(t=>Fe.rgbToAnsi256(...Fe.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:i(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,a;if(t>=232)n=((t-232)*10+8)/255,r=n,a=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,a=u%6/5}const s=Math.max(n,r,a)*2;if(s===0)return 30;let o=30+(Math.round(a)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(o+=60),o},"value"),enumerable:!1},rgbToAnsi:{value:i((t,n,r)=>Fe.ansi256ToAnsi(Fe.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:i(t=>Fe.ansi256ToAnsi(Fe.hexToAnsi256(t)),"value"),enumerable:!1}}),Fe}i(XD,"rD");const QD=XD(),Qr=new Set(["\x1B","\x9B"]),eg=39,ha="\x07",Bu="[",tg="]",Su="m",Da=`${tg}8;;`,Ou=i(e=>`${Qr.values().next().value}${Bu}${e}${Su}`,"z"),Ru=i(e=>`${Qr.values().next().value}${Da}${e}${ha}`,"K"),ng=i(e=>e.split(" ").map(t=>hr(t)),"aD"),ga=i((e,t,n)=>{const r=[...t];let a=!1,s=!1,o=hr(Au(e[e.length-1]));for(const[u,l]of r.entries()){const c=hr(l);if(o+c<=n?e[e.length-1]+=l:(e.push(l),o=0),Qr.has(l)&&(a=!0,s=r.slice(u+1).join("").startsWith(Da)),a){s?l===ha&&(a=!1,s=!1):l===Su&&(a=!1);continue}o+=c,o===n&&u<r.length-1&&(e.push(""),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"k$1"),rg=i(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(hr(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"hD"),og=i((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",a,s;const o=ng(e);let u=[""];for(const[c,d]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u[u.length-1].trimStart());let m=hr(u[u.length-1]);if(c!==0&&(m>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),m=0),(m>0||n.trim===!1)&&(u[u.length-1]+=" ",m++)),n.hard&&o[c]>t){const h=t-m,D=1+Math.floor((o[c]-h-1)/t);Math.floor((o[c]-1)/t)<D&&u.push(""),ga(u,d,t);continue}if(m+o[c]>t&&m>0&&o[c]>0){if(n.wordWrap===!1&&m<t){ga(u,d,t);continue}u.push("")}if(m+o[c]>t&&n.wordWrap===!1){ga(u,d,t);continue}u[u.length-1]+=d}n.trim!==!1&&(u=u.map(c=>rg(c)));const l=[...u.join(`
28
- `)];for(const[c,d]of l.entries()){if(r+=d,Qr.has(d)){const{groups:h}=new RegExp(`(?:\\${Bu}(?<code>\\d+)m|\\${Da}(?<uri>.*)${ha})`).exec(l.slice(c).join(""))||{groups:{}};if(h.code!==void 0){const D=Number.parseFloat(h.code);a=D===eg?void 0:D}else h.uri!==void 0&&(s=h.uri.length===0?void 0:h.uri)}const m=QD.codes.get(Number(a));l[c+1]===`
29
- `?(s&&(r+=Ru("")),a&&m&&(r+=Ou(m))):d===`
30
- `&&(a&&m&&(r+=Ou(a)),s&&(r+=Ru(s)))}return r},"lD");function Nu(e,t,n){return String(e).normalize().replace(/\r\n/g,`
26
+ `);return F?(r.originalMessage=r.message,r.message=b):r=new Error(b),r.shortMessage=E,r.command=o,r.escapedCommand=u,r.exitCode=s,r.signal=a,r.signalDescription=D,r.stdout=e,r.stderr=t,r.cwd=h,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=c,r.killed=d&&!l,r},"makeError"),Kr=["stdin","stdout","stderr"],Xh=i(e=>Kr.some(t=>e[t]!==void 0),"hasAlias"),Qh=i(e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Kr.map(r=>e[r]);if(Xh(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Kr.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,Kr.length);return Array.from({length:n},(r,a)=>t[a])},"normalizeStdio");var Rt={exports:{}},na={exports:{}},hu;function eD(){return hu||(hu=1,(function(e){e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")})(na)),na.exports}i(eD,"requireSignals");var Du;function tD(){if(Du)return Rt.exports;Du=1;var e=wt.process;const t=i(function(y){return y&&typeof y=="object"&&typeof y.removeListener=="function"&&typeof y.emit=="function"&&typeof y.reallyExit=="function"&&typeof y.listeners=="function"&&typeof y.kill=="function"&&typeof y.pid=="number"&&typeof y.on=="function"},"processOk");if(!t(e))Rt.exports=function(){return function(){}};else{var n=Hm,r=eD(),a=/^win/i.test(e.platform),s=Jm;typeof s!="function"&&(s=s.EventEmitter);var o;e.__signal_exit_emitter__?o=e.__signal_exit_emitter__:(o=e.__signal_exit_emitter__=new s,o.count=0,o.emitted={}),o.infinite||(o.setMaxListeners(1/0),o.infinite=!0),Rt.exports=function(y,F){if(!t(wt.process))return function(){};n.equal(typeof y,"function","a callback must be provided for exit handler"),d===!1&&m();var E="exit";F&&F.alwaysLast&&(E="afterexit");var b=i(function(){o.removeListener(E,y),o.listeners("exit").length===0&&o.listeners("afterexit").length===0&&u()},"remove");return o.on(E,y),b};var u=i(function(){!d||!t(wt.process)||(d=!1,r.forEach(function(F){try{e.removeListener(F,c[F])}catch{}}),e.emit=f,e.reallyExit=h,o.count-=1)},"unload2");Rt.exports.unload=u;var l=i(function(F,E,b){o.emitted[F]||(o.emitted[F]=!0,o.emit(F,E,b))},"emit2"),c={};r.forEach(function(y){c[y]=i(function(){if(t(wt.process)){var E=e.listeners(y);E.length===o.count&&(u(),l("exit",null,y),l("afterexit",null,y),a&&y==="SIGHUP"&&(y="SIGINT"),e.kill(e.pid,y))}},"listener")}),Rt.exports.signals=function(){return r};var d=!1,m=i(function(){d||!t(wt.process)||(d=!0,o.count+=1,r=r.filter(function(F){try{return e.on(F,c[F]),!0}catch{return!1}}),e.emit=v,e.reallyExit=D)},"load2");Rt.exports.load=m;var h=e.reallyExit,D=i(function(F){t(wt.process)&&(e.exitCode=F||0,l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),h.call(e,e.exitCode))},"processReallyExit2"),f=e.emit,v=i(function(F,E){if(F==="exit"&&t(wt.process)){E!==void 0&&(e.exitCode=E);var b=f.apply(this,arguments);return l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),b}else return f.apply(this,arguments)},"processEmit2")}return Rt.exports}i(tD,"requireSignalExit");var nD=tD(),rD=St(nD);const oD=1e3*5,aD=i((e,t="SIGTERM",n={})=>{const r=e(t);return sD(e,t,n,r),r},"spawnedKill"),sD=i((e,t,n,r)=>{if(!iD(t,n,r))return;const a=lD(n),s=setTimeout(()=>{e("SIGKILL")},a);s.unref&&s.unref()},"setKillTimeout"),iD=i((e,{forceKillAfterTimeout:t},n)=>uD(e)&&t!==!1&&n,"shouldForceKill"),uD=i(e=>e===Wm.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM","isSigterm"),lD=i(({forceKillAfterTimeout:e=!0})=>{if(e===!0)return oD;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},"getForceKillAfterTimeout"),cD=i((e,t)=>{e.kill()&&(t.isCanceled=!0)},"spawnedCancel"),pD=i((e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},"timeoutKill"),dD=i((e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let a;const s=new Promise((u,l)=>{a=setTimeout(()=>{pD(e,n,l)},t)}),o=r.finally(()=>{clearTimeout(a)});return Promise.race([s,o])},"setupTimeout"),mD=i(({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},"validateTimeout"),fD=i(async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;const a=rD(()=>{e.kill()});return r.finally(()=>{a()})},"setExitHandler");function gu(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}i(gu,"isStream");function vu(e){return gu(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}i(vu,"isWritableStream");const hD=i(e=>e instanceof Vm&&typeof e.then=="function","isExecaChildProcess"),ra=i((e,t,n)=>{if(typeof n=="string")return e[t].pipe(Km(n)),e;if(vu(n))return e[t].pipe(n),e;if(!hD(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!vu(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},"pipeToTarget"),DD=i(e=>{e.stdout!==null&&(e.pipeStdout=ra.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=ra.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=ra.bind(void 0,e,"all"))},"addPipeMethods");var on={exports:{}},oa,yu;function gD(){if(yu)return oa;yu=1;const{PassThrough:e}=Po;return oa=i(t=>{t={...t};const{array:n}=t;let{encoding:r}=t;const a=r==="buffer";let s=!1;n?s=!(r||a):r=r||"utf8",a&&(r=null);const o=new e({objectMode:s});r&&o.setEncoding(r);let u=0;const l=[];return o.on("data",c=>{l.push(c),s?u=l.length:u+=c.length}),o.getBufferedValue=()=>n?l:a?Buffer.concat(l,u):l.join(""),o.getBufferedLength=()=>u,o},"bufferStream"),oa}i(gD,"requireBufferStream");var _u;function vD(){if(_u)return on.exports;_u=1;const{constants:e}=Xm,t=Po,{promisify:n}=Qm,r=gD(),a=n(t.pipeline),u=class u extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};i(u,"MaxBufferError");let s=u;async function o(l,c){if(!l)throw new Error("Expected a stream");c={maxBuffer:1/0,...c};const{maxBuffer:d}=c,m=r(c);return await new Promise((h,D)=>{const f=i(v=>{v&&m.getBufferedLength()<=e.MAX_LENGTH&&(v.bufferedData=m.getBufferedValue()),D(v)},"rejectPromise");(async()=>{try{await a(l,m),h()}catch(v){f(v)}})(),m.on("data",()=>{m.getBufferedLength()>d&&f(new s)})}),m.getBufferedValue()}return i(o,"getStream"),on.exports=o,on.exports.buffer=(l,c)=>o(l,{...c,encoding:"buffer"}),on.exports.array=(l,c)=>o(l,{...c,array:!0}),on.exports.MaxBufferError=s,on.exports}i(vD,"requireGetStream");var yD=vD(),Fu=St(yD),aa,Cu;function _D(){if(Cu)return aa;Cu=1;const{PassThrough:e}=Po;return aa=i(function(){var t=[],n=new e({objectMode:!0});return n.setMaxListeners(0),n.add=r,n.isEmpty=a,n.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),n;function r(o){return Array.isArray(o)?(o.forEach(r),this):(t.push(o),o.once("end",s.bind(null,o)),o.once("error",n.emit.bind(n,"error")),o.pipe(n,{end:!1}),this)}i(r,"add");function a(){return t.length==0}i(a,"isEmpty");function s(o){t=t.filter(function(u){return u!==o}),!t.length&&n.readable&&n.end()}i(s,"remove")},"mergeStream$1"),aa}i(_D,"requireMergeStream");var FD=_D(),CD=St(FD);const bD=i(e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},"validateInputOptions"),ED=i(({input:e,inputFile:t})=>typeof t!="string"?e:(bD(e),Ym(t)),"getInput"),wD=i((e,t)=>{const n=ED(t);n!==void 0&&(gu(n)?n.pipe(e.stdin):e.stdin.end(n))},"handleInput"),AD=i((e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=CD();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},"makeAllStream"),sa=i(async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},"getBufferedData"),ia=i((e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?Fu(e,{encoding:t,maxBuffer:r}):Fu.buffer(e,{maxBuffer:r})},"getStreamPromise"),ID=i(async({stdout:e,stderr:t,all:n},{encoding:r,buffer:a,maxBuffer:s},o)=>{const u=ia(e,{encoding:r,buffer:a,maxBuffer:s}),l=ia(t,{encoding:r,buffer:a,maxBuffer:s}),c=ia(n,{encoding:r,buffer:a,maxBuffer:s*2});try{return await Promise.all([o,u,l,c])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},sa(e,u),sa(t,l),sa(n,c)])}},"getSpawnedResult"),xD=(async()=>{})().constructor.prototype,kD=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(xD,e)]),bu=i((e,t)=>{for(const[n,r]of kD){const a=typeof t=="function"?(...s)=>Reflect.apply(r.value,t(),s):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:a})}},"mergePromise"),$D=i(e=>new Promise((t,n)=>{e.on("exit",(r,a)=>{t({exitCode:r,signal:a})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})}),"getSpawnedPromise"),Eu=i((e,t=[])=>Array.isArray(t)?[e,...t]:[e],"normalizeArgs"),TD=/^[\w.-]+$/,BD=/"/g,SD=i(e=>typeof e!="string"||TD.test(e)?e:`"${e.replace(BD,'\\"')}"`,"escapeArg"),OD=i((e,t)=>Eu(e,t).join(" "),"joinCommand"),RD=i((e,t)=>Eu(e,t).map(n=>SD(n)).join(" "),"getEscapedCommand"),ND=tf("execa").enabled,Yr=i((e,t)=>String(e).padStart(t,"0"),"padField"),PD=i(()=>{const e=new Date;return`${Yr(e.getHours(),2)}:${Yr(e.getMinutes(),2)}:${Yr(e.getSeconds(),2)}.${Yr(e.getMilliseconds(),3)}`},"getTimestamp"),MD=i((e,{verbose:t})=>{t&&ke.stderr.write(`[${PD()}] ${e}
27
+ `)},"logCommand"),jD=1e3*1e3*100,zD=i(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:a})=>{const s=t?{...ke.env,...e}:e;return n?Bh({env:s,cwd:r,execPath:a}):s},"getEnv"),qD=i((e,t,n={})=>{const r=Ih._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:jD,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||ke.cwd(),execPath:ke.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:ND,...n},n.env=zD(n),n.stdio=Qh(n),ke.platform==="win32"&&nn.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},"handleArguments"),ua=i((e,t,n)=>typeof t!="string"&&!Lm.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?xh(t):t,"handleOutput");function Ge(e,t,n){const r=qD(e,t,n),a=OD(e,t),s=RD(e,t);MD(s,r.options),mD(r.options);let o;try{o=ri.spawn(r.file,r.args,r.options)}catch(D){const f=new ri.ChildProcess,v=Promise.reject(fu({error:D,stdout:"",stderr:"",all:"",command:a,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return bu(f,v),f}const u=$D(o),l=dD(o,r.options,u),c=fD(o,r.options,l),d={isCanceled:!1};o.kill=aD.bind(null,o.kill.bind(o)),o.cancel=cD.bind(null,o,d);const h=cu(i(async()=>{const[{error:D,exitCode:f,signal:v,timedOut:y},F,E,b]=await ID(o,r.options,c),w=ua(r.options,F),S=ua(r.options,E),k=ua(r.options,b);if(D||f!==0||v!==null){const C=fu({error:D,exitCode:f,signal:v,stdout:w,stderr:S,all:k,command:a,escapedCommand:s,parsed:r,timedOut:y,isCanceled:d.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:o.killed});if(!r.options.reject)return C;throw C}return{command:a,escapedCommand:s,exitCode:0,stdout:w,stderr:S,all:k,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return wD(o,r.options),o.all=AD(o,r.options),DD(o),bu(o,h),o}i(Ge,"execa");let Nt=!0;const an=typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{};let mr=0;if(an.process&&an.process.env&&an.process.stdout){const{FORCE_COLOR:e,NODE_DISABLE_COLORS:t,NO_COLOR:n,TERM:r,COLORTERM:a}=an.process.env;t||n||e==="0"?Nt=!1:e==="1"||e==="2"||e==="3"?Nt=!0:r==="dumb"?Nt=!1:"CI"in an.process.env&&["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(s=>s in an.process.env)?Nt=!0:Nt=process.stdout.isTTY,Nt&&(process.platform==="win32"||a&&(a==="truecolor"||a==="24bit")?mr=3:r&&(r.endsWith("-256color")||r.endsWith("256"))?mr=2:mr=1)}let la={enabled:Nt,supportLevel:mr};function sn(e,t,n=1){const r=`\x1B[${e}m`,a=`\x1B[${t}m`,s=new RegExp(`\\x1b\\[${t}m`,"g");return o=>la.enabled&&la.supportLevel>=n?r+(""+o).replace(s,r)+a:""+o}i(sn,"kolorist");const ca=sn(2,22),Xr=sn(30,39),pa=sn(31,39),ft=sn(32,39),da=sn(33,39),Qr=sn(46,49);var ZD=Object.freeze({__proto__:null,bgCyan:Qr,black:Xr,dim:ca,green:ft,options:la,red:pa,yellow:da});const fr={};fr.write=async e=>{await navigator.clipboard.writeText(e)},fr.read=async()=>navigator.clipboard.readText(),fr.readSync=()=>{throw new Error("`.readSync()` is not supported in browsers!")},fr.writeSync=()=>{throw new Error("`.writeSync()` is not supported in browsers!")};async function wu(e){try{return process.platform==="darwin"?await Ge("pbcopy",{input:e}):await fr.write(e),!0}catch{return!1}}i(wu,"copyToClipboard");var ma,Au;function UD(){if(Au)return ma;Au=1;const e="\x1B",t=`${e}[`,n="\x07",r={to(o,u){return u?`${t}${u+1};${o+1}H`:`${t}${o+1}G`},move(o,u){let l="";return o<0?l+=`${t}${-o}D`:o>0&&(l+=`${t}${o}C`),u<0?l+=`${t}${-u}A`:u>0&&(l+=`${t}${u}B`),l},up:i((o=1)=>`${t}${o}A`,"up"),down:i((o=1)=>`${t}${o}B`,"down"),forward:i((o=1)=>`${t}${o}C`,"forward"),backward:i((o=1)=>`${t}${o}D`,"backward"),nextLine:i((o=1)=>`${t}E`.repeat(o),"nextLine"),prevLine:i((o=1)=>`${t}F`.repeat(o),"prevLine"),left:`${t}G`,hide:`${t}?25l`,show:`${t}?25h`,save:`${e}7`,restore:`${e}8`},a={up:i((o=1)=>`${t}S`.repeat(o),"up"),down:i((o=1)=>`${t}T`.repeat(o),"down")},s={screen:`${t}2J`,up:i((o=1)=>`${t}1J`.repeat(o),"up"),down:i((o=1)=>`${t}J`.repeat(o),"down"),line:`${t}2K`,lineEnd:`${t}K`,lineStart:`${t}1K`,lines(o){let u="";for(let l=0;l<o;l++)u+=this.line+(l<o-1?r.up():"");return o&&(u+=r.left),u}};return ma={cursor:r,scroll:a,erase:s,beep:n},ma}i(UD,"requireSrc");var Me=UD(),eo={exports:{}},Iu;function LD(){if(Iu)return eo.exports;Iu=1;let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes("--no-color"))&&(!!n.FORCE_COLOR||t.includes("--color")||e.platform==="win32"||(e.stdout||{}).isTTY&&n.TERM!=="dumb"||!!n.CI),a=i((u,l,c=u)=>d=>{let m=""+d,h=m.indexOf(l,u.length);return~h?u+s(m,l,c,h)+l:u+m+l},"formatter"),s=i((u,l,c,d)=>{let m="",h=0;do m+=u.substring(h,d)+c,h=d+l.length,d=u.indexOf(l,h);while(~d);return m+u.substring(h)},"replaceClose"),o=i((u=r)=>{let l=u?a:()=>String;return{isColorSupported:u,reset:l("\x1B[0m","\x1B[0m"),bold:l("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:l("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:l("\x1B[3m","\x1B[23m"),underline:l("\x1B[4m","\x1B[24m"),inverse:l("\x1B[7m","\x1B[27m"),hidden:l("\x1B[8m","\x1B[28m"),strikethrough:l("\x1B[9m","\x1B[29m"),black:l("\x1B[30m","\x1B[39m"),red:l("\x1B[31m","\x1B[39m"),green:l("\x1B[32m","\x1B[39m"),yellow:l("\x1B[33m","\x1B[39m"),blue:l("\x1B[34m","\x1B[39m"),magenta:l("\x1B[35m","\x1B[39m"),cyan:l("\x1B[36m","\x1B[39m"),white:l("\x1B[37m","\x1B[39m"),gray:l("\x1B[90m","\x1B[39m"),bgBlack:l("\x1B[40m","\x1B[49m"),bgRed:l("\x1B[41m","\x1B[49m"),bgGreen:l("\x1B[42m","\x1B[49m"),bgYellow:l("\x1B[43m","\x1B[49m"),bgBlue:l("\x1B[44m","\x1B[49m"),bgMagenta:l("\x1B[45m","\x1B[49m"),bgCyan:l("\x1B[46m","\x1B[49m"),bgWhite:l("\x1B[47m","\x1B[49m"),blackBright:l("\x1B[90m","\x1B[39m"),redBright:l("\x1B[91m","\x1B[39m"),greenBright:l("\x1B[92m","\x1B[39m"),yellowBright:l("\x1B[93m","\x1B[39m"),blueBright:l("\x1B[94m","\x1B[39m"),magentaBright:l("\x1B[95m","\x1B[39m"),cyanBright:l("\x1B[96m","\x1B[39m"),whiteBright:l("\x1B[97m","\x1B[39m"),bgBlackBright:l("\x1B[100m","\x1B[49m"),bgRedBright:l("\x1B[101m","\x1B[49m"),bgGreenBright:l("\x1B[102m","\x1B[49m"),bgYellowBright:l("\x1B[103m","\x1B[49m"),bgBlueBright:l("\x1B[104m","\x1B[49m"),bgMagentaBright:l("\x1B[105m","\x1B[49m"),bgCyanBright:l("\x1B[106m","\x1B[49m"),bgWhiteBright:l("\x1B[107m","\x1B[49m")}},"createColors");return eo.exports=o(),eo.exports.createColors=o,eo.exports}i(LD,"requirePicocolors");var VD=LD(),N=St(VD);function GD({onlyFirst:e=!1}={}){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}i(GD,"DD");const WD=GD();function xu(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(WD,"")}i(xu,"P$1");function ku(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(ku,"L$1");var $u={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(r){var a=r.charCodeAt(0),s=r.length==2?r.charCodeAt(1):0,o=a;return 55296<=a&&a<=56319&&56320<=s&&s<=57343&&(a&=1023,s&=1023,o=a<<10|s,o+=65536),o==12288||65281<=o&&o<=65376||65504<=o&&o<=65510?"F":o==8361||65377<=o&&o<=65470||65474<=o&&o<=65479||65482<=o&&o<=65487||65490<=o&&o<=65495||65498<=o&&o<=65500||65512<=o&&o<=65518?"H":4352<=o&&o<=4447||4515<=o&&o<=4519||4602<=o&&o<=4607||9001<=o&&o<=9002||11904<=o&&o<=11929||11931<=o&&o<=12019||12032<=o&&o<=12245||12272<=o&&o<=12283||12289<=o&&o<=12350||12353<=o&&o<=12438||12441<=o&&o<=12543||12549<=o&&o<=12589||12593<=o&&o<=12686||12688<=o&&o<=12730||12736<=o&&o<=12771||12784<=o&&o<=12830||12832<=o&&o<=12871||12880<=o&&o<=13054||13056<=o&&o<=19903||19968<=o&&o<=42124||42128<=o&&o<=42182||43360<=o&&o<=43388||44032<=o&&o<=55203||55216<=o&&o<=55238||55243<=o&&o<=55291||63744<=o&&o<=64255||65040<=o&&o<=65049||65072<=o&&o<=65106||65108<=o&&o<=65126||65128<=o&&o<=65131||110592<=o&&o<=110593||127488<=o&&o<=127490||127504<=o&&o<=127546||127552<=o&&o<=127560||127568<=o&&o<=127569||131072<=o&&o<=194367||177984<=o&&o<=196605||196608<=o&&o<=262141?"W":32<=o&&o<=126||162<=o&&o<=163||165<=o&&o<=166||o==172||o==175||10214<=o&&o<=10221||10629<=o&&o<=10630?"Na":o==161||o==164||167<=o&&o<=168||o==170||173<=o&&o<=174||176<=o&&o<=180||182<=o&&o<=186||188<=o&&o<=191||o==198||o==208||215<=o&&o<=216||222<=o&&o<=225||o==230||232<=o&&o<=234||236<=o&&o<=237||o==240||242<=o&&o<=243||247<=o&&o<=250||o==252||o==254||o==257||o==273||o==275||o==283||294<=o&&o<=295||o==299||305<=o&&o<=307||o==312||319<=o&&o<=322||o==324||328<=o&&o<=331||o==333||338<=o&&o<=339||358<=o&&o<=359||o==363||o==462||o==464||o==466||o==468||o==470||o==472||o==474||o==476||o==593||o==609||o==708||o==711||713<=o&&o<=715||o==717||o==720||728<=o&&o<=731||o==733||o==735||768<=o&&o<=879||913<=o&&o<=929||931<=o&&o<=937||945<=o&&o<=961||963<=o&&o<=969||o==1025||1040<=o&&o<=1103||o==1105||o==8208||8211<=o&&o<=8214||8216<=o&&o<=8217||8220<=o&&o<=8221||8224<=o&&o<=8226||8228<=o&&o<=8231||o==8240||8242<=o&&o<=8243||o==8245||o==8251||o==8254||o==8308||o==8319||8321<=o&&o<=8324||o==8364||o==8451||o==8453||o==8457||o==8467||o==8470||8481<=o&&o<=8482||o==8486||o==8491||8531<=o&&o<=8532||8539<=o&&o<=8542||8544<=o&&o<=8555||8560<=o&&o<=8569||o==8585||8592<=o&&o<=8601||8632<=o&&o<=8633||o==8658||o==8660||o==8679||o==8704||8706<=o&&o<=8707||8711<=o&&o<=8712||o==8715||o==8719||o==8721||o==8725||o==8730||8733<=o&&o<=8736||o==8739||o==8741||8743<=o&&o<=8748||o==8750||8756<=o&&o<=8759||8764<=o&&o<=8765||o==8776||o==8780||o==8786||8800<=o&&o<=8801||8804<=o&&o<=8807||8810<=o&&o<=8811||8814<=o&&o<=8815||8834<=o&&o<=8835||8838<=o&&o<=8839||o==8853||o==8857||o==8869||o==8895||o==8978||9312<=o&&o<=9449||9451<=o&&o<=9547||9552<=o&&o<=9587||9600<=o&&o<=9615||9618<=o&&o<=9621||9632<=o&&o<=9633||9635<=o&&o<=9641||9650<=o&&o<=9651||9654<=o&&o<=9655||9660<=o&&o<=9661||9664<=o&&o<=9665||9670<=o&&o<=9672||o==9675||9678<=o&&o<=9681||9698<=o&&o<=9701||o==9711||9733<=o&&o<=9734||o==9737||9742<=o&&o<=9743||9748<=o&&o<=9749||o==9756||o==9758||o==9792||o==9794||9824<=o&&o<=9825||9827<=o&&o<=9829||9831<=o&&o<=9834||9836<=o&&o<=9837||o==9839||9886<=o&&o<=9887||9918<=o&&o<=9919||9924<=o&&o<=9933||9935<=o&&o<=9953||o==9955||9960<=o&&o<=9983||o==10045||o==10071||10102<=o&&o<=10111||11093<=o&&o<=11097||12872<=o&&o<=12879||57344<=o&&o<=63743||65024<=o&&o<=65039||o==65533||127232<=o&&o<=127242||127248<=o&&o<=127277||127280<=o&&o<=127337||127344<=o&&o<=127386||917760<=o&&o<=917999||983040<=o&&o<=1048573||1048576<=o&&o<=1114109?"A":"N"},t.characterLength=function(r){var a=this.eastAsianWidth(r);return a=="F"||a=="W"||a=="A"?2:1};function n(r){return r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}i(n,"t"),t.length=function(r){for(var a=n(r),s=0,o=0;o<a.length;o++)s=s+this.characterLength(a[o]);return s},t.slice=function(r,a,s){textLen=t.length(r),a=a||0,s=s||1,a<0&&(a=textLen+a),s<0&&(s=textLen+s);for(var o="",u=0,l=n(r),c=0;c<l.length;c++){var d=l[c],m=t.length(d);if(u>=a-(m==2?1:0))if(u+m<=s)o+=d;else break;u+=m}return o}})($u);var HD=$u.exports;const JD=ku(HD);var KD=i(function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},"FD");const YD=ku(KD);function hr(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=xu(e),e.length===0))return 0;e=e.replace(YD()," ");const n=t.ambiguousIsNarrow?1:2;let r=0;for(const a of e){const s=a.codePointAt(0);if(!(s<=31||s>=127&&s<=159||s>=768&&s<=879))switch(JD.eastAsianWidth(a)){case"F":case"W":r+=2;break;case"A":r+=n;break;default:r+=1}}return r}i(hr,"p");const fa=10,Tu=i((e=0)=>t=>`\x1B[${t+e}m`,"N"),Bu=i((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"I"),Su=i((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"R"),Fe={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Fe.modifier);const XD=Object.keys(Fe.color),QD=Object.keys(Fe.bgColor);[...XD,...QD];function eg(){const e=new Map;for(const[t,n]of Object.entries(Fe)){for(const[r,a]of Object.entries(n))Fe[r]={open:`\x1B[${a[0]}m`,close:`\x1B[${a[1]}m`},n[r]=Fe[r],e.set(a[0],a[1]);Object.defineProperty(Fe,t,{value:n,enumerable:!1})}return Object.defineProperty(Fe,"codes",{value:e,enumerable:!1}),Fe.color.close="\x1B[39m",Fe.bgColor.close="\x1B[49m",Fe.color.ansi=Tu(),Fe.color.ansi256=Bu(),Fe.color.ansi16m=Su(),Fe.bgColor.ansi=Tu(fa),Fe.bgColor.ansi256=Bu(fa),Fe.bgColor.ansi16m=Su(fa),Object.defineProperties(Fe,{rgbToAnsi256:{value:i((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:i(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,a&255]},"value"),enumerable:!1},hexToAnsi256:{value:i(t=>Fe.rgbToAnsi256(...Fe.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:i(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,a;if(t>=232)n=((t-232)*10+8)/255,r=n,a=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,a=u%6/5}const s=Math.max(n,r,a)*2;if(s===0)return 30;let o=30+(Math.round(a)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(o+=60),o},"value"),enumerable:!1},rgbToAnsi:{value:i((t,n,r)=>Fe.ansi256ToAnsi(Fe.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:i(t=>Fe.ansi256ToAnsi(Fe.hexToAnsi256(t)),"value"),enumerable:!1}}),Fe}i(eg,"rD");const tg=eg(),to=new Set(["\x1B","\x9B"]),ng=39,ha="\x07",Ou="[",rg="]",Ru="m",Da=`${rg}8;;`,Nu=i(e=>`${to.values().next().value}${Ou}${e}${Ru}`,"z"),Pu=i(e=>`${to.values().next().value}${Da}${e}${ha}`,"K"),og=i(e=>e.split(" ").map(t=>hr(t)),"aD"),ga=i((e,t,n)=>{const r=[...t];let a=!1,s=!1,o=hr(xu(e[e.length-1]));for(const[u,l]of r.entries()){const c=hr(l);if(o+c<=n?e[e.length-1]+=l:(e.push(l),o=0),to.has(l)&&(a=!0,s=r.slice(u+1).join("").startsWith(Da)),a){s?l===ha&&(a=!1,s=!1):l===Ru&&(a=!1);continue}o+=c,o===n&&u<r.length-1&&(e.push(""),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"k$1"),ag=i(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(hr(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"hD"),sg=i((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",a,s;const o=og(e);let u=[""];for(const[c,d]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u[u.length-1].trimStart());let m=hr(u[u.length-1]);if(c!==0&&(m>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),m=0),(m>0||n.trim===!1)&&(u[u.length-1]+=" ",m++)),n.hard&&o[c]>t){const h=t-m,D=1+Math.floor((o[c]-h-1)/t);Math.floor((o[c]-1)/t)<D&&u.push(""),ga(u,d,t);continue}if(m+o[c]>t&&m>0&&o[c]>0){if(n.wordWrap===!1&&m<t){ga(u,d,t);continue}u.push("")}if(m+o[c]>t&&n.wordWrap===!1){ga(u,d,t);continue}u[u.length-1]+=d}n.trim!==!1&&(u=u.map(c=>ag(c)));const l=[...u.join(`
28
+ `)];for(const[c,d]of l.entries()){if(r+=d,to.has(d)){const{groups:h}=new RegExp(`(?:\\${Ou}(?<code>\\d+)m|\\${Da}(?<uri>.*)${ha})`).exec(l.slice(c).join(""))||{groups:{}};if(h.code!==void 0){const D=Number.parseFloat(h.code);a=D===ng?void 0:D}else h.uri!==void 0&&(s=h.uri.length===0?void 0:h.uri)}const m=tg.codes.get(Number(a));l[c+1]===`
29
+ `?(s&&(r+=Pu("")),a&&m&&(r+=Nu(m))):d===`
30
+ `&&(a&&m&&(r+=Nu(a)),s&&(r+=Pu(s)))}return r},"lD");function Mu(e,t,n){return String(e).normalize().replace(/\r\n/g,`
31
31
  `).split(`
32
- `).map(r=>og(r,t,n)).join(`
33
- `)}i(Nu,"Y$1");const ag=["up","down","left","right","space","enter","cancel"],eo={actions:new Set(ag),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]])};function va(e,t){if(typeof e=="string")return eo.aliases.get(e)===t;for(const n of e)if(n!==void 0&&va(n,t))return!0;return!1}i(va,"$");function sg(e,t){if(e===t)return;const n=e.split(`
32
+ `).map(r=>sg(r,t,n)).join(`
33
+ `)}i(Mu,"Y$1");const ig=["up","down","left","right","space","enter","cancel"],no={actions:new Set(ig),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]])};function va(e,t){if(typeof e=="string")return no.aliases.get(e)===t;for(const n of e)if(n!==void 0&&va(n,t))return!0;return!1}i(va,"$");function ug(e,t){if(e===t)return;const n=e.split(`
34
34
  `),r=t.split(`
35
- `),a=[];for(let s=0;s<Math.max(n.length,r.length);s++)n[s]!==r[s]&&a.push(s);return a}i(sg,"BD");const ig=globalThis.process.platform.startsWith("win"),ya=Symbol("clack:cancel");function Dr(e){return e===ya}i(Dr,"pD");function to(e,t){const n=e;n.isTTY&&n.setRawMode(t)}i(to,"m");function ug({input:e=ri,output:t=oi,overwrite:n=!0,hideCursor:r=!0}={}){const a=jr.createInterface({input:e,output:t,prompt:"",tabSize:1});jr.emitKeypressEvents(e,a),e.isTTY&&e.setRawMode(!0);const s=i((o,{name:u,sequence:l})=>{const c=String(o);if(va([c,u,l],"cancel")){r&&t.write(Me.cursor.show),process.exit(0);return}if(!n)return;const d=u==="return"?0:-1,m=u==="return"?-1:0;jr.moveCursor(t,d,m,()=>{jr.clearLine(t,1,()=>{e.once("keypress",s)})})},"i");return r&&t.write(Me.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),r&&t.write(Me.cursor.show),e.isTTY&&!ig&&e.setRawMode(!1),a.terminal=!1,a.close()}}i(ug,"fD");var lg=Object.defineProperty,cg=i((e,t,n)=>t in e?lg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"vD"),We=i((e,t,n)=>(cg(e,typeof t!="symbol"?t+"":t,n),n),"h");const Os=class Os{constructor(t,n=!0){We(this,"input"),We(this,"output"),We(this,"_abortSignal"),We(this,"rl"),We(this,"opts"),We(this,"_render"),We(this,"_track",!1),We(this,"_prevFrame",""),We(this,"_subscribers",new Map),We(this,"_cursor",0),We(this,"state","initial"),We(this,"error",""),We(this,"value");const{input:r=ri,output:a=oi,render:s,signal:o,...u}=t;this.opts=u,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=n,this._abortSignal=o,this.input=r,this.output=a}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){const r=this._subscribers.get(t)??[];r.push(n),this._subscribers.set(t,r)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){const r=this._subscribers.get(t)??[],a=[];for(const s of r)s.cb(...n),s.once&&a.push(()=>r.splice(r.indexOf(s),1));for(const s of a)s()}prompt(){return new Promise((t,n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(ya);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}const r=new ef;r._write=(a,s,o)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,""),this._cursor=this.rl?.cursor??0,this.emit("value",this.value)),o()},this.input.pipe(r),this.rl=ii.createInterface({input:this.input,output:r,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),ii.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),to(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Me.cursor.show),this.output.off("resize",this.render),to(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Me.cursor.show),this.output.off("resize",this.render),to(this.input,!1),t(ya)})})}onKeypress(t,n){if(this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&eo.aliases.has(n.name)&&this.emit("cursor",eo.aliases.get(n.name)),eo.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),t===" "&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),t&&this.emit("key",t.toLowerCase()),n?.name==="return"){if(this.opts.validate){const r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.value))}this.state!=="error"&&(this.state="submit")}va([t,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
36
- `),to(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){const t=Nu(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
37
- `).length-1;this.output.write(Me.cursor.move(-999,t*-1))}render(){const t=Nu(this._render(this)??"",process.stdout.columns,{hard:!0});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Me.cursor.hide);else{const n=sg(this._prevFrame,t);if(this.restoreCursor(),n&&n?.length===1){const r=n[0];this.output.write(Me.cursor.move(0,r)),this.output.write(Me.erase.lines(1));const a=t.split(`
35
+ `),a=[];for(let s=0;s<Math.max(n.length,r.length);s++)n[s]!==r[s]&&a.push(s);return a}i(ug,"BD");const lg=globalThis.process.platform.startsWith("win"),ya=Symbol("clack:cancel");function Dr(e){return e===ya}i(Dr,"pD");function ro(e,t){const n=e;n.isTTY&&n.setRawMode(t)}i(ro,"m");function cg({input:e=oi,output:t=ai,overwrite:n=!0,hideCursor:r=!0}={}){const a=zr.createInterface({input:e,output:t,prompt:"",tabSize:1});zr.emitKeypressEvents(e,a),e.isTTY&&e.setRawMode(!0);const s=i((o,{name:u,sequence:l})=>{const c=String(o);if(va([c,u,l],"cancel")){r&&t.write(Me.cursor.show),process.exit(0);return}if(!n)return;const d=u==="return"?0:-1,m=u==="return"?-1:0;zr.moveCursor(t,d,m,()=>{zr.clearLine(t,1,()=>{e.once("keypress",s)})})},"i");return r&&t.write(Me.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),r&&t.write(Me.cursor.show),e.isTTY&&!lg&&e.setRawMode(!1),a.terminal=!1,a.close()}}i(cg,"fD");var pg=Object.defineProperty,dg=i((e,t,n)=>t in e?pg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"vD"),We=i((e,t,n)=>(dg(e,typeof t!="symbol"?t+"":t,n),n),"h");const Os=class Os{constructor(t,n=!0){We(this,"input"),We(this,"output"),We(this,"_abortSignal"),We(this,"rl"),We(this,"opts"),We(this,"_render"),We(this,"_track",!1),We(this,"_prevFrame",""),We(this,"_subscribers",new Map),We(this,"_cursor",0),We(this,"state","initial"),We(this,"error",""),We(this,"value");const{input:r=oi,output:a=ai,render:s,signal:o,...u}=t;this.opts=u,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=n,this._abortSignal=o,this.input=r,this.output=a}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){const r=this._subscribers.get(t)??[];r.push(n),this._subscribers.set(t,r)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){const r=this._subscribers.get(t)??[],a=[];for(const s of r)s.cb(...n),s.once&&a.push(()=>r.splice(r.indexOf(s),1));for(const s of a)s()}prompt(){return new Promise((t,n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(ya);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}const r=new nf;r._write=(a,s,o)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,""),this._cursor=this.rl?.cursor??0,this.emit("value",this.value)),o()},this.input.pipe(r),this.rl=li.createInterface({input:this.input,output:r,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),li.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),ro(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Me.cursor.show),this.output.off("resize",this.render),ro(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Me.cursor.show),this.output.off("resize",this.render),ro(this.input,!1),t(ya)})})}onKeypress(t,n){if(this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&no.aliases.has(n.name)&&this.emit("cursor",no.aliases.get(n.name)),no.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),t===" "&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),t&&this.emit("key",t.toLowerCase()),n?.name==="return"){if(this.opts.validate){const r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.value))}this.state!=="error"&&(this.state="submit")}va([t,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
36
+ `),ro(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){const t=Mu(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
37
+ `).length-1;this.output.write(Me.cursor.move(-999,t*-1))}render(){const t=Mu(this._render(this)??"",process.stdout.columns,{hard:!0});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Me.cursor.hide);else{const n=ug(this._prevFrame,t);if(this.restoreCursor(),n&&n?.length===1){const r=n[0];this.output.write(Me.cursor.move(0,r)),this.output.write(Me.erase.lines(1));const a=t.split(`
38
38
  `);this.output.write(a[r]),this._prevFrame=t,this.output.write(Me.cursor.move(0,a.length-r-1));return}if(n&&n?.length>1){const r=n[0];this.output.write(Me.cursor.move(0,r)),this.output.write(Me.erase.down());const a=t.split(`
39
39
  `).slice(r);this.output.write(a.join(`
40
- `)),this._prevFrame=t;return}this.output.write(Me.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};i(Os,"x");let un=Os;const Rs=class Rs extends un{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(Me.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};i(Rs,"dD");let _a=Rs;var pg=Object.defineProperty,dg=i((e,t,n)=>t in e?pg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"jD"),Pu=i((e,t,n)=>(dg(e,typeof t!="symbol"?t+"":t,n),n),"U");const Ns=class Ns extends un{constructor({mask:t,...n}){super(n),Pu(this,"valueWithCursor",""),Pu(this,"_mask","\u2022"),this._mask=t??"\u2022",this.on("finalize",()=>{this.valueWithCursor=this.masked}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${N.inverse(N.hidden("_"))}`;else{const r=this.masked.slice(0,this.cursor),a=this.masked.slice(this.cursor);this.valueWithCursor=`${r}${N.inverse(a[0])}${a.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}};i(Ns,"MD");let Fa=Ns;var mg=Object.defineProperty,fg=i((e,t,n)=>t in e?mg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"PD"),Mu=i((e,t,n)=>(fg(e,typeof t!="symbol"?t+"":t,n),n),"J");const Ps=class Ps extends un{constructor(t){super(t,!1),Mu(this,"options"),Mu(this,"cursor",0),this.options=t.options,this.cursor=this.options.findIndex(({value:n})=>n===t.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}};i(Ps,"LD");let Ca=Ps;const Ms=class Ms extends un{get valueWithCursor(){if(this.state==="submit")return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;const t=this.value.slice(0,this.cursor),[n,...r]=this.value.slice(this.cursor);return`${t}${N.inverse(n)}${r.join("")}`}get cursor(){return this._cursor}constructor(t){super(t),this.on("finalize",()=>{this.value||(this.value=t.defaultValue)})}};i(Ms,"RD");let ba=Ms;function hg(){return ke.platform!=="win32"?ke.env.TERM!=="linux":!!ke.env.CI||!!ke.env.WT_SESSION||!!ke.env.TERMINUS_SUBLIME||ke.env.ConEmuTask==="{cmd::Cmder}"||ke.env.TERM_PROGRAM==="Terminus-Sublime"||ke.env.TERM_PROGRAM==="vscode"||ke.env.TERM==="xterm-256color"||ke.env.TERM==="alacritty"||ke.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}i(hg,"ce");const Ea=hg(),ht=i((e,t)=>Ea?e:t,"u"),Dg=ht("\u25C6","*"),ju=ht("\u25A0","x"),zu=ht("\u25B2","x"),qu=ht("\u25C7","o"),gg=ht("\u250C","T"),fe=ht("\u2502","|"),Pt=ht("\u2514","\u2014"),wa=ht("\u25CF",">"),Aa=ht("\u25CB"," "),vg=ht("\u25AA","\u2022"),no=i(e=>{switch(e){case"initial":case"active":return N.cyan(Dg);case"cancel":return N.red(ju);case"error":return N.yellow(zu);case"submit":return N.green(qu)}},"b"),yg=i(e=>{const{cursor:t,options:n,style:r}=e,a=e.maxItems??Number.POSITIVE_INFINITY,s=Math.max(process.stdout.rows-4,0),o=Math.min(s,Math.max(a,5));let u=0;t>=u+o-3?u=Math.max(Math.min(t-o+3,n.length-o),0):t<u+2&&(u=Math.max(t-2,0));const l=o<n.length&&u>0,c=o<n.length&&u+o<n.length;return n.slice(u,u+o).map((d,m,h)=>{const D=m===0&&l,f=m===h.length-1&&c;return D||f?N.dim("..."):r(d,m+u===t)})},"G"),Zu=i(e=>new ba({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){const t=`${N.gray(fe)}
41
- ${no(this.state)} ${e.message}
40
+ `)),this._prevFrame=t;return}this.output.write(Me.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};i(Os,"x");let un=Os;const Rs=class Rs extends un{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(Me.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};i(Rs,"dD");let _a=Rs;var mg=Object.defineProperty,fg=i((e,t,n)=>t in e?mg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"jD"),ju=i((e,t,n)=>(fg(e,typeof t!="symbol"?t+"":t,n),n),"U");const Ns=class Ns extends un{constructor({mask:t,...n}){super(n),ju(this,"valueWithCursor",""),ju(this,"_mask","\u2022"),this._mask=t??"\u2022",this.on("finalize",()=>{this.valueWithCursor=this.masked}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${N.inverse(N.hidden("_"))}`;else{const r=this.masked.slice(0,this.cursor),a=this.masked.slice(this.cursor);this.valueWithCursor=`${r}${N.inverse(a[0])}${a.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}};i(Ns,"MD");let Fa=Ns;var hg=Object.defineProperty,Dg=i((e,t,n)=>t in e?hg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"PD"),zu=i((e,t,n)=>(Dg(e,typeof t!="symbol"?t+"":t,n),n),"J");const Ps=class Ps extends un{constructor(t){super(t,!1),zu(this,"options"),zu(this,"cursor",0),this.options=t.options,this.cursor=this.options.findIndex(({value:n})=>n===t.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}};i(Ps,"LD");let Ca=Ps;const Ms=class Ms extends un{get valueWithCursor(){if(this.state==="submit")return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;const t=this.value.slice(0,this.cursor),[n,...r]=this.value.slice(this.cursor);return`${t}${N.inverse(n)}${r.join("")}`}get cursor(){return this._cursor}constructor(t){super(t),this.on("finalize",()=>{this.value||(this.value=t.defaultValue)})}};i(Ms,"RD");let ba=Ms;function gg(){return ke.platform!=="win32"?ke.env.TERM!=="linux":!!ke.env.CI||!!ke.env.WT_SESSION||!!ke.env.TERMINUS_SUBLIME||ke.env.ConEmuTask==="{cmd::Cmder}"||ke.env.TERM_PROGRAM==="Terminus-Sublime"||ke.env.TERM_PROGRAM==="vscode"||ke.env.TERM==="xterm-256color"||ke.env.TERM==="alacritty"||ke.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}i(gg,"ce");const Ea=gg(),ht=i((e,t)=>Ea?e:t,"u"),vg=ht("\u25C6","*"),qu=ht("\u25A0","x"),Zu=ht("\u25B2","x"),Uu=ht("\u25C7","o"),yg=ht("\u250C","T"),fe=ht("\u2502","|"),Pt=ht("\u2514","\u2014"),wa=ht("\u25CF",">"),Aa=ht("\u25CB"," "),_g=ht("\u25AA","\u2022"),oo=i(e=>{switch(e){case"initial":case"active":return N.cyan(vg);case"cancel":return N.red(qu);case"error":return N.yellow(Zu);case"submit":return N.green(Uu)}},"b"),Fg=i(e=>{const{cursor:t,options:n,style:r}=e,a=e.maxItems??Number.POSITIVE_INFINITY,s=Math.max(process.stdout.rows-4,0),o=Math.min(s,Math.max(a,5));let u=0;t>=u+o-3?u=Math.max(Math.min(t-o+3,n.length-o),0):t<u+2&&(u=Math.max(t-2,0));const l=o<n.length&&u>0,c=o<n.length&&u+o<n.length;return n.slice(u,u+o).map((d,m,h)=>{const D=m===0&&l,f=m===h.length-1&&c;return D||f?N.dim("..."):r(d,m+u===t)})},"G"),Lu=i(e=>new ba({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){const t=`${N.gray(fe)}
41
+ ${oo(this.state)} ${e.message}
42
42
  `,n=e.placeholder?N.inverse(e.placeholder[0])+N.dim(e.placeholder.slice(1)):N.inverse(N.hidden("_")),r=this.value?this.valueWithCursor:n;switch(this.state){case"error":return`${t.trim()}
43
43
  ${N.yellow(fe)} ${r}
44
44
  ${N.yellow(Pt)} ${N.yellow(this.error)}
45
45
  `;case"submit":return`${t}${N.gray(fe)} ${N.dim(this.value||e.placeholder)}`;case"cancel":return`${t}${N.gray(fe)} ${N.strikethrough(N.dim(this.value??""))}${this.value?.trim()?`
46
46
  ${N.gray(fe)}`:""}`;default:return`${t}${N.cyan(fe)} ${r}
47
47
  ${N.cyan(Pt)}
48
- `}}}).prompt(),"he"),_g=i(e=>new Fa({validate:e.validate,mask:e.mask??vg,render(){const t=`${N.gray(fe)}
49
- ${no(this.state)} ${e.message}
48
+ `}}}).prompt(),"he"),Cg=i(e=>new Fa({validate:e.validate,mask:e.mask??_g,render(){const t=`${N.gray(fe)}
49
+ ${oo(this.state)} ${e.message}
50
50
  `,n=this.valueWithCursor,r=this.masked;switch(this.state){case"error":return`${t.trim()}
51
51
  ${N.yellow(fe)} ${r}
52
52
  ${N.yellow(Pt)} ${N.yellow(this.error)}
53
53
  `;case"submit":return`${t}${N.gray(fe)} ${N.dim(r)}`;case"cancel":return`${t}${N.gray(fe)} ${N.strikethrough(N.dim(r??""))}${r?`
54
54
  ${N.gray(fe)}`:""}`;default:return`${t}${N.cyan(fe)} ${n}
55
55
  ${N.cyan(Pt)}
56
- `}}}).prompt(),"ge"),Fg=i(e=>{const t=e.active??"Yes",n=e.inactive??"No";return new _a({active:t,inactive:n,initialValue:e.initialValue??!0,render(){const r=`${N.gray(fe)}
57
- ${no(this.state)} ${e.message}
56
+ `}}}).prompt(),"ge"),bg=i(e=>{const t=e.active??"Yes",n=e.inactive??"No";return new _a({active:t,inactive:n,initialValue:e.initialValue??!0,render(){const r=`${N.gray(fe)}
57
+ ${oo(this.state)} ${e.message}
58
58
  `,a=this.value?t:n;switch(this.state){case"submit":return`${r}${N.gray(fe)} ${N.dim(a)}`;case"cancel":return`${r}${N.gray(fe)} ${N.strikethrough(N.dim(a))}
59
59
  ${N.gray(fe)}`;default:return`${r}${N.cyan(fe)} ${this.value?`${N.green(wa)} ${t}`:`${N.dim(Aa)} ${N.dim(t)}`} ${N.dim("/")} ${this.value?`${N.dim(Aa)} ${N.dim(n)}`:`${N.green(wa)} ${n}`}
60
60
  ${N.cyan(Pt)}
61
- `}}}).prompt()},"ye"),Lu=i(e=>{const t=i((n,r)=>{const a=n.label??String(n.value);switch(r){case"selected":return`${N.dim(a)}`;case"active":return`${N.green(wa)} ${a} ${n.hint?N.dim(`(${n.hint})`):""}`;case"cancelled":return`${N.strikethrough(N.dim(a))}`;default:return`${N.dim(Aa)} ${N.dim(a)}`}},"n");return new Ca({options:e.options,initialValue:e.initialValue,render(){const n=`${N.gray(fe)}
62
- ${no(this.state)} ${e.message}
61
+ `}}}).prompt()},"ye"),Vu=i(e=>{const t=i((n,r)=>{const a=n.label??String(n.value);switch(r){case"selected":return`${N.dim(a)}`;case"active":return`${N.green(wa)} ${a} ${n.hint?N.dim(`(${n.hint})`):""}`;case"cancelled":return`${N.strikethrough(N.dim(a))}`;default:return`${N.dim(Aa)} ${N.dim(a)}`}},"n");return new Ca({options:e.options,initialValue:e.initialValue,render(){const n=`${N.gray(fe)}
62
+ ${oo(this.state)} ${e.message}
63
63
  `;switch(this.state){case"submit":return`${n}${N.gray(fe)} ${t(this.options[this.cursor],"selected")}`;case"cancel":return`${n}${N.gray(fe)} ${t(this.options[this.cursor],"cancelled")}
64
- ${N.gray(fe)}`;default:return`${n}${N.cyan(fe)} ${yg({cursor:this.cursor,options:this.options,maxItems:e.maxItems,style:i((r,a)=>t(r,a?"active":"inactive"),"style")}).join(`
64
+ ${N.gray(fe)}`;default:return`${n}${N.cyan(fe)} ${Fg({cursor:this.cursor,options:this.options,maxItems:e.maxItems,style:i((r,a)=>t(r,a?"active":"inactive"),"style")}).join(`
65
65
  ${N.cyan(fe)} `)}
66
66
  ${N.cyan(Pt)}
67
- `}}}).prompt()},"ve"),ro=i((e="")=>{process.stdout.write(`${N.gray(gg)} ${e}
67
+ `}}}).prompt()},"ve"),ao=i((e="")=>{process.stdout.write(`${N.gray(yg)} ${e}
68
68
  `)},"Ie"),ve=i((e="")=>{process.stdout.write(`${N.gray(fe)}
69
69
  ${N.gray(Pt)} ${e}
70
70
 
71
71
  `)},"Se");`${N.gray(fe)}`;const Mt=i(({indicator:e="dots"}={})=>{const t=Ea?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],n=Ea?80:120,r=process.env.CI==="true";let a,s,o=!1,u="",l,c=performance.now();const d=i(w=>{const S=w>1?"Something went wrong":"Canceled";o&&b(S,w)},"p"),m=i(()=>d(2),"v"),h=i(()=>d(1),"f"),D=i(()=>{process.on("uncaughtExceptionMonitor",m),process.on("unhandledRejection",m),process.on("SIGINT",h),process.on("SIGTERM",h),process.on("exit",d)},"j"),f=i(()=>{process.removeListener("uncaughtExceptionMonitor",m),process.removeListener("unhandledRejection",m),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),process.removeListener("exit",d)},"E"),v=i(()=>{if(l===void 0)return;r&&process.stdout.write(`
72
72
  `);const w=l.split(`
73
- `);process.stdout.write(Me.cursor.move(-999,w.length-1)),process.stdout.write(Me.erase.down(w.length))},"B"),y=i(w=>w.replace(/\.+$/,""),"R"),F=i(w=>{const S=(performance.now()-w)/1e3,k=Math.floor(S/60),C=Math.floor(S%60);return k>0?`[${k}m ${C}s]`:`[${C}s]`},"O"),E=i((w="")=>{o=!0,a=ug(),u=y(w),c=performance.now(),process.stdout.write(`${N.gray(fe)}
74
- `);let S=0,k=0;D(),s=setInterval(()=>{if(r&&u===l)return;v(),l=u;const C=N.magenta(t[S]);if(r)process.stdout.write(`${C} ${u}...`);else if(e==="timer")process.stdout.write(`${C} ${u} ${F(c)}`);else{const z=".".repeat(Math.floor(k)).slice(0,3);process.stdout.write(`${C} ${u}${z}`)}S=S+1<t.length?S+1:0,k=k<t.length?k+.125:0},n)},"H"),b=i((w="",S=0)=>{o=!1,clearInterval(s),v();const k=S===0?N.green(qu):S===1?N.red(ju):N.red(zu);u=y(w??u),e==="timer"?process.stdout.write(`${k} ${u} ${F(c)}
73
+ `);process.stdout.write(Me.cursor.move(-999,w.length-1)),process.stdout.write(Me.erase.down(w.length))},"B"),y=i(w=>w.replace(/\.+$/,""),"R"),F=i(w=>{const S=(performance.now()-w)/1e3,k=Math.floor(S/60),C=Math.floor(S%60);return k>0?`[${k}m ${C}s]`:`[${C}s]`},"O"),E=i((w="")=>{o=!0,a=cg(),u=y(w),c=performance.now(),process.stdout.write(`${N.gray(fe)}
74
+ `);let S=0,k=0;D(),s=setInterval(()=>{if(r&&u===l)return;v(),l=u;const C=N.magenta(t[S]);if(r)process.stdout.write(`${C} ${u}...`);else if(e==="timer")process.stdout.write(`${C} ${u} ${F(c)}`);else{const z=".".repeat(Math.floor(k)).slice(0,3);process.stdout.write(`${C} ${u}${z}`)}S=S+1<t.length?S+1:0,k=k<t.length?k+.125:0},n)},"H"),b=i((w="",S=0)=>{o=!1,clearInterval(s),v();const k=S===0?N.green(Uu):S===1?N.red(qu):N.red(Zu);u=y(w??u),e==="timer"?process.stdout.write(`${k} ${u} ${F(c)}
75
75
  `):process.stdout.write(`${k} ${u}
76
- `),f(),a()},"N");return{start:E,stop:b,message:i((w="")=>{u=y(w??u)},"message")}},"Y");var gr=Object.freeze({__proto__:null,confirm:Fg,intro:ro,isCancel:Dr,outro:ve,password:_g,select:Lu,spinner:Mt,text:Zu});const{version:Cg}=Vo,js=class js extends Error{};i(js,"KnownError");let ue=js;const Ia=" ",Uu=i(e=>{e instanceof Error&&!(e instanceof ue)&&(e.stack&&console.error(ca(e.stack.split(`
76
+ `),f(),a()},"N");return{start:E,stop:b,message:i((w="")=>{u=y(w??u)},"message")}},"Y");var gr=Object.freeze({__proto__:null,confirm:bg,intro:ao,isCancel:Dr,outro:ve,password:Cg,select:Vu,spinner:Mt,text:Lu});const{version:Eg}=Gr,js=class js extends Error{};i(js,"KnownError");let ue=js;const Ia=" ",Gu=i(e=>{e instanceof Error&&!(e instanceof ue)&&(e.stack&&console.error(ca(e.stack.split(`
77
77
  `).slice(1).join(`
78
78
  `))),console.error(`
79
- ${Ia}${ca(`aicommits v${Cg}`)}`),console.error(`
80
- ${Ia}Please open a Bug report with the information above:`),console.error(`${Ia}https://github.com/Nutlope/aicommits/issues/new/choose`))},"handleCliError"),oo=i(e=>{process.stderr.write(`${pa("\u2716")} ${e.message}
81
- `),Uu(e),process.exit(1)},"handleCommandError"),xa=i(async()=>{const{stdout:e,failed:t}=await Ge("git",["rev-parse","--show-toplevel"],{reject:!1});if(t)throw new ue("The current directory must be a Git repository!");return e},"assertGitRepo"),ao=i(e=>`:(exclude)${e}`,"excludeFromDiff"),Vu=["package-lock.json","pnpm-lock.yaml","*.lock"],bg=i(e=>Vu.some(t=>t.includes("*")?e.endsWith(".lock"):e===t),"isLockFile"),Gu=Vu.map(ao),Wu=i(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await Ge("git",[...t,"--name-only",...e?e.map(ao):[]]);if(!n)return;const a=n.split(`
82
- `).filter(Boolean).some(l=>!bg(l));let s=[];a&&(s=[...Gu]),s=[...s,...e?e.map(ao):[]];const{stdout:o}=await Ge("git",[...t,"--name-only",...s]);if(!o)return;const{stdout:u}=await Ge("git",[...t,...s]);return{files:o.split(`
83
- `),diff:u}},"getStagedDiff"),Eg=i(async(e,t)=>{const n=["diff","--cached","--diff-algorithm=minimal"],r=[...Gu,...t?t.map(ao):[]],{stdout:a}=await Ge("git",[...n,...r,"--",...e]);return{files:e,diff:a}},"getStagedDiffForFiles"),Hu=i(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage");var ka,Ju;function wg(){if(Ju)return ka;Ju=1;const{hasOwnProperty:e}=Object.prototype,t=typeof process<"u"&&process.platform==="win32"?`\r
79
+ ${Ia}${ca(`aicommits v${Eg}`)}`),console.error(`
80
+ ${Ia}Please open a Bug report with the information above:`),console.error(`${Ia}https://github.com/Nutlope/aicommits/issues/new/choose`))},"handleCliError"),so=i(e=>{process.stderr.write(`${pa("\u2716")} ${e.message}
81
+ `),Gu(e),process.exit(1)},"handleCommandError"),xa=i(async()=>{const{stdout:e,failed:t}=await Ge("git",["rev-parse","--show-toplevel"],{reject:!1});if(t)throw new ue("The current directory must be a Git repository!");return e},"assertGitRepo"),io=i(e=>`:(exclude)${e}`,"excludeFromDiff"),Wu=["package-lock.json","pnpm-lock.yaml","*.lock"],wg=i(e=>Wu.some(t=>t.includes("*")?e.endsWith(".lock"):e===t),"isLockFile"),Hu=Wu.map(io),Ju=i(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await Ge("git",[...t,"--name-only",...e?e.map(io):[]]);if(!n)return;const a=n.split(`
82
+ `).filter(Boolean).some(l=>!wg(l));let s=[];a&&(s=[...Hu]),s=[...s,...e?e.map(io):[]];const{stdout:o}=await Ge("git",[...t,"--name-only",...s]);if(!o)return;const{stdout:u}=await Ge("git",[...t,...s]);return{files:o.split(`
83
+ `),diff:u}},"getStagedDiff"),Ag=i(async(e,t)=>{const n=["diff","--cached","--diff-algorithm=minimal"],r=[...Hu,...t?t.map(io):[]],{stdout:a}=await Ge("git",[...n,...r,"--",...e]);return{files:e,diff:a}},"getStagedDiffForFiles"),Ku=i(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage");var ka,Yu;function Ig(){if(Yu)return ka;Yu=1;const{hasOwnProperty:e}=Object.prototype,t=typeof process<"u"&&process.platform==="win32"?`\r
84
84
  `:`
85
- `,n=i((l,c)=>{const d=[];let m="";typeof c=="string"?c={section:c,whitespace:!1}:(c=c||Object.create(null),c.whitespace=c.whitespace===!0);const h=c.whitespace?" = ":"=";for(const D of Object.keys(l)){const f=l[D];if(f&&Array.isArray(f))for(const v of f)m+=o(D+"[]")+h+o(v)+t;else f&&typeof f=="object"?d.push(D):m+=o(D)+h+o(f)+t}c.section&&m.length&&(m="["+o(c.section)+"]"+t+m);for(const D of d){const f=r(D).join("\\."),v=(c.section?c.section+".":"")+f,{whitespace:y}=c,F=n(l[D],{section:v,whitespace:y});m.length&&F.length&&(m+=t),m+=F}return m},"encode"),r=i(l=>l.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(c=>c.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),"dotSplit"),a=i(l=>{const c=Object.create(null);let d=c,m=null;const h=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,D=l.split(/[\r\n]+/g);for(const v of D){if(!v||v.match(/^\s*[;#]/))continue;const y=v.match(h);if(!y)continue;if(y[1]!==void 0){if(m=u(y[1]),m==="__proto__"){d=Object.create(null);continue}d=c[m]=c[m]||Object.create(null);continue}const F=u(y[2]),E=F.length>2&&F.slice(-2)==="[]",b=E?F.slice(0,-2):F;if(b==="__proto__")continue;const w=y[3]?u(y[4]):!0,S=w==="true"||w==="false"||w==="null"?JSON.parse(w):w;E&&(e.call(d,b)?Array.isArray(d[b])||(d[b]=[d[b]]):d[b]=[]),Array.isArray(d[b])?d[b].push(S):d[b]=S}const f=[];for(const v of Object.keys(c)){if(!e.call(c,v)||typeof c[v]!="object"||Array.isArray(c[v]))continue;const y=r(v);d=c;const F=y.pop(),E=F.replace(/\\\./g,".");for(const b of y)b!=="__proto__"&&((!e.call(d,b)||typeof d[b]!="object")&&(d[b]=Object.create(null)),d=d[b]);d===c&&E===F||(d[E]=c[v],f.push(v))}for(const v of f)delete c[v];return c},"decode"),s=i(l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"),"isQuoted"),o=i(l=>typeof l!="string"||l.match(/[=\r\n]/)||l.match(/^\[/)||l.length>1&&s(l)||l!==l.trim()?JSON.stringify(l):l.split(";").join("\\;").split("#").join("\\#"),"safe"),u=i((l,c)=>{if(l=(l||"").trim(),s(l)){l.charAt(0)==="'"&&(l=l.slice(1,-1));try{l=JSON.parse(l)}catch{}}else{let d=!1,m="";for(let h=0,D=l.length;h<D;h++){const f=l.charAt(h);if(d)"\\;#".indexOf(f)!==-1?m+=f:m+="\\"+f,d=!1;else{if(";#".indexOf(f)!==-1)break;f==="\\"?d=!0:m+=f}}return d&&(m+="\\"),m.trim()}return l},"unsafe");return ka={parse:a,decode:a,stringify:n,encode:n,safe:o,unsafe:u},ka}i(wg,"requireIni");var Ag=wg(),Ku=St(Ag);const $a=i(e=>Ne.lstat(e).then(()=>!0,()=>!1),"fileExists"),Ig=["","conventional","gitmoji"],{hasOwnProperty:xg}=Object.prototype,Ta=i((e,t)=>xg.call(e,t),"hasOwn"),Dt=i((e,t,n)=>{if(!t)throw new ue(`Invalid config property ${e}: ${n}`)},"parseAssert"),so={OPENAI_API_KEY(e){return e},OPENAI_BASE_URL(e){return e},OPENAI_MODEL(e){return e||""},locale(e){return e?(Dt("locale",!!e,"Cannot be empty"),Dt("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores)."),e):"en"},generate(e){if(!e)return 1;Dt("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Dt("generate",t>0,"Must be greater than 0"),Dt("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(Dt("type",Ig.includes(e),"Invalid commit type"),e):""},proxy(e){if(!(!e||e.length===0))throw new ue('The "proxy" config property is deprecated and no longer supported.')},timeout(e){if(!e)return;Dt("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Dt("timeout",t>=500,"Must be greater than 500ms"),t},"max-length"(e){if(!e)return 72;Dt("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Dt("max-length",t>=20,"Must be greater than 20 characters"),t}},kg={name:"togetherai",displayName:"Together AI (recommended)",baseUrl:"https://api.together.xyz/v1",apiKeyFormat:"tgp_",modelsFilter:i(e=>e.filter(t=>(!t.type||t.type==="chat"||t.type==="language")&&!t.id.toLowerCase().includes("vision")).map(t=>t.id),"modelsFilter"),defaultModels:["moonshotai/Kimi-K2-Instruct-0905","Qwen/Qwen3-Next-80B-A3B-Instruct","meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo","meta-llama/Llama-3.2-3B-Instruct-Turbo"],requiresApiKey:!0},$g={name:"openai",displayName:"OpenAI",baseUrl:"https://api.openai.com/v1",apiKeyFormat:"sk-",modelsFilter:i(e=>e.filter(t=>t.id&&(t.id.includes("gpt")||t.id.includes("o1")||t.id.includes("o3")||t.id.includes("o4")||t.id.includes("o5")||!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["gpt-5-mini","gpt-4o-mini","gpt-4o","gpt-5-nano"],requiresApiKey:!0},Tg={name:"ollama",displayName:"Ollama (local)",baseUrl:"http://localhost:11434/v1",modelsFilter:i(e=>e.filter(t=>t.name).map(t=>t.name),"modelsFilter"),defaultModels:["gpt-oss:latest","llama3.2:latest"],requiresApiKey:!1},Bg={name:"custom",displayName:"Custom (OpenAI-compatible)",baseUrl:"",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:[],requiresApiKey:!0},Sg={name:"openrouter",displayName:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyFormat:"sk-or-v1-",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["openai/gpt-oss-20b:free","z-ai/glm-4.5-air:free"],requiresApiKey:!0},Og={name:"lmstudio",displayName:"LM Studio (local)",baseUrl:"http://localhost:1234/v1",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:["qwen/qwen3-4b-2507","qwen/qwen3-8b"],requiresApiKey:!1},vr=[kg,$g,Tg,Og,Sg,Bg],Rg=i(()=>vr.find(t=>t.name==="openai")?.baseUrl||"","getDefaultBaseUrl"),Ng=i((e,t)=>{if(e){const n=vr.find(r=>r.baseUrl===e||r.name==="ollama"&&e.startsWith(r.baseUrl.slice(0,-3)));return n?n.name:"custom"}else if(t)return"openai"},"detectProvider"),Ba=i(()=>at.join(ui.homedir(),".aicommits"),"getConfigPath"),Yu=i(async()=>{if(!await $a(Ba()))return Object.create(null);const t=await Ne.readFile(Ba(),"utf8");return Ku.parse(t)},"readConfigFile"),jt=i(async(e,t,n)=>{const r=await Yu();Ta(r,"proxy")&&console.warn('The "proxy" config property is deprecated and no longer supported');const a={},s=t??{};for(const c of Object.keys(so)){const d=so[c],m=e?.[c]??s?.[c]??r[c];if(n)try{a[c]=d(m)}catch{}else a[c]=d(m)}let o,u=a.OPENAI_BASE_URL;const l=a.OPENAI_API_KEY;return!u&&l&&(u=Rg(),a.OPENAI_BASE_URL=u),o=Ng(u,l),{...a,model:a.OPENAI_MODEL,provider:o}},"getConfig"),Sa=i(async e=>{const t=await Yu();for(const[n,r]of e){if(!Ta(so,n))throw new ue(`Invalid config property: ${n}`);if(r==="")delete t[n];else{const a=so[n](r);t[n]=a}}await Ne.writeFile(Ba(),Ku.stringify(t),"utf8")},"setConfigs"),Xu=i(e=>`[${e} - \u2705]`,"CURRENT_LABEL_FORMAT"),Pg=3600*1e3,Qu=i(()=>{const e=process.platform,t=ui.homedir();if(e==="darwin")return at.join(t,"Library","Caches","aicommits","models");if(e==="win32")return at.join(t,"AppData","Local","aicommits","models");{const n=process.env.XDG_CACHE_HOME,r=n||at.join(t,".cache");return at.join(r,"aicommits","models")}},"getCacheDir"),Mg=i(e=>{const t=tf.createHash("sha256");return t.update(e),t.digest("hex")},"getCacheKey"),el=i(e=>at.join(Qu(),`${e}.json`),"getCachePath"),jg=i(async e=>{const t=el(e);try{if(!await $a(t))return null;const n=await Ne.readFile(t,"utf8");return JSON.parse(n)}catch{return null}},"readCache"),zg=i(async(e,t)=>{try{const n=Qu();await Ne.mkdir(n,{recursive:!0});const r=el(e);await Ne.writeFile(r,JSON.stringify(t),"utf8")}catch{}},"writeCache"),Oa=i(async(e,t)=>{const n=Mg(e),r=Date.now(),a=await jg(n);if(a&&r-a.timestamp<Pg)return a.data;try{const s=await fetch(`${e}/models`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const o=await s.json(),u=(o.data?o.data:o)||[],l={models:u};return u.length>0&&await zg(n,{data:l,timestamp:r}),l}catch(s){const o=s instanceof Error?s.message:"Request failed";return{models:[],error:o}}},"fetchModels"),qg=i(async(e,t,n)=>{const r=await Oa(e,t);r.error&&console.error(`Failed to fetch models: ${r.error}`);let a=[];return n?.modelsFilter?a=n.modelsFilter(r.models):a=r.models.map(s=>s.id||s.name).filter(Boolean),a},"fetchAndFilterModels"),Zg=i((e,t,n)=>{let r=e.map(a=>({label:a,value:a}));if(n?.defaultModels&&n.defaultModels.length>0){const a=n.defaultModels.filter(s=>r.some(o=>o.value===s));a.forEach(s=>{const o=r.findIndex(u=>u.value===s);o>=0&&r.splice(o,1)}),a.forEach((s,o)=>{const l=o===0?`\u{1F451} ${s} (default)`:`\u{1F525} ${s}`;r.unshift({label:l,value:s})})}if(t&&t!=="undefined"){const a=n?.defaultModels?.includes(t),s=r.findIndex(o=>o.value===t);if(s>=0&&!a){if(r[s].label=Xu(r[s].value),s>0){const[o]=r.splice(s,1),u=n?.defaultModels?.length||0;r.splice(u,0,o)}}else if(s<0&&!a){const o=n?.defaultModels?.length||0;r.splice(o,0,{label:Xu(t),value:t})}}return r},"prepareModelOptions"),Lg=i(async(e,t,n,r)=>{const a=await n({message:"Enter search term for models:",placeholder:"e.g., gpt, llama"});if(r(a))return null;let s=e;a&&(s=e.filter(l=>l.toLowerCase().includes(a.toLowerCase())));let o=s.slice(0,20).map(l=>({label:l,value:l}));const u=await t({message:`Choose your model (filtered by "${a}"):`,options:[...o,{label:"Custom model name...",value:"custom"}]});return r(u)?null:u},"handleSearch"),Ug=i(async e=>{const t=await e({message:"Enter your custom model name:",validate:i(n=>{if(!n)return"Model name is required"},"validate")});return Dr(t)?null:t},"handleCustom"),tl=i(async(e,t,n,r)=>{(!n||n==="undefined")&&(n=r?.defaultModels?.[0]);const a=Mt();a.start("Fetching available models...");const s=await qg(e,t,r);a.stop();let o=null;if(s.length>0){const{select:u,text:l,isCancel:c}=await Promise.resolve().then(function(){return gr});let d=Zg(s,n,r);const m=10;d.length>m&&(d=d.slice(0,m));let h=await u({message:"Choose your model:",options:[{label:"\u{1F50D} Search models...",value:"search"},...d,{label:"Custom model name...",value:"custom"}],initialValue:d.length>0?d[0].value:void 0});if(c(h))return null;if(h==="search"){const D=await Lg(s,u,l,c);if(D===null)return null;h=D}if(h==="custom"){if(o=await Ug(l),o===null)return null}else o=h}else{console.log("Could not fetch available models. Please specify a model name manually.");const{text:u,isCancel:l}=await Promise.resolve().then(function(){return gr});try{const c=await u({message:"Enter your model name:",validate:i(d=>{if(!d)return"Model name is required"},"validate")});if(l(c))return null;o=c}catch{return null}}return o},"selectModel");var Vg=Object.freeze({__proto__:null,fetchModels:Oa,selectModel:tl}),Gg=Object.defineProperty,Wg=i((e,t,n)=>t in e?Gg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"__defNormalProp"),nl=i((e,t,n)=>Wg(e,typeof t!="symbol"?t+"":t,n),"__publicField");const zs=class zs{constructor(t,n){nl(this,"config"),nl(this,"def"),this.def=t,this.config=n}get name(){return this.def.name}get displayName(){return this.def.displayName}getDefinition(){return this.def}async setup(){const{text:t,password:n,isCancel:r}=await Promise.resolve().then(function(){return gr}),a=[];if(this.def.requiresApiKey){const s=this.getApiKey(),o=await n({message:s?`Enter your API key (leave empty to keep current: ${s.substring(0,4)}****):`:"Enter your API key:",validate:i(u=>{if(!u&&!s)return"API key is required"},"validate")});if(r(o))throw new Error("Setup cancelled");o&&a.push(["OPENAI_API_KEY",o])}if(this.name==="ollama"){const s=this.getBaseUrl(),o=await t({message:"Enter Ollama endpoint (leave empty for default):",placeholder:s});if(r(o))throw new Error("Setup cancelled");o&&o!=="http://localhost:11434/v1"&&a.push(["OPENAI_BASE_URL",o])}return a}async getModels(){const t=this.getBaseUrl(),n=this.getApiKey()||"",r=await Oa(t,n);if(r.error)return{models:[],error:r.error};let a;return this.def.modelsFilter?a=this.def.modelsFilter(r.models):a=r.models.map(s=>s.id||s.name).filter(Boolean),{models:a}}getApiKey(){return this.def.requiresApiKey?this.config.OPENAI_API_KEY:void 0}getBaseUrl(){return this.name==="custom"?this.config.OPENAI_BASE_URL||"":this.def.baseUrl}getDefaultModel(){return this.def.defaultModels[0]||""}getHighlightedModels(){return this.def.defaultModels}validateConfig(){const t=[];return this.def.requiresApiKey&&!this.getApiKey()&&t.push(`${this.displayName} API key is required`),this.name==="custom"&&!this.getBaseUrl()&&t.push("Custom endpoint is required"),{valid:t.length===0,errors:t}}};i(zs,"Provider");let Ra=zs;function ln(e){const t=e.provider,n=vr.find(r=>r.name===t);return n?new Ra(n,e):null}i(ln,"getProvider");function Hg(){return vr.map(e=>({value:e.name,label:e.displayName}))}i(Hg,"getAvailableProviders");function Jg(e){return vr.find(n=>n.name===e)?.baseUrl||""}i(Jg,"getProviderBaseUrl");var rl="vercel.ai.error",Kg=Symbol.for(rl),ol,al,V=(Kt=class extends(al=Error,ol=Kg,al){constructor({name:t,message:n,cause:r}){super(n),this[ol]=!0,this.name=t,this.cause=r}static isInstance(t){return Kt.hasMarker(t,rl)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},i(Kt,"_AISDKError"),Kt),sl="AI_APICallError",il=`vercel.ai.error.${sl}`,Yg=Symbol.for(il),ul,ll,Re=(vn=class extends(ll=V,ul=Yg,ll){constructor({message:t,url:n,requestBodyValues:r,statusCode:a,responseHeaders:s,responseBody:o,cause:u,isRetryable:l=a!=null&&(a===408||a===409||a===429||a>=500),data:c}){super({name:sl,message:t,cause:u}),this[ul]=!0,this.url=n,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=s,this.responseBody=o,this.isRetryable=l,this.data=c}static isInstance(t){return V.hasMarker(t,il)}},i(vn,"APICallError"),vn),cl="AI_EmptyResponseBodyError",pl=`vercel.ai.error.${cl}`,Xg=Symbol.for(pl),dl,ml,Qg=(yn=class extends(ml=V,dl=Xg,ml){constructor({message:t="Empty response body"}={}){super({name:cl,message:t}),this[dl]=!0}static isInstance(t){return V.hasMarker(t,pl)}},i(yn,"EmptyResponseBodyError"),yn);function yr(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(yr,"getErrorMessage$1");var fl="AI_InvalidArgumentError",hl=`vercel.ai.error.${fl}`,ev=Symbol.for(hl),Dl,gl,vl=(_n=class extends(gl=V,Dl=ev,gl){constructor({message:t,cause:n,argument:r}){super({name:fl,message:t,cause:n}),this[Dl]=!0,this.argument=r}static isInstance(t){return V.hasMarker(t,hl)}},i(_n,"InvalidArgumentError"),_n),yl="AI_InvalidPromptError",_l=`vercel.ai.error.${yl}`,tv=Symbol.for(_l),Fl,Cl,At=(Fn=class extends(Cl=V,Fl=tv,Cl){constructor({prompt:t,message:n,cause:r}){super({name:yl,message:`Invalid prompt: ${n}`,cause:r}),this[Fl]=!0,this.prompt=t}static isInstance(t){return V.hasMarker(t,_l)}},i(Fn,"InvalidPromptError"),Fn),bl="AI_InvalidResponseDataError",El=`vercel.ai.error.${bl}`,nv=Symbol.for(El),wl,Al,_r=(Cn=class extends(Al=V,wl=nv,Al){constructor({data:t,message:n=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:bl,message:n}),this[wl]=!0,this.data=t}static isInstance(t){return V.hasMarker(t,El)}},i(Cn,"InvalidResponseDataError"),Cn),Il="AI_JSONParseError",xl=`vercel.ai.error.${Il}`,rv=Symbol.for(xl),kl,$l,io=(bn=class extends($l=V,kl=rv,$l){constructor({text:t,cause:n}){super({name:Il,message:`JSON parsing failed: Text: ${t}.
86
- Error message: ${yr(n)}`,cause:n}),this[kl]=!0,this.text=t}static isInstance(t){return V.hasMarker(t,xl)}},i(bn,"JSONParseError"),bn),Tl="AI_LoadAPIKeyError",Bl=`vercel.ai.error.${Tl}`,ov=Symbol.for(Bl),Sl,Ol,uo=(En=class extends(Ol=V,Sl=ov,Ol){constructor({message:t}){super({name:Tl,message:t}),this[Sl]=!0}static isInstance(t){return V.hasMarker(t,Bl)}},i(En,"LoadAPIKeyError"),En),Rl="AI_TooManyEmbeddingValuesForCallError",Nl=`vercel.ai.error.${Rl}`,av=Symbol.for(Nl),Pl,Ml,jl=(wn=class extends(Ml=V,Pl=av,Ml){constructor(t){super({name:Rl,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[Pl]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return V.hasMarker(t,Nl)}},i(wn,"TooManyEmbeddingValuesForCallError"),wn),zl="AI_TypeValidationError",ql=`vercel.ai.error.${zl}`,sv=Symbol.for(ql),Zl,Ll,zt=(Tt=class extends(Ll=V,Zl=sv,Ll){constructor({value:t,cause:n}){super({name:zl,message:`Type validation failed: Value: ${JSON.stringify(t)}.
87
- Error message: ${yr(n)}`,cause:n}),this[Zl]=!0,this.value=t}static isInstance(t){return V.hasMarker(t,ql)}static wrap({value:t,cause:n}){return Tt.isInstance(n)&&n.value===t?n:new Tt({value:t,cause:n})}},i(Tt,"_TypeValidationError"),Tt),Ul="AI_UnsupportedFunctionalityError",Vl=`vercel.ai.error.${Ul}`,iv=Symbol.for(Vl),Gl,Wl,He=(An=class extends(Wl=V,Gl=iv,Wl){constructor({functionality:t,message:n=`'${t}' functionality not supported.`}){super({name:Ul,message:n}),this[Gl]=!0,this.functionality=t}static isInstance(t){return V.hasMarker(t,Vl)}},i(An,"UnsupportedFunctionalityError"),An);function x(e,t,n){function r(l,c){var d;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(d=l._zod).traits??(d.traits=new Set),l._zod.traits.add(e),t(l,c);for(const m in o.prototype)m in l||Object.defineProperty(l,m,{value:o.prototype[m].bind(l)});l._zod.constr=o,l._zod.def=c}i(r,"init");const a=n?.Parent??Object,u=class u extends a{};i(u,"Definition");let s=u;Object.defineProperty(s,"name",{value:e});function o(l){var c;const d=n?.Parent?new s:this;r(d,l),(c=d._zod).deferred??(c.deferred=[]);for(const m of d._zod.deferred)m();return d}return i(o,"_"),Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:i(l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e),"value")}),Object.defineProperty(o,"name",{value:e}),o}i(x,"$constructor");const qs=class qs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};i(qs,"$ZodAsyncError");let qt=qs;const Hl={};function It(e){return Hl}i(It,"config");function Jl(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}i(Jl,"getEnumValues");function uv(e,t){return typeof t=="bigint"?t.toString():t}i(uv,"jsonStringifyReplacer");function Na(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}i(Na,"cached");function Pa(e){return e==null}i(Pa,"nullish");function Ma(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}i(Ma,"cleanRegex");function lv(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,a=n>r?n:r,s=Number.parseInt(e.toFixed(a).replace(".","")),o=Number.parseInt(t.toFixed(a).replace(".",""));return s%o/10**a}i(lv,"floatSafeRemainder");function se(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}i(se,"defineLazy");function ja(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(ja,"assignProp");function Fr(e){return JSON.stringify(e)}i(Fr,"esc");const Kl=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function lo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(lo,"isObject");const cv=Na(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function co(e){if(lo(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(lo(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}i(co,"isPlainObject");const pv=new Set(["string","number","symbol"]);function Cr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(Cr,"escapeRegex");function Zt(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}i(Zt,"clone");function q(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:i(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:i(()=>t.error,"error")}:t}i(q,"normalizeParams");function dv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}i(dv,"optionalKeys");const mv={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function fv(e,t){const n={},r=e._zod.def;for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(n[a]=r.shape[a])}return Zt(e,{...e._zod.def,shape:n,checks:[]})}i(fv,"pick");function hv(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete n[a]}return Zt(e,{...e._zod.def,shape:n,checks:[]})}i(hv,"omit");function Dv(e,t){if(!co(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return ja(this,"shape",r),r},checks:[]};return Zt(e,n)}i(Dv,"extend");function gv(e,t){return Zt(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ja(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}i(gv,"merge");function vv(e,t,n){const r=t._zod.def.shape,a={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(a[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)a[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return Zt(t,{...t._zod.def,shape:a,checks:[]})}i(vv,"partial");function yv(e,t,n){const r=t._zod.def.shape,a={...r};if(n)for(const s in n){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(a[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)a[s]=new e({type:"nonoptional",innerType:r[s]});return Zt(t,{...t._zod.def,shape:a,checks:[]})}i(yv,"required");function br(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}i(br,"aborted");function Lt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}i(Lt,"prefixIssues");function po(e){return typeof e=="string"?e:e?.message}i(po,"unwrapMessage");function xt(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const a=po(e.inst?._zod.def?.error?.(e))??po(t?.error?.(e))??po(n.customError?.(e))??po(n.localeError?.(e))??"Invalid input";r.message=a}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}i(xt,"finalizeIssue");function za(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}i(za,"getLengthableOrigin");function Er(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}i(Er,"issue");const Yl=i((e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,uv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:i(()=>e.message,"value"),enumerable:!1})},"initializer$1"),Xl=x("$ZodError",Yl),Ql=x("$ZodError",Yl,{Parent:Error});function _v(e,t=n=>n.message){const n={},r=[];for(const a of e.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}i(_v,"flattenError");function Fv(e,t){const n=t||function(s){return s.message},r={_errors:[]},a=i(s=>{for(const o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(u=>a({issues:u}));else if(o.code==="invalid_key")a({issues:o.issues});else if(o.code==="invalid_element")a({issues:o.issues});else if(o.path.length===0)r._errors.push(n(o));else{let u=r,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(o))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return a(e),r}i(Fv,"formatError");const Cv=i(e=>(t,n,r,a)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise)throw new qt;if(o.issues.length){const u=new(a?.Err??e)(o.issues.map(l=>xt(l,s,It())));throw Kl(u,a?.callee),u}return o.value},"_parse$1"),bv=i(e=>async(t,n,r,a)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const u=new(a?.Err??e)(o.issues.map(l=>xt(l,s,It())));throw Kl(u,a?.callee),u}return o.value},"_parseAsync"),ec=i(e=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise)throw new qt;return s.issues.length?{success:!1,error:new(e??Xl)(s.issues.map(o=>xt(o,a,It())))}:{success:!0,data:s.value}},"_safeParse"),Ev=ec(Ql),tc=i(e=>async(t,n,r)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},a);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>xt(o,a,It())))}:{success:!0,data:s.value}},"_safeParseAsync"),wv=tc(Ql),Av=/^[cC][^\s-]{8,}$/,Iv=/^[0-9a-z]+$/,xv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,kv=/^[0-9a-vA-V]{20}$/,$v=/^[A-Za-z0-9]{27}$/,Tv=/^[a-zA-Z0-9_-]{21}$/,Bv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Sv=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,nc=i(e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,"uuid"),Ov=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Rv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Nv(){return new RegExp(Rv,"u")}i(Nv,"emoji");const Pv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,jv=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,zv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rc=/^[A-Za-z0-9_-]*$/,Zv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Lv=/^\+(?:[0-9]){6,14}[0-9]$/,oc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Uv=new RegExp(`^${oc}$`);function ac(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}i(ac,"timeSource");function Vv(e){return new RegExp(`^${ac(e)}$`)}i(Vv,"time$1");function Gv(e){const t=ac({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${oc}T(?:${r})$`)}i(Gv,"datetime$1");const Wv=i(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),Hv=/^\d+$/,Jv=/^-?\d+(?:\.\d+)?/i,Kv=/true|false/i,Yv=/null/i,Xv=/^[^A-Z]*$/,Qv=/^[^a-z]*$/,Le=x("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),sc={number:"number",bigint:"bigint",object:"date"},ic=x("$ZodCheckLessThan",(e,t)=>{Le.init(e,t);const n=sc[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,s=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?a.maximum=t.value:a.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),uc=x("$ZodCheckGreaterThan",(e,t)=>{Le.init(e,t);const n=sc[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,s=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ey=x("$ZodCheckMultipleOf",(e,t)=>{Le.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):lv(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),ty=x("$ZodCheckNumberFormat",(e,t)=>{Le.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[a,s]=mv[t.format];e._zod.onattach.push(o=>{const u=o._zod.bag;u.format=t.format,u.minimum=a,u.maximum=s,n&&(u.pattern=Hv)}),e._zod.check=o=>{const u=o.value;if(n){if(!Number.isInteger(u)){o.issues.push({expected:r,format:t.format,code:"invalid_type",input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?o.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):o.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}u<a&&o.issues.push({origin:"number",input:u,code:"too_small",minimum:a,inclusive:!0,inst:e,continue:!t.abort}),u>s&&o.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inst:e})}}),ny=x("$ZodCheckMaxLength",(e,t)=>{var n;Le.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!Pa(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const a=r.value;if(a.length<=t.maximum)return;const o=za(a);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),ry=x("$ZodCheckMinLength",(e,t)=>{var n;Le.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!Pa(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const a=r.value;if(a.length>=t.minimum)return;const o=za(a);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),oy=x("$ZodCheckLengthEquals",(e,t)=>{var n;Le.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!Pa(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),e._zod.check=r=>{const a=r.value,s=a.length;if(s===t.length)return;const o=za(a),u=s>t.length;r.issues.push({origin:o,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),mo=x("$ZodCheckStringFormat",(e,t)=>{var n,r;Le.init(e,t),e._zod.onattach.push(a=>{const s=a._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),ay=x("$ZodCheckRegex",(e,t)=>{mo.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),sy=x("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Xv),mo.init(e,t)}),iy=x("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Qv),mo.init(e,t)}),uy=x("$ZodCheckIncludes",(e,t)=>{Le.init(e,t);const n=Cr(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(a=>{const s=a._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:e,continue:!t.abort})}}),ly=x("$ZodCheckStartsWith",(e,t)=>{Le.init(e,t);const n=new RegExp(`^${Cr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),cy=x("$ZodCheckEndsWith",(e,t)=>{Le.init(e,t);const n=new RegExp(`.*${Cr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),py=x("$ZodCheckOverwrite",(e,t)=>{Le.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}}),Zs=class Zs{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
85
+ `,n=i((l,c)=>{const d=[];let m="";typeof c=="string"?c={section:c,whitespace:!1}:(c=c||Object.create(null),c.whitespace=c.whitespace===!0);const h=c.whitespace?" = ":"=";for(const D of Object.keys(l)){const f=l[D];if(f&&Array.isArray(f))for(const v of f)m+=o(D+"[]")+h+o(v)+t;else f&&typeof f=="object"?d.push(D):m+=o(D)+h+o(f)+t}c.section&&m.length&&(m="["+o(c.section)+"]"+t+m);for(const D of d){const f=r(D).join("\\."),v=(c.section?c.section+".":"")+f,{whitespace:y}=c,F=n(l[D],{section:v,whitespace:y});m.length&&F.length&&(m+=t),m+=F}return m},"encode"),r=i(l=>l.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(c=>c.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),"dotSplit"),a=i(l=>{const c=Object.create(null);let d=c,m=null;const h=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,D=l.split(/[\r\n]+/g);for(const v of D){if(!v||v.match(/^\s*[;#]/))continue;const y=v.match(h);if(!y)continue;if(y[1]!==void 0){if(m=u(y[1]),m==="__proto__"){d=Object.create(null);continue}d=c[m]=c[m]||Object.create(null);continue}const F=u(y[2]),E=F.length>2&&F.slice(-2)==="[]",b=E?F.slice(0,-2):F;if(b==="__proto__")continue;const w=y[3]?u(y[4]):!0,S=w==="true"||w==="false"||w==="null"?JSON.parse(w):w;E&&(e.call(d,b)?Array.isArray(d[b])||(d[b]=[d[b]]):d[b]=[]),Array.isArray(d[b])?d[b].push(S):d[b]=S}const f=[];for(const v of Object.keys(c)){if(!e.call(c,v)||typeof c[v]!="object"||Array.isArray(c[v]))continue;const y=r(v);d=c;const F=y.pop(),E=F.replace(/\\\./g,".");for(const b of y)b!=="__proto__"&&((!e.call(d,b)||typeof d[b]!="object")&&(d[b]=Object.create(null)),d=d[b]);d===c&&E===F||(d[E]=c[v],f.push(v))}for(const v of f)delete c[v];return c},"decode"),s=i(l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"),"isQuoted"),o=i(l=>typeof l!="string"||l.match(/[=\r\n]/)||l.match(/^\[/)||l.length>1&&s(l)||l!==l.trim()?JSON.stringify(l):l.split(";").join("\\;").split("#").join("\\#"),"safe"),u=i((l,c)=>{if(l=(l||"").trim(),s(l)){l.charAt(0)==="'"&&(l=l.slice(1,-1));try{l=JSON.parse(l)}catch{}}else{let d=!1,m="";for(let h=0,D=l.length;h<D;h++){const f=l.charAt(h);if(d)"\\;#".indexOf(f)!==-1?m+=f:m+="\\"+f,d=!1;else{if(";#".indexOf(f)!==-1)break;f==="\\"?d=!0:m+=f}}return d&&(m+="\\"),m.trim()}return l},"unsafe");return ka={parse:a,decode:a,stringify:n,encode:n,safe:o,unsafe:u},ka}i(Ig,"requireIni");var xg=Ig(),Xu=St(xg);const $a=i(e=>Ne.lstat(e).then(()=>!0,()=>!1),"fileExists"),kg=["","conventional","gitmoji"],{hasOwnProperty:$g}=Object.prototype,Ta=i((e,t)=>$g.call(e,t),"hasOwn"),Dt=i((e,t,n)=>{if(!t)throw new ue(`Invalid config property ${e}: ${n}`)},"parseAssert"),uo={OPENAI_API_KEY(e){return e},OPENAI_BASE_URL(e){return e},OPENAI_MODEL(e){return e||""},locale(e){return e?(Dt("locale",!!e,"Cannot be empty"),Dt("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores)."),e):"en"},generate(e){if(!e)return 1;Dt("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Dt("generate",t>0,"Must be greater than 0"),Dt("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(Dt("type",kg.includes(e),"Invalid commit type"),e):""},proxy(e){if(!(!e||e.length===0))throw new ue('The "proxy" config property is deprecated and no longer supported.')},timeout(e){if(!e)return;Dt("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Dt("timeout",t>=500,"Must be greater than 500ms"),t},"max-length"(e){if(!e)return 72;Dt("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Dt("max-length",t>=20,"Must be greater than 20 characters"),t}},Tg={name:"togetherai",displayName:"Together AI (recommended)",baseUrl:"https://api.together.xyz/v1",apiKeyFormat:"tgp_",modelsFilter:i(e=>e.filter(t=>(!t.type||t.type==="chat"||t.type==="language")&&!t.id.toLowerCase().includes("vision")).map(t=>t.id),"modelsFilter"),defaultModels:["moonshotai/Kimi-K2-Instruct-0905","Qwen/Qwen3-Next-80B-A3B-Instruct","meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo","meta-llama/Llama-3.2-3B-Instruct-Turbo"],requiresApiKey:!0},Bg={name:"openai",displayName:"OpenAI",baseUrl:"https://api.openai.com/v1",apiKeyFormat:"sk-",modelsFilter:i(e=>e.filter(t=>t.id&&(t.id.includes("gpt")||t.id.includes("o1")||t.id.includes("o3")||t.id.includes("o4")||t.id.includes("o5")||!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["gpt-5-mini","gpt-4o-mini","gpt-4o","gpt-5-nano"],requiresApiKey:!0},Sg={name:"ollama",displayName:"Ollama (local)",baseUrl:"http://localhost:11434/v1",modelsFilter:i(e=>e.filter(t=>t.name).map(t=>t.name),"modelsFilter"),defaultModels:["gpt-oss:latest","llama3.2:latest"],requiresApiKey:!1},Og={name:"custom",displayName:"Custom (OpenAI-compatible)",baseUrl:"",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:[],requiresApiKey:!0},Rg={name:"openrouter",displayName:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyFormat:"sk-or-v1-",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["openai/gpt-oss-20b:free","z-ai/glm-4.5-air:free"],requiresApiKey:!0},Ng={name:"lmstudio",displayName:"LM Studio (local)",baseUrl:"http://localhost:1234/v1",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:["qwen/qwen3-4b-2507","qwen/qwen3-8b"],requiresApiKey:!1},vr=[Tg,Bg,Sg,Ng,Rg,Og],Pg=i(()=>vr.find(t=>t.name==="openai")?.baseUrl||"","getDefaultBaseUrl"),Mg=i((e,t)=>{if(e){const n=vr.find(r=>r.baseUrl===e||r.name==="ollama"&&e.startsWith(r.baseUrl.slice(0,-3)));return n?n.name:"custom"}else if(t)return"openai"},"detectProvider"),Ba=i(()=>at.join(ci.homedir(),".aicommits"),"getConfigPath"),Qu=i(async()=>{if(!await $a(Ba()))return Object.create(null);const t=await Ne.readFile(Ba(),"utf8");return Xu.parse(t)},"readConfigFile"),jt=i(async(e,t,n)=>{const r=await Qu();Ta(r,"proxy")&&console.warn('The "proxy" config property is deprecated and no longer supported');const a={},s=t??{};for(const c of Object.keys(uo)){const d=uo[c],m=e?.[c]??s?.[c]??r[c];if(n)try{a[c]=d(m)}catch{}else a[c]=d(m)}let o,u=a.OPENAI_BASE_URL;const l=a.OPENAI_API_KEY;return!u&&l&&(u=Pg(),a.OPENAI_BASE_URL=u),o=Mg(u,l),{...a,model:a.OPENAI_MODEL,provider:o}},"getConfig"),Sa=i(async e=>{const t=await Qu();for(const[n,r]of e){if(!Ta(uo,n))throw new ue(`Invalid config property: ${n}`);if(r==="")delete t[n];else{const a=uo[n](r);t[n]=a}}await Ne.writeFile(Ba(),Xu.stringify(t),"utf8")},"setConfigs"),el=i(e=>`[${e} - \u2705]`,"CURRENT_LABEL_FORMAT"),jg=3600*1e3,tl=i(()=>{const e=process.platform,t=ci.homedir();if(e==="darwin")return at.join(t,"Library","Caches","aicommits","models");if(e==="win32")return at.join(t,"AppData","Local","aicommits","models");{const n=process.env.XDG_CACHE_HOME,r=n||at.join(t,".cache");return at.join(r,"aicommits","models")}},"getCacheDir"),zg=i(e=>{const t=rf.createHash("sha256");return t.update(e),t.digest("hex")},"getCacheKey"),nl=i(e=>at.join(tl(),`${e}.json`),"getCachePath"),qg=i(async e=>{const t=nl(e);try{if(!await $a(t))return null;const n=await Ne.readFile(t,"utf8");return JSON.parse(n)}catch{return null}},"readCache"),Zg=i(async(e,t)=>{try{const n=tl();await Ne.mkdir(n,{recursive:!0});const r=nl(e);await Ne.writeFile(r,JSON.stringify(t),"utf8")}catch{}},"writeCache"),Oa=i(async(e,t)=>{const n=zg(e),r=Date.now(),a=await qg(n);if(a&&r-a.timestamp<jg)return a.data;try{const s=await fetch(`${e}/models`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const o=await s.json(),u=(o.data?o.data:o)||[],l={models:u};return u.length>0&&await Zg(n,{data:l,timestamp:r}),l}catch(s){const o=s instanceof Error?s.message:"Request failed";return{models:[],error:o}}},"fetchModels"),Ug=i(async(e,t,n)=>{const r=await Oa(e,t);r.error&&console.error(`Failed to fetch models: ${r.error}`);let a=[];return n?.modelsFilter?a=n.modelsFilter(r.models):a=r.models.map(s=>s.id||s.name).filter(Boolean),a},"fetchAndFilterModels"),Lg=i((e,t,n)=>{let r=e.map(a=>({label:a,value:a}));if(n?.defaultModels&&n.defaultModels.length>0){const a=n.defaultModels.filter(s=>r.some(o=>o.value===s));a.forEach(s=>{const o=r.findIndex(u=>u.value===s);o>=0&&r.splice(o,1)}),a.forEach((s,o)=>{const l=o===0?`\u{1F451} ${s} (default)`:`\u{1F525} ${s}`;r.unshift({label:l,value:s})})}if(t&&t!=="undefined"){const a=n?.defaultModels?.includes(t),s=r.findIndex(o=>o.value===t);if(s>=0&&!a){if(r[s].label=el(r[s].value),s>0){const[o]=r.splice(s,1),u=n?.defaultModels?.length||0;r.splice(u,0,o)}}else if(s<0&&!a){const o=n?.defaultModels?.length||0;r.splice(o,0,{label:el(t),value:t})}}return r},"prepareModelOptions"),Vg=i(async(e,t,n,r)=>{const a=await n({message:"Enter search term for models:",placeholder:"e.g., gpt, llama"});if(r(a))return null;let s=e;a&&(s=e.filter(l=>l.toLowerCase().includes(a.toLowerCase())));let o=s.slice(0,20).map(l=>({label:l,value:l}));const u=await t({message:`Choose your model (filtered by "${a}"):`,options:[...o,{label:"Custom model name...",value:"custom"}]});return r(u)?null:u},"handleSearch"),Gg=i(async e=>{const t=await e({message:"Enter your custom model name:",validate:i(n=>{if(!n)return"Model name is required"},"validate")});return Dr(t)?null:t},"handleCustom"),rl=i(async(e,t,n,r)=>{(!n||n==="undefined")&&(n=r?.defaultModels?.[0]);const a=Mt();a.start("Fetching available models...");const s=await Ug(e,t,r);a.stop();let o=null;if(s.length>0){const{select:u,text:l,isCancel:c}=await Promise.resolve().then(function(){return gr});let d=Lg(s,n,r);const m=10;d.length>m&&(d=d.slice(0,m));let h=await u({message:"Choose your model:",options:[{label:"\u{1F50D} Search models...",value:"search"},...d,{label:"Custom model name...",value:"custom"}],initialValue:d.length>0?d[0].value:void 0});if(c(h))return null;if(h==="search"){const D=await Vg(s,u,l,c);if(D===null)return null;h=D}if(h==="custom"){if(o=await Gg(l),o===null)return null}else o=h}else{console.log("Could not fetch available models. Please specify a model name manually.");const{text:u,isCancel:l}=await Promise.resolve().then(function(){return gr});try{const c=await u({message:"Enter your model name:",validate:i(d=>{if(!d)return"Model name is required"},"validate")});if(l(c))return null;o=c}catch{return null}}return o},"selectModel");var Wg=Object.freeze({__proto__:null,fetchModels:Oa,selectModel:rl}),Hg=Object.defineProperty,Jg=i((e,t,n)=>t in e?Hg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"__defNormalProp"),ol=i((e,t,n)=>Jg(e,typeof t!="symbol"?t+"":t,n),"__publicField");const zs=class zs{constructor(t,n){ol(this,"config"),ol(this,"def"),this.def=t,this.config=n}get name(){return this.def.name}get displayName(){return this.def.displayName}getDefinition(){return this.def}async setup(){const{text:t,password:n,isCancel:r}=await Promise.resolve().then(function(){return gr}),a=[];if(this.def.requiresApiKey){const s=this.getApiKey(),o=await n({message:s?`Enter your API key (leave empty to keep current: ${s.substring(0,4)}****):`:"Enter your API key:",validate:i(u=>{if(!u&&!s)return"API key is required"},"validate")});if(r(o))throw new Error("Setup cancelled");o&&a.push(["OPENAI_API_KEY",o])}if(this.name==="ollama"){const s=this.getBaseUrl(),o=await t({message:"Enter Ollama endpoint (leave empty for default):",placeholder:s});if(r(o))throw new Error("Setup cancelled");o&&o!=="http://localhost:11434/v1"&&a.push(["OPENAI_BASE_URL",o])}return a}async getModels(){const t=this.getBaseUrl(),n=this.getApiKey()||"",r=await Oa(t,n);if(r.error)return{models:[],error:r.error};let a;return this.def.modelsFilter?a=this.def.modelsFilter(r.models):a=r.models.map(s=>s.id||s.name).filter(Boolean),{models:a}}getApiKey(){return this.def.requiresApiKey?this.config.OPENAI_API_KEY:void 0}getBaseUrl(){return this.name==="custom"?this.config.OPENAI_BASE_URL||"":this.def.baseUrl}getDefaultModel(){return this.def.defaultModels[0]||""}getHighlightedModels(){return this.def.defaultModels}validateConfig(){const t=[];return this.def.requiresApiKey&&!this.getApiKey()&&t.push(`${this.displayName} API key is required`),this.name==="custom"&&!this.getBaseUrl()&&t.push("Custom endpoint is required"),{valid:t.length===0,errors:t}}};i(zs,"Provider");let Ra=zs;function ln(e){const t=e.provider,n=vr.find(r=>r.name===t);return n?new Ra(n,e):null}i(ln,"getProvider");function Kg(){return vr.map(e=>({value:e.name,label:e.displayName}))}i(Kg,"getAvailableProviders");function Yg(e){return vr.find(n=>n.name===e)?.baseUrl||""}i(Yg,"getProviderBaseUrl");var al="vercel.ai.error",Xg=Symbol.for(al),sl,il,V=(Kt=class extends(il=Error,sl=Xg,il){constructor({name:t,message:n,cause:r}){super(n),this[sl]=!0,this.name=t,this.cause=r}static isInstance(t){return Kt.hasMarker(t,al)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},i(Kt,"_AISDKError"),Kt),ul="AI_APICallError",ll=`vercel.ai.error.${ul}`,Qg=Symbol.for(ll),cl,pl,Re=(vn=class extends(pl=V,cl=Qg,pl){constructor({message:t,url:n,requestBodyValues:r,statusCode:a,responseHeaders:s,responseBody:o,cause:u,isRetryable:l=a!=null&&(a===408||a===409||a===429||a>=500),data:c}){super({name:ul,message:t,cause:u}),this[cl]=!0,this.url=n,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=s,this.responseBody=o,this.isRetryable=l,this.data=c}static isInstance(t){return V.hasMarker(t,ll)}},i(vn,"APICallError"),vn),dl="AI_EmptyResponseBodyError",ml=`vercel.ai.error.${dl}`,ev=Symbol.for(ml),fl,hl,tv=(yn=class extends(hl=V,fl=ev,hl){constructor({message:t="Empty response body"}={}){super({name:dl,message:t}),this[fl]=!0}static isInstance(t){return V.hasMarker(t,ml)}},i(yn,"EmptyResponseBodyError"),yn);function yr(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(yr,"getErrorMessage$1");var Dl="AI_InvalidArgumentError",gl=`vercel.ai.error.${Dl}`,nv=Symbol.for(gl),vl,yl,_l=(_n=class extends(yl=V,vl=nv,yl){constructor({message:t,cause:n,argument:r}){super({name:Dl,message:t,cause:n}),this[vl]=!0,this.argument=r}static isInstance(t){return V.hasMarker(t,gl)}},i(_n,"InvalidArgumentError"),_n),Fl="AI_InvalidPromptError",Cl=`vercel.ai.error.${Fl}`,rv=Symbol.for(Cl),bl,El,At=(Fn=class extends(El=V,bl=rv,El){constructor({prompt:t,message:n,cause:r}){super({name:Fl,message:`Invalid prompt: ${n}`,cause:r}),this[bl]=!0,this.prompt=t}static isInstance(t){return V.hasMarker(t,Cl)}},i(Fn,"InvalidPromptError"),Fn),wl="AI_InvalidResponseDataError",Al=`vercel.ai.error.${wl}`,ov=Symbol.for(Al),Il,xl,_r=(Cn=class extends(xl=V,Il=ov,xl){constructor({data:t,message:n=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:wl,message:n}),this[Il]=!0,this.data=t}static isInstance(t){return V.hasMarker(t,Al)}},i(Cn,"InvalidResponseDataError"),Cn),kl="AI_JSONParseError",$l=`vercel.ai.error.${kl}`,av=Symbol.for($l),Tl,Bl,lo=(bn=class extends(Bl=V,Tl=av,Bl){constructor({text:t,cause:n}){super({name:kl,message:`JSON parsing failed: Text: ${t}.
86
+ Error message: ${yr(n)}`,cause:n}),this[Tl]=!0,this.text=t}static isInstance(t){return V.hasMarker(t,$l)}},i(bn,"JSONParseError"),bn),Sl="AI_LoadAPIKeyError",Ol=`vercel.ai.error.${Sl}`,sv=Symbol.for(Ol),Rl,Nl,co=(En=class extends(Nl=V,Rl=sv,Nl){constructor({message:t}){super({name:Sl,message:t}),this[Rl]=!0}static isInstance(t){return V.hasMarker(t,Ol)}},i(En,"LoadAPIKeyError"),En),Pl="AI_TooManyEmbeddingValuesForCallError",Ml=`vercel.ai.error.${Pl}`,iv=Symbol.for(Ml),jl,zl,ql=(wn=class extends(zl=V,jl=iv,zl){constructor(t){super({name:Pl,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[jl]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return V.hasMarker(t,Ml)}},i(wn,"TooManyEmbeddingValuesForCallError"),wn),Zl="AI_TypeValidationError",Ul=`vercel.ai.error.${Zl}`,uv=Symbol.for(Ul),Ll,Vl,zt=(Tt=class extends(Vl=V,Ll=uv,Vl){constructor({value:t,cause:n}){super({name:Zl,message:`Type validation failed: Value: ${JSON.stringify(t)}.
87
+ Error message: ${yr(n)}`,cause:n}),this[Ll]=!0,this.value=t}static isInstance(t){return V.hasMarker(t,Ul)}static wrap({value:t,cause:n}){return Tt.isInstance(n)&&n.value===t?n:new Tt({value:t,cause:n})}},i(Tt,"_TypeValidationError"),Tt),Gl="AI_UnsupportedFunctionalityError",Wl=`vercel.ai.error.${Gl}`,lv=Symbol.for(Wl),Hl,Jl,He=(An=class extends(Jl=V,Hl=lv,Jl){constructor({functionality:t,message:n=`'${t}' functionality not supported.`}){super({name:Gl,message:n}),this[Hl]=!0,this.functionality=t}static isInstance(t){return V.hasMarker(t,Wl)}},i(An,"UnsupportedFunctionalityError"),An);function x(e,t,n){function r(l,c){var d;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(d=l._zod).traits??(d.traits=new Set),l._zod.traits.add(e),t(l,c);for(const m in o.prototype)m in l||Object.defineProperty(l,m,{value:o.prototype[m].bind(l)});l._zod.constr=o,l._zod.def=c}i(r,"init");const a=n?.Parent??Object,u=class u extends a{};i(u,"Definition");let s=u;Object.defineProperty(s,"name",{value:e});function o(l){var c;const d=n?.Parent?new s:this;r(d,l),(c=d._zod).deferred??(c.deferred=[]);for(const m of d._zod.deferred)m();return d}return i(o,"_"),Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:i(l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e),"value")}),Object.defineProperty(o,"name",{value:e}),o}i(x,"$constructor");const qs=class qs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};i(qs,"$ZodAsyncError");let qt=qs;const Kl={};function It(e){return Kl}i(It,"config");function Yl(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}i(Yl,"getEnumValues");function cv(e,t){return typeof t=="bigint"?t.toString():t}i(cv,"jsonStringifyReplacer");function Na(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}i(Na,"cached");function Pa(e){return e==null}i(Pa,"nullish");function Ma(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}i(Ma,"cleanRegex");function pv(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,a=n>r?n:r,s=Number.parseInt(e.toFixed(a).replace(".","")),o=Number.parseInt(t.toFixed(a).replace(".",""));return s%o/10**a}i(pv,"floatSafeRemainder");function se(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}i(se,"defineLazy");function ja(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(ja,"assignProp");function Fr(e){return JSON.stringify(e)}i(Fr,"esc");const Xl=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function po(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(po,"isObject");const dv=Na(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function mo(e){if(po(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(po(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}i(mo,"isPlainObject");const mv=new Set(["string","number","symbol"]);function Cr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(Cr,"escapeRegex");function Zt(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}i(Zt,"clone");function q(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:i(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:i(()=>t.error,"error")}:t}i(q,"normalizeParams");function fv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}i(fv,"optionalKeys");const hv={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Dv(e,t){const n={},r=e._zod.def;for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(n[a]=r.shape[a])}return Zt(e,{...e._zod.def,shape:n,checks:[]})}i(Dv,"pick");function gv(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete n[a]}return Zt(e,{...e._zod.def,shape:n,checks:[]})}i(gv,"omit");function vv(e,t){if(!mo(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return ja(this,"shape",r),r},checks:[]};return Zt(e,n)}i(vv,"extend");function yv(e,t){return Zt(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ja(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}i(yv,"merge");function _v(e,t,n){const r=t._zod.def.shape,a={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(a[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)a[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return Zt(t,{...t._zod.def,shape:a,checks:[]})}i(_v,"partial");function Fv(e,t,n){const r=t._zod.def.shape,a={...r};if(n)for(const s in n){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(a[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)a[s]=new e({type:"nonoptional",innerType:r[s]});return Zt(t,{...t._zod.def,shape:a,checks:[]})}i(Fv,"required");function br(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}i(br,"aborted");function Ut(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}i(Ut,"prefixIssues");function fo(e){return typeof e=="string"?e:e?.message}i(fo,"unwrapMessage");function xt(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const a=fo(e.inst?._zod.def?.error?.(e))??fo(t?.error?.(e))??fo(n.customError?.(e))??fo(n.localeError?.(e))??"Invalid input";r.message=a}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}i(xt,"finalizeIssue");function za(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}i(za,"getLengthableOrigin");function Er(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}i(Er,"issue");const Ql=i((e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,cv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:i(()=>e.message,"value"),enumerable:!1})},"initializer$1"),ec=x("$ZodError",Ql),tc=x("$ZodError",Ql,{Parent:Error});function Cv(e,t=n=>n.message){const n={},r=[];for(const a of e.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}i(Cv,"flattenError");function bv(e,t){const n=t||function(s){return s.message},r={_errors:[]},a=i(s=>{for(const o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(u=>a({issues:u}));else if(o.code==="invalid_key")a({issues:o.issues});else if(o.code==="invalid_element")a({issues:o.issues});else if(o.path.length===0)r._errors.push(n(o));else{let u=r,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(o))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return a(e),r}i(bv,"formatError");const Ev=i(e=>(t,n,r,a)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise)throw new qt;if(o.issues.length){const u=new(a?.Err??e)(o.issues.map(l=>xt(l,s,It())));throw Xl(u,a?.callee),u}return o.value},"_parse$1"),wv=i(e=>async(t,n,r,a)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const u=new(a?.Err??e)(o.issues.map(l=>xt(l,s,It())));throw Xl(u,a?.callee),u}return o.value},"_parseAsync"),nc=i(e=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise)throw new qt;return s.issues.length?{success:!1,error:new(e??ec)(s.issues.map(o=>xt(o,a,It())))}:{success:!0,data:s.value}},"_safeParse"),Av=nc(tc),rc=i(e=>async(t,n,r)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},a);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>xt(o,a,It())))}:{success:!0,data:s.value}},"_safeParseAsync"),Iv=rc(tc),xv=/^[cC][^\s-]{8,}$/,kv=/^[0-9a-z]+$/,$v=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Tv=/^[0-9a-vA-V]{20}$/,Bv=/^[A-Za-z0-9]{27}$/,Sv=/^[a-zA-Z0-9_-]{21}$/,Ov=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Rv=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,oc=i(e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,"uuid"),Nv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Pv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Mv(){return new RegExp(Pv,"u")}i(Mv,"emoji");const jv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,zv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,qv=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Zv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Uv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ac=/^[A-Za-z0-9_-]*$/,Lv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Vv=/^\+(?:[0-9]){6,14}[0-9]$/,sc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Gv=new RegExp(`^${sc}$`);function ic(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}i(ic,"timeSource");function Wv(e){return new RegExp(`^${ic(e)}$`)}i(Wv,"time$1");function Hv(e){const t=ic({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${sc}T(?:${r})$`)}i(Hv,"datetime$1");const Jv=i(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),Kv=/^\d+$/,Yv=/^-?\d+(?:\.\d+)?/i,Xv=/true|false/i,Qv=/null/i,ey=/^[^A-Z]*$/,ty=/^[^a-z]*$/,Ue=x("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),uc={number:"number",bigint:"bigint",object:"date"},lc=x("$ZodCheckLessThan",(e,t)=>{Ue.init(e,t);const n=uc[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,s=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?a.maximum=t.value:a.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),cc=x("$ZodCheckGreaterThan",(e,t)=>{Ue.init(e,t);const n=uc[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,s=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ny=x("$ZodCheckMultipleOf",(e,t)=>{Ue.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):pv(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),ry=x("$ZodCheckNumberFormat",(e,t)=>{Ue.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[a,s]=hv[t.format];e._zod.onattach.push(o=>{const u=o._zod.bag;u.format=t.format,u.minimum=a,u.maximum=s,n&&(u.pattern=Kv)}),e._zod.check=o=>{const u=o.value;if(n){if(!Number.isInteger(u)){o.issues.push({expected:r,format:t.format,code:"invalid_type",input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?o.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):o.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}u<a&&o.issues.push({origin:"number",input:u,code:"too_small",minimum:a,inclusive:!0,inst:e,continue:!t.abort}),u>s&&o.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inst:e})}}),oy=x("$ZodCheckMaxLength",(e,t)=>{var n;Ue.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!Pa(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const a=r.value;if(a.length<=t.maximum)return;const o=za(a);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),ay=x("$ZodCheckMinLength",(e,t)=>{var n;Ue.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!Pa(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const a=r.value;if(a.length>=t.minimum)return;const o=za(a);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),sy=x("$ZodCheckLengthEquals",(e,t)=>{var n;Ue.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!Pa(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),e._zod.check=r=>{const a=r.value,s=a.length;if(s===t.length)return;const o=za(a),u=s>t.length;r.issues.push({origin:o,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),ho=x("$ZodCheckStringFormat",(e,t)=>{var n,r;Ue.init(e,t),e._zod.onattach.push(a=>{const s=a._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),iy=x("$ZodCheckRegex",(e,t)=>{ho.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),uy=x("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ey),ho.init(e,t)}),ly=x("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ty),ho.init(e,t)}),cy=x("$ZodCheckIncludes",(e,t)=>{Ue.init(e,t);const n=Cr(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(a=>{const s=a._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:e,continue:!t.abort})}}),py=x("$ZodCheckStartsWith",(e,t)=>{Ue.init(e,t);const n=new RegExp(`^${Cr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),dy=x("$ZodCheckEndsWith",(e,t)=>{Ue.init(e,t);const n=new RegExp(`.*${Cr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),my=x("$ZodCheckOverwrite",(e,t)=>{Ue.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}}),Zs=class Zs{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
88
88
  `).filter(o=>o),a=Math.min(...r.map(o=>o.length-o.trimStart().length)),s=r.map(o=>o.slice(a)).map(o=>" ".repeat(this.indent*2)+o);for(const o of s)this.content.push(o)}compile(){const t=Function,n=this?.args,a=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,a.join(`
89
- `))}};i(Zs,"Doc");let qa=Zs;const dy={major:4,minor:0,patch:0},de=x("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=dy;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const a of r)for(const s of a._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const a=i((s,o,u)=>{let l=br(s),c;for(const d of o){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(l)continue;const m=s.issues.length,h=d._zod.check(s);if(h instanceof Promise&&u?.async===!1)throw new qt;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,s.issues.length!==m&&(l||(l=br(s,m)))});else{if(s.issues.length===m)continue;l||(l=br(s,m))}}return c?c.then(()=>s):s},"runChecks");e._zod.run=(s,o)=>{const u=e._zod.parse(s,o);if(u instanceof Promise){if(o.async===!1)throw new qt;return u.then(l=>a(l,r,o))}return a(u,r,o)}}e["~standard"]={validate:i(a=>{try{const s=Ev(e,a);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return wv(e,a).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},"validate"),vendor:"zod",version:1}}),Za=x("$ZodString",(e,t)=>{de.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Wv(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ce=x("$ZodStringFormat",(e,t)=>{mo.init(e,t),Za.init(e,t)}),my=x("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Sv),Ce.init(e,t)}),fy=x("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=nc(r))}else t.pattern??(t.pattern=nc());Ce.init(e,t)}),hy=x("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ov),Ce.init(e,t)}),Dy=x("$ZodURL",(e,t)=>{Ce.init(e,t),e._zod.check=n=>{try{const r=n.value,a=new URL(r),s=a.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Zv.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),gy=x("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Nv()),Ce.init(e,t)}),vy=x("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Tv),Ce.init(e,t)}),yy=x("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Av),Ce.init(e,t)}),_y=x("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Iv),Ce.init(e,t)}),Fy=x("$ZodULID",(e,t)=>{t.pattern??(t.pattern=xv),Ce.init(e,t)}),Cy=x("$ZodXID",(e,t)=>{t.pattern??(t.pattern=kv),Ce.init(e,t)}),by=x("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=$v),Ce.init(e,t)}),Ey=x("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Gv(t)),Ce.init(e,t)}),wy=x("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Uv),Ce.init(e,t)}),Ay=x("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Vv(t)),Ce.init(e,t)}),Iy=x("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Bv),Ce.init(e,t)}),xy=x("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Pv),Ce.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),ky=x("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Mv),Ce.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),$y=x("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=jv),Ce.init(e,t)}),Ty=x("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=zv),Ce.init(e,t),e._zod.check=n=>{const[r,a]=n.value.split("/");try{if(!a)throw new Error;const s=Number(a);if(`${s}`!==a)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function lc(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}i(lc,"isValidBase64");const By=x("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=qv),Ce.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{lc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Sy(e){if(!rc.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return lc(n)}i(Sy,"isValidBase64URL");const Oy=x("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=rc),Ce.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Sy(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Ry=x("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Lv),Ce.init(e,t)});function Ny(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const a=JSON.parse(atob(r));return!("typ"in a&&a?.typ!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}i(Ny,"isValidJWT");const Py=x("$ZodJWT",(e,t)=>{Ce.init(e,t),e._zod.check=n=>{Ny(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),cc=x("$ZodNumber",(e,t)=>{de.init(e,t),e._zod.pattern=e._zod.bag.pattern??Jv,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;const s=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:e,...s?{received:s}:{}}),n}}),My=x("$ZodNumber",(e,t)=>{ty.init(e,t),cc.init(e,t)}),jy=x("$ZodBoolean",(e,t)=>{de.init(e,t),e._zod.pattern=Kv,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:e}),n}}),zy=x("$ZodNull",(e,t)=>{de.init(e,t),e._zod.pattern=Yv,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const a=n.value;return a===null||n.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),n}}),qy=x("$ZodAny",(e,t)=>{de.init(e,t),e._zod.parse=n=>n}),Zy=x("$ZodUnknown",(e,t)=>{de.init(e,t),e._zod.parse=n=>n}),Ly=x("$ZodNever",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function pc(e,t,n){e.issues.length&&t.issues.push(...Lt(n,e.issues)),t.value[n]=e.value}i(pc,"handleArrayResult");const Uy=x("$ZodArray",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),n;n.value=Array(a.length);const s=[];for(let o=0;o<a.length;o++){const u=a[o],l=t.element._zod.run({value:u,issues:[]},r);l instanceof Promise?s.push(l.then(c=>pc(c,n,o))):pc(l,n,o)}return s.length?Promise.all(s).then(()=>n):n}});function fo(e,t,n){e.issues.length&&t.issues.push(...Lt(n,e.issues)),t.value[n]=e.value}i(fo,"handleObjectResult");function dc(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...Lt(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}i(dc,"handleOptionalObjectResult");const Vy=x("$ZodObject",(e,t)=>{de.init(e,t);const n=Na(()=>{const m=Object.keys(t.shape);for(const D of m)if(!(t.shape[D]instanceof de))throw new Error(`Invalid element at key "${D}": expected a Zod schema`);const h=dv(t.shape);return{shape:t.shape,keys:m,keySet:new Set(m),numKeys:m.length,optionalKeys:new Set(h)}});se(e._zod,"propValues",()=>{const m=t.shape,h={};for(const D in m){const f=m[D]._zod;if(f.values){h[D]??(h[D]=new Set);for(const v of f.values)h[D].add(v)}}return h});const r=i(m=>{const h=new qa(["shape","payload","ctx"]),D=n.value,f=i(E=>{const b=Fr(E);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`},"parseStr");h.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const E of D.keys)v[E]=`key_${y++}`;h.write("const newResult = {}");for(const E of D.keys)if(D.optionalKeys.has(E)){const b=v[E];h.write(`const ${b} = ${f(E)};`);const w=Fr(E);h.write(`
89
+ `))}};i(Zs,"Doc");let qa=Zs;const fy={major:4,minor:0,patch:0},de=x("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=fy;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const a of r)for(const s of a._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const a=i((s,o,u)=>{let l=br(s),c;for(const d of o){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(l)continue;const m=s.issues.length,h=d._zod.check(s);if(h instanceof Promise&&u?.async===!1)throw new qt;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,s.issues.length!==m&&(l||(l=br(s,m)))});else{if(s.issues.length===m)continue;l||(l=br(s,m))}}return c?c.then(()=>s):s},"runChecks");e._zod.run=(s,o)=>{const u=e._zod.parse(s,o);if(u instanceof Promise){if(o.async===!1)throw new qt;return u.then(l=>a(l,r,o))}return a(u,r,o)}}e["~standard"]={validate:i(a=>{try{const s=Av(e,a);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Iv(e,a).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},"validate"),vendor:"zod",version:1}}),Za=x("$ZodString",(e,t)=>{de.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Jv(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ce=x("$ZodStringFormat",(e,t)=>{ho.init(e,t),Za.init(e,t)}),hy=x("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Rv),Ce.init(e,t)}),Dy=x("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=oc(r))}else t.pattern??(t.pattern=oc());Ce.init(e,t)}),gy=x("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Nv),Ce.init(e,t)}),vy=x("$ZodURL",(e,t)=>{Ce.init(e,t),e._zod.check=n=>{try{const r=n.value,a=new URL(r),s=a.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Lv.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),yy=x("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Mv()),Ce.init(e,t)}),_y=x("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Sv),Ce.init(e,t)}),Fy=x("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=xv),Ce.init(e,t)}),Cy=x("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=kv),Ce.init(e,t)}),by=x("$ZodULID",(e,t)=>{t.pattern??(t.pattern=$v),Ce.init(e,t)}),Ey=x("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Tv),Ce.init(e,t)}),wy=x("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Bv),Ce.init(e,t)}),Ay=x("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Hv(t)),Ce.init(e,t)}),Iy=x("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Gv),Ce.init(e,t)}),xy=x("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Wv(t)),Ce.init(e,t)}),ky=x("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ov),Ce.init(e,t)}),$y=x("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=jv),Ce.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),Ty=x("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=zv),Ce.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),By=x("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=qv),Ce.init(e,t)}),Sy=x("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Zv),Ce.init(e,t),e._zod.check=n=>{const[r,a]=n.value.split("/");try{if(!a)throw new Error;const s=Number(a);if(`${s}`!==a)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function pc(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}i(pc,"isValidBase64");const Oy=x("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Uv),Ce.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{pc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Ry(e){if(!ac.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return pc(n)}i(Ry,"isValidBase64URL");const Ny=x("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ac),Ce.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Ry(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Py=x("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Vv),Ce.init(e,t)});function My(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const a=JSON.parse(atob(r));return!("typ"in a&&a?.typ!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}i(My,"isValidJWT");const jy=x("$ZodJWT",(e,t)=>{Ce.init(e,t),e._zod.check=n=>{My(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),dc=x("$ZodNumber",(e,t)=>{de.init(e,t),e._zod.pattern=e._zod.bag.pattern??Yv,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;const s=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:e,...s?{received:s}:{}}),n}}),zy=x("$ZodNumber",(e,t)=>{ry.init(e,t),dc.init(e,t)}),qy=x("$ZodBoolean",(e,t)=>{de.init(e,t),e._zod.pattern=Xv,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:e}),n}}),Zy=x("$ZodNull",(e,t)=>{de.init(e,t),e._zod.pattern=Qv,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const a=n.value;return a===null||n.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),n}}),Uy=x("$ZodAny",(e,t)=>{de.init(e,t),e._zod.parse=n=>n}),Ly=x("$ZodUnknown",(e,t)=>{de.init(e,t),e._zod.parse=n=>n}),Vy=x("$ZodNever",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function mc(e,t,n){e.issues.length&&t.issues.push(...Ut(n,e.issues)),t.value[n]=e.value}i(mc,"handleArrayResult");const Gy=x("$ZodArray",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),n;n.value=Array(a.length);const s=[];for(let o=0;o<a.length;o++){const u=a[o],l=t.element._zod.run({value:u,issues:[]},r);l instanceof Promise?s.push(l.then(c=>mc(c,n,o))):mc(l,n,o)}return s.length?Promise.all(s).then(()=>n):n}});function Do(e,t,n){e.issues.length&&t.issues.push(...Ut(n,e.issues)),t.value[n]=e.value}i(Do,"handleObjectResult");function fc(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...Ut(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}i(fc,"handleOptionalObjectResult");const Wy=x("$ZodObject",(e,t)=>{de.init(e,t);const n=Na(()=>{const m=Object.keys(t.shape);for(const D of m)if(!(t.shape[D]instanceof de))throw new Error(`Invalid element at key "${D}": expected a Zod schema`);const h=fv(t.shape);return{shape:t.shape,keys:m,keySet:new Set(m),numKeys:m.length,optionalKeys:new Set(h)}});se(e._zod,"propValues",()=>{const m=t.shape,h={};for(const D in m){const f=m[D]._zod;if(f.values){h[D]??(h[D]=new Set);for(const v of f.values)h[D].add(v)}}return h});const r=i(m=>{const h=new qa(["shape","payload","ctx"]),D=n.value,f=i(E=>{const b=Fr(E);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`},"parseStr");h.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const E of D.keys)v[E]=`key_${y++}`;h.write("const newResult = {}");for(const E of D.keys)if(D.optionalKeys.has(E)){const b=v[E];h.write(`const ${b} = ${f(E)};`);const w=Fr(E);h.write(`
90
90
  if (${b}.issues.length) {
91
91
  if (input[${w}] === undefined) {
92
92
  if (${w} in input) {
@@ -109,18 +109,18 @@ Error message: ${yr(n)}`,cause:n}),this[Zl]=!0,this.value=t}static isInstance(t)
109
109
  if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
110
110
  ...iss,
111
111
  path: iss.path ? [${Fr(E)}, ...iss.path] : [${Fr(E)}]
112
- })));`),h.write(`newResult[${Fr(E)}] = ${b}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const F=h.compile();return(E,b)=>F(m,E,b)},"generateFastpass");let a;const s=lo,o=!Hl.jitless,l=o&&cv.value,c=t.catchall;let d;e._zod.parse=(m,h)=>{d??(d=n.value);const D=m.value;if(!s(D))return m.issues.push({expected:"object",code:"invalid_type",input:D,inst:e}),m;const f=[];if(o&&l&&h?.async===!1&&h.jitless!==!0)a||(a=r(t.shape)),m=a(m,h);else{m.value={};const b=d.shape;for(const w of d.keys){const S=b[w],k=S._zod.run({value:D[w],issues:[]},h),C=S._zod.optin==="optional"&&S._zod.optout==="optional";k instanceof Promise?f.push(k.then(z=>C?dc(z,m,w,D):fo(z,m,w))):C?dc(k,m,w,D):fo(k,m,w)}}if(!c)return f.length?Promise.all(f).then(()=>m):m;const v=[],y=d.keySet,F=c._zod,E=F.def.type;for(const b of Object.keys(D)){if(y.has(b))continue;if(E==="never"){v.push(b);continue}const w=F.run({value:D[b],issues:[]},h);w instanceof Promise?f.push(w.then(S=>fo(S,m,b))):fo(w,m,b)}return v.length&&m.issues.push({code:"unrecognized_keys",keys:v,input:D,inst:e}),f.length?Promise.all(f).then(()=>m):m}});function mc(e,t,n,r){for(const a of e)if(a.issues.length===0)return t.value=a.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(a=>a.issues.map(s=>xt(s,r,It())))}),t}i(mc,"handleUnionResults");const fc=x("$ZodUnion",(e,t)=>{de.init(e,t),se(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),se(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),se(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),se(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Ma(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let a=!1;const s=[];for(const o of t.options){const u=o._zod.run({value:n.value,issues:[]},r);if(u instanceof Promise)s.push(u),a=!0;else{if(u.issues.length===0)return u;s.push(u)}}return a?Promise.all(s).then(o=>mc(o,n,e,r)):mc(s,n,e,r)}}),Gy=x("$ZodDiscriminatedUnion",(e,t)=>{fc.init(e,t);const n=e._zod.parse;se(e._zod,"propValues",()=>{const a={};for(const s of t.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[u,l]of Object.entries(o)){a[u]||(a[u]=new Set);for(const c of l)a[u].add(c)}}return a});const r=Na(()=>{const a=t.options,s=new Map;for(const o of a){const u=o._zod.propValues[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const l of u){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,o)}}return s});e._zod.parse=(a,s)=>{const o=a.value;if(!lo(o))return a.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),a;const u=r.value.get(o?.[t.discriminator]);return u?u._zod.run(a,s):t.unionFallback?n(a,s):(a.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[t.discriminator],inst:e}),a)}}),Wy=x("$ZodIntersection",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=n.value,s=t.left._zod.run({value:a,issues:[]},r),o=t.right._zod.run({value:a,issues:[]},r);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([l,c])=>hc(n,l,c)):hc(n,s,o)}});function La(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(co(e)&&co(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),a={...e,...t};for(const s of r){const o=La(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};a[s]=o.data}return{valid:!0,data:a}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const a=e[r],s=t[r],o=La(a,s);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}i(La,"mergeValues");function hc(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),br(e))return e;const r=La(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}i(hc,"handleIntersectionResults");const Hy=x("$ZodRecord",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!co(a))return n.issues.push({expected:"record",code:"invalid_type",input:a,inst:e}),n;const s=[];if(t.keyType._zod.values){const o=t.keyType._zod.values;n.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:a[l],issues:[]},r);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(...Lt(l,d.issues)),n.value[l]=d.value})):(c.issues.length&&n.issues.push(...Lt(l,c.issues)),n.value[l]=c.value)}let u;for(const l in a)o.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:a,inst:e,keys:u})}else{n.value={};for(const o of Reflect.ownKeys(a)){if(o==="__proto__")continue;const u=t.keyType._zod.run({value:o,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:u.issues.map(c=>xt(c,r,It())),input:o,path:[o],inst:e}),n.value[u.value]=u.value;continue}const l=t.valueType._zod.run({value:a[o],issues:[]},r);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&n.issues.push(...Lt(o,c.issues)),n.value[u.value]=c.value})):(l.issues.length&&n.issues.push(...Lt(o,l.issues)),n.value[u.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Jy=x("$ZodEnum",(e,t)=>{de.init(e,t);const n=Jl(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>pv.has(typeof r)).map(r=>typeof r=="string"?Cr(r):r.toString()).join("|")})$`),e._zod.parse=(r,a)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Ky=x("$ZodLiteral",(e,t)=>{de.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Cr(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const a=n.value;return e._zod.values.has(a)||n.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),n}}),Yy=x("$ZodTransform",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=t.transform(n.value,n);if(r.async)return(a instanceof Promise?a:Promise.resolve(a)).then(o=>(n.value=o,n));if(a instanceof Promise)throw new qt;return n.value=a,n}}),Xy=x("$ZodOptional",(e,t)=>{de.init(e,t),e._zod.optin="optional",e._zod.optout="optional",se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),se(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ma(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),Qy=x("$ZodNullable",(e,t)=>{de.init(e,t),se(e._zod,"optin",()=>t.innerType._zod.optin),se(e._zod,"optout",()=>t.innerType._zod.optout),se(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ma(n.source)}|null)$`):void 0}),se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),e0=x("$ZodDefault",(e,t)=>{de.init(e,t),e._zod.optin="optional",se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(s=>Dc(s,t)):Dc(a,t)}});function Dc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}i(Dc,"handleDefaultResult");const t0=x("$ZodPrefault",(e,t)=>{de.init(e,t),e._zod.optin="optional",se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),n0=x("$ZodNonOptional",(e,t)=>{de.init(e,t),se(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(s=>gc(s,e)):gc(a,e)}});function gc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}i(gc,"handleNonOptionalResult");const r0=x("$ZodCatch",(e,t)=>{de.init(e,t),e._zod.optin="optional",se(e._zod,"optout",()=>t.innerType._zod.optout),se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(o=>xt(o,r,It()))},input:n.value}),n.issues=[]),n)):(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(s=>xt(s,r,It()))},input:n.value}),n.issues=[]),n)}}),o0=x("$ZodPipe",(e,t)=>{de.init(e,t),se(e._zod,"values",()=>t.in._zod.values),se(e._zod,"optin",()=>t.in._zod.optin),se(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(s=>vc(s,t,r)):vc(a,t,r)}});function vc(e,t,n){return br(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}i(vc,"handlePipeResult");const a0=x("$ZodReadonly",(e,t)=>{de.init(e,t),se(e._zod,"propValues",()=>t.innerType._zod.propValues),se(e._zod,"values",()=>t.innerType._zod.values),se(e._zod,"optin",()=>t.innerType._zod.optin),se(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(yc):yc(a)}});function yc(e){return e.value=Object.freeze(e.value),e}i(yc,"handleReadonlyResult");const s0=x("$ZodLazy",(e,t)=>{de.init(e,t),se(e._zod,"innerType",()=>t.getter()),se(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),se(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),se(e._zod,"optin",()=>e._zod.innerType._zod.optin),se(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),i0=x("$ZodCustom",(e,t)=>{Le.init(e,t),de.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,a=t.fn(r);if(a instanceof Promise)return a.then(s=>_c(s,n,r,e));_c(a,n,r,e)}});function _c(e,t,n,r){if(!e){const a={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(a.params=r._zod.def.params),t.issues.push(Er(a))}}i(_c,"handleRefineResult");const Ls=class Ls{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};i(Ls,"$ZodRegistry");let ho=Ls;function u0(){return new ho}i(u0,"registry");const wr=u0();function l0(e,t){return new e({type:"string",...q(t)})}i(l0,"_string");function c0(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...q(t)})}i(c0,"_email");function Fc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...q(t)})}i(Fc,"_guid");function p0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...q(t)})}i(p0,"_uuid");function d0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(t)})}i(d0,"_uuidv4");function m0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(t)})}i(m0,"_uuidv6");function f0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(t)})}i(f0,"_uuidv7");function h0(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...q(t)})}i(h0,"_url");function D0(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...q(t)})}i(D0,"_emoji");function g0(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(t)})}i(g0,"_nanoid");function v0(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...q(t)})}i(v0,"_cuid");function y0(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(t)})}i(y0,"_cuid2");function _0(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...q(t)})}i(_0,"_ulid");function F0(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...q(t)})}i(F0,"_xid");function C0(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(t)})}i(C0,"_ksuid");function b0(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(t)})}i(b0,"_ipv4");function E0(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(t)})}i(E0,"_ipv6");function w0(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(t)})}i(w0,"_cidrv4");function A0(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(t)})}i(A0,"_cidrv6");function I0(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...q(t)})}i(I0,"_base64");function x0(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...q(t)})}i(x0,"_base64url");function k0(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...q(t)})}i(k0,"_e164");function $0(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...q(t)})}i($0,"_jwt");function T0(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(t)})}i(T0,"_isoDateTime");function B0(e,t){return new e({type:"string",format:"date",check:"string_format",...q(t)})}i(B0,"_isoDate");function S0(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...q(t)})}i(S0,"_isoTime");function O0(e,t){return new e({type:"string",format:"duration",check:"string_format",...q(t)})}i(O0,"_isoDuration");function R0(e,t){return new e({type:"number",checks:[],...q(t)})}i(R0,"_number");function N0(e,t){return new e({type:"number",coerce:!0,checks:[],...q(t)})}i(N0,"_coercedNumber");function P0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...q(t)})}i(P0,"_int");function M0(e,t){return new e({type:"boolean",...q(t)})}i(M0,"_boolean");function j0(e,t){return new e({type:"null",...q(t)})}i(j0,"_null$1");function z0(e){return new e({type:"any"})}i(z0,"_any");function q0(e){return new e({type:"unknown"})}i(q0,"_unknown");function Z0(e,t){return new e({type:"never",...q(t)})}i(Z0,"_never");function Cc(e,t){return new ic({check:"less_than",...q(t),value:e,inclusive:!1})}i(Cc,"_lt");function Ua(e,t){return new ic({check:"less_than",...q(t),value:e,inclusive:!0})}i(Ua,"_lte");function bc(e,t){return new uc({check:"greater_than",...q(t),value:e,inclusive:!1})}i(bc,"_gt");function Va(e,t){return new uc({check:"greater_than",...q(t),value:e,inclusive:!0})}i(Va,"_gte");function Ec(e,t){return new ey({check:"multiple_of",...q(t),value:e})}i(Ec,"_multipleOf");function wc(e,t){return new ny({check:"max_length",...q(t),maximum:e})}i(wc,"_maxLength");function Do(e,t){return new ry({check:"min_length",...q(t),minimum:e})}i(Do,"_minLength");function Ac(e,t){return new oy({check:"length_equals",...q(t),length:e})}i(Ac,"_length");function L0(e,t){return new ay({check:"string_format",format:"regex",...q(t),pattern:e})}i(L0,"_regex");function U0(e){return new sy({check:"string_format",format:"lowercase",...q(e)})}i(U0,"_lowercase");function V0(e){return new iy({check:"string_format",format:"uppercase",...q(e)})}i(V0,"_uppercase");function G0(e,t){return new uy({check:"string_format",format:"includes",...q(t),includes:e})}i(G0,"_includes");function W0(e,t){return new ly({check:"string_format",format:"starts_with",...q(t),prefix:e})}i(W0,"_startsWith");function H0(e,t){return new cy({check:"string_format",format:"ends_with",...q(t),suffix:e})}i(H0,"_endsWith");function Ar(e){return new py({check:"overwrite",tx:e})}i(Ar,"_overwrite");function J0(e){return Ar(t=>t.normalize(e))}i(J0,"_normalize");function K0(){return Ar(e=>e.trim())}i(K0,"_trim");function Y0(){return Ar(e=>e.toLowerCase())}i(Y0,"_toLowerCase");function X0(){return Ar(e=>e.toUpperCase())}i(X0,"_toUpperCase");function Q0(e,t,n){return new e({type:"array",element:t,...q(n)})}i(Q0,"_array");function e_(e,t,n){const r=q(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}i(e_,"_custom");function t_(e,t,n){return new e({type:"custom",check:"custom",fn:t,...q(n)})}i(t_,"_refine");const Us=class Us{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??wr,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var r;const a=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(t);if(o)return o.count++,n.schemaPath.includes(t)&&(o.cycle=n.path),o.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,u);const l=t._zod.toJSONSchema?.();if(l)u.schema=l;else{const m={...n,schemaPath:[...n.schemaPath,t],path:n.path},h=t._zod.parent;if(h)u.ref=h,this.process(h,m),this.seen.get(h).isParent=!0;else{const D=u.schema;switch(a.type){case"string":{const f=D;f.type="string";const{minimum:v,maximum:y,format:F,patterns:E,contentEncoding:b}=t._zod.bag;if(typeof v=="number"&&(f.minLength=v),typeof y=="number"&&(f.maxLength=y),F&&(f.format=s[F]??F,f.format===""&&delete f.format),b&&(f.contentEncoding=b),E&&E.size>0){const w=[...E];w.length===1?f.pattern=w[0].source:w.length>1&&(u.schema.allOf=[...w.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{const f=D,{minimum:v,maximum:y,format:F,multipleOf:E,exclusiveMaximum:b,exclusiveMinimum:w}=t._zod.bag;typeof F=="string"&&F.includes("int")?f.type="integer":f.type="number",typeof w=="number"&&(f.exclusiveMinimum=w),typeof v=="number"&&(f.minimum=v,typeof w=="number"&&(w>=v?delete f.minimum:delete f.exclusiveMinimum)),typeof b=="number"&&(f.exclusiveMaximum=b),typeof y=="number"&&(f.maximum=y,typeof b=="number"&&(b<=y?delete f.maximum:delete f.exclusiveMaximum)),typeof E=="number"&&(f.multipleOf=E);break}case"boolean":{const f=D;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{D.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{D.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const f=D,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(f.minItems=v),typeof y=="number"&&(f.maxItems=y),f.type="array",f.items=this.process(a.element,{...m,path:[...m.path,"items"]});break}case"object":{const f=D;f.type="object",f.properties={};const v=a.shape;for(const E in v)f.properties[E]=this.process(v[E],{...m,path:[...m.path,"properties",E]});const y=new Set(Object.keys(v)),F=new Set([...y].filter(E=>{const b=a.shape[E]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));F.size>0&&(f.required=Array.from(F)),a.catchall?._zod.def.type==="never"?f.additionalProperties=!1:a.catchall?a.catchall&&(f.additionalProperties=this.process(a.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=D;f.anyOf=a.options.map((v,y)=>this.process(v,{...m,path:[...m.path,"anyOf",y]}));break}case"intersection":{const f=D,v=this.process(a.left,{...m,path:[...m.path,"allOf",0]}),y=this.process(a.right,{...m,path:[...m.path,"allOf",1]}),F=i(b=>"allOf"in b&&Object.keys(b).length===1,"isSimpleIntersection"),E=[...F(v)?v.allOf:[v],...F(y)?y.allOf:[y]];f.allOf=E;break}case"tuple":{const f=D;f.type="array";const v=a.items.map((E,b)=>this.process(E,{...m,path:[...m.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?f.prefixItems=v:f.items=v,a.rest){const E=this.process(a.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?f.items=E:f.additionalItems=E}a.rest&&(f.items=this.process(a.rest,{...m,path:[...m.path,"items"]}));const{minimum:y,maximum:F}=t._zod.bag;typeof y=="number"&&(f.minItems=y),typeof F=="number"&&(f.maxItems=F);break}case"record":{const f=D;f.type="object",f.propertyNames=this.process(a.keyType,{...m,path:[...m.path,"propertyNames"]}),f.additionalProperties=this.process(a.valueType,{...m,path:[...m.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const f=D,v=Jl(a.entries);v.every(y=>typeof y=="number")&&(f.type="number"),v.every(y=>typeof y=="string")&&(f.type="string"),f.enum=v;break}case"literal":{const f=D,v=[];for(const y of a.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];f.type=y===null?"null":typeof y,f.const=y}else v.every(y=>typeof y=="number")&&(f.type="number"),v.every(y=>typeof y=="string")&&(f.type="string"),v.every(y=>typeof y=="boolean")&&(f.type="string"),v.every(y=>y===null)&&(f.type="null"),f.enum=v;break}case"file":{const f=D,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:F,mime:E}=t._zod.bag;y!==void 0&&(v.minLength=y),F!==void 0&&(v.maxLength=F),E?E.length===1?(v.contentMediaType=E[0],Object.assign(f,v)):f.anyOf=E.map(b=>({...v,contentMediaType:b})):Object.assign(f,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(a.innerType,m);D.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(a.innerType,m),u.ref=a.innerType;break}case"success":{const f=D;f.type="boolean";break}case"default":{this.process(a.innerType,m),u.ref=a.innerType,D.default=JSON.parse(JSON.stringify(a.defaultValue));break}case"prefault":{this.process(a.innerType,m),u.ref=a.innerType,this.io==="input"&&(D._prefault=JSON.parse(JSON.stringify(a.defaultValue)));break}case"catch":{this.process(a.innerType,m),u.ref=a.innerType;let f;try{f=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}D.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=D,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=v.source;break}case"pipe":{const f=this.io==="input"?a.in._zod.def.type==="transform"?a.out:a.in:a.out;this.process(f,m),u.ref=f;break}case"readonly":{this.process(a.innerType,m),u.ref=a.innerType,D.readOnly=!0;break}case"promise":{this.process(a.innerType,m),u.ref=a.innerType;break}case"optional":{this.process(a.innerType,m),u.ref=a.innerType;break}case"lazy":{const f=t._zod.innerType;this.process(f,m),u.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(u.schema,c),this.io==="input"&&Te(t)&&(delete u.schema.examples,delete u.schema.default),this.io==="input"&&u.schema._prefault&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,this.seen.get(t).schema}emit(t,n){const r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},a=this.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i(d=>{const m=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const v=r.external.registry.get(d[0])?.id,y=r.external.uri??(E=>E);if(v)return{ref:y(v)};const F=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=F,{defId:F,ref:`${y("__shared")}#/${m}/${F}`}}if(d[1]===a)return{ref:"#"};const D=`#/${m}/`,f=d[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:D+f}},"makeURI"),o=i(d=>{if(d[1].schema.$ref)return;const m=d[1],{ref:h,defId:D}=s(d);m.def={...m.schema},D&&(m.defId=D);const f=m.schema;for(const v in f)delete f[v];f.$ref=h},"extractToDef");if(r.cycles==="throw")for(const d of this.seen.entries()){const m=d[1];if(m.cycle)throw new Error(`Cycle detected: #/${m.cycle?.join("/")}/<root>
112
+ })));`),h.write(`newResult[${Fr(E)}] = ${b}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const F=h.compile();return(E,b)=>F(m,E,b)},"generateFastpass");let a;const s=po,o=!Kl.jitless,l=o&&dv.value,c=t.catchall;let d;e._zod.parse=(m,h)=>{d??(d=n.value);const D=m.value;if(!s(D))return m.issues.push({expected:"object",code:"invalid_type",input:D,inst:e}),m;const f=[];if(o&&l&&h?.async===!1&&h.jitless!==!0)a||(a=r(t.shape)),m=a(m,h);else{m.value={};const b=d.shape;for(const w of d.keys){const S=b[w],k=S._zod.run({value:D[w],issues:[]},h),C=S._zod.optin==="optional"&&S._zod.optout==="optional";k instanceof Promise?f.push(k.then(z=>C?fc(z,m,w,D):Do(z,m,w))):C?fc(k,m,w,D):Do(k,m,w)}}if(!c)return f.length?Promise.all(f).then(()=>m):m;const v=[],y=d.keySet,F=c._zod,E=F.def.type;for(const b of Object.keys(D)){if(y.has(b))continue;if(E==="never"){v.push(b);continue}const w=F.run({value:D[b],issues:[]},h);w instanceof Promise?f.push(w.then(S=>Do(S,m,b))):Do(w,m,b)}return v.length&&m.issues.push({code:"unrecognized_keys",keys:v,input:D,inst:e}),f.length?Promise.all(f).then(()=>m):m}});function hc(e,t,n,r){for(const a of e)if(a.issues.length===0)return t.value=a.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(a=>a.issues.map(s=>xt(s,r,It())))}),t}i(hc,"handleUnionResults");const Dc=x("$ZodUnion",(e,t)=>{de.init(e,t),se(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),se(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),se(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),se(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Ma(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let a=!1;const s=[];for(const o of t.options){const u=o._zod.run({value:n.value,issues:[]},r);if(u instanceof Promise)s.push(u),a=!0;else{if(u.issues.length===0)return u;s.push(u)}}return a?Promise.all(s).then(o=>hc(o,n,e,r)):hc(s,n,e,r)}}),Hy=x("$ZodDiscriminatedUnion",(e,t)=>{Dc.init(e,t);const n=e._zod.parse;se(e._zod,"propValues",()=>{const a={};for(const s of t.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[u,l]of Object.entries(o)){a[u]||(a[u]=new Set);for(const c of l)a[u].add(c)}}return a});const r=Na(()=>{const a=t.options,s=new Map;for(const o of a){const u=o._zod.propValues[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const l of u){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,o)}}return s});e._zod.parse=(a,s)=>{const o=a.value;if(!po(o))return a.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),a;const u=r.value.get(o?.[t.discriminator]);return u?u._zod.run(a,s):t.unionFallback?n(a,s):(a.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[t.discriminator],inst:e}),a)}}),Jy=x("$ZodIntersection",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=n.value,s=t.left._zod.run({value:a,issues:[]},r),o=t.right._zod.run({value:a,issues:[]},r);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([l,c])=>gc(n,l,c)):gc(n,s,o)}});function Ua(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(mo(e)&&mo(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),a={...e,...t};for(const s of r){const o=Ua(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};a[s]=o.data}return{valid:!0,data:a}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const a=e[r],s=t[r],o=Ua(a,s);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}i(Ua,"mergeValues");function gc(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),br(e))return e;const r=Ua(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}i(gc,"handleIntersectionResults");const Ky=x("$ZodRecord",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!mo(a))return n.issues.push({expected:"record",code:"invalid_type",input:a,inst:e}),n;const s=[];if(t.keyType._zod.values){const o=t.keyType._zod.values;n.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:a[l],issues:[]},r);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(...Ut(l,d.issues)),n.value[l]=d.value})):(c.issues.length&&n.issues.push(...Ut(l,c.issues)),n.value[l]=c.value)}let u;for(const l in a)o.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:a,inst:e,keys:u})}else{n.value={};for(const o of Reflect.ownKeys(a)){if(o==="__proto__")continue;const u=t.keyType._zod.run({value:o,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:u.issues.map(c=>xt(c,r,It())),input:o,path:[o],inst:e}),n.value[u.value]=u.value;continue}const l=t.valueType._zod.run({value:a[o],issues:[]},r);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&n.issues.push(...Ut(o,c.issues)),n.value[u.value]=c.value})):(l.issues.length&&n.issues.push(...Ut(o,l.issues)),n.value[u.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Yy=x("$ZodEnum",(e,t)=>{de.init(e,t);const n=Yl(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>mv.has(typeof r)).map(r=>typeof r=="string"?Cr(r):r.toString()).join("|")})$`),e._zod.parse=(r,a)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Xy=x("$ZodLiteral",(e,t)=>{de.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Cr(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const a=n.value;return e._zod.values.has(a)||n.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),n}}),Qy=x("$ZodTransform",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=t.transform(n.value,n);if(r.async)return(a instanceof Promise?a:Promise.resolve(a)).then(o=>(n.value=o,n));if(a instanceof Promise)throw new qt;return n.value=a,n}}),e0=x("$ZodOptional",(e,t)=>{de.init(e,t),e._zod.optin="optional",e._zod.optout="optional",se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),se(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ma(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),t0=x("$ZodNullable",(e,t)=>{de.init(e,t),se(e._zod,"optin",()=>t.innerType._zod.optin),se(e._zod,"optout",()=>t.innerType._zod.optout),se(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ma(n.source)}|null)$`):void 0}),se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),n0=x("$ZodDefault",(e,t)=>{de.init(e,t),e._zod.optin="optional",se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(s=>vc(s,t)):vc(a,t)}});function vc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}i(vc,"handleDefaultResult");const r0=x("$ZodPrefault",(e,t)=>{de.init(e,t),e._zod.optin="optional",se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),o0=x("$ZodNonOptional",(e,t)=>{de.init(e,t),se(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(s=>yc(s,e)):yc(a,e)}});function yc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}i(yc,"handleNonOptionalResult");const a0=x("$ZodCatch",(e,t)=>{de.init(e,t),e._zod.optin="optional",se(e._zod,"optout",()=>t.innerType._zod.optout),se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(o=>xt(o,r,It()))},input:n.value}),n.issues=[]),n)):(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(s=>xt(s,r,It()))},input:n.value}),n.issues=[]),n)}}),s0=x("$ZodPipe",(e,t)=>{de.init(e,t),se(e._zod,"values",()=>t.in._zod.values),se(e._zod,"optin",()=>t.in._zod.optin),se(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(s=>_c(s,t,r)):_c(a,t,r)}});function _c(e,t,n){return br(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}i(_c,"handlePipeResult");const i0=x("$ZodReadonly",(e,t)=>{de.init(e,t),se(e._zod,"propValues",()=>t.innerType._zod.propValues),se(e._zod,"values",()=>t.innerType._zod.values),se(e._zod,"optin",()=>t.innerType._zod.optin),se(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(Fc):Fc(a)}});function Fc(e){return e.value=Object.freeze(e.value),e}i(Fc,"handleReadonlyResult");const u0=x("$ZodLazy",(e,t)=>{de.init(e,t),se(e._zod,"innerType",()=>t.getter()),se(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),se(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),se(e._zod,"optin",()=>e._zod.innerType._zod.optin),se(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),l0=x("$ZodCustom",(e,t)=>{Ue.init(e,t),de.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,a=t.fn(r);if(a instanceof Promise)return a.then(s=>Cc(s,n,r,e));Cc(a,n,r,e)}});function Cc(e,t,n,r){if(!e){const a={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(a.params=r._zod.def.params),t.issues.push(Er(a))}}i(Cc,"handleRefineResult");const Us=class Us{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};i(Us,"$ZodRegistry");let go=Us;function c0(){return new go}i(c0,"registry");const wr=c0();function p0(e,t){return new e({type:"string",...q(t)})}i(p0,"_string");function d0(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...q(t)})}i(d0,"_email");function bc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...q(t)})}i(bc,"_guid");function m0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...q(t)})}i(m0,"_uuid");function f0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(t)})}i(f0,"_uuidv4");function h0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(t)})}i(h0,"_uuidv6");function D0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(t)})}i(D0,"_uuidv7");function g0(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...q(t)})}i(g0,"_url");function v0(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...q(t)})}i(v0,"_emoji");function y0(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(t)})}i(y0,"_nanoid");function _0(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...q(t)})}i(_0,"_cuid");function F0(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(t)})}i(F0,"_cuid2");function C0(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...q(t)})}i(C0,"_ulid");function b0(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...q(t)})}i(b0,"_xid");function E0(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(t)})}i(E0,"_ksuid");function w0(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(t)})}i(w0,"_ipv4");function A0(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(t)})}i(A0,"_ipv6");function I0(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(t)})}i(I0,"_cidrv4");function x0(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(t)})}i(x0,"_cidrv6");function k0(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...q(t)})}i(k0,"_base64");function $0(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...q(t)})}i($0,"_base64url");function T0(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...q(t)})}i(T0,"_e164");function B0(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...q(t)})}i(B0,"_jwt");function S0(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(t)})}i(S0,"_isoDateTime");function O0(e,t){return new e({type:"string",format:"date",check:"string_format",...q(t)})}i(O0,"_isoDate");function R0(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...q(t)})}i(R0,"_isoTime");function N0(e,t){return new e({type:"string",format:"duration",check:"string_format",...q(t)})}i(N0,"_isoDuration");function P0(e,t){return new e({type:"number",checks:[],...q(t)})}i(P0,"_number");function M0(e,t){return new e({type:"number",coerce:!0,checks:[],...q(t)})}i(M0,"_coercedNumber");function j0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...q(t)})}i(j0,"_int");function z0(e,t){return new e({type:"boolean",...q(t)})}i(z0,"_boolean");function q0(e,t){return new e({type:"null",...q(t)})}i(q0,"_null$1");function Z0(e){return new e({type:"any"})}i(Z0,"_any");function U0(e){return new e({type:"unknown"})}i(U0,"_unknown");function L0(e,t){return new e({type:"never",...q(t)})}i(L0,"_never");function Ec(e,t){return new lc({check:"less_than",...q(t),value:e,inclusive:!1})}i(Ec,"_lt");function La(e,t){return new lc({check:"less_than",...q(t),value:e,inclusive:!0})}i(La,"_lte");function wc(e,t){return new cc({check:"greater_than",...q(t),value:e,inclusive:!1})}i(wc,"_gt");function Va(e,t){return new cc({check:"greater_than",...q(t),value:e,inclusive:!0})}i(Va,"_gte");function Ac(e,t){return new ny({check:"multiple_of",...q(t),value:e})}i(Ac,"_multipleOf");function Ic(e,t){return new oy({check:"max_length",...q(t),maximum:e})}i(Ic,"_maxLength");function vo(e,t){return new ay({check:"min_length",...q(t),minimum:e})}i(vo,"_minLength");function xc(e,t){return new sy({check:"length_equals",...q(t),length:e})}i(xc,"_length");function V0(e,t){return new iy({check:"string_format",format:"regex",...q(t),pattern:e})}i(V0,"_regex");function G0(e){return new uy({check:"string_format",format:"lowercase",...q(e)})}i(G0,"_lowercase");function W0(e){return new ly({check:"string_format",format:"uppercase",...q(e)})}i(W0,"_uppercase");function H0(e,t){return new cy({check:"string_format",format:"includes",...q(t),includes:e})}i(H0,"_includes");function J0(e,t){return new py({check:"string_format",format:"starts_with",...q(t),prefix:e})}i(J0,"_startsWith");function K0(e,t){return new dy({check:"string_format",format:"ends_with",...q(t),suffix:e})}i(K0,"_endsWith");function Ar(e){return new my({check:"overwrite",tx:e})}i(Ar,"_overwrite");function Y0(e){return Ar(t=>t.normalize(e))}i(Y0,"_normalize");function X0(){return Ar(e=>e.trim())}i(X0,"_trim");function Q0(){return Ar(e=>e.toLowerCase())}i(Q0,"_toLowerCase");function e_(){return Ar(e=>e.toUpperCase())}i(e_,"_toUpperCase");function t_(e,t,n){return new e({type:"array",element:t,...q(n)})}i(t_,"_array");function n_(e,t,n){const r=q(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}i(n_,"_custom");function r_(e,t,n){return new e({type:"custom",check:"custom",fn:t,...q(n)})}i(r_,"_refine");const Ls=class Ls{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??wr,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var r;const a=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(t);if(o)return o.count++,n.schemaPath.includes(t)&&(o.cycle=n.path),o.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,u);const l=t._zod.toJSONSchema?.();if(l)u.schema=l;else{const m={...n,schemaPath:[...n.schemaPath,t],path:n.path},h=t._zod.parent;if(h)u.ref=h,this.process(h,m),this.seen.get(h).isParent=!0;else{const D=u.schema;switch(a.type){case"string":{const f=D;f.type="string";const{minimum:v,maximum:y,format:F,patterns:E,contentEncoding:b}=t._zod.bag;if(typeof v=="number"&&(f.minLength=v),typeof y=="number"&&(f.maxLength=y),F&&(f.format=s[F]??F,f.format===""&&delete f.format),b&&(f.contentEncoding=b),E&&E.size>0){const w=[...E];w.length===1?f.pattern=w[0].source:w.length>1&&(u.schema.allOf=[...w.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{const f=D,{minimum:v,maximum:y,format:F,multipleOf:E,exclusiveMaximum:b,exclusiveMinimum:w}=t._zod.bag;typeof F=="string"&&F.includes("int")?f.type="integer":f.type="number",typeof w=="number"&&(f.exclusiveMinimum=w),typeof v=="number"&&(f.minimum=v,typeof w=="number"&&(w>=v?delete f.minimum:delete f.exclusiveMinimum)),typeof b=="number"&&(f.exclusiveMaximum=b),typeof y=="number"&&(f.maximum=y,typeof b=="number"&&(b<=y?delete f.maximum:delete f.exclusiveMaximum)),typeof E=="number"&&(f.multipleOf=E);break}case"boolean":{const f=D;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{D.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{D.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const f=D,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(f.minItems=v),typeof y=="number"&&(f.maxItems=y),f.type="array",f.items=this.process(a.element,{...m,path:[...m.path,"items"]});break}case"object":{const f=D;f.type="object",f.properties={};const v=a.shape;for(const E in v)f.properties[E]=this.process(v[E],{...m,path:[...m.path,"properties",E]});const y=new Set(Object.keys(v)),F=new Set([...y].filter(E=>{const b=a.shape[E]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));F.size>0&&(f.required=Array.from(F)),a.catchall?._zod.def.type==="never"?f.additionalProperties=!1:a.catchall?a.catchall&&(f.additionalProperties=this.process(a.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=D;f.anyOf=a.options.map((v,y)=>this.process(v,{...m,path:[...m.path,"anyOf",y]}));break}case"intersection":{const f=D,v=this.process(a.left,{...m,path:[...m.path,"allOf",0]}),y=this.process(a.right,{...m,path:[...m.path,"allOf",1]}),F=i(b=>"allOf"in b&&Object.keys(b).length===1,"isSimpleIntersection"),E=[...F(v)?v.allOf:[v],...F(y)?y.allOf:[y]];f.allOf=E;break}case"tuple":{const f=D;f.type="array";const v=a.items.map((E,b)=>this.process(E,{...m,path:[...m.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?f.prefixItems=v:f.items=v,a.rest){const E=this.process(a.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?f.items=E:f.additionalItems=E}a.rest&&(f.items=this.process(a.rest,{...m,path:[...m.path,"items"]}));const{minimum:y,maximum:F}=t._zod.bag;typeof y=="number"&&(f.minItems=y),typeof F=="number"&&(f.maxItems=F);break}case"record":{const f=D;f.type="object",f.propertyNames=this.process(a.keyType,{...m,path:[...m.path,"propertyNames"]}),f.additionalProperties=this.process(a.valueType,{...m,path:[...m.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const f=D,v=Yl(a.entries);v.every(y=>typeof y=="number")&&(f.type="number"),v.every(y=>typeof y=="string")&&(f.type="string"),f.enum=v;break}case"literal":{const f=D,v=[];for(const y of a.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];f.type=y===null?"null":typeof y,f.const=y}else v.every(y=>typeof y=="number")&&(f.type="number"),v.every(y=>typeof y=="string")&&(f.type="string"),v.every(y=>typeof y=="boolean")&&(f.type="string"),v.every(y=>y===null)&&(f.type="null"),f.enum=v;break}case"file":{const f=D,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:F,mime:E}=t._zod.bag;y!==void 0&&(v.minLength=y),F!==void 0&&(v.maxLength=F),E?E.length===1?(v.contentMediaType=E[0],Object.assign(f,v)):f.anyOf=E.map(b=>({...v,contentMediaType:b})):Object.assign(f,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(a.innerType,m);D.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(a.innerType,m),u.ref=a.innerType;break}case"success":{const f=D;f.type="boolean";break}case"default":{this.process(a.innerType,m),u.ref=a.innerType,D.default=JSON.parse(JSON.stringify(a.defaultValue));break}case"prefault":{this.process(a.innerType,m),u.ref=a.innerType,this.io==="input"&&(D._prefault=JSON.parse(JSON.stringify(a.defaultValue)));break}case"catch":{this.process(a.innerType,m),u.ref=a.innerType;let f;try{f=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}D.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=D,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=v.source;break}case"pipe":{const f=this.io==="input"?a.in._zod.def.type==="transform"?a.out:a.in:a.out;this.process(f,m),u.ref=f;break}case"readonly":{this.process(a.innerType,m),u.ref=a.innerType,D.readOnly=!0;break}case"promise":{this.process(a.innerType,m),u.ref=a.innerType;break}case"optional":{this.process(a.innerType,m),u.ref=a.innerType;break}case"lazy":{const f=t._zod.innerType;this.process(f,m),u.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(u.schema,c),this.io==="input"&&Te(t)&&(delete u.schema.examples,delete u.schema.default),this.io==="input"&&u.schema._prefault&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,this.seen.get(t).schema}emit(t,n){const r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},a=this.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i(d=>{const m=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const v=r.external.registry.get(d[0])?.id,y=r.external.uri??(E=>E);if(v)return{ref:y(v)};const F=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=F,{defId:F,ref:`${y("__shared")}#/${m}/${F}`}}if(d[1]===a)return{ref:"#"};const D=`#/${m}/`,f=d[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:D+f}},"makeURI"),o=i(d=>{if(d[1].schema.$ref)return;const m=d[1],{ref:h,defId:D}=s(d);m.def={...m.schema},D&&(m.defId=D);const f=m.schema;for(const v in f)delete f[v];f.$ref=h},"extractToDef");if(r.cycles==="throw")for(const d of this.seen.entries()){const m=d[1];if(m.cycle)throw new Error(`Cycle detected: #/${m.cycle?.join("/")}/<root>
113
113
 
114
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of this.seen.entries()){const m=d[1];if(t===d[0]){o(d);continue}if(r.external){const D=r.external.registry.get(d[0])?.id;if(t!==d[0]&&D){o(d);continue}}if(this.metadataRegistry.get(d[0])?.id){o(d);continue}if(m.cycle){o(d);continue}if(m.count>1&&r.reused==="ref"){o(d);continue}}const u=i((d,m)=>{const h=this.seen.get(d),D=h.def??h.schema,f={...D};if(h.ref===null)return;const v=h.ref;if(h.ref=null,v){u(v,m);const y=this.seen.get(v).schema;y.$ref&&m.target==="draft-7"?(D.allOf=D.allOf??[],D.allOf.push(y)):(Object.assign(D,y),Object.assign(D,f))}h.isParent||this.override({zodSchema:d,jsonSchema:D,path:h.path??[]})},"flattenRef");for(const d of[...this.seen.entries()].reverse())u(d[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const d=r.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(d)}Object.assign(l,a.def);const c=r.external?.defs??{};for(const d of this.seen.entries()){const m=d[1];m.def&&m.defId&&(c[m.defId]=m.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}};i(Us,"JSONSchemaGenerator");let go=Us;function n_(e,t){if(e instanceof ho){const r=new go(t),a={};for(const u of e._idmap.entries()){const[l,c]=u;r.process(c)}const s={},o={registry:e,uri:t?.uri,defs:a};for(const u of e._idmap.entries()){const[l,c]=u;s[l]=r.emit(c,{...t,external:o})}if(Object.keys(a).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:a}}return{schemas:s}}const n=new go(t);return n.process(e),n.emit(e,t)}i(n_,"toJSONSchema");function Te(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;switch(a.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Te(a.element,n);case"object":{for(const s in a.shape)if(Te(a.shape[s],n))return!0;return!1}case"union":{for(const s of a.options)if(Te(s,n))return!0;return!1}case"intersection":return Te(a.left,n)||Te(a.right,n);case"tuple":{for(const s of a.items)if(Te(s,n))return!0;return!!(a.rest&&Te(a.rest,n))}case"record":return Te(a.keyType,n)||Te(a.valueType,n);case"map":return Te(a.keyType,n)||Te(a.valueType,n);case"set":return Te(a.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Te(a.innerType,n);case"lazy":return Te(a.getter(),n);case"default":return Te(a.innerType,n);case"prefault":return Te(a.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Te(a.in,n)||Te(a.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${a.type}`)}i(Te,"isTransforming");const r_=x("ZodISODateTime",(e,t)=>{Ey.init(e,t),Ee.init(e,t)});function o_(e){return T0(r_,e)}i(o_,"datetime");const a_=x("ZodISODate",(e,t)=>{wy.init(e,t),Ee.init(e,t)});function s_(e){return B0(a_,e)}i(s_,"date");const i_=x("ZodISOTime",(e,t)=>{Ay.init(e,t),Ee.init(e,t)});function u_(e){return S0(i_,e)}i(u_,"time");const l_=x("ZodISODuration",(e,t)=>{Iy.init(e,t),Ee.init(e,t)});function c_(e){return O0(l_,e)}i(c_,"duration");const p_=i((e,t)=>{Xl.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:i(n=>Fv(e,n),"value")},flatten:{value:i(n=>_v(e,n),"value")},addIssue:{value:i(n=>e.issues.push(n),"value")},addIssues:{value:i(n=>e.issues.push(...n),"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),vo=x("ZodError",p_,{Parent:Error}),d_=Cv(vo),m_=bv(vo),f_=ec(vo),Ic=tc(vo),ye=x("ZodType",(e,t)=>(de.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>Zt(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>d_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>f_(e,n,r),e.parseAsync=async(n,r)=>m_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Ic(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(lF(n,r)),e.superRefine=n=>e.check(cF(n)),e.overwrite=n=>e.check(Ar(n)),e.optional=()=>Oc(e),e.nullable=()=>Rc(e),e.nullish=()=>Oc(Rc(e)),e.nonoptional=n=>eF(e,n),e.array=()=>T(e),e.or=n=>H([e,n]),e.and=n=>U_(e,n),e.transform=n=>Pc(e,H_(n)),e.default=n=>Y_(e,n),e.prefault=n=>Q_(e,n),e.catch=n=>nF(e,n),e.pipe=n=>Pc(e,n),e.readonly=()=>aF(e),e.describe=n=>{const r=e.clone();return wr.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return wr.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return wr.get(e);const r=e.clone();return wr.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),xc=x("_ZodString",(e,t)=>{Za.init(e,t),ye.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(L0(...r)),e.includes=(...r)=>e.check(G0(...r)),e.startsWith=(...r)=>e.check(W0(...r)),e.endsWith=(...r)=>e.check(H0(...r)),e.min=(...r)=>e.check(Do(...r)),e.max=(...r)=>e.check(wc(...r)),e.length=(...r)=>e.check(Ac(...r)),e.nonempty=(...r)=>e.check(Do(1,...r)),e.lowercase=r=>e.check(U0(r)),e.uppercase=r=>e.check(V0(r)),e.trim=()=>e.check(K0()),e.normalize=(...r)=>e.check(J0(...r)),e.toLowerCase=()=>e.check(Y0()),e.toUpperCase=()=>e.check(X0())}),h_=x("ZodString",(e,t)=>{Za.init(e,t),xc.init(e,t),e.email=n=>e.check(c0(D_,n)),e.url=n=>e.check(h0(g_,n)),e.jwt=n=>e.check($0(B_,n)),e.emoji=n=>e.check(D0(v_,n)),e.guid=n=>e.check(Fc(kc,n)),e.uuid=n=>e.check(p0(yo,n)),e.uuidv4=n=>e.check(d0(yo,n)),e.uuidv6=n=>e.check(m0(yo,n)),e.uuidv7=n=>e.check(f0(yo,n)),e.nanoid=n=>e.check(g0(y_,n)),e.guid=n=>e.check(Fc(kc,n)),e.cuid=n=>e.check(v0(__,n)),e.cuid2=n=>e.check(y0(F_,n)),e.ulid=n=>e.check(_0(C_,n)),e.base64=n=>e.check(I0(k_,n)),e.base64url=n=>e.check(x0($_,n)),e.xid=n=>e.check(F0(b_,n)),e.ksuid=n=>e.check(C0(E_,n)),e.ipv4=n=>e.check(b0(w_,n)),e.ipv6=n=>e.check(E0(A_,n)),e.cidrv4=n=>e.check(w0(I_,n)),e.cidrv6=n=>e.check(A0(x_,n)),e.e164=n=>e.check(k0(T_,n)),e.datetime=n=>e.check(o_(n)),e.date=n=>e.check(s_(n)),e.time=n=>e.check(u_(n)),e.duration=n=>e.check(c_(n))});function p(e){return l0(h_,e)}i(p,"string");const Ee=x("ZodStringFormat",(e,t)=>{Ce.init(e,t),xc.init(e,t)}),D_=x("ZodEmail",(e,t)=>{hy.init(e,t),Ee.init(e,t)}),kc=x("ZodGUID",(e,t)=>{my.init(e,t),Ee.init(e,t)}),yo=x("ZodUUID",(e,t)=>{fy.init(e,t),Ee.init(e,t)}),g_=x("ZodURL",(e,t)=>{Dy.init(e,t),Ee.init(e,t)}),v_=x("ZodEmoji",(e,t)=>{gy.init(e,t),Ee.init(e,t)}),y_=x("ZodNanoID",(e,t)=>{vy.init(e,t),Ee.init(e,t)}),__=x("ZodCUID",(e,t)=>{yy.init(e,t),Ee.init(e,t)}),F_=x("ZodCUID2",(e,t)=>{_y.init(e,t),Ee.init(e,t)}),C_=x("ZodULID",(e,t)=>{Fy.init(e,t),Ee.init(e,t)}),b_=x("ZodXID",(e,t)=>{Cy.init(e,t),Ee.init(e,t)}),E_=x("ZodKSUID",(e,t)=>{by.init(e,t),Ee.init(e,t)}),w_=x("ZodIPv4",(e,t)=>{xy.init(e,t),Ee.init(e,t)}),A_=x("ZodIPv6",(e,t)=>{ky.init(e,t),Ee.init(e,t)}),I_=x("ZodCIDRv4",(e,t)=>{$y.init(e,t),Ee.init(e,t)}),x_=x("ZodCIDRv6",(e,t)=>{Ty.init(e,t),Ee.init(e,t)}),k_=x("ZodBase64",(e,t)=>{By.init(e,t),Ee.init(e,t)}),$_=x("ZodBase64URL",(e,t)=>{Oy.init(e,t),Ee.init(e,t)}),T_=x("ZodE164",(e,t)=>{Ry.init(e,t),Ee.init(e,t)}),B_=x("ZodJWT",(e,t)=>{Py.init(e,t),Ee.init(e,t)}),Ga=x("ZodNumber",(e,t)=>{cc.init(e,t),ye.init(e,t),e.gt=(r,a)=>e.check(bc(r,a)),e.gte=(r,a)=>e.check(Va(r,a)),e.min=(r,a)=>e.check(Va(r,a)),e.lt=(r,a)=>e.check(Cc(r,a)),e.lte=(r,a)=>e.check(Ua(r,a)),e.max=(r,a)=>e.check(Ua(r,a)),e.int=r=>e.check($c(r)),e.safe=r=>e.check($c(r)),e.positive=r=>e.check(bc(0,r)),e.nonnegative=r=>e.check(Va(0,r)),e.negative=r=>e.check(Cc(0,r)),e.nonpositive=r=>e.check(Ua(0,r)),e.multipleOf=(r,a)=>e.check(Ec(r,a)),e.step=(r,a)=>e.check(Ec(r,a)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function A(e){return R0(Ga,e)}i(A,"number$1");const S_=x("ZodNumberFormat",(e,t)=>{My.init(e,t),Ga.init(e,t)});function $c(e){return P0(S_,e)}i($c,"int");const O_=x("ZodBoolean",(e,t)=>{jy.init(e,t),ye.init(e,t)});function Ae(e){return M0(O_,e)}i(Ae,"boolean");const R_=x("ZodNull",(e,t)=>{zy.init(e,t),ye.init(e,t)});function Tc(e){return j0(R_,e)}i(Tc,"_null");const N_=x("ZodAny",(e,t)=>{qy.init(e,t),ye.init(e,t)});function qe(){return z0(N_)}i(qe,"any");const P_=x("ZodUnknown",(e,t)=>{Zy.init(e,t),ye.init(e,t)});function gt(){return q0(P_)}i(gt,"unknown");const M_=x("ZodNever",(e,t)=>{Ly.init(e,t),ye.init(e,t)});function j_(e){return Z0(M_,e)}i(j_,"never");const z_=x("ZodArray",(e,t)=>{Uy.init(e,t),ye.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(Do(n,r)),e.nonempty=n=>e.check(Do(1,n)),e.max=(n,r)=>e.check(wc(n,r)),e.length=(n,r)=>e.check(Ac(n,r)),e.unwrap=()=>e.element});function T(e,t){return Q0(z_,e,t)}i(T,"array$1");const q_=x("ZodObject",(e,t)=>{Vy.init(e,t),ye.init(e,t),se(e,"shape",()=>t.shape),e.keyof=()=>re(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:gt()}),e.loose=()=>e.clone({...e._zod.def,catchall:gt()}),e.strict=()=>e.clone({...e._zod.def,catchall:j_()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Dv(e,n),e.merge=n=>gv(e,n),e.pick=n=>fv(e,n),e.omit=n=>hv(e,n),e.partial=(...n)=>vv(Sc,e,n[0]),e.required=(...n)=>yv(Nc,e,n[0])});function g(e,t){const n={type:"object",get shape(){return ja(this,"shape",{...e}),this.shape},...q(t)};return new q_(n)}i(g,"object$1");const Bc=x("ZodUnion",(e,t)=>{fc.init(e,t),ye.init(e,t),e.options=t.options});function H(e,t){return new Bc({type:"union",options:e,...q(t)})}i(H,"union");const Z_=x("ZodDiscriminatedUnion",(e,t)=>{Bc.init(e,t),Gy.init(e,t)});function Ie(e,t,n){return new Z_({type:"union",options:t,discriminator:e,...q(n)})}i(Ie,"discriminatedUnion");const L_=x("ZodIntersection",(e,t)=>{Wy.init(e,t),ye.init(e,t)});function U_(e,t){return new L_({type:"intersection",left:e,right:t})}i(U_,"intersection");const V_=x("ZodRecord",(e,t)=>{Hy.init(e,t),ye.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function me(e,t,n){return new V_({type:"record",keyType:e,valueType:t,...q(n)})}i(me,"record");const Wa=x("ZodEnum",(e,t)=>{Jy.init(e,t),ye.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,a)=>{const s={};for(const o of r)if(n.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Wa({...t,checks:[],...q(a),entries:s})},e.exclude=(r,a)=>{const s={...t.entries};for(const o of r)if(n.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Wa({...t,checks:[],...q(a),entries:s})}});function re(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Wa({type:"enum",entries:n,...q(t)})}i(re,"_enum");const G_=x("ZodLiteral",(e,t)=>{Ky.init(e,t),ye.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function I(e,t){return new G_({type:"literal",values:Array.isArray(e)?e:[e],...q(t)})}i(I,"literal");const W_=x("ZodTransform",(e,t)=>{Yy.init(e,t),ye.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(Er(s,n.value,t));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),n.issues.push(Er(o))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(s=>(n.value=s,n)):(n.value=a,n)}});function H_(e){return new W_({type:"transform",transform:e})}i(H_,"transform");const Sc=x("ZodOptional",(e,t)=>{Xy.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Oc(e){return new Sc({type:"optional",innerType:e})}i(Oc,"optional");const J_=x("ZodNullable",(e,t)=>{Qy.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Rc(e){return new J_({type:"nullable",innerType:e})}i(Rc,"nullable");const K_=x("ZodDefault",(e,t)=>{e0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Y_(e,t){return new K_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Y_,"_default");const X_=x("ZodPrefault",(e,t)=>{t0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Q_(e,t){return new X_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Q_,"prefault");const Nc=x("ZodNonOptional",(e,t)=>{n0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function eF(e,t){return new Nc({type:"nonoptional",innerType:e,...q(t)})}i(eF,"nonoptional");const tF=x("ZodCatch",(e,t)=>{r0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function nF(e,t){return new tF({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}i(nF,"_catch");const rF=x("ZodPipe",(e,t)=>{o0.init(e,t),ye.init(e,t),e.in=t.in,e.out=t.out});function Pc(e,t){return new rF({type:"pipe",in:e,out:t})}i(Pc,"pipe");const oF=x("ZodReadonly",(e,t)=>{a0.init(e,t),ye.init(e,t)});function aF(e){return new oF({type:"readonly",innerType:e})}i(aF,"readonly");const sF=x("ZodLazy",(e,t)=>{s0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ha(e){return new sF({type:"lazy",getter:e})}i(Ha,"lazy");const Ja=x("ZodCustom",(e,t)=>{i0.init(e,t),ye.init(e,t)});function iF(e){const t=new Le({check:"custom"});return t._zod.check=e,t}i(iF,"check");function uF(e,t){return e_(Ja,e??(()=>!0),t)}i(uF,"custom");function lF(e,t={}){return t_(Ja,e,t)}i(lF,"refine");function cF(e){const t=iF(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Er(r,n.value,t._zod.def));else{const a=r;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=t),a.continue??(a.continue=!t._zod.def.abort),n.issues.push(Er(a))}},e(n.value,n)));return t}i(cF,"superRefine");function _o(e,t={error:`Input not instance of ${e.name}`}){const n=new Ja({type:"custom",check:"custom",fn:i(r=>r instanceof e,"fn"),abort:!0,...q(t)});return n._zod.bag.Class=e,n}i(_o,"_instanceof");function pF(e){return N0(Ga,e)}i(pF,"number");var Y;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Y||(Y={}));const Vs=class Vs extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};i(Vs,"ParseError");let Fo=Vs;function Ka(e){}i(Ka,"noop");function dF(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Ka,onError:n=Ka,onRetry:r=Ka,onComment:a}=e;let s="",o=!0,u,l="",c="";function d(v){const y=o?v.replace(/^\xEF\xBB\xBF/,""):v,[F,E]=mF(`${s}${y}`);for(const b of F)m(b);s=E,o=!1}i(d,"feed");function m(v){if(v===""){D();return}if(v.startsWith(":")){a&&a(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const F=v.slice(0,y),E=v[y+1]===" "?2:1,b=v.slice(y+E);h(F,b,v);return}h(v,"",v)}i(m,"parseLine");function h(v,y,F){switch(v){case"event":c=y;break;case"data":l=`${l}${y}
115
- `;break;case"id":u=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?r(parseInt(y,10)):n(new Fo(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:F}));break;default:n(new Fo(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:y,line:F}));break}}i(h,"processField");function D(){l.length>0&&t({id:u,event:c||void 0,data:l.endsWith(`
116
- `)?l.slice(0,-1):l}),u=void 0,l="",c=""}i(D,"dispatchEvent");function f(v={}){s&&v.consume&&m(s),o=!0,u=void 0,l="",c="",s=""}return i(f,"reset"),{feed:d,reset:f}}i(dF,"createParser");function mF(e){const t=[];let n="",r=0;for(;r<e.length;){const a=e.indexOf("\r",r),s=e.indexOf(`
114
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of this.seen.entries()){const m=d[1];if(t===d[0]){o(d);continue}if(r.external){const D=r.external.registry.get(d[0])?.id;if(t!==d[0]&&D){o(d);continue}}if(this.metadataRegistry.get(d[0])?.id){o(d);continue}if(m.cycle){o(d);continue}if(m.count>1&&r.reused==="ref"){o(d);continue}}const u=i((d,m)=>{const h=this.seen.get(d),D=h.def??h.schema,f={...D};if(h.ref===null)return;const v=h.ref;if(h.ref=null,v){u(v,m);const y=this.seen.get(v).schema;y.$ref&&m.target==="draft-7"?(D.allOf=D.allOf??[],D.allOf.push(y)):(Object.assign(D,y),Object.assign(D,f))}h.isParent||this.override({zodSchema:d,jsonSchema:D,path:h.path??[]})},"flattenRef");for(const d of[...this.seen.entries()].reverse())u(d[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const d=r.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(d)}Object.assign(l,a.def);const c=r.external?.defs??{};for(const d of this.seen.entries()){const m=d[1];m.def&&m.defId&&(c[m.defId]=m.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}};i(Ls,"JSONSchemaGenerator");let yo=Ls;function o_(e,t){if(e instanceof go){const r=new yo(t),a={};for(const u of e._idmap.entries()){const[l,c]=u;r.process(c)}const s={},o={registry:e,uri:t?.uri,defs:a};for(const u of e._idmap.entries()){const[l,c]=u;s[l]=r.emit(c,{...t,external:o})}if(Object.keys(a).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:a}}return{schemas:s}}const n=new yo(t);return n.process(e),n.emit(e,t)}i(o_,"toJSONSchema");function Te(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;switch(a.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Te(a.element,n);case"object":{for(const s in a.shape)if(Te(a.shape[s],n))return!0;return!1}case"union":{for(const s of a.options)if(Te(s,n))return!0;return!1}case"intersection":return Te(a.left,n)||Te(a.right,n);case"tuple":{for(const s of a.items)if(Te(s,n))return!0;return!!(a.rest&&Te(a.rest,n))}case"record":return Te(a.keyType,n)||Te(a.valueType,n);case"map":return Te(a.keyType,n)||Te(a.valueType,n);case"set":return Te(a.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Te(a.innerType,n);case"lazy":return Te(a.getter(),n);case"default":return Te(a.innerType,n);case"prefault":return Te(a.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Te(a.in,n)||Te(a.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${a.type}`)}i(Te,"isTransforming");const a_=x("ZodISODateTime",(e,t)=>{Ay.init(e,t),Ee.init(e,t)});function s_(e){return S0(a_,e)}i(s_,"datetime");const i_=x("ZodISODate",(e,t)=>{Iy.init(e,t),Ee.init(e,t)});function u_(e){return O0(i_,e)}i(u_,"date");const l_=x("ZodISOTime",(e,t)=>{xy.init(e,t),Ee.init(e,t)});function c_(e){return R0(l_,e)}i(c_,"time");const p_=x("ZodISODuration",(e,t)=>{ky.init(e,t),Ee.init(e,t)});function d_(e){return N0(p_,e)}i(d_,"duration");const m_=i((e,t)=>{ec.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:i(n=>bv(e,n),"value")},flatten:{value:i(n=>Cv(e,n),"value")},addIssue:{value:i(n=>e.issues.push(n),"value")},addIssues:{value:i(n=>e.issues.push(...n),"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),_o=x("ZodError",m_,{Parent:Error}),f_=Ev(_o),h_=wv(_o),D_=nc(_o),kc=rc(_o),ye=x("ZodType",(e,t)=>(de.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>Zt(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>f_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>D_(e,n,r),e.parseAsync=async(n,r)=>h_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>kc(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(pF(n,r)),e.superRefine=n=>e.check(dF(n)),e.overwrite=n=>e.check(Ar(n)),e.optional=()=>Nc(e),e.nullable=()=>Pc(e),e.nullish=()=>Nc(Pc(e)),e.nonoptional=n=>nF(e,n),e.array=()=>T(e),e.or=n=>H([e,n]),e.and=n=>G_(e,n),e.transform=n=>jc(e,K_(n)),e.default=n=>Q_(e,n),e.prefault=n=>tF(e,n),e.catch=n=>oF(e,n),e.pipe=n=>jc(e,n),e.readonly=()=>iF(e),e.describe=n=>{const r=e.clone();return wr.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return wr.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return wr.get(e);const r=e.clone();return wr.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),$c=x("_ZodString",(e,t)=>{Za.init(e,t),ye.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(V0(...r)),e.includes=(...r)=>e.check(H0(...r)),e.startsWith=(...r)=>e.check(J0(...r)),e.endsWith=(...r)=>e.check(K0(...r)),e.min=(...r)=>e.check(vo(...r)),e.max=(...r)=>e.check(Ic(...r)),e.length=(...r)=>e.check(xc(...r)),e.nonempty=(...r)=>e.check(vo(1,...r)),e.lowercase=r=>e.check(G0(r)),e.uppercase=r=>e.check(W0(r)),e.trim=()=>e.check(X0()),e.normalize=(...r)=>e.check(Y0(...r)),e.toLowerCase=()=>e.check(Q0()),e.toUpperCase=()=>e.check(e_())}),g_=x("ZodString",(e,t)=>{Za.init(e,t),$c.init(e,t),e.email=n=>e.check(d0(v_,n)),e.url=n=>e.check(g0(y_,n)),e.jwt=n=>e.check(B0(O_,n)),e.emoji=n=>e.check(v0(__,n)),e.guid=n=>e.check(bc(Tc,n)),e.uuid=n=>e.check(m0(Fo,n)),e.uuidv4=n=>e.check(f0(Fo,n)),e.uuidv6=n=>e.check(h0(Fo,n)),e.uuidv7=n=>e.check(D0(Fo,n)),e.nanoid=n=>e.check(y0(F_,n)),e.guid=n=>e.check(bc(Tc,n)),e.cuid=n=>e.check(_0(C_,n)),e.cuid2=n=>e.check(F0(b_,n)),e.ulid=n=>e.check(C0(E_,n)),e.base64=n=>e.check(k0(T_,n)),e.base64url=n=>e.check($0(B_,n)),e.xid=n=>e.check(b0(w_,n)),e.ksuid=n=>e.check(E0(A_,n)),e.ipv4=n=>e.check(w0(I_,n)),e.ipv6=n=>e.check(A0(x_,n)),e.cidrv4=n=>e.check(I0(k_,n)),e.cidrv6=n=>e.check(x0($_,n)),e.e164=n=>e.check(T0(S_,n)),e.datetime=n=>e.check(s_(n)),e.date=n=>e.check(u_(n)),e.time=n=>e.check(c_(n)),e.duration=n=>e.check(d_(n))});function p(e){return p0(g_,e)}i(p,"string");const Ee=x("ZodStringFormat",(e,t)=>{Ce.init(e,t),$c.init(e,t)}),v_=x("ZodEmail",(e,t)=>{gy.init(e,t),Ee.init(e,t)}),Tc=x("ZodGUID",(e,t)=>{hy.init(e,t),Ee.init(e,t)}),Fo=x("ZodUUID",(e,t)=>{Dy.init(e,t),Ee.init(e,t)}),y_=x("ZodURL",(e,t)=>{vy.init(e,t),Ee.init(e,t)}),__=x("ZodEmoji",(e,t)=>{yy.init(e,t),Ee.init(e,t)}),F_=x("ZodNanoID",(e,t)=>{_y.init(e,t),Ee.init(e,t)}),C_=x("ZodCUID",(e,t)=>{Fy.init(e,t),Ee.init(e,t)}),b_=x("ZodCUID2",(e,t)=>{Cy.init(e,t),Ee.init(e,t)}),E_=x("ZodULID",(e,t)=>{by.init(e,t),Ee.init(e,t)}),w_=x("ZodXID",(e,t)=>{Ey.init(e,t),Ee.init(e,t)}),A_=x("ZodKSUID",(e,t)=>{wy.init(e,t),Ee.init(e,t)}),I_=x("ZodIPv4",(e,t)=>{$y.init(e,t),Ee.init(e,t)}),x_=x("ZodIPv6",(e,t)=>{Ty.init(e,t),Ee.init(e,t)}),k_=x("ZodCIDRv4",(e,t)=>{By.init(e,t),Ee.init(e,t)}),$_=x("ZodCIDRv6",(e,t)=>{Sy.init(e,t),Ee.init(e,t)}),T_=x("ZodBase64",(e,t)=>{Oy.init(e,t),Ee.init(e,t)}),B_=x("ZodBase64URL",(e,t)=>{Ny.init(e,t),Ee.init(e,t)}),S_=x("ZodE164",(e,t)=>{Py.init(e,t),Ee.init(e,t)}),O_=x("ZodJWT",(e,t)=>{jy.init(e,t),Ee.init(e,t)}),Ga=x("ZodNumber",(e,t)=>{dc.init(e,t),ye.init(e,t),e.gt=(r,a)=>e.check(wc(r,a)),e.gte=(r,a)=>e.check(Va(r,a)),e.min=(r,a)=>e.check(Va(r,a)),e.lt=(r,a)=>e.check(Ec(r,a)),e.lte=(r,a)=>e.check(La(r,a)),e.max=(r,a)=>e.check(La(r,a)),e.int=r=>e.check(Bc(r)),e.safe=r=>e.check(Bc(r)),e.positive=r=>e.check(wc(0,r)),e.nonnegative=r=>e.check(Va(0,r)),e.negative=r=>e.check(Ec(0,r)),e.nonpositive=r=>e.check(La(0,r)),e.multipleOf=(r,a)=>e.check(Ac(r,a)),e.step=(r,a)=>e.check(Ac(r,a)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function A(e){return P0(Ga,e)}i(A,"number$1");const R_=x("ZodNumberFormat",(e,t)=>{zy.init(e,t),Ga.init(e,t)});function Bc(e){return j0(R_,e)}i(Bc,"int");const N_=x("ZodBoolean",(e,t)=>{qy.init(e,t),ye.init(e,t)});function Ae(e){return z0(N_,e)}i(Ae,"boolean");const P_=x("ZodNull",(e,t)=>{Zy.init(e,t),ye.init(e,t)});function Sc(e){return q0(P_,e)}i(Sc,"_null");const M_=x("ZodAny",(e,t)=>{Uy.init(e,t),ye.init(e,t)});function qe(){return Z0(M_)}i(qe,"any");const j_=x("ZodUnknown",(e,t)=>{Ly.init(e,t),ye.init(e,t)});function gt(){return U0(j_)}i(gt,"unknown");const z_=x("ZodNever",(e,t)=>{Vy.init(e,t),ye.init(e,t)});function q_(e){return L0(z_,e)}i(q_,"never");const Z_=x("ZodArray",(e,t)=>{Gy.init(e,t),ye.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(vo(n,r)),e.nonempty=n=>e.check(vo(1,n)),e.max=(n,r)=>e.check(Ic(n,r)),e.length=(n,r)=>e.check(xc(n,r)),e.unwrap=()=>e.element});function T(e,t){return t_(Z_,e,t)}i(T,"array$1");const U_=x("ZodObject",(e,t)=>{Wy.init(e,t),ye.init(e,t),se(e,"shape",()=>t.shape),e.keyof=()=>re(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:gt()}),e.loose=()=>e.clone({...e._zod.def,catchall:gt()}),e.strict=()=>e.clone({...e._zod.def,catchall:q_()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>vv(e,n),e.merge=n=>yv(e,n),e.pick=n=>Dv(e,n),e.omit=n=>gv(e,n),e.partial=(...n)=>_v(Rc,e,n[0]),e.required=(...n)=>Fv(Mc,e,n[0])});function g(e,t){const n={type:"object",get shape(){return ja(this,"shape",{...e}),this.shape},...q(t)};return new U_(n)}i(g,"object$1");const Oc=x("ZodUnion",(e,t)=>{Dc.init(e,t),ye.init(e,t),e.options=t.options});function H(e,t){return new Oc({type:"union",options:e,...q(t)})}i(H,"union");const L_=x("ZodDiscriminatedUnion",(e,t)=>{Oc.init(e,t),Hy.init(e,t)});function Ie(e,t,n){return new L_({type:"union",options:t,discriminator:e,...q(n)})}i(Ie,"discriminatedUnion");const V_=x("ZodIntersection",(e,t)=>{Jy.init(e,t),ye.init(e,t)});function G_(e,t){return new V_({type:"intersection",left:e,right:t})}i(G_,"intersection");const W_=x("ZodRecord",(e,t)=>{Ky.init(e,t),ye.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function me(e,t,n){return new W_({type:"record",keyType:e,valueType:t,...q(n)})}i(me,"record");const Wa=x("ZodEnum",(e,t)=>{Yy.init(e,t),ye.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,a)=>{const s={};for(const o of r)if(n.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Wa({...t,checks:[],...q(a),entries:s})},e.exclude=(r,a)=>{const s={...t.entries};for(const o of r)if(n.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Wa({...t,checks:[],...q(a),entries:s})}});function re(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Wa({type:"enum",entries:n,...q(t)})}i(re,"_enum");const H_=x("ZodLiteral",(e,t)=>{Xy.init(e,t),ye.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function I(e,t){return new H_({type:"literal",values:Array.isArray(e)?e:[e],...q(t)})}i(I,"literal");const J_=x("ZodTransform",(e,t)=>{Qy.init(e,t),ye.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(Er(s,n.value,t));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),n.issues.push(Er(o))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(s=>(n.value=s,n)):(n.value=a,n)}});function K_(e){return new J_({type:"transform",transform:e})}i(K_,"transform");const Rc=x("ZodOptional",(e,t)=>{e0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Nc(e){return new Rc({type:"optional",innerType:e})}i(Nc,"optional");const Y_=x("ZodNullable",(e,t)=>{t0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Pc(e){return new Y_({type:"nullable",innerType:e})}i(Pc,"nullable");const X_=x("ZodDefault",(e,t)=>{n0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Q_(e,t){return new X_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Q_,"_default");const eF=x("ZodPrefault",(e,t)=>{r0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function tF(e,t){return new eF({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(tF,"prefault");const Mc=x("ZodNonOptional",(e,t)=>{o0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nF(e,t){return new Mc({type:"nonoptional",innerType:e,...q(t)})}i(nF,"nonoptional");const rF=x("ZodCatch",(e,t)=>{a0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function oF(e,t){return new rF({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}i(oF,"_catch");const aF=x("ZodPipe",(e,t)=>{s0.init(e,t),ye.init(e,t),e.in=t.in,e.out=t.out});function jc(e,t){return new aF({type:"pipe",in:e,out:t})}i(jc,"pipe");const sF=x("ZodReadonly",(e,t)=>{i0.init(e,t),ye.init(e,t)});function iF(e){return new sF({type:"readonly",innerType:e})}i(iF,"readonly");const uF=x("ZodLazy",(e,t)=>{u0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ha(e){return new uF({type:"lazy",getter:e})}i(Ha,"lazy");const Ja=x("ZodCustom",(e,t)=>{l0.init(e,t),ye.init(e,t)});function lF(e){const t=new Ue({check:"custom"});return t._zod.check=e,t}i(lF,"check");function cF(e,t){return n_(Ja,e??(()=>!0),t)}i(cF,"custom");function pF(e,t={}){return r_(Ja,e,t)}i(pF,"refine");function dF(e){const t=lF(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Er(r,n.value,t._zod.def));else{const a=r;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=t),a.continue??(a.continue=!t._zod.def.abort),n.issues.push(Er(a))}},e(n.value,n)));return t}i(dF,"superRefine");function Co(e,t={error:`Input not instance of ${e.name}`}){const n=new Ja({type:"custom",check:"custom",fn:i(r=>r instanceof e,"fn"),abort:!0,...q(t)});return n._zod.bag.Class=e,n}i(Co,"_instanceof");function mF(e){return M0(Ga,e)}i(mF,"number");var Y;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Y||(Y={}));const Vs=class Vs extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};i(Vs,"ParseError");let bo=Vs;function Ka(e){}i(Ka,"noop");function fF(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Ka,onError:n=Ka,onRetry:r=Ka,onComment:a}=e;let s="",o=!0,u,l="",c="";function d(v){const y=o?v.replace(/^\xEF\xBB\xBF/,""):v,[F,E]=hF(`${s}${y}`);for(const b of F)m(b);s=E,o=!1}i(d,"feed");function m(v){if(v===""){D();return}if(v.startsWith(":")){a&&a(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const F=v.slice(0,y),E=v[y+1]===" "?2:1,b=v.slice(y+E);h(F,b,v);return}h(v,"",v)}i(m,"parseLine");function h(v,y,F){switch(v){case"event":c=y;break;case"data":l=`${l}${y}
115
+ `;break;case"id":u=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?r(parseInt(y,10)):n(new bo(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:F}));break;default:n(new bo(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:y,line:F}));break}}i(h,"processField");function D(){l.length>0&&t({id:u,event:c||void 0,data:l.endsWith(`
116
+ `)?l.slice(0,-1):l}),u=void 0,l="",c=""}i(D,"dispatchEvent");function f(v={}){s&&v.consume&&m(s),o=!0,u=void 0,l="",c="",s=""}return i(f,"reset"),{feed:d,reset:f}}i(fF,"createParser");function hF(e){const t=[];let n="",r=0;for(;r<e.length;){const a=e.indexOf("\r",r),s=e.indexOf(`
117
117
  `,r);let o=-1;if(a!==-1&&s!==-1?o=Math.min(a,s):a!==-1?a===e.length-1?o=-1:o=a:s!==-1&&(o=s),o===-1){n=e.slice(r);break}else{const u=e.slice(r,o);t.push(u),r=o+1,e[r-1]==="\r"&&e[r]===`
118
- `&&r++}}return[t,n]}i(mF,"splitLines");const Gs=class Gs extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let a;super({start(s){a=dF({onEvent:i(o=>{s.enqueue(o)},"onEvent"),onError(o){t==="terminate"?s.error(o):typeof t=="function"&&t(o)},onRetry:n,onComment:r})},transform(s){a.feed(s)}})}};i(Gs,"EventSourceParserStream");let Ya=Gs;function xe(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}i(xe,"combineHeaders");function fF({tools:e=[],providerToolNames:t}){const n={},r={};for(const a of e)if(a.type==="provider"&&a.id in t){const s=t[a.id];n[a.name]=s,r[s]=a.name}return{toProviderToolName:i(a=>{var s;return(s=n[a])!=null?s:a},"toProviderToolName"),toCustomToolName:i(a=>{var s;return(s=r[a])!=null?s:a},"toCustomToolName")}}i(fF,"createToolNameMapping");async function hF(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((r,a)=>{if(n?.aborted){a(Mc());return}const s=setTimeout(()=>{o(),r()},e),o=i(()=>{clearTimeout(s),n?.removeEventListener("abort",u)},"cleanup"),u=i(()=>{o(),a(Mc())},"onAbort");n?.addEventListener("abort",u)})}i(hF,"delay");function Mc(){return new DOMException("Delay was aborted","AbortError")}i(Mc,"createAbortError");function cn(e){return Object.fromEntries([...e.headers])}i(cn,"extractResponseHeaders");var{btoa:DF,atob:gF}=globalThis;function Ut(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=gF(t);return Uint8Array.from(n,r=>r.codePointAt(0))}i(Ut,"convertBase64ToUint8Array");function Ir(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return DF(t)}i(Ir,"convertUint8ArrayToBase64");function Vt(e){return e instanceof Uint8Array?Ir(e):e}i(Vt,"convertToBase64");function jc(e,t={}){const{useArrayBrackets:n=!0}=t,r=new FormData;for(const[a,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){r.append(a,s[0]);continue}const o=n?`${a}[]`:a;for(const u of s)r.append(o,u);continue}r.append(a,s)}return r}i(jc,"convertToFormData");var zc="AI_DownloadError",qc=`vercel.ai.error.${zc}`,vF=Symbol.for(qc),Zc,Lc,pn=(In=class extends(Lc=V,Zc=vF,Lc){constructor({url:t,statusCode:n,statusText:r,cause:a,message:s=a==null?`Failed to download ${t}: ${n} ${r}`:`Failed to download ${t}: ${a}`}){super({name:zc,message:s,cause:a}),this[Zc]=!0,this.url=t,this.statusCode=n,this.statusText=r}static isInstance(t){return V.hasMarker(t,qc)}},i(In,"DownloadError"),In);async function Xa(e){try{const t=await fetch(e);if(!t.ok)throw new pn({url:e,statusCode:t.status,statusText:t.statusText});return await t.blob()}catch(t){throw pn.isInstance(t)?t:new pn({url:e,cause:t})}}i(Xa,"downloadBlob");var xr=i(({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const a=i(()=>{const s=n.length,o=new Array(t);for(let u=0;u<t;u++)o[u]=n[Math.random()*s|0];return o.join("")},"generator");if(e==null)return a;if(n.includes(r))throw new vl({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${a()}`},"createIdGenerator"),Be=xr();function Uc(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(Uc,"getErrorMessage");function dn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}i(dn,"isAbortError");var yF=["fetch failed","failed to fetch"];function Vc({error:e,url:t,requestBodyValues:n}){if(dn(e))return e;if(e instanceof TypeError&&yF.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Re({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}i(Vc,"handleFetchError");function Qa(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}i(Qa,"getRuntimeEnvironmentUserAgent");function _F(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}i(_F,"normalizeHeaders");function Gt(e,...t){const n=new Headers(_F(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}i(Gt,"withUserAgentSuffix");var Gc="4.0.4",FF=i(()=>globalThis.fetch,"getOriginalFetch"),Wc=i(async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:a,fetch:s=FF()})=>{try{const o=await s(e,{method:"GET",headers:Gt(t,`ai-sdk/provider-utils/${Gc}`,Qa()),signal:a}),u=cn(o);if(!o.ok){let l;try{l=await r({response:o,url:e,requestBodyValues:{}})}catch(c){throw dn(c)||Re.isInstance(c)?c:new Re({message:"Failed to process error response",cause:c,statusCode:o.status,url:e,responseHeaders:u,requestBodyValues:{}})}throw l.value}try{return await n({response:o,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(dn(l)||Re.isInstance(l))?l:new Re({message:"Failed to process successful response",cause:l,statusCode:o.status,url:e,responseHeaders:u,requestBodyValues:{}})}}catch(o){throw Vc({error:o,url:e,requestBodyValues:{}})}},"getFromApi");function CF(e){return e!=null}i(CF,"isNonNullable");function bF({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,a])=>{const s=r.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:a}:{mediaTypePrefix:s.replace(/\*/,""),regexes:a}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}i(bF,"isUrlSupported");function EF({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new uo({message:`${r} API key must be a string.`});if(typeof process>"u")throw new uo({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 uo({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new uo({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}i(EF,"loadApiKey");function kr({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}i(kr,"loadOptionalSetting");function wF(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}i(wF,"mediaTypeToExtension");var AF=/"__proto__"\s*:/,IF=/"constructor"\s*:/;function Hc(e){const t=JSON.parse(e);return t===null||typeof t!="object"||AF.test(e)===!1&&IF.test(e)===!1?t:xF(t)}i(Hc,"_parse");function xF(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const a in r){const s=r[a];s&&typeof s=="object"&&t.push(s)}}}return e}i(xF,"filter");function es(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Hc(e)}try{return Hc(e)}finally{Error.stackTraceLimit=t}}i(es,"secureJsonParse");function Jc(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:n}=e;if(n!=null)for(const r of Object.keys(n))n[r]=Wt(n[r])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Wt):Wt(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Wt)),e.allOf!=null&&(e.allOf=e.allOf.map(Wt)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Wt));const{definitions:t}=e;if(t!=null)for(const n of Object.keys(t))t[n]=Wt(t[n]);return e}i(Jc,"addAdditionalPropertiesToJsonSchema");function Wt(e){return typeof e=="boolean"?e:Jc(e)}i(Wt,"visit");var kF=Symbol("Let zodToJsonSchema decide on which parser to use"),Kc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},$F=i(e=>typeof e=="string"?{...Kc,name:e}:{...Kc,...e},"getDefaultOptions");function Je(){return{}}i(Je,"parseAnyDef");function TF(e,t){var n,r,a;const s={type:"array"};return(n=e.type)!=null&&n._def&&((a=(r=e.type)==null?void 0:r._def)==null?void 0:a.typeName)!==Y.ZodAny&&(s.items=le(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}i(TF,"parseArrayDef");function BF(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(BF,"parseBigintDef");function SF(){return{type:"boolean"}}i(SF,"parseBooleanDef");function Yc(e,t){return le(e.type._def,t)}i(Yc,"parseBrandedDef");var OF=i((e,t)=>le(e.innerType._def,t),"parseCatchDef");function Xc(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((a,s)=>Xc(e,t,a))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return RF(e)}}i(Xc,"parseDateDef");var RF=i(e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t},"integerDateParser");function NF(e,t){return{...le(e.innerType._def,t),default:e.defaultValue()}}i(NF,"parseDefaultDef");function PF(e,t){return t.effectStrategy==="input"?le(e.schema._def,t):Je()}i(PF,"parseEffectsDef");function MF(e){return{type:"string",enum:Array.from(e.values)}}i(MF,"parseEnumDef");var jF=i(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function zF(e,t){const n=[le(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),le(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a),r=[];return n.forEach(a=>{if(jF(a))r.push(...a.allOf);else{let s=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...u}=a;s=u}r.push(s)}}),r.length?{allOf:r}:void 0}i(zF,"parseIntersectionDef");function qF(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}i(qF,"parseLiteralDef");var ts=void 0,st={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:i(()=>(ts===void 0&&(ts=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ts),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Qc(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":it(n,"email",r.message,t);break;case"format:idn-email":it(n,"idn-email",r.message,t);break;case"pattern:zod":Ze(n,st.email,r.message,t);break}break;case"url":it(n,"uri",r.message,t);break;case"uuid":it(n,"uuid",r.message,t);break;case"regex":Ze(n,r.regex,r.message,t);break;case"cuid":Ze(n,st.cuid,r.message,t);break;case"cuid2":Ze(n,st.cuid2,r.message,t);break;case"startsWith":Ze(n,RegExp(`^${ns(r.value,t)}`),r.message,t);break;case"endsWith":Ze(n,RegExp(`${ns(r.value,t)}$`),r.message,t);break;case"datetime":it(n,"date-time",r.message,t);break;case"date":it(n,"date",r.message,t);break;case"time":it(n,"time",r.message,t);break;case"duration":it(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{Ze(n,RegExp(ns(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&it(n,"ipv4",r.message,t),r.version!=="v4"&&it(n,"ipv6",r.message,t);break}case"base64url":Ze(n,st.base64url,r.message,t);break;case"jwt":Ze(n,st.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Ze(n,st.ipv4Cidr,r.message,t),r.version!=="v4"&&Ze(n,st.ipv6Cidr,r.message,t);break}case"emoji":Ze(n,st.emoji(),r.message,t);break;case"ulid":{Ze(n,st.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{it(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Ze(n,st.base64,r.message,t);break}}break}case"nanoid":Ze(n,st.nanoid,r.message,t)}return n}i(Qc,"parseStringDef");function ns(e,t){return t.patternStrategy==="escape"?LF(e):e}i(ns,"escapeLiteralCheckValue");var ZF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function LF(e){let t="";for(let n=0;n<e.length;n++)ZF.has(e[n])||(t+="\\"),t+=e[n];return t}i(LF,"escapeNonAlphaNumeric");function it(e,t,n,r){var a;e.format||(a=e.anyOf)!=null&&a.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}i(it,"addFormat");function Ze(e,t,n,r){var a;e.pattern||(a=e.allOf)!=null&&a.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:ep(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=ep(t,r)}i(Ze,"addPattern");function ep(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=r.i?e.source.toLowerCase():e.source;let s="",o=!1,u=!1,l=!1;for(let c=0;c<a.length;c++){if(o){s+=a[c],o=!1;continue}if(r.i){if(u){if(a[c].match(/[a-z]/)){l?(s+=a[c],s+=`${a[c-2]}-${a[c]}`.toUpperCase(),l=!1):a[c+1]==="-"&&((n=a[c+2])!=null&&n.match(/[a-z]/))?(s+=a[c],l=!0):s+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){s+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(r.m){if(a[c]==="^"){s+=`(^|(?<=[\r
118
+ `&&r++}}return[t,n]}i(hF,"splitLines");const Gs=class Gs extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let a;super({start(s){a=fF({onEvent:i(o=>{s.enqueue(o)},"onEvent"),onError(o){t==="terminate"?s.error(o):typeof t=="function"&&t(o)},onRetry:n,onComment:r})},transform(s){a.feed(s)}})}};i(Gs,"EventSourceParserStream");let Ya=Gs;function xe(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}i(xe,"combineHeaders");function DF({tools:e=[],providerToolNames:t}){const n={},r={};for(const a of e)if(a.type==="provider"&&a.id in t){const s=t[a.id];n[a.name]=s,r[s]=a.name}return{toProviderToolName:i(a=>{var s;return(s=n[a])!=null?s:a},"toProviderToolName"),toCustomToolName:i(a=>{var s;return(s=r[a])!=null?s:a},"toCustomToolName")}}i(DF,"createToolNameMapping");async function gF(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((r,a)=>{if(n?.aborted){a(zc());return}const s=setTimeout(()=>{o(),r()},e),o=i(()=>{clearTimeout(s),n?.removeEventListener("abort",u)},"cleanup"),u=i(()=>{o(),a(zc())},"onAbort");n?.addEventListener("abort",u)})}i(gF,"delay");function zc(){return new DOMException("Delay was aborted","AbortError")}i(zc,"createAbortError");function cn(e){return Object.fromEntries([...e.headers])}i(cn,"extractResponseHeaders");var{btoa:vF,atob:yF}=globalThis;function Lt(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=yF(t);return Uint8Array.from(n,r=>r.codePointAt(0))}i(Lt,"convertBase64ToUint8Array");function Ir(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return vF(t)}i(Ir,"convertUint8ArrayToBase64");function Vt(e){return e instanceof Uint8Array?Ir(e):e}i(Vt,"convertToBase64");function qc(e,t={}){const{useArrayBrackets:n=!0}=t,r=new FormData;for(const[a,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){r.append(a,s[0]);continue}const o=n?`${a}[]`:a;for(const u of s)r.append(o,u);continue}r.append(a,s)}return r}i(qc,"convertToFormData");var Zc="AI_DownloadError",Uc=`vercel.ai.error.${Zc}`,_F=Symbol.for(Uc),Lc,Vc,pn=(In=class extends(Vc=V,Lc=_F,Vc){constructor({url:t,statusCode:n,statusText:r,cause:a,message:s=a==null?`Failed to download ${t}: ${n} ${r}`:`Failed to download ${t}: ${a}`}){super({name:Zc,message:s,cause:a}),this[Lc]=!0,this.url=t,this.statusCode=n,this.statusText=r}static isInstance(t){return V.hasMarker(t,Uc)}},i(In,"DownloadError"),In);async function Xa(e){try{const t=await fetch(e);if(!t.ok)throw new pn({url:e,statusCode:t.status,statusText:t.statusText});return await t.blob()}catch(t){throw pn.isInstance(t)?t:new pn({url:e,cause:t})}}i(Xa,"downloadBlob");var xr=i(({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const a=i(()=>{const s=n.length,o=new Array(t);for(let u=0;u<t;u++)o[u]=n[Math.random()*s|0];return o.join("")},"generator");if(e==null)return a;if(n.includes(r))throw new _l({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${a()}`},"createIdGenerator"),Be=xr();function Gc(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(Gc,"getErrorMessage");function dn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}i(dn,"isAbortError");var FF=["fetch failed","failed to fetch"];function Wc({error:e,url:t,requestBodyValues:n}){if(dn(e))return e;if(e instanceof TypeError&&FF.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Re({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}i(Wc,"handleFetchError");function Qa(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}i(Qa,"getRuntimeEnvironmentUserAgent");function CF(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}i(CF,"normalizeHeaders");function Gt(e,...t){const n=new Headers(CF(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}i(Gt,"withUserAgentSuffix");var Hc="4.0.4",bF=i(()=>globalThis.fetch,"getOriginalFetch"),Jc=i(async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:a,fetch:s=bF()})=>{try{const o=await s(e,{method:"GET",headers:Gt(t,`ai-sdk/provider-utils/${Hc}`,Qa()),signal:a}),u=cn(o);if(!o.ok){let l;try{l=await r({response:o,url:e,requestBodyValues:{}})}catch(c){throw dn(c)||Re.isInstance(c)?c:new Re({message:"Failed to process error response",cause:c,statusCode:o.status,url:e,responseHeaders:u,requestBodyValues:{}})}throw l.value}try{return await n({response:o,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(dn(l)||Re.isInstance(l))?l:new Re({message:"Failed to process successful response",cause:l,statusCode:o.status,url:e,responseHeaders:u,requestBodyValues:{}})}}catch(o){throw Wc({error:o,url:e,requestBodyValues:{}})}},"getFromApi");function EF(e){return e!=null}i(EF,"isNonNullable");function wF({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,a])=>{const s=r.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:a}:{mediaTypePrefix:s.replace(/\*/,""),regexes:a}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}i(wF,"isUrlSupported");function AF({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new co({message:`${r} API key must be a string.`});if(typeof process>"u")throw new co({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 co({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new co({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}i(AF,"loadApiKey");function kr({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}i(kr,"loadOptionalSetting");function IF(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}i(IF,"mediaTypeToExtension");var xF=/"__proto__"\s*:/,kF=/"constructor"\s*:/;function Kc(e){const t=JSON.parse(e);return t===null||typeof t!="object"||xF.test(e)===!1&&kF.test(e)===!1?t:$F(t)}i(Kc,"_parse");function $F(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const a in r){const s=r[a];s&&typeof s=="object"&&t.push(s)}}}return e}i($F,"filter");function es(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Kc(e)}try{return Kc(e)}finally{Error.stackTraceLimit=t}}i(es,"secureJsonParse");function Yc(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:n}=e;if(n!=null)for(const r of Object.keys(n))n[r]=Wt(n[r])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Wt):Wt(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Wt)),e.allOf!=null&&(e.allOf=e.allOf.map(Wt)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Wt));const{definitions:t}=e;if(t!=null)for(const n of Object.keys(t))t[n]=Wt(t[n]);return e}i(Yc,"addAdditionalPropertiesToJsonSchema");function Wt(e){return typeof e=="boolean"?e:Yc(e)}i(Wt,"visit");var TF=Symbol("Let zodToJsonSchema decide on which parser to use"),Xc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},BF=i(e=>typeof e=="string"?{...Xc,name:e}:{...Xc,...e},"getDefaultOptions");function Je(){return{}}i(Je,"parseAnyDef");function SF(e,t){var n,r,a;const s={type:"array"};return(n=e.type)!=null&&n._def&&((a=(r=e.type)==null?void 0:r._def)==null?void 0:a.typeName)!==Y.ZodAny&&(s.items=le(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}i(SF,"parseArrayDef");function OF(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(OF,"parseBigintDef");function RF(){return{type:"boolean"}}i(RF,"parseBooleanDef");function Qc(e,t){return le(e.type._def,t)}i(Qc,"parseBrandedDef");var NF=i((e,t)=>le(e.innerType._def,t),"parseCatchDef");function ep(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((a,s)=>ep(e,t,a))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return PF(e)}}i(ep,"parseDateDef");var PF=i(e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t},"integerDateParser");function MF(e,t){return{...le(e.innerType._def,t),default:e.defaultValue()}}i(MF,"parseDefaultDef");function jF(e,t){return t.effectStrategy==="input"?le(e.schema._def,t):Je()}i(jF,"parseEffectsDef");function zF(e){return{type:"string",enum:Array.from(e.values)}}i(zF,"parseEnumDef");var qF=i(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function ZF(e,t){const n=[le(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),le(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a),r=[];return n.forEach(a=>{if(qF(a))r.push(...a.allOf);else{let s=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...u}=a;s=u}r.push(s)}}),r.length?{allOf:r}:void 0}i(ZF,"parseIntersectionDef");function UF(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}i(UF,"parseLiteralDef");var ts=void 0,st={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:i(()=>(ts===void 0&&(ts=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ts),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function tp(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":it(n,"email",r.message,t);break;case"format:idn-email":it(n,"idn-email",r.message,t);break;case"pattern:zod":Ze(n,st.email,r.message,t);break}break;case"url":it(n,"uri",r.message,t);break;case"uuid":it(n,"uuid",r.message,t);break;case"regex":Ze(n,r.regex,r.message,t);break;case"cuid":Ze(n,st.cuid,r.message,t);break;case"cuid2":Ze(n,st.cuid2,r.message,t);break;case"startsWith":Ze(n,RegExp(`^${ns(r.value,t)}`),r.message,t);break;case"endsWith":Ze(n,RegExp(`${ns(r.value,t)}$`),r.message,t);break;case"datetime":it(n,"date-time",r.message,t);break;case"date":it(n,"date",r.message,t);break;case"time":it(n,"time",r.message,t);break;case"duration":it(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{Ze(n,RegExp(ns(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&it(n,"ipv4",r.message,t),r.version!=="v4"&&it(n,"ipv6",r.message,t);break}case"base64url":Ze(n,st.base64url,r.message,t);break;case"jwt":Ze(n,st.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Ze(n,st.ipv4Cidr,r.message,t),r.version!=="v4"&&Ze(n,st.ipv6Cidr,r.message,t);break}case"emoji":Ze(n,st.emoji(),r.message,t);break;case"ulid":{Ze(n,st.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{it(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Ze(n,st.base64,r.message,t);break}}break}case"nanoid":Ze(n,st.nanoid,r.message,t)}return n}i(tp,"parseStringDef");function ns(e,t){return t.patternStrategy==="escape"?VF(e):e}i(ns,"escapeLiteralCheckValue");var LF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function VF(e){let t="";for(let n=0;n<e.length;n++)LF.has(e[n])||(t+="\\"),t+=e[n];return t}i(VF,"escapeNonAlphaNumeric");function it(e,t,n,r){var a;e.format||(a=e.anyOf)!=null&&a.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}i(it,"addFormat");function Ze(e,t,n,r){var a;e.pattern||(a=e.allOf)!=null&&a.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:np(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=np(t,r)}i(Ze,"addPattern");function np(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=r.i?e.source.toLowerCase():e.source;let s="",o=!1,u=!1,l=!1;for(let c=0;c<a.length;c++){if(o){s+=a[c],o=!1;continue}if(r.i){if(u){if(a[c].match(/[a-z]/)){l?(s+=a[c],s+=`${a[c-2]}-${a[c]}`.toUpperCase(),l=!1):a[c+1]==="-"&&((n=a[c+2])!=null&&n.match(/[a-z]/))?(s+=a[c],l=!0):s+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){s+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(r.m){if(a[c]==="^"){s+=`(^|(?<=[\r
119
119
  ]))`;continue}else if(a[c]==="$"){s+=`($|(?=[\r
120
120
  ]))`;continue}}if(r.s&&a[c]==="."){s+=u?`${a[c]}\r
121
121
  `:`[${a[c]}\r
122
- ]`;continue}s+=a[c],a[c]==="\\"?o=!0:u&&a[c]==="]"?u=!1:!u&&a[c]==="["&&(u=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}i(ep,"stringifyRegExpWithFlags");function tp(e,t){var n,r,a,s,o,u;const l={type:"object",additionalProperties:(n=le(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===Y.ZodString&&((a=e.keyType._def.checks)!=null&&a.length)){const{type:c,...d}=Qc(e.keyType._def,t);return{...l,propertyNames:d}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Y.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((o=e.keyType)==null?void 0:o._def.typeName)===Y.ZodBranded&&e.keyType._def.type._def.typeName===Y.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){const{type:c,...d}=Yc(e.keyType._def,t);return{...l,propertyNames:d}}}return l}i(tp,"parseRecordDef");function UF(e,t){if(t.mapStrategy==="record")return tp(e,t);const n=le(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Je(),r=le(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Je();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}i(UF,"parseMapDef");function VF(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),a=Array.from(new Set(r.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:r}}i(VF,"parseNativeEnumDef");function GF(){return{not:Je()}}i(GF,"parseNeverDef");function WF(){return{type:"null"}}i(WF,"parseNullDef");var rs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function HF(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in rs&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((a,s)=>{const o=rs[s._def.typeName];return o&&!a.includes(o)?[...a,o]:a},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((a,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...a,o];case"bigint":return[...a,"integer"];case"object":if(s._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(r.length===n.length){const a=r.filter((s,o,u)=>u.indexOf(s)===o);return{type:a.length>1?a:a[0],enum:n.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,a)=>[...r,...a._def.values.filter(s=>!r.includes(s))],[])};return JF(e,t)}i(HF,"parseUnionDef");var JF=i((e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,a)=>le(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0},"asAnyOf");function KF(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[rs[e.innerType._def.typeName],"null"]};const n=le(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}i(KF,"parseNullableDef");function YF(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(YF,"parseNumberDef");function XF(e,t){const n={type:"object",properties:{}},r=[],a=e.shape();for(const o in a){let u=a[o];if(u===void 0||u._def===void 0)continue;const l=e2(u),c=le(u._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});c!==void 0&&(n.properties[o]=c,l||r.push(o))}r.length&&(n.required=r);const s=QF(e,t);return s!==void 0&&(n.additionalProperties=s),n}i(XF,"parseObjectDef");function QF(e,t){if(e.catchall._def.typeName!=="ZodNever")return le(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}i(QF,"decideAdditionalProperties");function e2(e){try{return e.isOptional()}catch{return!0}}i(e2,"safeIsOptional");var t2=i((e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return le(e.innerType._def,t);const r=le(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Je()},r]}:Je()},"parseOptionalDef"),n2=i((e,t)=>{if(t.pipeStrategy==="input")return le(e.in._def,t);if(t.pipeStrategy==="output")return le(e.out._def,t);const n=le(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=le(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(a=>a!==void 0)}},"parsePipelineDef");function r2(e,t){return le(e.type._def,t)}i(r2,"parsePromiseDef");function o2(e,t){const r={type:"array",uniqueItems:!0,items:le(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}i(o2,"parseSetDef");function a2(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>le(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:le(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>le(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}i(a2,"parseTupleDef");function s2(){return{not:Je()}}i(s2,"parseUndefinedDef");function i2(){return Je()}i(i2,"parseUnknownDef");var u2=i((e,t)=>le(e.innerType._def,t),"parseReadonlyDef"),l2=i((e,t,n)=>{switch(t){case Y.ZodString:return Qc(e,n);case Y.ZodNumber:return YF(e);case Y.ZodObject:return XF(e,n);case Y.ZodBigInt:return BF(e);case Y.ZodBoolean:return SF();case Y.ZodDate:return Xc(e,n);case Y.ZodUndefined:return s2();case Y.ZodNull:return WF();case Y.ZodArray:return TF(e,n);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return HF(e,n);case Y.ZodIntersection:return zF(e,n);case Y.ZodTuple:return a2(e,n);case Y.ZodRecord:return tp(e,n);case Y.ZodLiteral:return qF(e);case Y.ZodEnum:return MF(e);case Y.ZodNativeEnum:return VF(e);case Y.ZodNullable:return KF(e,n);case Y.ZodOptional:return t2(e,n);case Y.ZodMap:return UF(e,n);case Y.ZodSet:return o2(e,n);case Y.ZodLazy:return()=>e.getter()._def;case Y.ZodPromise:return r2(e,n);case Y.ZodNaN:case Y.ZodNever:return GF();case Y.ZodEffects:return PF(e,n);case Y.ZodAny:return Je();case Y.ZodUnknown:return i2();case Y.ZodDefault:return NF(e,n);case Y.ZodBranded:return Yc(e,n);case Y.ZodReadonly:return u2(e,n);case Y.ZodCatch:return OF(e,n);case Y.ZodPipeline:return n2(e,n);case Y.ZodFunction:case Y.ZodVoid:case Y.ZodSymbol:return;default:return(r=>{})()}},"selectParser"),c2=i((e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},"getRelativePath");function le(e,t,n=!1){var r;const a=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,a,n);if(l!==kF)return l}if(a&&!n){const l=p2(a,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const o=l2(e,e.typeName,t),u=typeof o=="function"?le(o(),t):o;if(u&&d2(e,t,u),t.postProcess){const l=t.postProcess(u,e,t);return s.jsonSchema=u,l}return s.jsonSchema=u,u}i(le,"parseDef");var p2=i((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:c2(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Je()):t.$refStrategy==="seen"?Je():void 0}},"get$ref"),d2=i((e,t,n)=>(e.description&&(n.description=e.description),n),"addMeta"),m2=i(e=>{const t=$F(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,a])=>[a._def,{def:a._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},"getRefs"),f2=i((e,t)=>{var n;const r=m2(t);let a=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,m])=>{var h;return{...c,[d]:(h=le(m._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0))!=null?h:Je()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=(n=le(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:Je(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(o.title=u);const l=s===void 0?a?{...o,[r.definitionPath]:a}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...a,[s]:o}};return l.$schema="http://json-schema.org/draft-07/schema#",l},"zod3ToJsonSchema"),os=Symbol.for("vercel.ai.schema");function J(e){let t;return()=>(t==null&&(t=e()),t)}i(J,"lazySchema");function Co(e,{validate:t}={}){return{[os]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}i(Co,"jsonSchema");function h2(e){return typeof e=="object"&&e!==null&&os in e&&e[os]===!0&&"jsonSchema"in e&&"validate"in e}i(h2,"isSchema");function mn(e){return e==null?Co({properties:{},additionalProperties:!1}):h2(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?G(e):D2(e):e()}i(mn,"asSchema");function D2(e){return Co(()=>e["~standard"].jsonSchema.input({target:"draft-07"}),{validate:i(async t=>{const n=await e["~standard"].validate(t);return"value"in n?{success:!0,value:n.value}:{success:!1,error:new zt({value:t,cause:n.issues})}},"validate")})}i(D2,"standardSchema");function g2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Co(()=>f2(e,{$refStrategy:r?"root":"none"}),{validate:i(async a=>{const s=await e.safeParseAsync(a);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(g2,"zod3Schema");function v2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Co(()=>Jc(n_(e,{target:"draft-7",io:"input",reused:r?"ref":"inline"})),{validate:i(async a=>{const s=await Ic(e,a);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(v2,"zod4Schema");function y2(e){return"_zod"in e}i(y2,"isZod4Schema");function G(e,t){return y2(e)?v2(e):g2(e)}i(G,"zodSchema");async function et({value:e,schema:t}){const n=await ut({value:e,schema:t});if(!n.success)throw zt.wrap({value:e,cause:n.error});return n.value}i(et,"validateTypes");async function ut({value:e,schema:t}){const n=mn(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:zt.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:zt.wrap({value:e,cause:r}),rawValue:e}}}i(ut,"safeValidateTypes");async function _2({text:e,schema:t}){try{const n=es(e);return t==null?n:et({value:n,schema:t})}catch(n){throw io.isInstance(n)||zt.isInstance(n)?n:new io({text:e,cause:n})}}i(_2,"parseJSON");async function lt({text:e,schema:t}){try{const n=es(e);return t==null?{success:!0,value:n,rawValue:n}:await ut({value:n,schema:t})}catch(n){return{success:!1,error:io.isInstance(n)?n:new io({text:e,cause:n}),rawValue:void 0}}}i(lt,"safeParseJSON");function bo(e){try{return es(e),!0}catch{return!1}}i(bo,"isParsableJson");function F2({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ya).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await lt({text:n,schema:t}))}}))}i(F2,"parseJsonEventStream");async function Ue({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;const r=await ut({value:t[e],schema:n});if(!r.success)throw new vl({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}i(Ue,"parseProviderOptions");var C2=i(()=>globalThis.fetch,"getOriginalFetch2"),Se=i(async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:a,abortSignal:s,fetch:o})=>np({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:a,abortSignal:s,fetch:o}),"postJsonToApi"),as=i(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:a,abortSignal:s,fetch:o})=>np({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:a,abortSignal:s,fetch:o}),"postFormDataToApi"),np=i(async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:a,abortSignal:s,fetch:o=C2()})=>{try{const u=await o(e,{method:"POST",headers:Gt(t,`ai-sdk/provider-utils/${Gc}`,Qa()),body:n.content,signal:s}),l=cn(u);if(!u.ok){let c;try{c=await a({response:u,url:e,requestBodyValues:n.values})}catch(d){throw dn(d)||Re.isInstance(d)?d:new Re({message:"Failed to process error response",cause:d,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:u,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(dn(c)||Re.isInstance(c))?c:new Re({message:"Failed to process successful response",cause:c,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(u){throw Vc({error:u,url:e,requestBodyValues:n.values})}},"postToApi");function O1(e){return e}i(O1,"tool");function yt({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:r}){return({execute:a,needsApproval:s,toModelOutput:o,onInputStart:u,onInputDelta:l,onInputAvailable:c,...d})=>({type:"provider",id:e,args:d,inputSchema:t,outputSchema:n,execute:a,needsApproval:s,toModelOutput:o,onInputStart:u,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:r})}i(yt,"createProviderToolFactoryWithOutputSchema");async function tt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}i(tt,"resolve");var nt=i(({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:a,requestBodyValues:s})=>{const o=await r.text(),u=cn(r);if(o.trim()==="")return{responseHeaders:u,value:new Re({message:r.statusText,url:a,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:o,isRetryable:n?.(r)})};try{const l=await _2({text:o,schema:e});return{responseHeaders:u,value:new Re({message:t(l),url:a,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:u,value:new Re({message:r.statusText,url:a,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:o,isRetryable:n?.(r)})}}},"createJsonErrorResponseHandler"),fn=i(e=>async({response:t})=>{const n=cn(t);if(t.body==null)throw new Qg({});return{responseHeaders:n,value:F2({stream:t.body,schema:e})}},"createEventSourceResponseHandler"),Pe=i(e=>async({response:t,url:n,requestBodyValues:r})=>{const a=await t.text(),s=await lt({text:a,schema:e}),o=cn(t);if(!s.success)throw new Re({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:o,responseBody:a,url:n,requestBodyValues:r});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},"createJsonResponseHandler"),b2=i(()=>async({response:e,url:t,requestBodyValues:n})=>{const r=cn(e);if(!e.body)throw new Re({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const a=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(a)}}catch(a){throw new Re({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:a})}},"createBinaryResponseHandler");function ss(e){return e?.replace(/\/$/,"")}i(ss,"withoutTrailingSlash");function E2(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}i(E2,"isAsyncIterable");async function*w2({execute:e,input:t,options:n}){const r=e(t,n);if(E2(r)){let a;for await(const s of r)a=s,yield{type:"preliminary",output:s};yield{type:"final",output:a}}else yield{type:"final",output:await r}}i(w2,"executeTool");var is,rp;function op(){if(rp)return is;rp=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=i((d,m)=>{for(var h in m)e(d,h,{get:m[h],enumerable:!0})},"__export"),s=i((d,m,h,D)=>{if(m&&typeof m=="object"||typeof m=="function")for(let f of n(m))!r.call(d,f)&&f!==h&&e(d,f,{get:i(()=>m[f],"get"),enumerable:!(D=t(m,f))||D.enumerable});return d},"__copyProps"),o=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};a(u,{SYMBOL_FOR_REQ_CONTEXT:i(()=>l,"SYMBOL_FOR_REQ_CONTEXT"),getContext:i(()=>c,"getContext")}),is=o(u);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return i(c,"getContext"),is}i(op,"requireGetContext");var us,ap;function sp(){if(ap)return us;ap=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=i((d,m)=>{for(var h in m)e(d,h,{get:m[h],enumerable:!0})},"__export"),s=i((d,m,h,D)=>{if(m&&typeof m=="object"||typeof m=="function")for(let f of n(m))!r.call(d,f)&&f!==h&&e(d,f,{get:i(()=>m[f],"get"),enumerable:!(D=t(m,f))||D.enumerable});return d},"__copyProps"),o=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};a(u,{VercelOidcTokenError:i(()=>l,"VercelOidcTokenError")}),us=o(u);const c=class c extends Error{constructor(m,h){super(m),this.name="VercelOidcTokenError",this.cause=h}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}};i(c,"VercelOidcTokenError");let l=c;return us}i(sp,"requireTokenError");var ls,ip;function A2(){if(ip)return ls;ip=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=i((h,D)=>{for(var f in D)e(h,f,{get:D[f],enumerable:!0})},"__export"),s=i((h,D,f,v)=>{if(D&&typeof D=="object"||typeof D=="function")for(let y of n(D))!r.call(h,y)&&y!==f&&e(h,y,{get:i(()=>D[y],"get"),enumerable:!(v=t(D,y))||v.enumerable});return h},"__copyProps"),o=i(h=>s(e({},"__esModule",{value:!0}),h),"__toCommonJS"),u={};a(u,{getVercelOidcToken:i(()=>d,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>m,"getVercelOidcTokenSync")}),ls=o(u);var l=op(),c=sp();async function d(){let h="",D;try{h=m()}catch(f){D=f}try{const[{getTokenPayload:f,isExpired:v},{refreshToken:y}]=await Promise.all([await import("./token-util-ChIErf4e.mjs").then(function(F){return F.t}),await import("./token-0l1w5aDM.mjs").then(function(F){return F.t})]);(!h||v(f(h)))&&(await y(),h=m())}catch(f){let v=D instanceof Error?D.message:"";throw f instanceof Error&&(v=`${v}
123
- ${f.message}`),v?new c.VercelOidcTokenError(v):f}return h}i(d,"getVercelOidcToken");function m(){const h=(0,l.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!h)throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return h}return i(m,"getVercelOidcTokenSync"),ls}i(A2,"requireGetVercelOidcToken");var cs,up;function I2(){if(up)return cs;up=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=i((d,m)=>{for(var h in m)e(d,h,{get:m[h],enumerable:!0})},"__export"),s=i((d,m,h,D)=>{if(m&&typeof m=="object"||typeof m=="function")for(let f of n(m))!r.call(d,f)&&f!==h&&e(d,f,{get:i(()=>m[f],"get"),enumerable:!(D=t(m,f))||D.enumerable});return d},"__copyProps"),o=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};a(u,{getContext:i(()=>c.getContext,"getContext"),getVercelOidcToken:i(()=>l.getVercelOidcToken,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>l.getVercelOidcTokenSync,"getVercelOidcTokenSync")}),cs=o(u);var l=A2(),c=op();return cs}i(I2,"requireDist");var lp=I2(),x2="vercel.ai.gateway.error",ps=Symbol.for(x2),cp,pp,Ke=(Yt=class extends(pp=Error,cp=ps,pp){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[cp]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return Yt.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&ps in t&&t[ps]===!0}},i(Yt,"_GatewayError"),Yt),dp="GatewayAuthenticationError",k2=`vercel.ai.gateway.error.${dp}`,mp=Symbol.for(k2),fp,hp,ds=(Xt=class extends(hp=Ke,fp=mp,hp){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[fp]=!0,this.name=dp,this.type="authentication_error"}static isInstance(t){return Ke.hasMarker(t)&&mp in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:a=401,cause:s}){let o;return t?o=`AI Gateway authentication failed: Invalid API key.
122
+ ]`;continue}s+=a[c],a[c]==="\\"?o=!0:u&&a[c]==="]"?u=!1:!u&&a[c]==="["&&(u=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}i(np,"stringifyRegExpWithFlags");function rp(e,t){var n,r,a,s,o,u;const l={type:"object",additionalProperties:(n=le(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===Y.ZodString&&((a=e.keyType._def.checks)!=null&&a.length)){const{type:c,...d}=tp(e.keyType._def,t);return{...l,propertyNames:d}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Y.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((o=e.keyType)==null?void 0:o._def.typeName)===Y.ZodBranded&&e.keyType._def.type._def.typeName===Y.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){const{type:c,...d}=Qc(e.keyType._def,t);return{...l,propertyNames:d}}}return l}i(rp,"parseRecordDef");function GF(e,t){if(t.mapStrategy==="record")return rp(e,t);const n=le(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Je(),r=le(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Je();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}i(GF,"parseMapDef");function WF(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),a=Array.from(new Set(r.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:r}}i(WF,"parseNativeEnumDef");function HF(){return{not:Je()}}i(HF,"parseNeverDef");function JF(){return{type:"null"}}i(JF,"parseNullDef");var rs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function KF(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in rs&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((a,s)=>{const o=rs[s._def.typeName];return o&&!a.includes(o)?[...a,o]:a},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((a,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...a,o];case"bigint":return[...a,"integer"];case"object":if(s._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(r.length===n.length){const a=r.filter((s,o,u)=>u.indexOf(s)===o);return{type:a.length>1?a:a[0],enum:n.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,a)=>[...r,...a._def.values.filter(s=>!r.includes(s))],[])};return YF(e,t)}i(KF,"parseUnionDef");var YF=i((e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,a)=>le(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0},"asAnyOf");function XF(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[rs[e.innerType._def.typeName],"null"]};const n=le(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}i(XF,"parseNullableDef");function QF(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(QF,"parseNumberDef");function e2(e,t){const n={type:"object",properties:{}},r=[],a=e.shape();for(const o in a){let u=a[o];if(u===void 0||u._def===void 0)continue;const l=n2(u),c=le(u._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});c!==void 0&&(n.properties[o]=c,l||r.push(o))}r.length&&(n.required=r);const s=t2(e,t);return s!==void 0&&(n.additionalProperties=s),n}i(e2,"parseObjectDef");function t2(e,t){if(e.catchall._def.typeName!=="ZodNever")return le(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}i(t2,"decideAdditionalProperties");function n2(e){try{return e.isOptional()}catch{return!0}}i(n2,"safeIsOptional");var r2=i((e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return le(e.innerType._def,t);const r=le(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Je()},r]}:Je()},"parseOptionalDef"),o2=i((e,t)=>{if(t.pipeStrategy==="input")return le(e.in._def,t);if(t.pipeStrategy==="output")return le(e.out._def,t);const n=le(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=le(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(a=>a!==void 0)}},"parsePipelineDef");function a2(e,t){return le(e.type._def,t)}i(a2,"parsePromiseDef");function s2(e,t){const r={type:"array",uniqueItems:!0,items:le(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}i(s2,"parseSetDef");function i2(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>le(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:le(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>le(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}i(i2,"parseTupleDef");function u2(){return{not:Je()}}i(u2,"parseUndefinedDef");function l2(){return Je()}i(l2,"parseUnknownDef");var c2=i((e,t)=>le(e.innerType._def,t),"parseReadonlyDef"),p2=i((e,t,n)=>{switch(t){case Y.ZodString:return tp(e,n);case Y.ZodNumber:return QF(e);case Y.ZodObject:return e2(e,n);case Y.ZodBigInt:return OF(e);case Y.ZodBoolean:return RF();case Y.ZodDate:return ep(e,n);case Y.ZodUndefined:return u2();case Y.ZodNull:return JF();case Y.ZodArray:return SF(e,n);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return KF(e,n);case Y.ZodIntersection:return ZF(e,n);case Y.ZodTuple:return i2(e,n);case Y.ZodRecord:return rp(e,n);case Y.ZodLiteral:return UF(e);case Y.ZodEnum:return zF(e);case Y.ZodNativeEnum:return WF(e);case Y.ZodNullable:return XF(e,n);case Y.ZodOptional:return r2(e,n);case Y.ZodMap:return GF(e,n);case Y.ZodSet:return s2(e,n);case Y.ZodLazy:return()=>e.getter()._def;case Y.ZodPromise:return a2(e,n);case Y.ZodNaN:case Y.ZodNever:return HF();case Y.ZodEffects:return jF(e,n);case Y.ZodAny:return Je();case Y.ZodUnknown:return l2();case Y.ZodDefault:return MF(e,n);case Y.ZodBranded:return Qc(e,n);case Y.ZodReadonly:return c2(e,n);case Y.ZodCatch:return NF(e,n);case Y.ZodPipeline:return o2(e,n);case Y.ZodFunction:case Y.ZodVoid:case Y.ZodSymbol:return;default:return(r=>{})()}},"selectParser"),d2=i((e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},"getRelativePath");function le(e,t,n=!1){var r;const a=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,a,n);if(l!==TF)return l}if(a&&!n){const l=m2(a,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const o=p2(e,e.typeName,t),u=typeof o=="function"?le(o(),t):o;if(u&&f2(e,t,u),t.postProcess){const l=t.postProcess(u,e,t);return s.jsonSchema=u,l}return s.jsonSchema=u,u}i(le,"parseDef");var m2=i((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:d2(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Je()):t.$refStrategy==="seen"?Je():void 0}},"get$ref"),f2=i((e,t,n)=>(e.description&&(n.description=e.description),n),"addMeta"),h2=i(e=>{const t=BF(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,a])=>[a._def,{def:a._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},"getRefs"),D2=i((e,t)=>{var n;const r=h2(t);let a=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,m])=>{var h;return{...c,[d]:(h=le(m._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0))!=null?h:Je()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=(n=le(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:Je(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(o.title=u);const l=s===void 0?a?{...o,[r.definitionPath]:a}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...a,[s]:o}};return l.$schema="http://json-schema.org/draft-07/schema#",l},"zod3ToJsonSchema"),os=Symbol.for("vercel.ai.schema");function J(e){let t;return()=>(t==null&&(t=e()),t)}i(J,"lazySchema");function Eo(e,{validate:t}={}){return{[os]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}i(Eo,"jsonSchema");function g2(e){return typeof e=="object"&&e!==null&&os in e&&e[os]===!0&&"jsonSchema"in e&&"validate"in e}i(g2,"isSchema");function mn(e){return e==null?Eo({properties:{},additionalProperties:!1}):g2(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?G(e):v2(e):e()}i(mn,"asSchema");function v2(e){return Eo(()=>e["~standard"].jsonSchema.input({target:"draft-07"}),{validate:i(async t=>{const n=await e["~standard"].validate(t);return"value"in n?{success:!0,value:n.value}:{success:!1,error:new zt({value:t,cause:n.issues})}},"validate")})}i(v2,"standardSchema");function y2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Eo(()=>D2(e,{$refStrategy:r?"root":"none"}),{validate:i(async a=>{const s=await e.safeParseAsync(a);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(y2,"zod3Schema");function _2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Eo(()=>Yc(o_(e,{target:"draft-7",io:"input",reused:r?"ref":"inline"})),{validate:i(async a=>{const s=await kc(e,a);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(_2,"zod4Schema");function F2(e){return"_zod"in e}i(F2,"isZod4Schema");function G(e,t){return F2(e)?_2(e):y2(e)}i(G,"zodSchema");async function et({value:e,schema:t}){const n=await ut({value:e,schema:t});if(!n.success)throw zt.wrap({value:e,cause:n.error});return n.value}i(et,"validateTypes");async function ut({value:e,schema:t}){const n=mn(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:zt.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:zt.wrap({value:e,cause:r}),rawValue:e}}}i(ut,"safeValidateTypes");async function C2({text:e,schema:t}){try{const n=es(e);return t==null?n:et({value:n,schema:t})}catch(n){throw lo.isInstance(n)||zt.isInstance(n)?n:new lo({text:e,cause:n})}}i(C2,"parseJSON");async function lt({text:e,schema:t}){try{const n=es(e);return t==null?{success:!0,value:n,rawValue:n}:await ut({value:n,schema:t})}catch(n){return{success:!1,error:lo.isInstance(n)?n:new lo({text:e,cause:n}),rawValue:void 0}}}i(lt,"safeParseJSON");function wo(e){try{return es(e),!0}catch{return!1}}i(wo,"isParsableJson");function b2({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ya).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await lt({text:n,schema:t}))}}))}i(b2,"parseJsonEventStream");async function Le({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;const r=await ut({value:t[e],schema:n});if(!r.success)throw new _l({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}i(Le,"parseProviderOptions");var E2=i(()=>globalThis.fetch,"getOriginalFetch2"),Se=i(async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:a,abortSignal:s,fetch:o})=>op({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:a,abortSignal:s,fetch:o}),"postJsonToApi"),as=i(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:a,abortSignal:s,fetch:o})=>op({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:a,abortSignal:s,fetch:o}),"postFormDataToApi"),op=i(async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:a,abortSignal:s,fetch:o=E2()})=>{try{const u=await o(e,{method:"POST",headers:Gt(t,`ai-sdk/provider-utils/${Hc}`,Qa()),body:n.content,signal:s}),l=cn(u);if(!u.ok){let c;try{c=await a({response:u,url:e,requestBodyValues:n.values})}catch(d){throw dn(d)||Re.isInstance(d)?d:new Re({message:"Failed to process error response",cause:d,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:u,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(dn(c)||Re.isInstance(c))?c:new Re({message:"Failed to process successful response",cause:c,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(u){throw Wc({error:u,url:e,requestBodyValues:n.values})}},"postToApi");function z1(e){return e}i(z1,"tool");function yt({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:r}){return({execute:a,needsApproval:s,toModelOutput:o,onInputStart:u,onInputDelta:l,onInputAvailable:c,...d})=>({type:"provider",id:e,args:d,inputSchema:t,outputSchema:n,execute:a,needsApproval:s,toModelOutput:o,onInputStart:u,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:r})}i(yt,"createProviderToolFactoryWithOutputSchema");async function tt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}i(tt,"resolve");var nt=i(({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:a,requestBodyValues:s})=>{const o=await r.text(),u=cn(r);if(o.trim()==="")return{responseHeaders:u,value:new Re({message:r.statusText,url:a,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:o,isRetryable:n?.(r)})};try{const l=await C2({text:o,schema:e});return{responseHeaders:u,value:new Re({message:t(l),url:a,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:u,value:new Re({message:r.statusText,url:a,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:o,isRetryable:n?.(r)})}}},"createJsonErrorResponseHandler"),fn=i(e=>async({response:t})=>{const n=cn(t);if(t.body==null)throw new tv({});return{responseHeaders:n,value:b2({stream:t.body,schema:e})}},"createEventSourceResponseHandler"),Pe=i(e=>async({response:t,url:n,requestBodyValues:r})=>{const a=await t.text(),s=await lt({text:a,schema:e}),o=cn(t);if(!s.success)throw new Re({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:o,responseBody:a,url:n,requestBodyValues:r});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},"createJsonResponseHandler"),w2=i(()=>async({response:e,url:t,requestBodyValues:n})=>{const r=cn(e);if(!e.body)throw new Re({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const a=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(a)}}catch(a){throw new Re({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:a})}},"createBinaryResponseHandler");function ss(e){return e?.replace(/\/$/,"")}i(ss,"withoutTrailingSlash");function A2(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}i(A2,"isAsyncIterable");async function*I2({execute:e,input:t,options:n}){const r=e(t,n);if(A2(r)){let a;for await(const s of r)a=s,yield{type:"preliminary",output:s};yield{type:"final",output:a}}else yield{type:"final",output:await r}}i(I2,"executeTool");var is,ap;function sp(){if(ap)return is;ap=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=i((d,m)=>{for(var h in m)e(d,h,{get:m[h],enumerable:!0})},"__export"),s=i((d,m,h,D)=>{if(m&&typeof m=="object"||typeof m=="function")for(let f of n(m))!r.call(d,f)&&f!==h&&e(d,f,{get:i(()=>m[f],"get"),enumerable:!(D=t(m,f))||D.enumerable});return d},"__copyProps"),o=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};a(u,{SYMBOL_FOR_REQ_CONTEXT:i(()=>l,"SYMBOL_FOR_REQ_CONTEXT"),getContext:i(()=>c,"getContext")}),is=o(u);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return i(c,"getContext"),is}i(sp,"requireGetContext");var us,ip;function up(){if(ip)return us;ip=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=i((d,m)=>{for(var h in m)e(d,h,{get:m[h],enumerable:!0})},"__export"),s=i((d,m,h,D)=>{if(m&&typeof m=="object"||typeof m=="function")for(let f of n(m))!r.call(d,f)&&f!==h&&e(d,f,{get:i(()=>m[f],"get"),enumerable:!(D=t(m,f))||D.enumerable});return d},"__copyProps"),o=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};a(u,{VercelOidcTokenError:i(()=>l,"VercelOidcTokenError")}),us=o(u);const c=class c extends Error{constructor(m,h){super(m),this.name="VercelOidcTokenError",this.cause=h}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}};i(c,"VercelOidcTokenError");let l=c;return us}i(up,"requireTokenError");var ls,lp;function x2(){if(lp)return ls;lp=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=i((h,D)=>{for(var f in D)e(h,f,{get:D[f],enumerable:!0})},"__export"),s=i((h,D,f,v)=>{if(D&&typeof D=="object"||typeof D=="function")for(let y of n(D))!r.call(h,y)&&y!==f&&e(h,y,{get:i(()=>D[y],"get"),enumerable:!(v=t(D,y))||v.enumerable});return h},"__copyProps"),o=i(h=>s(e({},"__esModule",{value:!0}),h),"__toCommonJS"),u={};a(u,{getVercelOidcToken:i(()=>d,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>m,"getVercelOidcTokenSync")}),ls=o(u);var l=sp(),c=up();async function d(){let h="",D;try{h=m()}catch(f){D=f}try{const[{getTokenPayload:f,isExpired:v},{refreshToken:y}]=await Promise.all([await import("./token-util-DHPwkGN_.mjs").then(function(F){return F.t}),await import("./token-B4wZymUi.mjs").then(function(F){return F.t})]);(!h||v(f(h)))&&(await y(),h=m())}catch(f){let v=D instanceof Error?D.message:"";throw f instanceof Error&&(v=`${v}
123
+ ${f.message}`),v?new c.VercelOidcTokenError(v):f}return h}i(d,"getVercelOidcToken");function m(){const h=(0,l.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!h)throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return h}return i(m,"getVercelOidcTokenSync"),ls}i(x2,"requireGetVercelOidcToken");var cs,cp;function k2(){if(cp)return cs;cp=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=i((d,m)=>{for(var h in m)e(d,h,{get:m[h],enumerable:!0})},"__export"),s=i((d,m,h,D)=>{if(m&&typeof m=="object"||typeof m=="function")for(let f of n(m))!r.call(d,f)&&f!==h&&e(d,f,{get:i(()=>m[f],"get"),enumerable:!(D=t(m,f))||D.enumerable});return d},"__copyProps"),o=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};a(u,{getContext:i(()=>c.getContext,"getContext"),getVercelOidcToken:i(()=>l.getVercelOidcToken,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>l.getVercelOidcTokenSync,"getVercelOidcTokenSync")}),cs=o(u);var l=x2(),c=sp();return cs}i(k2,"requireDist");var pp=k2(),$2="vercel.ai.gateway.error",ps=Symbol.for($2),dp,mp,Ke=(Yt=class extends(mp=Error,dp=ps,mp){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[dp]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return Yt.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&ps in t&&t[ps]===!0}},i(Yt,"_GatewayError"),Yt),fp="GatewayAuthenticationError",T2=`vercel.ai.gateway.error.${fp}`,hp=Symbol.for(T2),Dp,gp,ds=(Xt=class extends(gp=Ke,Dp=hp,gp){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Dp]=!0,this.name=fp,this.type="authentication_error"}static isInstance(t){return Ke.hasMarker(t)&&hp in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:a=401,cause:s}){let o;return t?o=`AI Gateway authentication failed: Invalid API key.
124
124
 
125
125
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
126
126
 
@@ -135,7 +135,7 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
135
135
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
136
136
 
137
137
  Option 2 - OIDC token:
138
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Xt({message:o,statusCode:a,cause:s})}},i(Xt,"_GatewayAuthenticationError"),Xt),Dp="GatewayInvalidRequestError",$2=`vercel.ai.gateway.error.${Dp}`,gp=Symbol.for($2),vp,yp,T2=(xn=class extends(yp=Ke,vp=gp,yp){constructor({message:t="Invalid request",statusCode:n=400,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[vp]=!0,this.name=Dp,this.type="invalid_request_error"}static isInstance(t){return Ke.hasMarker(t)&&gp in t}},i(xn,"GatewayInvalidRequestError"),xn),_p="GatewayRateLimitError",B2=`vercel.ai.gateway.error.${_p}`,Fp=Symbol.for(B2),Cp,bp,S2=(kn=class extends(bp=Ke,Cp=Fp,bp){constructor({message:t="Rate limit exceeded",statusCode:n=429,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Cp]=!0,this.name=_p,this.type="rate_limit_exceeded"}static isInstance(t){return Ke.hasMarker(t)&&Fp in t}},i(kn,"GatewayRateLimitError"),kn),Ep="GatewayModelNotFoundError",O2=`vercel.ai.gateway.error.${Ep}`,wp=Symbol.for(O2),R2=J(()=>G(g({modelId:p()}))),Ap,Ip,N2=($n=class extends(Ip=Ke,Ap=wp,Ip){constructor({message:t="Model not found",statusCode:n=404,modelId:r,cause:a}={}){super({message:t,statusCode:n,cause:a}),this[Ap]=!0,this.name=Ep,this.type="model_not_found",this.modelId=r}static isInstance(t){return Ke.hasMarker(t)&&wp in t}},i($n,"GatewayModelNotFoundError"),$n),xp="GatewayInternalServerError",P2=`vercel.ai.gateway.error.${xp}`,kp=Symbol.for(P2),$p,Tp,Bp=(Tn=class extends(Tp=Ke,$p=kp,Tp){constructor({message:t="Internal server error",statusCode:n=500,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[$p]=!0,this.name=xp,this.type="internal_server_error"}static isInstance(t){return Ke.hasMarker(t)&&kp in t}},i(Tn,"GatewayInternalServerError"),Tn),Sp="GatewayResponseError",M2=`vercel.ai.gateway.error.${Sp}`,Op=Symbol.for(M2),Rp,Np,j2=(Bn=class extends(Np=Ke,Rp=Op,Np){constructor({message:t="Invalid response from Gateway",statusCode:n=502,response:r,validationError:a,cause:s}={}){super({message:t,statusCode:n,cause:s}),this[Rp]=!0,this.name=Sp,this.type="response_error",this.response=r,this.validationError=a}static isInstance(t){return Ke.hasMarker(t)&&Op in t}},i(Bn,"GatewayResponseError"),Bn);async function Pp({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:a}){const s=await ut({value:e,schema:z2});if(!s.success)return new j2({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:s.error,cause:r});const o=s.value,u=o.error.type,l=o.error.message;switch(u){case"authentication_error":return ds.createContextualError({apiKeyProvided:a==="api-key",oidcTokenProvided:a==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new T2({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new S2({message:l,statusCode:t,cause:r});case"model_not_found":{const c=await ut({value:o.error.param,schema:R2});return new N2({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:r})}case"internal_server_error":return new Bp({message:l,statusCode:t,cause:r});default:return new Bp({message:l,statusCode:t,cause:r})}}i(Pp,"createGatewayErrorFromResponse");var z2=J(()=>G(g({error:g({message:p(),type:p().nullish(),param:gt().nullish(),code:H([p(),A()]).nullish()})})));function kt(e,t){var n;return Ke.isInstance(e)?e:Re.isInstance(e)?Pp({response:q2(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):Pp({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}i(kt,"asGatewayError");function q2(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}i(q2,"extractApiCallResponse");var Mp="ai-gateway-auth-method";async function hn(e){const t=await ut({value:e[Mp],schema:Z2});return t.success?t.value:void 0}i(hn,"parseAuthMethod");var Z2=J(()=>G(H([I("api-key"),I("oidc")]))),jp=(Sn=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Wc({url:`${this.config.baseURL}/config`,headers:await tt(this.config.headers()),successfulResponseHandler:Pe(L2),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(n=>n,"errorToMessage")}),fetch:this.config.fetch});return t}catch(t){throw await kt(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:n}=await Wc({url:`${t.origin}/v1/credits`,headers:await tt(this.config.headers()),successfulResponseHandler:Pe(U2),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(r=>r,"errorToMessage")}),fetch:this.config.fetch});return n}catch(t){throw await kt(t)}}},i(Sn,"GatewayFetchMetadata"),Sn),L2=J(()=>G(g({models:T(g({id:p(),name:p(),description:p().nullish(),pricing:g({input:p(),output:p(),input_cache_read:p().nullish(),input_cache_write:p().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:g({specificationVersion:I("v3"),provider:p(),modelId:p()}),modelType:re(["language","embedding","image"]).nullish()}))}))),U2=J(()=>G(g({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),V2=(On=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:n,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,s=await tt(this.config.headers());try{const{responseHeaders:o,value:u,rawValue:l}=await Se({url:this.getUrl(),headers:xe(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await tt(this.config.o11yHeaders)),body:n,successfulResponseHandler:Pe(qe()),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(c=>c,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...u,request:{body:n},response:{headers:o,body:l},warnings:r}}catch(o){throw await kt(o,await hn(s))}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,s=await tt(this.config.headers());try{const{value:o,responseHeaders:u}=await Se({url:this.getUrl(),headers:xe(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await tt(this.config.o11yHeaders)),body:n,successfulResponseHandler:fn(qe()),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(l=>l,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(l){r.length>0&&l.enqueue({type:"stream-start",warnings:r})},transform(l,c){if(l.success){const d=l.value;if(d.type==="raw"&&!t.includeRawChunks)return;d.type==="response-metadata"&&d.timestamp&&typeof d.timestamp=="string"&&(d.timestamp=new Date(d.timestamp)),c.enqueue(d)}else c.error(l.error)}})),request:{body:n},response:{headers:u}}}catch(o){throw await kt(o,await hn(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const n of t.prompt)for(const r of n.content)if(this.isFilePart(r)){const a=r;if(a.data instanceof Uint8Array){const s=Uint8Array.from(a.data),o=Buffer.from(s).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${o}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,n){return{"ai-language-model-specification-version":"3","ai-language-model-id":t,"ai-language-model-streaming":String(n)}}},i(On,"GatewayLanguageModel"),On),G2=(Rn=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:a}){var s;const o=await tt(this.config.headers());try{const{responseHeaders:u,value:l,rawValue:c}=await Se({url:this.getUrl(),headers:xe(o,n??{},this.getModelConfigHeaders(),await tt(this.config.o11yHeaders)),body:{values:t,...a?{providerOptions:a}:{}},successfulResponseHandler:Pe(W2),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(d=>d,"errorToMessage")}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(s=l.usage)!=null?s:void 0,providerMetadata:l.providerMetadata,response:{headers:u,body:c},warnings:[]}}catch(u){throw await kt(u,await hn(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},i(Rn,"GatewayEmbeddingModel"),Rn),W2=J(()=>G(g({embeddings:T(T(A())),usage:g({tokens:A()}).nullish(),providerMetadata:me(p(),me(p(),gt())).optional()}))),H2=(Nn=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,size:r,aspectRatio:a,seed:s,files:o,mask:u,providerOptions:l,headers:c,abortSignal:d}){var m;const h=await tt(this.config.headers());try{const{responseHeaders:D,value:f,rawValue:v}=await Se({url:this.getUrl(),headers:xe(h,c??{},this.getModelConfigHeaders(),await tt(this.config.o11yHeaders)),body:{prompt:t,n,...r&&{size:r},...a&&{aspectRatio:a},...s&&{seed:s},...l&&{providerOptions:l},...o&&{files:o.map(y=>zp(y))},...u&&{mask:zp(u)}},successfulResponseHandler:Pe(K2),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(y=>y,"errorToMessage")}),...d&&{abortSignal:d},fetch:this.config.fetch});return{images:f.images,warnings:(m=f.warnings)!=null?m:[],providerMetadata:f.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:D}}}catch(D){throw kt(D,await hn(h))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}},i(Nn,"GatewayImageModel"),Nn);function zp(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Ir(e.data)}:e}i(zp,"maybeEncodeImageFile");var J2=g({images:T(gt()).optional()}).catchall(gt()),K2=g({images:T(p()),warnings:T(g({type:I("other"),message:p()})).optional(),providerMetadata:me(p(),J2).optional()});async function Y2(){var e;return(e=lp.getContext().headers)==null?void 0:e["x-vercel-id"]}i(Y2,"getVercelRequestId");var X2="3.0.9",Q2="0.0.1";function eC(e={}){var t,n;let r=null,a=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let o=0;const u=(n=ss(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",l=i(async()=>{try{const v=await nC(e);return Gt({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":Q2,[Mp]:v.authMethod,...e.headers},`ai-sdk/gateway/${X2}`)}catch(v){throw ds.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},"getHeaders"),c=i(()=>{const v=kr({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=kr({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),F=kr({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const E=await Y2();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...F&&{"ai-o11y-region":F},...E&&{"ai-o11y-request-id":E}}}},"createO11yHeaders"),d=i(v=>new V2(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createLanguageModel"),m=i(async()=>{var v,y,F;const E=(F=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?F:Date.now();return(!r||E-o>s)&&(o=E,r=new jp({baseURL:u,headers:l,fetch:e.fetch}).getAvailableModels().then(b=>(a=b,b)).catch(async b=>{throw await kt(b,await hn(await l()))})),a?Promise.resolve(a):r},"getAvailableModels"),h=i(async()=>new jp({baseURL:u,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await kt(v,await hn(await l()))}),"getCredits"),D=i(function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(v)},"provider");D.specificationVersion="v3",D.getAvailableModels=m,D.getCredits=h,D.imageModel=v=>new H2(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.languageModel=d;const f=i(v=>new G2(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createEmbeddingModel");return D.embeddingModel=f,D.textEmbeddingModel=f,D}i(eC,"createGatewayProvider");var tC=eC();async function nC(e){const t=kr({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await lp.getVercelOidcToken(),authMethod:"oidc"}}i(nC,"getGatewayAuthToken");var rC=typeof globalThis=="object"?globalThis:global,Ht="1.9.0",qp=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function oC(e){var t=new Set([e]),n=new Set,r=e.match(qp);if(!r)return function(){return!1};var a={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(a.prerelease!=null)return i(function(l){return l===e},"isExactmatch");function s(u){return n.add(u),!1}i(s,"_reject");function o(u){return t.add(u),!0}return i(o,"_accept"),i(function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(qp);if(!c)return s(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||a.major!==d.major?s(l):a.major===0?a.minor===d.minor&&a.patch<=d.patch?o(l):s(l):a.minor<=d.minor?o(l):s(l)},"isCompatible2")}i(oC,"_makeCompatibilityCheck");var aC=oC(Ht),sC=Ht.split(".")[0],$r=Symbol.for("opentelemetry.js.api."+sC),Tr=rC;function ms(e,t,n,r){var a;r===void 0&&(r=!1);var s=Tr[$r]=(a=Tr[$r])!==null&&a!==void 0?a:{version:Ht};if(!r&&s[e]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(o.stack||o.message),!1}if(s.version!==Ht){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Ht);return n.error(o.stack||o.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Ht+"."),!0}i(ms,"registerGlobal");function Br(e){var t,n,r=(t=Tr[$r])===null||t===void 0?void 0:t.version;if(!(!r||!aC(r)))return(n=Tr[$r])===null||n===void 0?void 0:n[e]}i(Br,"getGlobal");function fs(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Ht+".");var n=Tr[$r];n&&delete n[e]}i(fs,"unregisterGlobal");var iC=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,s=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)s.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s},"__read$3"),uC=i(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,s;r<a;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$3"),lC=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return i(e,"DiagComponentLogger2"),e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("verbose",this._namespace,t)},e})();function Sr(e,t,n){var r=Br("diag");if(r)return n.unshift(t),r[e].apply(r,uC([],iC(n),!1))}i(Sr,"logProxy");var Ye;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(Ye||(Ye={}));function cC(e,t){e<Ye.NONE?e=Ye.NONE:e>Ye.ALL&&(e=Ye.ALL),t=t||{};function n(r,a){var s=t[r];return typeof s=="function"&&e>=a?s.bind(t):function(){}}return i(n,"_filterFunc"),{error:n("error",Ye.ERROR),warn:n("warn",Ye.WARN),info:n("info",Ye.INFO),debug:n("debug",Ye.DEBUG),verbose:n("verbose",Ye.VERBOSE)}}i(cC,"createLogLevelDiagLogger");var pC=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,s=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)s.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s},"__read$2"),dC=i(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,s;r<a;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$2"),mC="diag",Eo=(function(){function e(){function t(a){return function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var u=Br("diag");if(u)return u[a].apply(u,dC([],pC(s),!1))}}i(t,"_logProxy");var n=this,r=i(function(a,s){var o,u,l;if(s===void 0&&(s={logLevel:Ye.INFO}),a===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((o=c.stack)!==null&&o!==void 0?o:c.message),!1}typeof s=="number"&&(s={logLevel:s});var d=Br("diag"),m=cC((u=s.logLevel)!==null&&u!==void 0?u:Ye.INFO,a);if(d&&!s.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+h),m.warn("Current logger will overwrite one already registered from "+h)}return ms("diag",m,n,!0)},"setLogger");n.setLogger=r,n.disable=function(){fs(mC,n)},n.createComponentLogger=function(a){return new lC(a)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return i(e,"DiagAPI2"),e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function fC(e){return Symbol.for(e)}i(fC,"createContextKey");var hC=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,a){var s=new e(n._currentContext);return s._currentContext.set(r,a),s},n.deleteValue=function(r){var a=new e(n._currentContext);return a._currentContext.delete(r),a}}return i(e,"BaseContext2"),e})(),DC=new hC,gC=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,s=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)s.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s},"__read$1"),vC=i(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,s;r<a;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$1"),yC=(function(){function e(){}return i(e,"NoopContextManager2"),e.prototype.active=function(){return DC},e.prototype.with=function(t,n,r){for(var a=[],s=3;s<arguments.length;s++)a[s-3]=arguments[s];return n.call.apply(n,vC([r],gC(a),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),_C=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,s=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)s.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s},"__read"),FC=i(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,s;r<a;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray"),hs="context",CC=new yC,Zp=(function(){function e(){}return i(e,"ContextAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return ms(hs,t,Eo.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var a,s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return(a=this._getContextManager()).with.apply(a,FC([t,n,r],_C(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Br(hs)||CC},e.prototype.disable=function(){this._getContextManager().disable(),fs(hs,Eo.instance())},e})(),Ds;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ds||(Ds={}));var Lp="0000000000000000",Up="00000000000000000000000000000000",bC={traceId:Up,spanId:Lp,traceFlags:Ds.NONE},Or=(function(){function e(t){t===void 0&&(t=bC),this._spanContext=t}return i(e,"NonRecordingSpan2"),e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e})(),gs=fC("OpenTelemetry Context Key SPAN");function vs(e){return e.getValue(gs)||void 0}i(vs,"getSpan");function EC(){return vs(Zp.getInstance().active())}i(EC,"getActiveSpan");function ys(e,t){return e.setValue(gs,t)}i(ys,"setSpan");function wC(e){return e.deleteValue(gs)}i(wC,"deleteSpan");function AC(e,t){return ys(e,new Or(t))}i(AC,"setSpanContext");function Vp(e){var t;return(t=vs(e))===null||t===void 0?void 0:t.spanContext()}i(Vp,"getSpanContext");var IC=/^([0-9a-f]{32})$/i,xC=/^[0-9a-f]{16}$/i;function kC(e){return IC.test(e)&&e!==Up}i(kC,"isValidTraceId");function $C(e){return xC.test(e)&&e!==Lp}i($C,"isValidSpanId");function Gp(e){return kC(e.traceId)&&$C(e.spanId)}i(Gp,"isSpanContextValid");function TC(e){return new Or(e)}i(TC,"wrapSpanContext");var _s=Zp.getInstance(),Wp=(function(){function e(){}return i(e,"NoopTracer2"),e.prototype.startSpan=function(t,n,r){r===void 0&&(r=_s.active());var a=!!n?.root;if(a)return new Or;var s=r&&Vp(r);return BC(s)&&Gp(s)?new Or(s):new Or},e.prototype.startActiveSpan=function(t,n,r,a){var s,o,u;if(!(arguments.length<2)){arguments.length===2?u=n:arguments.length===3?(s=n,u=r):(s=n,o=r,u=a);var l=o??_s.active(),c=this.startSpan(t,s,l),d=ys(l,c);return _s.with(d,u,void 0,c)}},e})();function BC(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}i(BC,"isSpanContext");var SC=new Wp,OC=(function(){function e(t,n,r,a){this._provider=t,this.name=n,this.version=r,this.options=a}return i(e,"ProxyTracer2"),e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,a){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):SC},e})(),RC=(function(){function e(){}return i(e,"NoopTracerProvider2"),e.prototype.getTracer=function(t,n,r){return new Wp},e})(),NC=new RC,Hp=(function(){function e(){}return i(e,"ProxyTracerProvider2"),e.prototype.getTracer=function(t,n,r){var a;return(a=this.getDelegateTracer(t,n,r))!==null&&a!==void 0?a:new OC(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:NC},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var a;return(a=this._delegate)===null||a===void 0?void 0:a.getTracer(t,n,r)},e})(),wo;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(wo||(wo={}));var Fs="trace",PC=(function(){function e(){this._proxyTracerProvider=new Hp,this.wrapSpanContext=TC,this.isSpanContextValid=Gp,this.deleteSpan=wC,this.getSpan=vs,this.getActiveSpan=EC,this.getSpanContext=Vp,this.setSpan=ys,this.setSpanContext=AC}return i(e,"TraceAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=ms(Fs,this._proxyTracerProvider,Eo.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return Br(Fs)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){fs(Fs,Eo.instance()),this._proxyTracerProvider=new Hp},e})(),MC=PC.getInstance(),jC=Object.defineProperty,zC=i((e,t)=>{for(var n in t)jC(e,n,{get:t[n],enumerable:!0})},"__export"),Jp="AI_InvalidArgumentError",Kp=`vercel.ai.error.${Jp}`,qC=Symbol.for(Kp),Yp,_t=(Pn=class extends V{constructor({parameter:t,value:n,message:r}){super({name:Jp,message:`Invalid argument for parameter ${t}: ${r}`}),this[Yp]=!0,this.parameter=t,this.value=n}static isInstance(t){return V.hasMarker(t,Kp)}},i(Pn,"InvalidArgumentError"),Pn);Yp=qC;var Xp="AI_InvalidToolApprovalError",Qp=`vercel.ai.error.${Xp}`,ZC=Symbol.for(Qp),ed,LC=(Mn=class extends V{constructor({approvalId:t}){super({name:Xp,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[ed]=!0,this.approvalId=t}static isInstance(t){return V.hasMarker(t,Qp)}},i(Mn,"InvalidToolApprovalError"),Mn);ed=ZC;var td="AI_InvalidToolInputError",nd=`vercel.ai.error.${td}`,UC=Symbol.for(nd),rd,Cs=(jn=class extends V{constructor({toolInput:t,toolName:n,cause:r,message:a=`Invalid input for tool ${n}: ${yr(r)}`}){super({name:td,message:a,cause:r}),this[rd]=!0,this.toolInput=t,this.toolName=n}static isInstance(t){return V.hasMarker(t,nd)}},i(jn,"InvalidToolInputError"),jn);rd=UC;var od="AI_ToolCallNotFoundForApprovalError",ad=`vercel.ai.error.${od}`,VC=Symbol.for(ad),sd,id=(zn=class extends V{constructor({toolCallId:t,approvalId:n}){super({name:od,message:`Tool call "${t}" not found for approval request "${n}".`}),this[sd]=!0,this.toolCallId=t,this.approvalId=n}static isInstance(t){return V.hasMarker(t,ad)}},i(zn,"ToolCallNotFoundForApprovalError"),zn);sd=VC;var ud="AI_NoObjectGeneratedError",ld=`vercel.ai.error.${ud}`,GC=Symbol.for(ld),cd,$t=(qn=class extends V{constructor({message:t="No object generated.",cause:n,text:r,response:a,usage:s,finishReason:o}){super({name:ud,message:t,cause:n}),this[cd]=!0,this.text=r,this.response=a,this.usage=s,this.finishReason=o}static isInstance(t){return V.hasMarker(t,ld)}},i(qn,"NoObjectGeneratedError"),qn);cd=GC;var pd="AI_NoOutputGeneratedError",dd=`vercel.ai.error.${pd}`,WC=Symbol.for(dd),md,HC=(Zn=class extends V{constructor({message:t="No output generated.",cause:n}={}){super({name:pd,message:t,cause:n}),this[md]=!0}static isInstance(t){return V.hasMarker(t,dd)}},i(Zn,"NoOutputGeneratedError"),Zn);md=WC;var fd="AI_NoSuchToolError",hd=`vercel.ai.error.${fd}`,JC=Symbol.for(hd),Dd,bs=(Ln=class extends V{constructor({toolName:t,availableTools:n=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${n===void 0?"No tools are available.":`Available tools: ${n.join(", ")}.`}`}){super({name:fd,message:r}),this[Dd]=!0,this.toolName=t,this.availableTools=n}static isInstance(t){return V.hasMarker(t,hd)}},i(Ln,"NoSuchToolError"),Ln);Dd=JC;var gd="AI_ToolCallRepairError",vd=`vercel.ai.error.${gd}`,KC=Symbol.for(vd),yd,YC=(Un=class extends V{constructor({cause:t,originalError:n,message:r=`Error repairing tool call: ${yr(t)}`}){super({name:gd,message:r,cause:t}),this[yd]=!0,this.originalError=n}static isInstance(t){return V.hasMarker(t,vd)}},i(Un,"ToolCallRepairError"),Un);yd=KC;var XC=(Vn=class extends V{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},i(Vn,"UnsupportedModelVersionError"),Vn),_d="AI_InvalidMessageRoleError",Fd=`vercel.ai.error.${_d}`,QC=Symbol.for(Fd),Cd,eb=(Gn=class extends V{constructor({role:t,message:n=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:_d,message:n}),this[Cd]=!0,this.role=t}static isInstance(t){return V.hasMarker(t,Fd)}},i(Gn,"InvalidMessageRoleError"),Gn);Cd=QC;var bd="AI_RetryError",Ed=`vercel.ai.error.${bd}`,tb=Symbol.for(Ed),wd,Ad=(Wn=class extends V{constructor({message:t,reason:n,errors:r}){super({name:bd,message:t}),this[wd]=!0,this.reason=n,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return V.hasMarker(t,Ed)}},i(Wn,"RetryError"),Wn);wd=tb;function nb({warning:e,provider:t,model:n}){const r=`AI SDK Warning (${t} / ${n}):`;switch(e.type){case"unsupported":{let a=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(a+=` ${e.details}`),a}case"compatibility":{let a=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(a+=` ${e.details}`),a}case"other":return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}i(nb,"formatWarning");var rb="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Id=!1,xd=i(e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}Id||(Id=!0,console.info(rb));for(const n of e.warnings)console.warn(nb({warning:n,provider:e.provider,model:e.model}))}},"logWarnings");function ob({provider:e,modelId:t}){xd({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}i(ob,"logV2CompatibilityWarning");function ab(e){return e.specificationVersion==="v3"?e:(ob({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){switch(n){case"specificationVersion":return"v3";case"doGenerate":return async(...r)=>{const a=await t.doGenerate(...r);return{...a,finishReason:kd(a.finishReason),usage:$d(a.usage)}};case"doStream":return async(...r)=>{const a=await t.doStream(...r);return{...a,stream:sb(a.stream)}};default:return t[n]}}}))}i(ab,"asLanguageModelV3");function sb(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:kd(t.finishReason),usage:$d(t.usage)});break;default:n.enqueue(t);break}}}))}i(sb,"convertV2StreamToV3");function kd(e){return{unified:e==="unknown"?"other":e,raw:void 0}}i(kd,"convertV2FinishReasonToV3");function $d(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}i($d,"convertV2UsageToV3");function Td(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new XC({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return ab(e)}return ib().languageModel(e)}i(Td,"resolveLanguageModel");function ib(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:tC}i(ib,"getGlobalProvider");var ub=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],lb=i(e=>{const t=typeof e=="string"?Ut(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)},"stripID3");function cb(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?lb(e):e}i(cb,"stripID3TagsIfPresent");function pb({data:e,signatures:t}){const n=cb(e),r=typeof n=="string"?Ut(n.substring(0,Math.min(n.length,24))):n;for(const a of t)if(r.length>=a.bytesPrefix.length&&a.bytesPrefix.every((s,o)=>s===null||r[o]===s))return a.mediaType}i(pb,"detectMediaType");var Bd="6.0.13",db=i(async({url:e})=>{var t;const n=e.toString();try{const r=await fetch(n,{headers:Gt({},`ai-sdk/${Bd}`,Qa())});if(!r.ok)throw new pn({url:n,statusCode:r.status,statusText:r.statusText});return{data:new Uint8Array(await r.arrayBuffer()),mediaType:(t=r.headers.get("content-type"))!=null?t:void 0}}catch(r){throw pn.isInstance(r)?r:new pn({url:n,cause:r})}},"download"),mb=i((e=db)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n))),"createDefaultDownloadFunction");function fb(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}i(fb,"splitDataUrl");var Sd=H([p(),_o(Uint8Array),_o(ArrayBuffer),uF(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function Od(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=fb(e.toString());if(t==null||n==null)throw new V({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}i(Od,"convertToLanguageModelV3DataContent");function hb(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Ir(new Uint8Array(e)):Ir(e)}i(hb,"convertDataContentToBase64String");function Es(e){return e===void 0?[]:Array.isArray(e)?e:[e]}i(Es,"asArray");async function Db({prompt:e,supportedUrls:t,download:n=mb()}){const r=await vb(e.messages,n,t),a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Es(e.system).map(o=>({role:"system",content:o.content,providerOptions:o.providerOptions})):[],...e.messages.map(o=>gb({message:o,downloadedAssets:r}))],s=[];for(const o of a){if(o.role!=="tool"){s.push(o);continue}const u=s.at(-1);u?.role==="tool"?u.content.push(...o.content):s.push(o)}return s}i(Db,"convertToLanguageModelPrompt");function gb({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>yb(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).filter(r=>r.type!=="tool-approval-request").map(r=>{const a=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:o}=Od(r.data);return{type:"file",data:s,filename:r.filename,mediaType:o??r.mediaType,providerOptions:a}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:a};case"text":return{type:"text",text:r.text,providerOptions:a};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:a};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:Rd(r.output),providerOptions:a}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(r=>r.type!=="tool-approval-response"||r.providerExecuted).map(r=>{switch(r.type){case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:Rd(r.output),providerOptions:r.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:r.approvalId,approved:r.approved,reason:r.reason}}}),providerOptions:e.providerOptions};default:{const r=n;throw new eb({role:r})}}}i(gb,"convertToLanguageModelMessage");async function vb(e,t,n){const r=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var o;const u=(o=s.mediaType)!=null?o:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:u,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&bF({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})})),a=await t(r);return Object.fromEntries(a.map((s,o)=>s==null?null:[r[o].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}i(vb,"downloadAssets");function yb(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const a=e.type;switch(a){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${a}`)}const{data:s,mediaType:o}=Od(r);let u=o??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,u??(u=c.mediaType))}switch(a){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(u=(n=pb({data:l,signatures:ub}))!=null?n:u),{type:"file",mediaType:u??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(u==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:u,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}i(yb,"convertPartToLanguageModelPart");function Rd(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}i(Rd,"mapToolResultOutput");async function Ao({toolCallId:e,input:t,output:n,tool:r,errorMode:a}){return a==="text"?{type:"error-text",value:yr(n)}:a==="json"?{type:"error-json",value:Nd(n)}:r?.toModelOutput?await r.toModelOutput({toolCallId:e,input:t,output:n}):typeof n=="string"?{type:"text",value:n}:{type:"json",value:Nd(n)}}i(Ao,"createToolModelOutput");function Nd(e){return e===void 0?null:e}i(Nd,"toJSONValue");function Pd({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:a,frequencyPenalty:s,seed:o,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new _t({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new _t({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new _t({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new _t({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new _t({parameter:"topK",value:r,message:"topK must be a number"});if(a!=null&&typeof a!="number")throw new _t({parameter:"presencePenalty",value:a,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new _t({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new _t({parameter:"seed",value:o,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:a,frequencyPenalty:s,stopSequences:u,seed:o}}i(Pd,"prepareCallSettings");function _b(e){return e!=null&&Object.keys(e).length>0}i(_b,"isNonEmptyObject");async function Fb({tools:e,toolChoice:t,activeTools:n}){if(!_b(e))return{tools:void 0,toolChoice:void 0};const r=n!=null?Object.entries(e).filter(([s])=>n.includes(s)):Object.entries(e),a=[];for(const[s,o]of r){const u=o.type;switch(u){case void 0:case"dynamic":case"function":a.push({type:"function",name:s,description:o.description,inputSchema:await mn(o.inputSchema).jsonSchema,...o.inputExamples!=null?{inputExamples:o.inputExamples}:{},providerOptions:o.providerOptions,...o.strict!=null?{strict:o.strict}:{}});break;case"provider":a.push({type:"provider",name:s,id:o.id,args:o.args});break;default:{const l=u;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:a,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}i(Fb,"prepareToolsAndToolChoice");var Rr=Ha(()=>H([Tc(),p(),A(),Ae(),me(p(),Rr.optional()),T(Rr)])),we=me(p(),me(p(),Rr.optional())),Md=g({type:I("text"),text:p(),providerOptions:we.optional()}),Cb=g({type:I("image"),image:H([Sd,_o(URL)]),mediaType:p().optional(),providerOptions:we.optional()}),jd=g({type:I("file"),data:H([Sd,_o(URL)]),filename:p().optional(),mediaType:p(),providerOptions:we.optional()}),bb=g({type:I("reasoning"),text:p(),providerOptions:we.optional()}),Eb=g({type:I("tool-call"),toolCallId:p(),toolName:p(),input:gt(),providerOptions:we.optional(),providerExecuted:Ae().optional()}),wb=Ie("type",[g({type:I("text"),value:p(),providerOptions:we.optional()}),g({type:I("json"),value:Rr,providerOptions:we.optional()}),g({type:I("execution-denied"),reason:p().optional(),providerOptions:we.optional()}),g({type:I("error-text"),value:p(),providerOptions:we.optional()}),g({type:I("error-json"),value:Rr,providerOptions:we.optional()}),g({type:I("content"),value:T(H([g({type:I("text"),text:p(),providerOptions:we.optional()}),g({type:I("media"),data:p(),mediaType:p()}),g({type:I("file-data"),data:p(),mediaType:p(),filename:p().optional(),providerOptions:we.optional()}),g({type:I("file-url"),url:p(),providerOptions:we.optional()}),g({type:I("file-id"),fileId:H([p(),me(p(),p())]),providerOptions:we.optional()}),g({type:I("image-data"),data:p(),mediaType:p(),providerOptions:we.optional()}),g({type:I("image-url"),url:p(),providerOptions:we.optional()}),g({type:I("image-file-id"),fileId:H([p(),me(p(),p())]),providerOptions:we.optional()}),g({type:I("custom"),providerOptions:we.optional()})]))})]),zd=g({type:I("tool-result"),toolCallId:p(),toolName:p(),output:wb,providerOptions:we.optional()}),Ab=g({type:I("tool-approval-request"),approvalId:p(),toolCallId:p()}),Ib=g({type:I("tool-approval-response"),approvalId:p(),approved:Ae(),reason:p().optional()}),xb=g({role:I("system"),content:p(),providerOptions:we.optional()}),kb=g({role:I("user"),content:H([p(),T(H([Md,Cb,jd]))]),providerOptions:we.optional()}),$b=g({role:I("assistant"),content:H([p(),T(H([Md,jd,bb,Eb,zd,Ab]))]),providerOptions:we.optional()}),Tb=g({role:I("tool"),content:T(H([zd,Ib])),providerOptions:we.optional()}),Bb=H([xb,kb,$b,Tb]);async function Sb(e){if(e.prompt==null&&e.messages==null)throw new At({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new At({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!Es(e.system).every(r=>typeof r=="object"&&r!==null&&"role"in r&&r.role==="system"))throw new At({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new At({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new At({prompt:e,message:"messages must not be empty"});const n=await ut({value:t,schema:T(Bb)});if(!n.success)throw new At({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:n.error});return{messages:t,system:e.system}}i(Sb,"standardizePrompt");function Ob(e){if(!ds.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",n="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new V({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
138
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Xt({message:o,statusCode:a,cause:s})}},i(Xt,"_GatewayAuthenticationError"),Xt),vp="GatewayInvalidRequestError",B2=`vercel.ai.gateway.error.${vp}`,yp=Symbol.for(B2),_p,Fp,S2=(xn=class extends(Fp=Ke,_p=yp,Fp){constructor({message:t="Invalid request",statusCode:n=400,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[_p]=!0,this.name=vp,this.type="invalid_request_error"}static isInstance(t){return Ke.hasMarker(t)&&yp in t}},i(xn,"GatewayInvalidRequestError"),xn),Cp="GatewayRateLimitError",O2=`vercel.ai.gateway.error.${Cp}`,bp=Symbol.for(O2),Ep,wp,R2=(kn=class extends(wp=Ke,Ep=bp,wp){constructor({message:t="Rate limit exceeded",statusCode:n=429,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Ep]=!0,this.name=Cp,this.type="rate_limit_exceeded"}static isInstance(t){return Ke.hasMarker(t)&&bp in t}},i(kn,"GatewayRateLimitError"),kn),Ap="GatewayModelNotFoundError",N2=`vercel.ai.gateway.error.${Ap}`,Ip=Symbol.for(N2),P2=J(()=>G(g({modelId:p()}))),xp,kp,M2=($n=class extends(kp=Ke,xp=Ip,kp){constructor({message:t="Model not found",statusCode:n=404,modelId:r,cause:a}={}){super({message:t,statusCode:n,cause:a}),this[xp]=!0,this.name=Ap,this.type="model_not_found",this.modelId=r}static isInstance(t){return Ke.hasMarker(t)&&Ip in t}},i($n,"GatewayModelNotFoundError"),$n),$p="GatewayInternalServerError",j2=`vercel.ai.gateway.error.${$p}`,Tp=Symbol.for(j2),Bp,Sp,Op=(Tn=class extends(Sp=Ke,Bp=Tp,Sp){constructor({message:t="Internal server error",statusCode:n=500,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Bp]=!0,this.name=$p,this.type="internal_server_error"}static isInstance(t){return Ke.hasMarker(t)&&Tp in t}},i(Tn,"GatewayInternalServerError"),Tn),Rp="GatewayResponseError",z2=`vercel.ai.gateway.error.${Rp}`,Np=Symbol.for(z2),Pp,Mp,q2=(Bn=class extends(Mp=Ke,Pp=Np,Mp){constructor({message:t="Invalid response from Gateway",statusCode:n=502,response:r,validationError:a,cause:s}={}){super({message:t,statusCode:n,cause:s}),this[Pp]=!0,this.name=Rp,this.type="response_error",this.response=r,this.validationError=a}static isInstance(t){return Ke.hasMarker(t)&&Np in t}},i(Bn,"GatewayResponseError"),Bn);async function jp({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:a}){const s=await ut({value:e,schema:Z2});if(!s.success)return new q2({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:s.error,cause:r});const o=s.value,u=o.error.type,l=o.error.message;switch(u){case"authentication_error":return ds.createContextualError({apiKeyProvided:a==="api-key",oidcTokenProvided:a==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new S2({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new R2({message:l,statusCode:t,cause:r});case"model_not_found":{const c=await ut({value:o.error.param,schema:P2});return new M2({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:r})}case"internal_server_error":return new Op({message:l,statusCode:t,cause:r});default:return new Op({message:l,statusCode:t,cause:r})}}i(jp,"createGatewayErrorFromResponse");var Z2=J(()=>G(g({error:g({message:p(),type:p().nullish(),param:gt().nullish(),code:H([p(),A()]).nullish()})})));function kt(e,t){var n;return Ke.isInstance(e)?e:Re.isInstance(e)?jp({response:U2(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):jp({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}i(kt,"asGatewayError");function U2(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}i(U2,"extractApiCallResponse");var zp="ai-gateway-auth-method";async function hn(e){const t=await ut({value:e[zp],schema:L2});return t.success?t.value:void 0}i(hn,"parseAuthMethod");var L2=J(()=>G(H([I("api-key"),I("oidc")]))),qp=(Sn=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Jc({url:`${this.config.baseURL}/config`,headers:await tt(this.config.headers()),successfulResponseHandler:Pe(V2),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(n=>n,"errorToMessage")}),fetch:this.config.fetch});return t}catch(t){throw await kt(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:n}=await Jc({url:`${t.origin}/v1/credits`,headers:await tt(this.config.headers()),successfulResponseHandler:Pe(G2),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(r=>r,"errorToMessage")}),fetch:this.config.fetch});return n}catch(t){throw await kt(t)}}},i(Sn,"GatewayFetchMetadata"),Sn),V2=J(()=>G(g({models:T(g({id:p(),name:p(),description:p().nullish(),pricing:g({input:p(),output:p(),input_cache_read:p().nullish(),input_cache_write:p().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:g({specificationVersion:I("v3"),provider:p(),modelId:p()}),modelType:re(["language","embedding","image"]).nullish()}))}))),G2=J(()=>G(g({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),W2=(On=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:n,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,s=await tt(this.config.headers());try{const{responseHeaders:o,value:u,rawValue:l}=await Se({url:this.getUrl(),headers:xe(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await tt(this.config.o11yHeaders)),body:n,successfulResponseHandler:Pe(qe()),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(c=>c,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...u,request:{body:n},response:{headers:o,body:l},warnings:r}}catch(o){throw await kt(o,await hn(s))}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,s=await tt(this.config.headers());try{const{value:o,responseHeaders:u}=await Se({url:this.getUrl(),headers:xe(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await tt(this.config.o11yHeaders)),body:n,successfulResponseHandler:fn(qe()),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(l=>l,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(l){r.length>0&&l.enqueue({type:"stream-start",warnings:r})},transform(l,c){if(l.success){const d=l.value;if(d.type==="raw"&&!t.includeRawChunks)return;d.type==="response-metadata"&&d.timestamp&&typeof d.timestamp=="string"&&(d.timestamp=new Date(d.timestamp)),c.enqueue(d)}else c.error(l.error)}})),request:{body:n},response:{headers:u}}}catch(o){throw await kt(o,await hn(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const n of t.prompt)for(const r of n.content)if(this.isFilePart(r)){const a=r;if(a.data instanceof Uint8Array){const s=Uint8Array.from(a.data),o=Buffer.from(s).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${o}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,n){return{"ai-language-model-specification-version":"3","ai-language-model-id":t,"ai-language-model-streaming":String(n)}}},i(On,"GatewayLanguageModel"),On),H2=(Rn=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:a}){var s;const o=await tt(this.config.headers());try{const{responseHeaders:u,value:l,rawValue:c}=await Se({url:this.getUrl(),headers:xe(o,n??{},this.getModelConfigHeaders(),await tt(this.config.o11yHeaders)),body:{values:t,...a?{providerOptions:a}:{}},successfulResponseHandler:Pe(J2),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(d=>d,"errorToMessage")}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(s=l.usage)!=null?s:void 0,providerMetadata:l.providerMetadata,response:{headers:u,body:c},warnings:[]}}catch(u){throw await kt(u,await hn(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},i(Rn,"GatewayEmbeddingModel"),Rn),J2=J(()=>G(g({embeddings:T(T(A())),usage:g({tokens:A()}).nullish(),providerMetadata:me(p(),me(p(),gt())).optional()}))),K2=(Nn=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,size:r,aspectRatio:a,seed:s,files:o,mask:u,providerOptions:l,headers:c,abortSignal:d}){var m;const h=await tt(this.config.headers());try{const{responseHeaders:D,value:f,rawValue:v}=await Se({url:this.getUrl(),headers:xe(h,c??{},this.getModelConfigHeaders(),await tt(this.config.o11yHeaders)),body:{prompt:t,n,...r&&{size:r},...a&&{aspectRatio:a},...s&&{seed:s},...l&&{providerOptions:l},...o&&{files:o.map(y=>Zp(y))},...u&&{mask:Zp(u)}},successfulResponseHandler:Pe(X2),failedResponseHandler:nt({errorSchema:qe(),errorToMessage:i(y=>y,"errorToMessage")}),...d&&{abortSignal:d},fetch:this.config.fetch});return{images:f.images,warnings:(m=f.warnings)!=null?m:[],providerMetadata:f.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:D}}}catch(D){throw kt(D,await hn(h))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}},i(Nn,"GatewayImageModel"),Nn);function Zp(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Ir(e.data)}:e}i(Zp,"maybeEncodeImageFile");var Y2=g({images:T(gt()).optional()}).catchall(gt()),X2=g({images:T(p()),warnings:T(g({type:I("other"),message:p()})).optional(),providerMetadata:me(p(),Y2).optional()});async function Q2(){var e;return(e=pp.getContext().headers)==null?void 0:e["x-vercel-id"]}i(Q2,"getVercelRequestId");var eC="3.0.9",tC="0.0.1";function nC(e={}){var t,n;let r=null,a=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let o=0;const u=(n=ss(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",l=i(async()=>{try{const v=await oC(e);return Gt({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":tC,[zp]:v.authMethod,...e.headers},`ai-sdk/gateway/${eC}`)}catch(v){throw ds.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},"getHeaders"),c=i(()=>{const v=kr({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=kr({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),F=kr({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const E=await Q2();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...F&&{"ai-o11y-region":F},...E&&{"ai-o11y-request-id":E}}}},"createO11yHeaders"),d=i(v=>new W2(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createLanguageModel"),m=i(async()=>{var v,y,F;const E=(F=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?F:Date.now();return(!r||E-o>s)&&(o=E,r=new qp({baseURL:u,headers:l,fetch:e.fetch}).getAvailableModels().then(b=>(a=b,b)).catch(async b=>{throw await kt(b,await hn(await l()))})),a?Promise.resolve(a):r},"getAvailableModels"),h=i(async()=>new qp({baseURL:u,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await kt(v,await hn(await l()))}),"getCredits"),D=i(function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(v)},"provider");D.specificationVersion="v3",D.getAvailableModels=m,D.getCredits=h,D.imageModel=v=>new K2(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.languageModel=d;const f=i(v=>new H2(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createEmbeddingModel");return D.embeddingModel=f,D.textEmbeddingModel=f,D}i(nC,"createGatewayProvider");var rC=nC();async function oC(e){const t=kr({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await pp.getVercelOidcToken(),authMethod:"oidc"}}i(oC,"getGatewayAuthToken");var aC=typeof globalThis=="object"?globalThis:global,Ht="1.9.0",Up=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function sC(e){var t=new Set([e]),n=new Set,r=e.match(Up);if(!r)return function(){return!1};var a={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(a.prerelease!=null)return i(function(l){return l===e},"isExactmatch");function s(u){return n.add(u),!1}i(s,"_reject");function o(u){return t.add(u),!0}return i(o,"_accept"),i(function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(Up);if(!c)return s(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||a.major!==d.major?s(l):a.major===0?a.minor===d.minor&&a.patch<=d.patch?o(l):s(l):a.minor<=d.minor?o(l):s(l)},"isCompatible2")}i(sC,"_makeCompatibilityCheck");var iC=sC(Ht),uC=Ht.split(".")[0],$r=Symbol.for("opentelemetry.js.api."+uC),Tr=aC;function ms(e,t,n,r){var a;r===void 0&&(r=!1);var s=Tr[$r]=(a=Tr[$r])!==null&&a!==void 0?a:{version:Ht};if(!r&&s[e]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(o.stack||o.message),!1}if(s.version!==Ht){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Ht);return n.error(o.stack||o.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Ht+"."),!0}i(ms,"registerGlobal");function Br(e){var t,n,r=(t=Tr[$r])===null||t===void 0?void 0:t.version;if(!(!r||!iC(r)))return(n=Tr[$r])===null||n===void 0?void 0:n[e]}i(Br,"getGlobal");function fs(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Ht+".");var n=Tr[$r];n&&delete n[e]}i(fs,"unregisterGlobal");var lC=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,s=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)s.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s},"__read$3"),cC=i(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,s;r<a;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$3"),pC=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return i(e,"DiagComponentLogger2"),e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("verbose",this._namespace,t)},e})();function Sr(e,t,n){var r=Br("diag");if(r)return n.unshift(t),r[e].apply(r,cC([],lC(n),!1))}i(Sr,"logProxy");var Ye;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(Ye||(Ye={}));function dC(e,t){e<Ye.NONE?e=Ye.NONE:e>Ye.ALL&&(e=Ye.ALL),t=t||{};function n(r,a){var s=t[r];return typeof s=="function"&&e>=a?s.bind(t):function(){}}return i(n,"_filterFunc"),{error:n("error",Ye.ERROR),warn:n("warn",Ye.WARN),info:n("info",Ye.INFO),debug:n("debug",Ye.DEBUG),verbose:n("verbose",Ye.VERBOSE)}}i(dC,"createLogLevelDiagLogger");var mC=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,s=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)s.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s},"__read$2"),fC=i(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,s;r<a;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$2"),hC="diag",Ao=(function(){function e(){function t(a){return function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var u=Br("diag");if(u)return u[a].apply(u,fC([],mC(s),!1))}}i(t,"_logProxy");var n=this,r=i(function(a,s){var o,u,l;if(s===void 0&&(s={logLevel:Ye.INFO}),a===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((o=c.stack)!==null&&o!==void 0?o:c.message),!1}typeof s=="number"&&(s={logLevel:s});var d=Br("diag"),m=dC((u=s.logLevel)!==null&&u!==void 0?u:Ye.INFO,a);if(d&&!s.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+h),m.warn("Current logger will overwrite one already registered from "+h)}return ms("diag",m,n,!0)},"setLogger");n.setLogger=r,n.disable=function(){fs(hC,n)},n.createComponentLogger=function(a){return new pC(a)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return i(e,"DiagAPI2"),e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function DC(e){return Symbol.for(e)}i(DC,"createContextKey");var gC=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,a){var s=new e(n._currentContext);return s._currentContext.set(r,a),s},n.deleteValue=function(r){var a=new e(n._currentContext);return a._currentContext.delete(r),a}}return i(e,"BaseContext2"),e})(),vC=new gC,yC=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,s=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)s.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s},"__read$1"),_C=i(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,s;r<a;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$1"),FC=(function(){function e(){}return i(e,"NoopContextManager2"),e.prototype.active=function(){return vC},e.prototype.with=function(t,n,r){for(var a=[],s=3;s<arguments.length;s++)a[s-3]=arguments[s];return n.call.apply(n,_C([r],yC(a),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),CC=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,s=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)s.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s},"__read"),bC=i(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,s;r<a;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray"),hs="context",EC=new FC,Lp=(function(){function e(){}return i(e,"ContextAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return ms(hs,t,Ao.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var a,s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return(a=this._getContextManager()).with.apply(a,bC([t,n,r],CC(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Br(hs)||EC},e.prototype.disable=function(){this._getContextManager().disable(),fs(hs,Ao.instance())},e})(),Ds;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ds||(Ds={}));var Vp="0000000000000000",Gp="00000000000000000000000000000000",wC={traceId:Gp,spanId:Vp,traceFlags:Ds.NONE},Or=(function(){function e(t){t===void 0&&(t=wC),this._spanContext=t}return i(e,"NonRecordingSpan2"),e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e})(),gs=DC("OpenTelemetry Context Key SPAN");function vs(e){return e.getValue(gs)||void 0}i(vs,"getSpan");function AC(){return vs(Lp.getInstance().active())}i(AC,"getActiveSpan");function ys(e,t){return e.setValue(gs,t)}i(ys,"setSpan");function IC(e){return e.deleteValue(gs)}i(IC,"deleteSpan");function xC(e,t){return ys(e,new Or(t))}i(xC,"setSpanContext");function Wp(e){var t;return(t=vs(e))===null||t===void 0?void 0:t.spanContext()}i(Wp,"getSpanContext");var kC=/^([0-9a-f]{32})$/i,$C=/^[0-9a-f]{16}$/i;function TC(e){return kC.test(e)&&e!==Gp}i(TC,"isValidTraceId");function BC(e){return $C.test(e)&&e!==Vp}i(BC,"isValidSpanId");function Hp(e){return TC(e.traceId)&&BC(e.spanId)}i(Hp,"isSpanContextValid");function SC(e){return new Or(e)}i(SC,"wrapSpanContext");var _s=Lp.getInstance(),Jp=(function(){function e(){}return i(e,"NoopTracer2"),e.prototype.startSpan=function(t,n,r){r===void 0&&(r=_s.active());var a=!!n?.root;if(a)return new Or;var s=r&&Wp(r);return OC(s)&&Hp(s)?new Or(s):new Or},e.prototype.startActiveSpan=function(t,n,r,a){var s,o,u;if(!(arguments.length<2)){arguments.length===2?u=n:arguments.length===3?(s=n,u=r):(s=n,o=r,u=a);var l=o??_s.active(),c=this.startSpan(t,s,l),d=ys(l,c);return _s.with(d,u,void 0,c)}},e})();function OC(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}i(OC,"isSpanContext");var RC=new Jp,NC=(function(){function e(t,n,r,a){this._provider=t,this.name=n,this.version=r,this.options=a}return i(e,"ProxyTracer2"),e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,a){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):RC},e})(),PC=(function(){function e(){}return i(e,"NoopTracerProvider2"),e.prototype.getTracer=function(t,n,r){return new Jp},e})(),MC=new PC,Kp=(function(){function e(){}return i(e,"ProxyTracerProvider2"),e.prototype.getTracer=function(t,n,r){var a;return(a=this.getDelegateTracer(t,n,r))!==null&&a!==void 0?a:new NC(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:MC},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var a;return(a=this._delegate)===null||a===void 0?void 0:a.getTracer(t,n,r)},e})(),Io;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Io||(Io={}));var Fs="trace",jC=(function(){function e(){this._proxyTracerProvider=new Kp,this.wrapSpanContext=SC,this.isSpanContextValid=Hp,this.deleteSpan=IC,this.getSpan=vs,this.getActiveSpan=AC,this.getSpanContext=Wp,this.setSpan=ys,this.setSpanContext=xC}return i(e,"TraceAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=ms(Fs,this._proxyTracerProvider,Ao.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return Br(Fs)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){fs(Fs,Ao.instance()),this._proxyTracerProvider=new Kp},e})(),zC=jC.getInstance(),qC=Object.defineProperty,ZC=i((e,t)=>{for(var n in t)qC(e,n,{get:t[n],enumerable:!0})},"__export"),Yp="AI_InvalidArgumentError",Xp=`vercel.ai.error.${Yp}`,UC=Symbol.for(Xp),Qp,_t=(Pn=class extends V{constructor({parameter:t,value:n,message:r}){super({name:Yp,message:`Invalid argument for parameter ${t}: ${r}`}),this[Qp]=!0,this.parameter=t,this.value=n}static isInstance(t){return V.hasMarker(t,Xp)}},i(Pn,"InvalidArgumentError"),Pn);Qp=UC;var ed="AI_InvalidToolApprovalError",td=`vercel.ai.error.${ed}`,LC=Symbol.for(td),nd,VC=(Mn=class extends V{constructor({approvalId:t}){super({name:ed,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[nd]=!0,this.approvalId=t}static isInstance(t){return V.hasMarker(t,td)}},i(Mn,"InvalidToolApprovalError"),Mn);nd=LC;var rd="AI_InvalidToolInputError",od=`vercel.ai.error.${rd}`,GC=Symbol.for(od),ad,Cs=(jn=class extends V{constructor({toolInput:t,toolName:n,cause:r,message:a=`Invalid input for tool ${n}: ${yr(r)}`}){super({name:rd,message:a,cause:r}),this[ad]=!0,this.toolInput=t,this.toolName=n}static isInstance(t){return V.hasMarker(t,od)}},i(jn,"InvalidToolInputError"),jn);ad=GC;var sd="AI_ToolCallNotFoundForApprovalError",id=`vercel.ai.error.${sd}`,WC=Symbol.for(id),ud,ld=(zn=class extends V{constructor({toolCallId:t,approvalId:n}){super({name:sd,message:`Tool call "${t}" not found for approval request "${n}".`}),this[ud]=!0,this.toolCallId=t,this.approvalId=n}static isInstance(t){return V.hasMarker(t,id)}},i(zn,"ToolCallNotFoundForApprovalError"),zn);ud=WC;var cd="AI_NoObjectGeneratedError",pd=`vercel.ai.error.${cd}`,HC=Symbol.for(pd),dd,$t=(qn=class extends V{constructor({message:t="No object generated.",cause:n,text:r,response:a,usage:s,finishReason:o}){super({name:cd,message:t,cause:n}),this[dd]=!0,this.text=r,this.response=a,this.usage=s,this.finishReason=o}static isInstance(t){return V.hasMarker(t,pd)}},i(qn,"NoObjectGeneratedError"),qn);dd=HC;var md="AI_NoOutputGeneratedError",fd=`vercel.ai.error.${md}`,JC=Symbol.for(fd),hd,KC=(Zn=class extends V{constructor({message:t="No output generated.",cause:n}={}){super({name:md,message:t,cause:n}),this[hd]=!0}static isInstance(t){return V.hasMarker(t,fd)}},i(Zn,"NoOutputGeneratedError"),Zn);hd=JC;var Dd="AI_NoSuchToolError",gd=`vercel.ai.error.${Dd}`,YC=Symbol.for(gd),vd,bs=(Un=class extends V{constructor({toolName:t,availableTools:n=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${n===void 0?"No tools are available.":`Available tools: ${n.join(", ")}.`}`}){super({name:Dd,message:r}),this[vd]=!0,this.toolName=t,this.availableTools=n}static isInstance(t){return V.hasMarker(t,gd)}},i(Un,"NoSuchToolError"),Un);vd=YC;var yd="AI_ToolCallRepairError",_d=`vercel.ai.error.${yd}`,XC=Symbol.for(_d),Fd,QC=(Ln=class extends V{constructor({cause:t,originalError:n,message:r=`Error repairing tool call: ${yr(t)}`}){super({name:yd,message:r,cause:t}),this[Fd]=!0,this.originalError=n}static isInstance(t){return V.hasMarker(t,_d)}},i(Ln,"ToolCallRepairError"),Ln);Fd=XC;var eb=(Vn=class extends V{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},i(Vn,"UnsupportedModelVersionError"),Vn),Cd="AI_InvalidMessageRoleError",bd=`vercel.ai.error.${Cd}`,tb=Symbol.for(bd),Ed,nb=(Gn=class extends V{constructor({role:t,message:n=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Cd,message:n}),this[Ed]=!0,this.role=t}static isInstance(t){return V.hasMarker(t,bd)}},i(Gn,"InvalidMessageRoleError"),Gn);Ed=tb;var wd="AI_RetryError",Ad=`vercel.ai.error.${wd}`,rb=Symbol.for(Ad),Id,xd=(Wn=class extends V{constructor({message:t,reason:n,errors:r}){super({name:wd,message:t}),this[Id]=!0,this.reason=n,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return V.hasMarker(t,Ad)}},i(Wn,"RetryError"),Wn);Id=rb;function ob({warning:e,provider:t,model:n}){const r=`AI SDK Warning (${t} / ${n}):`;switch(e.type){case"unsupported":{let a=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(a+=` ${e.details}`),a}case"compatibility":{let a=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(a+=` ${e.details}`),a}case"other":return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}i(ob,"formatWarning");var ab="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",kd=!1,$d=i(e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}kd||(kd=!0,console.info(ab));for(const n of e.warnings)console.warn(ob({warning:n,provider:e.provider,model:e.model}))}},"logWarnings");function sb({provider:e,modelId:t}){$d({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}i(sb,"logV2CompatibilityWarning");function ib(e){return e.specificationVersion==="v3"?e:(sb({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){switch(n){case"specificationVersion":return"v3";case"doGenerate":return async(...r)=>{const a=await t.doGenerate(...r);return{...a,finishReason:Td(a.finishReason),usage:Bd(a.usage)}};case"doStream":return async(...r)=>{const a=await t.doStream(...r);return{...a,stream:ub(a.stream)}};default:return t[n]}}}))}i(ib,"asLanguageModelV3");function ub(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:Td(t.finishReason),usage:Bd(t.usage)});break;default:n.enqueue(t);break}}}))}i(ub,"convertV2StreamToV3");function Td(e){return{unified:e==="unknown"?"other":e,raw:void 0}}i(Td,"convertV2FinishReasonToV3");function Bd(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}i(Bd,"convertV2UsageToV3");function Sd(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new eb({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return ib(e)}return lb().languageModel(e)}i(Sd,"resolveLanguageModel");function lb(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:rC}i(lb,"getGlobalProvider");var cb=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],pb=i(e=>{const t=typeof e=="string"?Lt(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)},"stripID3");function db(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?pb(e):e}i(db,"stripID3TagsIfPresent");function mb({data:e,signatures:t}){const n=db(e),r=typeof n=="string"?Lt(n.substring(0,Math.min(n.length,24))):n;for(const a of t)if(r.length>=a.bytesPrefix.length&&a.bytesPrefix.every((s,o)=>s===null||r[o]===s))return a.mediaType}i(mb,"detectMediaType");var Od="6.0.13",fb=i(async({url:e})=>{var t;const n=e.toString();try{const r=await fetch(n,{headers:Gt({},`ai-sdk/${Od}`,Qa())});if(!r.ok)throw new pn({url:n,statusCode:r.status,statusText:r.statusText});return{data:new Uint8Array(await r.arrayBuffer()),mediaType:(t=r.headers.get("content-type"))!=null?t:void 0}}catch(r){throw pn.isInstance(r)?r:new pn({url:n,cause:r})}},"download"),hb=i((e=fb)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n))),"createDefaultDownloadFunction");function Db(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}i(Db,"splitDataUrl");var Rd=H([p(),Co(Uint8Array),Co(ArrayBuffer),cF(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function Nd(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=Db(e.toString());if(t==null||n==null)throw new V({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}i(Nd,"convertToLanguageModelV3DataContent");function gb(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Ir(new Uint8Array(e)):Ir(e)}i(gb,"convertDataContentToBase64String");function Es(e){return e===void 0?[]:Array.isArray(e)?e:[e]}i(Es,"asArray");async function vb({prompt:e,supportedUrls:t,download:n=hb()}){const r=await _b(e.messages,n,t),a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Es(e.system).map(o=>({role:"system",content:o.content,providerOptions:o.providerOptions})):[],...e.messages.map(o=>yb({message:o,downloadedAssets:r}))],s=[];for(const o of a){if(o.role!=="tool"){s.push(o);continue}const u=s.at(-1);u?.role==="tool"?u.content.push(...o.content):s.push(o)}return s}i(vb,"convertToLanguageModelPrompt");function yb({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>Fb(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).filter(r=>r.type!=="tool-approval-request").map(r=>{const a=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:o}=Nd(r.data);return{type:"file",data:s,filename:r.filename,mediaType:o??r.mediaType,providerOptions:a}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:a};case"text":return{type:"text",text:r.text,providerOptions:a};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:a};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:Pd(r.output),providerOptions:a}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(r=>r.type!=="tool-approval-response"||r.providerExecuted).map(r=>{switch(r.type){case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:Pd(r.output),providerOptions:r.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:r.approvalId,approved:r.approved,reason:r.reason}}}),providerOptions:e.providerOptions};default:{const r=n;throw new nb({role:r})}}}i(yb,"convertToLanguageModelMessage");async function _b(e,t,n){const r=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var o;const u=(o=s.mediaType)!=null?o:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:u,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&wF({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})})),a=await t(r);return Object.fromEntries(a.map((s,o)=>s==null?null:[r[o].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}i(_b,"downloadAssets");function Fb(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const a=e.type;switch(a){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${a}`)}const{data:s,mediaType:o}=Nd(r);let u=o??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,u??(u=c.mediaType))}switch(a){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(u=(n=mb({data:l,signatures:cb}))!=null?n:u),{type:"file",mediaType:u??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(u==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:u,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}i(Fb,"convertPartToLanguageModelPart");function Pd(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}i(Pd,"mapToolResultOutput");async function xo({toolCallId:e,input:t,output:n,tool:r,errorMode:a}){return a==="text"?{type:"error-text",value:yr(n)}:a==="json"?{type:"error-json",value:Md(n)}:r?.toModelOutput?await r.toModelOutput({toolCallId:e,input:t,output:n}):typeof n=="string"?{type:"text",value:n}:{type:"json",value:Md(n)}}i(xo,"createToolModelOutput");function Md(e){return e===void 0?null:e}i(Md,"toJSONValue");function jd({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:a,frequencyPenalty:s,seed:o,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new _t({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new _t({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new _t({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new _t({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new _t({parameter:"topK",value:r,message:"topK must be a number"});if(a!=null&&typeof a!="number")throw new _t({parameter:"presencePenalty",value:a,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new _t({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new _t({parameter:"seed",value:o,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:a,frequencyPenalty:s,stopSequences:u,seed:o}}i(jd,"prepareCallSettings");function Cb(e){return e!=null&&Object.keys(e).length>0}i(Cb,"isNonEmptyObject");async function bb({tools:e,toolChoice:t,activeTools:n}){if(!Cb(e))return{tools:void 0,toolChoice:void 0};const r=n!=null?Object.entries(e).filter(([s])=>n.includes(s)):Object.entries(e),a=[];for(const[s,o]of r){const u=o.type;switch(u){case void 0:case"dynamic":case"function":a.push({type:"function",name:s,description:o.description,inputSchema:await mn(o.inputSchema).jsonSchema,...o.inputExamples!=null?{inputExamples:o.inputExamples}:{},providerOptions:o.providerOptions,...o.strict!=null?{strict:o.strict}:{}});break;case"provider":a.push({type:"provider",name:s,id:o.id,args:o.args});break;default:{const l=u;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:a,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}i(bb,"prepareToolsAndToolChoice");var Rr=Ha(()=>H([Sc(),p(),A(),Ae(),me(p(),Rr.optional()),T(Rr)])),we=me(p(),me(p(),Rr.optional())),zd=g({type:I("text"),text:p(),providerOptions:we.optional()}),Eb=g({type:I("image"),image:H([Rd,Co(URL)]),mediaType:p().optional(),providerOptions:we.optional()}),qd=g({type:I("file"),data:H([Rd,Co(URL)]),filename:p().optional(),mediaType:p(),providerOptions:we.optional()}),wb=g({type:I("reasoning"),text:p(),providerOptions:we.optional()}),Ab=g({type:I("tool-call"),toolCallId:p(),toolName:p(),input:gt(),providerOptions:we.optional(),providerExecuted:Ae().optional()}),Ib=Ie("type",[g({type:I("text"),value:p(),providerOptions:we.optional()}),g({type:I("json"),value:Rr,providerOptions:we.optional()}),g({type:I("execution-denied"),reason:p().optional(),providerOptions:we.optional()}),g({type:I("error-text"),value:p(),providerOptions:we.optional()}),g({type:I("error-json"),value:Rr,providerOptions:we.optional()}),g({type:I("content"),value:T(H([g({type:I("text"),text:p(),providerOptions:we.optional()}),g({type:I("media"),data:p(),mediaType:p()}),g({type:I("file-data"),data:p(),mediaType:p(),filename:p().optional(),providerOptions:we.optional()}),g({type:I("file-url"),url:p(),providerOptions:we.optional()}),g({type:I("file-id"),fileId:H([p(),me(p(),p())]),providerOptions:we.optional()}),g({type:I("image-data"),data:p(),mediaType:p(),providerOptions:we.optional()}),g({type:I("image-url"),url:p(),providerOptions:we.optional()}),g({type:I("image-file-id"),fileId:H([p(),me(p(),p())]),providerOptions:we.optional()}),g({type:I("custom"),providerOptions:we.optional()})]))})]),Zd=g({type:I("tool-result"),toolCallId:p(),toolName:p(),output:Ib,providerOptions:we.optional()}),xb=g({type:I("tool-approval-request"),approvalId:p(),toolCallId:p()}),kb=g({type:I("tool-approval-response"),approvalId:p(),approved:Ae(),reason:p().optional()}),$b=g({role:I("system"),content:p(),providerOptions:we.optional()}),Tb=g({role:I("user"),content:H([p(),T(H([zd,Eb,qd]))]),providerOptions:we.optional()}),Bb=g({role:I("assistant"),content:H([p(),T(H([zd,qd,wb,Ab,Zd,xb]))]),providerOptions:we.optional()}),Sb=g({role:I("tool"),content:T(H([Zd,kb])),providerOptions:we.optional()}),Ob=H([$b,Tb,Bb,Sb]);async function Rb(e){if(e.prompt==null&&e.messages==null)throw new At({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new At({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!Es(e.system).every(r=>typeof r=="object"&&r!==null&&"role"in r&&r.role==="system"))throw new At({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new At({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new At({prompt:e,message:"messages must not be empty"});const n=await ut({value:t,schema:T(Ob)});if(!n.success)throw new At({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:n.error});return{messages:t,system:e.system}}i(Rb,"standardizePrompt");function Nb(e){if(!ds.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",n="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new V({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
139
139
 
140
140
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
141
141
 
@@ -143,11 +143,11 @@ Alternatively, you can use a provider module instead of the AI Gateway.
143
143
 
144
144
  Learn more: \x1B[34m${n}\x1B[0m
145
145
 
146
- `),{name:"GatewayAuthenticationError"})}i(Ob,"wrapGatewayError");function ws({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}i(ws,"assembleOperationName");function Rb({model:e,settings:t,telemetry:n,headers:r}){var a;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[o,u])=>(s[`ai.settings.${o}`]=u,s),{}),...Object.entries((a=n?.metadata)!=null?a:{}).reduce((s,[o,u])=>(s[`ai.telemetry.metadata.${o}`]=u,s),{}),...Object.entries(r??{}).reduce((s,[o,u])=>(u!==void 0&&(s[`ai.request.headers.${o}`]=u),s),{})}}i(Rb,"getBaseTelemetryAttributes");var Nb={startSpan(){return Io},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Io);if(typeof n=="function")return n(Io);if(typeof r=="function")return r(Io)}},Io={spanContext(){return Pb},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},Pb={traceId:"",spanId:"",traceFlags:0};function Mb({isEnabled:e=!1,tracer:t}={}){return e?t||MC.getTracer("ai"):Nb}i(Mb,"getTracer");async function As({name:e,tracer:t,attributes:n,fn:r,endWhenDone:a=!0}){return t.startActiveSpan(e,{attributes:await n},async s=>{try{const o=await r(s);return a&&s.end(),o}catch(o){try{qd(s,o)}finally{s.end()}throw o}})}i(As,"recordSpan");function qd(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:wo.ERROR,message:t.message})):e.setStatus({code:wo.ERROR})}i(qd,"recordErrorOnSpan");async function Dn({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const n={};for(const[r,a]of Object.entries(t))if(a!=null){if(typeof a=="object"&&"input"in a&&typeof a.input=="function"){if(e?.recordInputs===!1)continue;const s=await a.input();s!=null&&(n[r]=s);continue}if(typeof a=="object"&&"output"in a&&typeof a.output=="function"){if(e?.recordOutputs===!1)continue;const s=await a.output();s!=null&&(n[r]=s);continue}n[r]=a}return n}i(Dn,"selectTelemetryAttributes");function jb(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?hb(n.data):n.data}:n)})))}i(jb,"stringifyForTelemetry");function zb(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:ct(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}i(zb,"asLanguageModelUsage");function qb(e,t){var n,r,a,s,o,u,l,c,d,m;return{inputTokens:ct(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:ct((n=e.inputTokenDetails)==null?void 0:n.noCacheTokens,(r=t.inputTokenDetails)==null?void 0:r.noCacheTokens),cacheReadTokens:ct((a=e.inputTokenDetails)==null?void 0:a.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:ct((o=e.inputTokenDetails)==null?void 0:o.cacheWriteTokens,(u=t.inputTokenDetails)==null?void 0:u.cacheWriteTokens)},outputTokens:ct(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:ct((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:ct((d=e.outputTokenDetails)==null?void 0:d.reasoningTokens,(m=t.outputTokenDetails)==null?void 0:m.reasoningTokens)},totalTokens:ct(e.totalTokens,t.totalTokens),reasoningTokens:ct(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:ct(e.cachedInputTokens,t.cachedInputTokens)}}i(qb,"addLanguageModelUsage");function ct(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}i(ct,"addTokenCounts");function Zd(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const a=t[r];if(a===void 0)continue;const s=r in e?e[r]:void 0,o=a!==null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp),u=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);o&&u?n[r]=Zd(s,a):n[r]=a}return n}i(Zd,"mergeObjects");function Zb({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const a=n["retry-after-ms"];if(a){const o=parseFloat(a);Number.isNaN(o)||(r=o)}const s=n["retry-after"];if(s&&r===void 0){const o=parseFloat(s);Number.isNaN(o)?r=Date.parse(s)-Date.now():r=o*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}i(Zb,"getRetryDelayInMs");var Lb=i(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async a=>Ld(a,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r}),"retryWithExponentialBackoffRespectingRetryHeaders");async function Ld(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:a},s=[]){try{return await e()}catch(o){if(dn(o)||t===0)throw o;const u=Uc(o),l=[...s,o],c=l.length;if(c>t)throw new Ad({message:`Failed after ${c} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:l});if(o instanceof Error&&Re.isInstance(o)&&o.isRetryable===!0&&c<=t)return await hF(Zb({error:o,exponentialBackoffDelay:n}),{abortSignal:a}),Ld(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:a},l);throw c===1?o:new Ad({message:`Failed after ${c} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:l})}}i(Ld,"_retryWithExponentialBackoff");function Ub({maxRetries:e,abortSignal:t}){if(!Number.isInteger(e))throw new _t({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});const n=e;return{maxRetries:n,retry:Lb({maxRetries:n,abortSignal:t})}}i(Ub,"prepareRetries");function Vb({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-call"&&(n[d.toolCallId]=d)}const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-approval-request"&&(r[d.approvalId]=d)}const a={};for(const l of t.content)l.type==="tool-result"&&(a[l.toolCallId]=l);const s=[],o=[],u=t.content.filter(l=>l.type==="tool-approval-response");for(const l of u){const c=r[l.approvalId];if(c==null)throw new LC({approvalId:l.approvalId});if(a[c.toolCallId]!=null)continue;const d=n[c.toolCallId];if(d==null)throw new id({toolCallId:c.toolCallId,approvalId:c.approvalId});const m={approvalRequest:c,approvalResponse:l,toolCall:d};l.approved?s.push(m):o.push(m)}return{approvedToolApprovals:s,deniedToolApprovals:o}}i(Vb,"collectToolApprovals");async function Gb({toolCall:e,tools:t,tracer:n,telemetry:r,messages:a,abortSignal:s,experimental_context:o,onPreliminaryToolResult:u}){const{toolName:l,toolCallId:c,input:d}=e,m=t?.[l];if(m?.execute!=null)return As({name:"ai.toolCall",attributes:Dn({telemetry:r,attributes:{...ws({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:i(()=>JSON.stringify(d),"output")}}}),tracer:n,fn:i(async h=>{let D;try{const f=w2({execute:m.execute.bind(m),input:d,options:{toolCallId:c,messages:a,abortSignal:s,experimental_context:o}});for await(const v of f)v.type==="preliminary"?u?.({...e,type:"tool-result",output:v.output,preliminary:!0}):D=v.output}catch(f){return qd(h,f),{type:"tool-error",toolCallId:c,toolName:l,input:d,error:f,dynamic:m.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}try{h.setAttributes(await Dn({telemetry:r,attributes:{"ai.toolCall.result":{output:i(()=>JSON.stringify(D),"output")}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:d,output:D,dynamic:m.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}i(Gb,"executeToolCall");function Ud(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}i(Ud,"extractTextContent");var Wb=(Hn=class{constructor({data:t,mediaType:n}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=n}get base64(){return this.base64Data==null&&(this.base64Data=Ir(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Ut(this.base64Data)),this.uint8ArrayData}},i(Hn,"DefaultGeneratedFile"),Hn);async function Hb({tool:e,toolCall:t,messages:n,experimental_context:r}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:n,experimental_context:r})}i(Hb,"isApprovalNeeded");var Jb={};zC(Jb,{array:i(()=>Xb,"array"),choice:i(()=>Qb,"choice"),json:i(()=>eE,"json"),object:i(()=>Yb,"object"),text:i(()=>Vd,"text")});function Kb(e){const t=["ROOT"];let n=-1,r=null;function a(l,c,d){switch(l){case'"':{n=c,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}i(a,"processValueStart");function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}i(s,"processAfterObjectValue");function o(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}i(o,"processAfterArrayValue");for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":a(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{a(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,a(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{a(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(r,l+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l)):n=l;break}}}let u=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?u+="true".slice(d.length):"false".startsWith(d)?u+="false".slice(d.length):"null".startsWith(d)&&(u+="null".slice(d.length))}}return u}i(Kb,"fixJson");async function xo(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await lt({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await lt({text:Kb(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}i(xo,"parsePartialJson");var Vd=i(()=>({responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}}}),"text"),Yb=i(({schema:e,name:t,description:n})=>{const r=mn(e);return{responseFormat:tt(r.jsonSchema).then(a=>({type:"json",schema:a,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:a},s){const o=await lt({text:a});if(!o.success)throw new $t({message:"No object generated: could not parse the response.",cause:o.error,text:a,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=await ut({value:o.value,schema:r});if(!u.success)throw new $t({message:"No object generated: response did not match schema.",cause:u.error,text:a,response:s.response,usage:s.usage,finishReason:s.finishReason});return u.value},async parsePartialOutput({text:a}){const s=await xo(a);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}}}},"object"),Xb=i(({element:e,name:t,description:n})=>{const r=mn(e);return{responseFormat:tt(r.jsonSchema).then(a=>{const{$schema:s,...o}=a;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:o}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:a},s){const o=await lt({text:a});if(!o.success)throw new $t({message:"No object generated: could not parse the response.",cause:o.error,text:a,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=o.value;if(u==null||typeof u!="object"||!("elements"in u)||!Array.isArray(u.elements))throw new $t({message:"No object generated: response did not match schema.",cause:new zt({value:u,cause:"response must be an object with an elements array"}),text:a,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of u.elements){const c=await ut({value:l,schema:r});if(!c.success)throw new $t({message:"No object generated: response did not match schema.",cause:c.error,text:a,response:s.response,usage:s.usage,finishReason:s.finishReason})}return u.elements},async parsePartialOutput({text:a}){const s=await xo(a);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const o=s.value;if(o==null||typeof o!="object"||!("elements"in o)||!Array.isArray(o.elements))return;const u=s.state==="repaired-parse"&&o.elements.length>0?o.elements.slice(0,-1):o.elements,l=[];for(const c of u){const d=await ut({value:c,schema:r});d.success&&l.push(d.value)}return{partial:l}}}}}},"array"),Qb=i(({options:e,name:t,description:n})=>({responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:r},a){const s=await lt({text:r});if(!s.success)throw new $t({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});const o=s.value;if(o==null||typeof o!="object"||!("result"in o)||typeof o.result!="string"||!e.includes(o.result))throw new $t({message:"No object generated: response did not match schema.",cause:new zt({value:o,cause:"response must be an object that contains a choice value."}),text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return o.result},async parsePartialOutput({text:r}){const a=await xo(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=a.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const o=e.filter(u=>u.startsWith(s.result));return a.state==="successful-parse"?o.includes(s.result)?{partial:s.result}:void 0:o.length===1?{partial:o[0]}:void 0}}}}),"choice"),eE=i(({name:e,description:t}={})=>({responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:n},r){const a=await lt({text:n});if(!a.success)throw new $t({message:"No object generated: could not parse the response.",cause:a.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return a.value},async parsePartialOutput({text:n}){const r=await xo(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return r.value===void 0?void 0:{partial:r.value}}}}),"json");async function tE({toolCall:e,tools:t,repairToolCall:n,system:r,messages:a}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Gd(e);throw new bs({toolName:e.toolName})}try{return await Wd({toolCall:e,tools:t})}catch(o){if(n==null||!(bs.isInstance(o)||Cs.isInstance(o)))throw o;let u=null;try{u=await n({toolCall:e,tools:t,inputSchema:i(async({toolName:l})=>{const{inputSchema:c}=t[l];return await mn(c).jsonSchema},"inputSchema"),system:r,messages:a,error:o})}catch(l){throw new YC({cause:l,originalError:o})}if(u==null)throw o;return await Wd({toolCall:u,tools:t})}}catch(o){const u=await lt({text:e.input}),l=u.success?u.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:o,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}i(tE,"parseToolCall");async function Gd(e){const t=e.input.trim()===""?{success:!0,value:{}}:await lt({text:e.input});if(t.success===!1)throw new Cs({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}i(Gd,"parseProviderExecutedDynamicToolCall");async function Wd({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null){if(e.providerExecuted&&e.dynamic)return await Gd(e);throw new bs({toolName:e.toolName,availableTools:Object.keys(t)})}const a=mn(r.inputSchema),s=e.input.trim()===""?await ut({value:{},schema:a}):await lt({text:e.input,schema:a});if(s.success===!1)throw new Cs({toolName:n,toolInput:e.input,cause:s.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:r.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:r.title}}i(Wd,"doParseToolCall");var nE=(Jn=class{constructor({content:t,finishReason:n,rawFinishReason:r,usage:a,warnings:s,request:o,response:u,providerMetadata:l}){this.content=t,this.finishReason=n,this.rawFinishReason=r,this.usage=a,this.warnings=s,this.request=o,this.response=u,this.providerMetadata=l}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}},i(Jn,"DefaultStepResult"),Jn);function rE(e){return({steps:t})=>t.length===e}i(rE,"stepCountIs");async function oE({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}i(oE,"isStopConditionMet");async function aE({content:e,tools:t}){const n=[],r=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":r.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":r.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":r.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":r.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const o=await Ao({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:o,providerOptions:s.providerMetadata});break}case"tool-error":{const o=await Ao({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:o,providerOptions:s.providerMetadata});break}case"tool-approval-request":r.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}r.length>0&&n.push({role:"assistant",content:r});const a=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const o=await Ao({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});a.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:o,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return a.length>0&&n.push({role:"tool",content:a}),n}i(aE,"toResponseMessages");var sE=xr({prefix:"aitxt",size:24});async function Nr({model:e,tools:t,toolChoice:n,system:r,prompt:a,messages:s,maxRetries:o,abortSignal:u,headers:l,stopWhen:c=rE(1),experimental_output:d,output:m=d,experimental_telemetry:h,providerOptions:D,experimental_activeTools:f,activeTools:v=f,experimental_prepareStep:y,prepareStep:F=y,experimental_repairToolCall:E,experimental_download:b,experimental_context:w,_internal:{generateId:S=sE,currentDate:k=i(()=>new Date,"currentDate")}={},onStepFinish:C,onFinish:z,...W}){const B=Td(e),R=Es(c),{maxRetries:O,retry:j}=Ub({maxRetries:o,abortSignal:u}),L=Pd(W),P=Gt(l??{},`ai/${Bd}`),Z=Rb({model:B,telemetry:h,headers:P,settings:{...L,maxRetries:O}}),X=await Sb({system:r,prompt:a,messages:s}),ce=Mb(h);try{return await As({name:"ai.generateText",attributes:Dn({telemetry:h,attributes:{...ws({operationId:"ai.generateText",telemetry:h}),...Z,"ai.model.provider":B.provider,"ai.model.id":B.modelId,"ai.prompt":{input:i(()=>JSON.stringify({system:r,prompt:a,messages:s}),"input")}}}),tracer:ce,fn:i(async K=>{var Q,ee,oe,ie,rt,Oe,Ft,ae;const dt=X.messages,ot=[],{approvedToolApprovals:vt,deniedToolApprovals:Ct}=Vb({messages:dt}),M=vt.filter(De=>!De.toolCall.providerExecuted);if(Ct.length>0||M.length>0){const De=await Hd({toolCalls:M.map($=>$.toolCall),tools:t,tracer:ce,telemetry:h,messages:dt,abortSignal:u,experimental_context:w}),_=[];for(const $ of De){const be=await Ao({toolCallId:$.toolCallId,input:$.input,tool:t?.[$.toolName],output:$.type==="tool-result"?$.output:$.error,errorMode:$.type==="tool-error"?"json":"none"});_.push({type:"tool-result",toolCallId:$.toolCallId,toolName:$.toolName,output:be})}for(const $ of Ct)_.push({type:"tool-result",toolCallId:$.toolCall.toolCallId,toolName:$.toolCall.toolName,output:{type:"execution-denied",reason:$.approvalResponse.reason,...$.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:$.approvalResponse.approvalId}}}}});ot.push({role:"tool",content:_})}const he=[...vt,...Ct].filter(De=>De.toolCall.providerExecuted);he.length>0&&ot.push({role:"tool",content:he.map(De=>({type:"tool-approval-response",approvalId:De.approvalResponse.approvalId,approved:De.approvalResponse.approved,reason:De.approvalResponse.reason,providerExecuted:!0}))});const Xe=Pd(W);let U,Bt=[],bt=[];const Qe=[],Qt=new Map;do{const De=[...dt,...ot],_=await F?.({model:B,steps:Qe,stepNumber:Qe.length,messages:De,experimental_context:w}),$=Td((Q=_?.model)!=null?Q:B),be=await Db({prompt:{system:(ee=_?.system)!=null?ee:X.system,messages:(oe=_?.messages)!=null?oe:De},supportedUrls:await $.supportedUrls,download:b});w=(ie=_?.experimental_context)!=null?ie:w;const{toolChoice:je,tools:en}=await Fb({tools:t,toolChoice:(rt=_?.toolChoice)!=null?rt:n,activeTools:(Oe=_?.activeTools)!=null?Oe:v});U=await j(()=>{var ne;return As({name:"ai.generateText.doGenerate",attributes:Dn({telemetry:h,attributes:{...ws({operationId:"ai.generateText.doGenerate",telemetry:h}),...Z,"ai.model.provider":$.provider,"ai.model.id":$.modelId,"ai.prompt.messages":{input:i(()=>jb(be),"input")},"ai.prompt.tools":{input:i(()=>en?.map(Ve=>JSON.stringify(Ve)),"input")},"ai.prompt.toolChoice":{input:i(()=>je!=null?JSON.stringify(je):void 0,"input")},"gen_ai.system":$.provider,"gen_ai.request.model":$.modelId,"gen_ai.request.frequency_penalty":W.frequencyPenalty,"gen_ai.request.max_tokens":W.maxOutputTokens,"gen_ai.request.presence_penalty":W.presencePenalty,"gen_ai.request.stop_sequences":W.stopSequences,"gen_ai.request.temperature":(ne=W.temperature)!=null?ne:void 0,"gen_ai.request.top_k":W.topK,"gen_ai.request.top_p":W.topP}}),tracer:ce,fn:i(async Ve=>{var Oo,pr,Js,Ks,Ys,Xs,Qs,ei;const jm=Zd(D,_?.providerOptions),ze=await $.doGenerate({...Xe,tools:en,toolChoice:je,responseFormat:await m?.responseFormat,prompt:be,providerOptions:jm,abortSignal:u,headers:P}),tn={id:(pr=(Oo=ze.response)==null?void 0:Oo.id)!=null?pr:S(),timestamp:(Ks=(Js=ze.response)==null?void 0:Js.timestamp)!=null?Ks:k(),modelId:(Xs=(Ys=ze.response)==null?void 0:Ys.modelId)!=null?Xs:$.modelId,headers:(Qs=ze.response)==null?void 0:Qs.headers,body:(ei=ze.response)==null?void 0:ei.body};return Ve.setAttributes(await Dn({telemetry:h,attributes:{"ai.response.finishReason":ze.finishReason.unified,"ai.response.text":{output:i(()=>Ud(ze.content),"output")},"ai.response.toolCalls":{output:i(()=>{const ti=Jd(ze.content);return ti==null?void 0:JSON.stringify(ti)},"output")},"ai.response.id":tn.id,"ai.response.model":tn.modelId,"ai.response.timestamp":tn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ze.providerMetadata),"ai.usage.promptTokens":ze.usage.inputTokens.total,"ai.usage.completionTokens":ze.usage.outputTokens.total,"gen_ai.response.finish_reasons":[ze.finishReason.unified],"gen_ai.response.id":tn.id,"gen_ai.response.model":tn.modelId,"gen_ai.usage.input_tokens":ze.usage.inputTokens.total,"gen_ai.usage.output_tokens":ze.usage.outputTokens.total}})),{...ze,response:tn}},"fn")})});const cr=await Promise.all(U.content.filter(ne=>ne.type==="tool-call").map(ne=>tE({toolCall:ne,tools:t,repairToolCall:E,system:r,messages:De}))),So={};for(const ne of cr){if(ne.invalid)continue;const Ve=t?.[ne.toolName];Ve!=null&&(Ve?.onInputAvailable!=null&&await Ve.onInputAvailable({input:ne.input,toolCallId:ne.toolCallId,messages:De,abortSignal:u,experimental_context:w}),await Hb({tool:Ve,toolCall:ne,messages:De,experimental_context:w})&&(So[ne.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:ne}))}const Mm=cr.filter(ne=>ne.invalid&&ne.dynamic);bt=[];for(const ne of Mm)bt.push({type:"tool-error",toolCallId:ne.toolCallId,toolName:ne.toolName,input:ne.input,error:Uc(ne.error),dynamic:!0});Bt=cr.filter(ne=>!ne.providerExecuted),t!=null&&bt.push(...await Hd({toolCalls:Bt.filter(ne=>!ne.invalid&&So[ne.toolCallId]==null),tools:t,tracer:ce,telemetry:h,messages:De,abortSignal:u,experimental_context:w}));for(const ne of cr){if(!ne.providerExecuted)continue;const Ve=t?.[ne.toolName];Ve?.type==="provider"&&Ve.supportsDeferredResults&&(U.content.some(pr=>pr.type==="tool-result"&&pr.toolCallId===ne.toolCallId)||Qt.set(ne.toolCallId,{toolName:ne.toolName}))}for(const ne of U.content)ne.type==="tool-result"&&Qt.delete(ne.toolCallId);const Ws=uE({content:U.content,toolCalls:cr,toolOutputs:bt,toolApprovalRequests:Object.values(So),tools:t});ot.push(...await aE({content:Ws,tools:t}));const Hs=new nE({content:Ws,finishReason:U.finishReason.unified,rawFinishReason:U.finishReason.raw,usage:zb(U.usage),warnings:U.warnings,providerMetadata:U.providerMetadata,request:(Ft=U.request)!=null?Ft:{},response:{...U.response,messages:structuredClone(ot)}});xd({warnings:(ae=U.warnings)!=null?ae:[],provider:$.provider,model:$.modelId}),Qe.push(Hs),await C?.(Hs)}while((Bt.length>0&&bt.length===Bt.length||Qt.size>0)&&!await oE({stopConditions:R,steps:Qe}));K.setAttributes(await Dn({telemetry:h,attributes:{"ai.response.finishReason":U.finishReason.unified,"ai.response.text":{output:i(()=>Ud(U.content),"output")},"ai.response.toolCalls":{output:i(()=>{const De=Jd(U.content);return De==null?void 0:JSON.stringify(De)},"output")},"ai.response.providerMetadata":JSON.stringify(U.providerMetadata),"ai.usage.promptTokens":U.usage.inputTokens.total,"ai.usage.completionTokens":U.usage.outputTokens.total}}));const pe=Qe[Qe.length-1],ur=Qe.reduce((De,_)=>qb(De,_.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await z?.({finishReason:pe.finishReason,rawFinishReason:pe.rawFinishReason,usage:pe.usage,content:pe.content,text:pe.text,reasoningText:pe.reasoningText,reasoning:pe.reasoning,files:pe.files,sources:pe.sources,toolCalls:pe.toolCalls,staticToolCalls:pe.staticToolCalls,dynamicToolCalls:pe.dynamicToolCalls,toolResults:pe.toolResults,staticToolResults:pe.staticToolResults,dynamicToolResults:pe.dynamicToolResults,request:pe.request,response:pe.response,warnings:pe.warnings,providerMetadata:pe.providerMetadata,steps:Qe,totalUsage:ur,experimental_context:w});let lr;return pe.finishReason==="stop"&&(lr=await(m??Vd()).parseCompleteOutput({text:pe.text},{response:pe.response,usage:pe.usage,finishReason:pe.finishReason})),new iE({steps:Qe,totalUsage:ur,output:lr})},"fn")})}catch(K){throw Ob(K)}}i(Nr,"generateText");async function Hd({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:a,abortSignal:s,experimental_context:o}){return(await Promise.all(e.map(async l=>Gb({toolCall:l,tools:t,tracer:n,telemetry:r,messages:a,abortSignal:s,experimental_context:o})))).filter(l=>l!=null)}i(Hd,"executeTools");var iE=(Kn=class{constructor(t){this.steps=t.steps,this._output=t.output,this.totalUsage=t.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new HC;return this._output}},i(Kn,"DefaultGenerateTextResult"),Kn);function Jd(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}i(Jd,"asToolCalls");function uE({content:e,toolCalls:t,toolOutputs:n,toolApprovalRequests:r,tools:a}){const s=[];for(const o of e)switch(o.type){case"text":case"reasoning":case"source":s.push(o);break;case"file":{s.push({type:"file",file:new Wb(o),...o.providerMetadata!=null?{providerMetadata:o.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(u=>u.toolCallId===o.toolCallId));break}case"tool-result":{const u=t.find(l=>l.toolCallId===o.toolCallId);if(u==null){const l=a?.[o.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${o.toolCallId} not found.`);o.isError?s.push({type:"tool-error",toolCallId:o.toolCallId,toolName:o.toolName,input:void 0,error:o.result,providerExecuted:!0,dynamic:o.dynamic}):s.push({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,input:void 0,output:o.result,providerExecuted:!0,dynamic:o.dynamic});break}o.isError?s.push({type:"tool-error",toolCallId:o.toolCallId,toolName:o.toolName,input:u.input,error:o.result,providerExecuted:!0,dynamic:u.dynamic}):s.push({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,input:u.input,output:o.result,providerExecuted:!0,dynamic:u.dynamic});break}case"tool-approval-request":{const u=t.find(l=>l.toolCallId===o.toolCallId);if(u==null)throw new id({toolCallId:o.toolCallId,approvalId:o.approvalId});s.push({type:"tool-approval-request",approvalId:o.approvalId,toolCall:u});break}}return[...s,...n,...r]}i(uE,"asContent"),class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
146
+ `),{name:"GatewayAuthenticationError"})}i(Nb,"wrapGatewayError");function ws({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}i(ws,"assembleOperationName");function Pb({model:e,settings:t,telemetry:n,headers:r}){var a;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[o,u])=>(s[`ai.settings.${o}`]=u,s),{}),...Object.entries((a=n?.metadata)!=null?a:{}).reduce((s,[o,u])=>(s[`ai.telemetry.metadata.${o}`]=u,s),{}),...Object.entries(r??{}).reduce((s,[o,u])=>(u!==void 0&&(s[`ai.request.headers.${o}`]=u),s),{})}}i(Pb,"getBaseTelemetryAttributes");var Mb={startSpan(){return ko},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(ko);if(typeof n=="function")return n(ko);if(typeof r=="function")return r(ko)}},ko={spanContext(){return jb},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},jb={traceId:"",spanId:"",traceFlags:0};function zb({isEnabled:e=!1,tracer:t}={}){return e?t||zC.getTracer("ai"):Mb}i(zb,"getTracer");async function As({name:e,tracer:t,attributes:n,fn:r,endWhenDone:a=!0}){return t.startActiveSpan(e,{attributes:await n},async s=>{try{const o=await r(s);return a&&s.end(),o}catch(o){try{Ud(s,o)}finally{s.end()}throw o}})}i(As,"recordSpan");function Ud(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Io.ERROR,message:t.message})):e.setStatus({code:Io.ERROR})}i(Ud,"recordErrorOnSpan");async function Dn({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const n={};for(const[r,a]of Object.entries(t))if(a!=null){if(typeof a=="object"&&"input"in a&&typeof a.input=="function"){if(e?.recordInputs===!1)continue;const s=await a.input();s!=null&&(n[r]=s);continue}if(typeof a=="object"&&"output"in a&&typeof a.output=="function"){if(e?.recordOutputs===!1)continue;const s=await a.output();s!=null&&(n[r]=s);continue}n[r]=a}return n}i(Dn,"selectTelemetryAttributes");function qb(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?gb(n.data):n.data}:n)})))}i(qb,"stringifyForTelemetry");function Zb(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:ct(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}i(Zb,"asLanguageModelUsage");function Ub(e,t){var n,r,a,s,o,u,l,c,d,m;return{inputTokens:ct(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:ct((n=e.inputTokenDetails)==null?void 0:n.noCacheTokens,(r=t.inputTokenDetails)==null?void 0:r.noCacheTokens),cacheReadTokens:ct((a=e.inputTokenDetails)==null?void 0:a.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:ct((o=e.inputTokenDetails)==null?void 0:o.cacheWriteTokens,(u=t.inputTokenDetails)==null?void 0:u.cacheWriteTokens)},outputTokens:ct(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:ct((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:ct((d=e.outputTokenDetails)==null?void 0:d.reasoningTokens,(m=t.outputTokenDetails)==null?void 0:m.reasoningTokens)},totalTokens:ct(e.totalTokens,t.totalTokens),reasoningTokens:ct(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:ct(e.cachedInputTokens,t.cachedInputTokens)}}i(Ub,"addLanguageModelUsage");function ct(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}i(ct,"addTokenCounts");function Ld(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const a=t[r];if(a===void 0)continue;const s=r in e?e[r]:void 0,o=a!==null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp),u=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);o&&u?n[r]=Ld(s,a):n[r]=a}return n}i(Ld,"mergeObjects");function Lb({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const a=n["retry-after-ms"];if(a){const o=parseFloat(a);Number.isNaN(o)||(r=o)}const s=n["retry-after"];if(s&&r===void 0){const o=parseFloat(s);Number.isNaN(o)?r=Date.parse(s)-Date.now():r=o*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}i(Lb,"getRetryDelayInMs");var Vb=i(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async a=>Vd(a,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r}),"retryWithExponentialBackoffRespectingRetryHeaders");async function Vd(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:a},s=[]){try{return await e()}catch(o){if(dn(o)||t===0)throw o;const u=Gc(o),l=[...s,o],c=l.length;if(c>t)throw new xd({message:`Failed after ${c} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:l});if(o instanceof Error&&Re.isInstance(o)&&o.isRetryable===!0&&c<=t)return await gF(Lb({error:o,exponentialBackoffDelay:n}),{abortSignal:a}),Vd(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:a},l);throw c===1?o:new xd({message:`Failed after ${c} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:l})}}i(Vd,"_retryWithExponentialBackoff");function Gb({maxRetries:e,abortSignal:t}){if(!Number.isInteger(e))throw new _t({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});const n=e;return{maxRetries:n,retry:Vb({maxRetries:n,abortSignal:t})}}i(Gb,"prepareRetries");function Wb({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-call"&&(n[d.toolCallId]=d)}const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-approval-request"&&(r[d.approvalId]=d)}const a={};for(const l of t.content)l.type==="tool-result"&&(a[l.toolCallId]=l);const s=[],o=[],u=t.content.filter(l=>l.type==="tool-approval-response");for(const l of u){const c=r[l.approvalId];if(c==null)throw new VC({approvalId:l.approvalId});if(a[c.toolCallId]!=null)continue;const d=n[c.toolCallId];if(d==null)throw new ld({toolCallId:c.toolCallId,approvalId:c.approvalId});const m={approvalRequest:c,approvalResponse:l,toolCall:d};l.approved?s.push(m):o.push(m)}return{approvedToolApprovals:s,deniedToolApprovals:o}}i(Wb,"collectToolApprovals");async function Hb({toolCall:e,tools:t,tracer:n,telemetry:r,messages:a,abortSignal:s,experimental_context:o,onPreliminaryToolResult:u}){const{toolName:l,toolCallId:c,input:d}=e,m=t?.[l];if(m?.execute!=null)return As({name:"ai.toolCall",attributes:Dn({telemetry:r,attributes:{...ws({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:i(()=>JSON.stringify(d),"output")}}}),tracer:n,fn:i(async h=>{let D;try{const f=I2({execute:m.execute.bind(m),input:d,options:{toolCallId:c,messages:a,abortSignal:s,experimental_context:o}});for await(const v of f)v.type==="preliminary"?u?.({...e,type:"tool-result",output:v.output,preliminary:!0}):D=v.output}catch(f){return Ud(h,f),{type:"tool-error",toolCallId:c,toolName:l,input:d,error:f,dynamic:m.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}try{h.setAttributes(await Dn({telemetry:r,attributes:{"ai.toolCall.result":{output:i(()=>JSON.stringify(D),"output")}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:d,output:D,dynamic:m.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}i(Hb,"executeToolCall");function Gd(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}i(Gd,"extractTextContent");var Jb=(Hn=class{constructor({data:t,mediaType:n}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=n}get base64(){return this.base64Data==null&&(this.base64Data=Ir(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Lt(this.base64Data)),this.uint8ArrayData}},i(Hn,"DefaultGeneratedFile"),Hn);async function Kb({tool:e,toolCall:t,messages:n,experimental_context:r}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:n,experimental_context:r})}i(Kb,"isApprovalNeeded");var Yb={};ZC(Yb,{array:i(()=>eE,"array"),choice:i(()=>tE,"choice"),json:i(()=>nE,"json"),object:i(()=>Qb,"object"),text:i(()=>Wd,"text")});function Xb(e){const t=["ROOT"];let n=-1,r=null;function a(l,c,d){switch(l){case'"':{n=c,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}i(a,"processValueStart");function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}i(s,"processAfterObjectValue");function o(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}i(o,"processAfterArrayValue");for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":a(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{a(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,a(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{a(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(r,l+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l)):n=l;break}}}let u=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?u+="true".slice(d.length):"false".startsWith(d)?u+="false".slice(d.length):"null".startsWith(d)&&(u+="null".slice(d.length))}}return u}i(Xb,"fixJson");async function $o(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await lt({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await lt({text:Xb(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}i($o,"parsePartialJson");var Wd=i(()=>({responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}}}),"text"),Qb=i(({schema:e,name:t,description:n})=>{const r=mn(e);return{responseFormat:tt(r.jsonSchema).then(a=>({type:"json",schema:a,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:a},s){const o=await lt({text:a});if(!o.success)throw new $t({message:"No object generated: could not parse the response.",cause:o.error,text:a,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=await ut({value:o.value,schema:r});if(!u.success)throw new $t({message:"No object generated: response did not match schema.",cause:u.error,text:a,response:s.response,usage:s.usage,finishReason:s.finishReason});return u.value},async parsePartialOutput({text:a}){const s=await $o(a);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}}}},"object"),eE=i(({element:e,name:t,description:n})=>{const r=mn(e);return{responseFormat:tt(r.jsonSchema).then(a=>{const{$schema:s,...o}=a;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:o}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:a},s){const o=await lt({text:a});if(!o.success)throw new $t({message:"No object generated: could not parse the response.",cause:o.error,text:a,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=o.value;if(u==null||typeof u!="object"||!("elements"in u)||!Array.isArray(u.elements))throw new $t({message:"No object generated: response did not match schema.",cause:new zt({value:u,cause:"response must be an object with an elements array"}),text:a,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of u.elements){const c=await ut({value:l,schema:r});if(!c.success)throw new $t({message:"No object generated: response did not match schema.",cause:c.error,text:a,response:s.response,usage:s.usage,finishReason:s.finishReason})}return u.elements},async parsePartialOutput({text:a}){const s=await $o(a);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const o=s.value;if(o==null||typeof o!="object"||!("elements"in o)||!Array.isArray(o.elements))return;const u=s.state==="repaired-parse"&&o.elements.length>0?o.elements.slice(0,-1):o.elements,l=[];for(const c of u){const d=await ut({value:c,schema:r});d.success&&l.push(d.value)}return{partial:l}}}}}},"array"),tE=i(({options:e,name:t,description:n})=>({responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:r},a){const s=await lt({text:r});if(!s.success)throw new $t({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});const o=s.value;if(o==null||typeof o!="object"||!("result"in o)||typeof o.result!="string"||!e.includes(o.result))throw new $t({message:"No object generated: response did not match schema.",cause:new zt({value:o,cause:"response must be an object that contains a choice value."}),text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return o.result},async parsePartialOutput({text:r}){const a=await $o(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=a.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const o=e.filter(u=>u.startsWith(s.result));return a.state==="successful-parse"?o.includes(s.result)?{partial:s.result}:void 0:o.length===1?{partial:o[0]}:void 0}}}}),"choice"),nE=i(({name:e,description:t}={})=>({responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:n},r){const a=await lt({text:n});if(!a.success)throw new $t({message:"No object generated: could not parse the response.",cause:a.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return a.value},async parsePartialOutput({text:n}){const r=await $o(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return r.value===void 0?void 0:{partial:r.value}}}}),"json");async function rE({toolCall:e,tools:t,repairToolCall:n,system:r,messages:a}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Hd(e);throw new bs({toolName:e.toolName})}try{return await Jd({toolCall:e,tools:t})}catch(o){if(n==null||!(bs.isInstance(o)||Cs.isInstance(o)))throw o;let u=null;try{u=await n({toolCall:e,tools:t,inputSchema:i(async({toolName:l})=>{const{inputSchema:c}=t[l];return await mn(c).jsonSchema},"inputSchema"),system:r,messages:a,error:o})}catch(l){throw new QC({cause:l,originalError:o})}if(u==null)throw o;return await Jd({toolCall:u,tools:t})}}catch(o){const u=await lt({text:e.input}),l=u.success?u.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:o,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}i(rE,"parseToolCall");async function Hd(e){const t=e.input.trim()===""?{success:!0,value:{}}:await lt({text:e.input});if(t.success===!1)throw new Cs({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}i(Hd,"parseProviderExecutedDynamicToolCall");async function Jd({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null){if(e.providerExecuted&&e.dynamic)return await Hd(e);throw new bs({toolName:e.toolName,availableTools:Object.keys(t)})}const a=mn(r.inputSchema),s=e.input.trim()===""?await ut({value:{},schema:a}):await lt({text:e.input,schema:a});if(s.success===!1)throw new Cs({toolName:n,toolInput:e.input,cause:s.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:r.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:r.title}}i(Jd,"doParseToolCall");var oE=(Jn=class{constructor({content:t,finishReason:n,rawFinishReason:r,usage:a,warnings:s,request:o,response:u,providerMetadata:l}){this.content=t,this.finishReason=n,this.rawFinishReason=r,this.usage=a,this.warnings=s,this.request=o,this.response=u,this.providerMetadata=l}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}},i(Jn,"DefaultStepResult"),Jn);function aE(e){return({steps:t})=>t.length===e}i(aE,"stepCountIs");async function sE({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}i(sE,"isStopConditionMet");async function iE({content:e,tools:t}){const n=[],r=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":r.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":r.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":r.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":r.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const o=await xo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:o,providerOptions:s.providerMetadata});break}case"tool-error":{const o=await xo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:o,providerOptions:s.providerMetadata});break}case"tool-approval-request":r.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}r.length>0&&n.push({role:"assistant",content:r});const a=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const o=await xo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});a.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:o,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return a.length>0&&n.push({role:"tool",content:a}),n}i(iE,"toResponseMessages");var uE=xr({prefix:"aitxt",size:24});async function Nr({model:e,tools:t,toolChoice:n,system:r,prompt:a,messages:s,maxRetries:o,abortSignal:u,headers:l,stopWhen:c=aE(1),experimental_output:d,output:m=d,experimental_telemetry:h,providerOptions:D,experimental_activeTools:f,activeTools:v=f,experimental_prepareStep:y,prepareStep:F=y,experimental_repairToolCall:E,experimental_download:b,experimental_context:w,_internal:{generateId:S=uE,currentDate:k=i(()=>new Date,"currentDate")}={},onStepFinish:C,onFinish:z,...W}){const B=Sd(e),R=Es(c),{maxRetries:O,retry:j}=Gb({maxRetries:o,abortSignal:u}),U=jd(W),P=Gt(l??{},`ai/${Od}`),Z=Pb({model:B,telemetry:h,headers:P,settings:{...U,maxRetries:O}}),X=await Rb({system:r,prompt:a,messages:s}),ce=zb(h);try{return await As({name:"ai.generateText",attributes:Dn({telemetry:h,attributes:{...ws({operationId:"ai.generateText",telemetry:h}),...Z,"ai.model.provider":B.provider,"ai.model.id":B.modelId,"ai.prompt":{input:i(()=>JSON.stringify({system:r,prompt:a,messages:s}),"input")}}}),tracer:ce,fn:i(async K=>{var Q,ee,oe,ie,rt,Oe,Ft,ae;const dt=X.messages,ot=[],{approvedToolApprovals:vt,deniedToolApprovals:Ct}=Wb({messages:dt}),M=vt.filter(De=>!De.toolCall.providerExecuted);if(Ct.length>0||M.length>0){const De=await Kd({toolCalls:M.map($=>$.toolCall),tools:t,tracer:ce,telemetry:h,messages:dt,abortSignal:u,experimental_context:w}),_=[];for(const $ of De){const be=await xo({toolCallId:$.toolCallId,input:$.input,tool:t?.[$.toolName],output:$.type==="tool-result"?$.output:$.error,errorMode:$.type==="tool-error"?"json":"none"});_.push({type:"tool-result",toolCallId:$.toolCallId,toolName:$.toolName,output:be})}for(const $ of Ct)_.push({type:"tool-result",toolCallId:$.toolCall.toolCallId,toolName:$.toolCall.toolName,output:{type:"execution-denied",reason:$.approvalResponse.reason,...$.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:$.approvalResponse.approvalId}}}}});ot.push({role:"tool",content:_})}const he=[...vt,...Ct].filter(De=>De.toolCall.providerExecuted);he.length>0&&ot.push({role:"tool",content:he.map(De=>({type:"tool-approval-response",approvalId:De.approvalResponse.approvalId,approved:De.approvalResponse.approved,reason:De.approvalResponse.reason,providerExecuted:!0}))});const Xe=jd(W);let L,Bt=[],bt=[];const Qe=[],Qt=new Map;do{const De=[...dt,...ot],_=await F?.({model:B,steps:Qe,stepNumber:Qe.length,messages:De,experimental_context:w}),$=Sd((Q=_?.model)!=null?Q:B),be=await vb({prompt:{system:(ee=_?.system)!=null?ee:X.system,messages:(oe=_?.messages)!=null?oe:De},supportedUrls:await $.supportedUrls,download:b});w=(ie=_?.experimental_context)!=null?ie:w;const{toolChoice:je,tools:en}=await bb({tools:t,toolChoice:(rt=_?.toolChoice)!=null?rt:n,activeTools:(Oe=_?.activeTools)!=null?Oe:v});L=await j(()=>{var ne;return As({name:"ai.generateText.doGenerate",attributes:Dn({telemetry:h,attributes:{...ws({operationId:"ai.generateText.doGenerate",telemetry:h}),...Z,"ai.model.provider":$.provider,"ai.model.id":$.modelId,"ai.prompt.messages":{input:i(()=>qb(be),"input")},"ai.prompt.tools":{input:i(()=>en?.map(Ve=>JSON.stringify(Ve)),"input")},"ai.prompt.toolChoice":{input:i(()=>je!=null?JSON.stringify(je):void 0,"input")},"gen_ai.system":$.provider,"gen_ai.request.model":$.modelId,"gen_ai.request.frequency_penalty":W.frequencyPenalty,"gen_ai.request.max_tokens":W.maxOutputTokens,"gen_ai.request.presence_penalty":W.presencePenalty,"gen_ai.request.stop_sequences":W.stopSequences,"gen_ai.request.temperature":(ne=W.temperature)!=null?ne:void 0,"gen_ai.request.top_k":W.topK,"gen_ai.request.top_p":W.topP}}),tracer:ce,fn:i(async Ve=>{var Ro,pr,Js,Ks,Ys,Xs,Qs,ei;const qm=Ld(D,_?.providerOptions),ze=await $.doGenerate({...Xe,tools:en,toolChoice:je,responseFormat:await m?.responseFormat,prompt:be,providerOptions:qm,abortSignal:u,headers:P}),tn={id:(pr=(Ro=ze.response)==null?void 0:Ro.id)!=null?pr:S(),timestamp:(Ks=(Js=ze.response)==null?void 0:Js.timestamp)!=null?Ks:k(),modelId:(Xs=(Ys=ze.response)==null?void 0:Ys.modelId)!=null?Xs:$.modelId,headers:(Qs=ze.response)==null?void 0:Qs.headers,body:(ei=ze.response)==null?void 0:ei.body};return Ve.setAttributes(await Dn({telemetry:h,attributes:{"ai.response.finishReason":ze.finishReason.unified,"ai.response.text":{output:i(()=>Gd(ze.content),"output")},"ai.response.toolCalls":{output:i(()=>{const ti=Yd(ze.content);return ti==null?void 0:JSON.stringify(ti)},"output")},"ai.response.id":tn.id,"ai.response.model":tn.modelId,"ai.response.timestamp":tn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ze.providerMetadata),"ai.usage.promptTokens":ze.usage.inputTokens.total,"ai.usage.completionTokens":ze.usage.outputTokens.total,"gen_ai.response.finish_reasons":[ze.finishReason.unified],"gen_ai.response.id":tn.id,"gen_ai.response.model":tn.modelId,"gen_ai.usage.input_tokens":ze.usage.inputTokens.total,"gen_ai.usage.output_tokens":ze.usage.outputTokens.total}})),{...ze,response:tn}},"fn")})});const cr=await Promise.all(L.content.filter(ne=>ne.type==="tool-call").map(ne=>rE({toolCall:ne,tools:t,repairToolCall:E,system:r,messages:De}))),Oo={};for(const ne of cr){if(ne.invalid)continue;const Ve=t?.[ne.toolName];Ve!=null&&(Ve?.onInputAvailable!=null&&await Ve.onInputAvailable({input:ne.input,toolCallId:ne.toolCallId,messages:De,abortSignal:u,experimental_context:w}),await Kb({tool:Ve,toolCall:ne,messages:De,experimental_context:w})&&(Oo[ne.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:ne}))}const zm=cr.filter(ne=>ne.invalid&&ne.dynamic);bt=[];for(const ne of zm)bt.push({type:"tool-error",toolCallId:ne.toolCallId,toolName:ne.toolName,input:ne.input,error:Gc(ne.error),dynamic:!0});Bt=cr.filter(ne=>!ne.providerExecuted),t!=null&&bt.push(...await Kd({toolCalls:Bt.filter(ne=>!ne.invalid&&Oo[ne.toolCallId]==null),tools:t,tracer:ce,telemetry:h,messages:De,abortSignal:u,experimental_context:w}));for(const ne of cr){if(!ne.providerExecuted)continue;const Ve=t?.[ne.toolName];Ve?.type==="provider"&&Ve.supportsDeferredResults&&(L.content.some(pr=>pr.type==="tool-result"&&pr.toolCallId===ne.toolCallId)||Qt.set(ne.toolCallId,{toolName:ne.toolName}))}for(const ne of L.content)ne.type==="tool-result"&&Qt.delete(ne.toolCallId);const Ws=cE({content:L.content,toolCalls:cr,toolOutputs:bt,toolApprovalRequests:Object.values(Oo),tools:t});ot.push(...await iE({content:Ws,tools:t}));const Hs=new oE({content:Ws,finishReason:L.finishReason.unified,rawFinishReason:L.finishReason.raw,usage:Zb(L.usage),warnings:L.warnings,providerMetadata:L.providerMetadata,request:(Ft=L.request)!=null?Ft:{},response:{...L.response,messages:structuredClone(ot)}});$d({warnings:(ae=L.warnings)!=null?ae:[],provider:$.provider,model:$.modelId}),Qe.push(Hs),await C?.(Hs)}while((Bt.length>0&&bt.length===Bt.length||Qt.size>0)&&!await sE({stopConditions:R,steps:Qe}));K.setAttributes(await Dn({telemetry:h,attributes:{"ai.response.finishReason":L.finishReason.unified,"ai.response.text":{output:i(()=>Gd(L.content),"output")},"ai.response.toolCalls":{output:i(()=>{const De=Yd(L.content);return De==null?void 0:JSON.stringify(De)},"output")},"ai.response.providerMetadata":JSON.stringify(L.providerMetadata),"ai.usage.promptTokens":L.usage.inputTokens.total,"ai.usage.completionTokens":L.usage.outputTokens.total}}));const pe=Qe[Qe.length-1],ur=Qe.reduce((De,_)=>Ub(De,_.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await z?.({finishReason:pe.finishReason,rawFinishReason:pe.rawFinishReason,usage:pe.usage,content:pe.content,text:pe.text,reasoningText:pe.reasoningText,reasoning:pe.reasoning,files:pe.files,sources:pe.sources,toolCalls:pe.toolCalls,staticToolCalls:pe.staticToolCalls,dynamicToolCalls:pe.dynamicToolCalls,toolResults:pe.toolResults,staticToolResults:pe.staticToolResults,dynamicToolResults:pe.dynamicToolResults,request:pe.request,response:pe.response,warnings:pe.warnings,providerMetadata:pe.providerMetadata,steps:Qe,totalUsage:ur,experimental_context:w});let lr;return pe.finishReason==="stop"&&(lr=await(m??Wd()).parseCompleteOutput({text:pe.text},{response:pe.response,usage:pe.usage,finishReason:pe.finishReason})),new lE({steps:Qe,totalUsage:ur,output:lr})},"fn")})}catch(K){throw Nb(K)}}i(Nr,"generateText");async function Kd({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:a,abortSignal:s,experimental_context:o}){return(await Promise.all(e.map(async l=>Hb({toolCall:l,tools:t,tracer:n,telemetry:r,messages:a,abortSignal:s,experimental_context:o})))).filter(l=>l!=null)}i(Kd,"executeTools");var lE=(Kn=class{constructor(t){this.steps=t.steps,this._output=t.output,this.totalUsage=t.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new KC;return this._output}},i(Kn,"DefaultGenerateTextResult"),Kn);function Yd(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}i(Yd,"asToolCalls");function cE({content:e,toolCalls:t,toolOutputs:n,toolApprovalRequests:r,tools:a}){const s=[];for(const o of e)switch(o.type){case"text":case"reasoning":case"source":s.push(o);break;case"file":{s.push({type:"file",file:new Jb(o),...o.providerMetadata!=null?{providerMetadata:o.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(u=>u.toolCallId===o.toolCallId));break}case"tool-result":{const u=t.find(l=>l.toolCallId===o.toolCallId);if(u==null){const l=a?.[o.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${o.toolCallId} not found.`);o.isError?s.push({type:"tool-error",toolCallId:o.toolCallId,toolName:o.toolName,input:void 0,error:o.result,providerExecuted:!0,dynamic:o.dynamic}):s.push({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,input:void 0,output:o.result,providerExecuted:!0,dynamic:o.dynamic});break}o.isError?s.push({type:"tool-error",toolCallId:o.toolCallId,toolName:o.toolName,input:u.input,error:o.result,providerExecuted:!0,dynamic:u.dynamic}):s.push({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,input:u.input,output:o.result,providerExecuted:!0,dynamic:u.dynamic});break}case"tool-approval-request":{const u=t.find(l=>l.toolCallId===o.toolCallId);if(u==null)throw new ld({toolCallId:o.toolCallId,approvalId:o.approvalId});s.push({type:"tool-approval-request",approvalId:o.approvalId,toolCall:u});break}}return[...s,...n,...r]}i(cE,"asContent"),class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
147
147
 
148
148
  `)},flush(e){e.enqueue(`data: [DONE]
149
149
 
150
- `)}})}},xr({prefix:"aitxt",size:24}),xr({prefix:"aiobj",size:24}),xr({prefix:"aiobj",size:24});var Is=g({error:g({message:p(),type:p().nullish(),param:qe().nullish(),code:H([p(),A()]).nullish()})}),pt=nt({errorSchema:Is,errorToMessage:i(e=>e.error.message,"errorToMessage")});function Kd(e){const 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=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),a=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?"developer":"system",supportsNonReasoningParameters:a}}i(Kd,"getOpenAILanguageModelCapabilities");function Yd(e){var t,n,r,a,s,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(a=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?a:0,d=(o=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?o:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(Yd,"convertOpenAIChatUsage");function lE({prompt:e,systemMessageMode:t="system"}){var n;const r=[],a=[];for(const{role:s,content:o}of e)switch(s){case"system":{switch(t){case"system":{r.push({role:"system",content:o});break}case"developer":{r.push({role:"developer",content:o});break}case"remove":{a.push({type:"other",message:"system messages are removed for this model"});break}default:{const u=t;throw new Error(`Unsupported system message mode: ${u}`)}}break}case"user":{if(o.length===1&&o[0].type==="text"){r.push({role:"user",content:o[0].text});break}r.push({role:"user",content:o.map((u,l)=>{var c,d,m;switch(u.type){case"text":return{type:"text",text:u.text};case"file":if(u.mediaType.startsWith("image/")){const h=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${h};base64,${Vt(u.data)}`,detail:(d=(c=u.providerOptions)==null?void 0:c.openai)==null?void 0:d.imageDetail}}}else if(u.mediaType.startsWith("audio/")){if(u.data instanceof URL)throw new He({functionality:"audio file parts with URLs"});switch(u.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Vt(u.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Vt(u.data),format:"mp3"}};default:throw new He({functionality:`audio content parts with media type ${u.mediaType}`})}}else if(u.mediaType==="application/pdf"){if(u.data instanceof URL)throw new He({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof u.data=="string"&&u.data.startsWith("file-")?{file_id:u.data}:{filename:(m=u.filename)!=null?m:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Vt(u.data)}`}}}else throw new He({functionality:`file part media type ${u.mediaType}`})}})});break}case"assistant":{let u="";const l=[];for(const c of o)switch(c.type){case"text":{u+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}r.push({role:"assistant",content:u,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const u of o){if(u.type==="tool-approval-response")continue;const l=u.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(n=l.reason)!=null?n:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}r.push({role:"tool",tool_call_id:u.toolCallId,content:c})}break}default:{const u=s;throw new Error(`Unsupported role: ${u}`)}}return{messages:r,warnings:a}}i(lE,"convertToOpenAIChatMessages");function xs({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}i(xs,"getResponseMetadata$1");function Xd(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"other"}}i(Xd,"mapOpenAIFinishReason");var cE=J(()=>G(g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({message:g({role:I("assistant").nullish(),content:p().nullish(),tool_calls:T(g({id:p().nullish(),type:I("function"),function:g({name:p(),arguments:p()})})).nullish(),annotations:T(g({type:I("url_citation"),url_citation:g({start_index:A(),end_index:A(),url:p(),title:p()})})).nullish()}),index:A(),logprobs:g({content:T(g({token:p(),logprob:A(),top_logprobs:T(g({token:p(),logprob:A()}))})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:g({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:g({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}))),pE=J(()=>G(H([g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({delta:g({role:re(["assistant"]).nullish(),content:p().nullish(),tool_calls:T(g({index:A(),id:p().nullish(),type:I("function").nullish(),function:g({name:p().nullish(),arguments:p().nullish()})})).nullish(),annotations:T(g({type:I("url_citation"),url_citation:g({start_index:A(),end_index:A(),url:p(),title:p()})})).nullish()}).nullish(),logprobs:g({content:T(g({token:p(),logprob:A(),top_logprobs:T(g({token:p(),logprob:A()}))})).nullish()}).nullish(),finish_reason:p().nullish(),index:A()})),usage:g({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:g({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}),Is]))),dE=J(()=>G(g({logitBias:me(pF(),A()).optional(),logprobs:H([Ae(),A()]).optional(),parallelToolCalls:Ae().optional(),user:p().optional(),reasoningEffort:re(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:A().optional(),store:Ae().optional(),metadata:me(p().max(64),p().max(512)).optional(),prediction:me(p(),qe()).optional(),serviceTier:re(["auto","flex","priority","default"]).optional(),strictJsonSchema:Ae().optional(),textVerbosity:re(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:re(["in_memory","24h"]).optional(),safetyIdentifier:p().optional(),systemMessageMode:re(["system","developer","remove"]).optional(),forceReasoning:Ae().optional()})));function mE({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:n.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:r,toolChoice:a,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=a;throw new He({functionality:`tool choice type: ${s}`})}}}i(mE,"prepareChatTools");var fE=(Yn=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:s,frequencyPenalty:o,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,tools:m,toolChoice:h,providerOptions:D}){var f,v,y,F,E;const b=[],w=(f=await Ue({provider:"openai",providerOptions:D,schema:dE}))!=null?f:{},S=Kd(this.modelId),k=(v=w.forceReasoning)!=null?v:S.isReasoningModel;s!=null&&b.push({type:"unsupported",feature:"topK"});const{messages:C,warnings:z}=lE({prompt:t,systemMessageMode:(y=w.systemMessageMode)!=null?y:k?"developer":S.systemMessageMode});b.push(...z);const W=(F=w.strictJsonSchema)!=null?F:!0,B={model:this.modelId,logit_bias:w.logitBias,logprobs:w.logprobs===!0||typeof w.logprobs=="number"?!0:void 0,top_logprobs:typeof w.logprobs=="number"?w.logprobs:typeof w.logprobs=="boolean"&&w.logprobs?0:void 0,user:w.user,parallel_tool_calls:w.parallelToolCalls,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,response_format:c?.type==="json"?c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:W,name:(E=c.name)!=null?E:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,verbosity:w.textVerbosity,max_completion_tokens:w.maxCompletionTokens,store:w.store,metadata:w.metadata,prediction:w.prediction,reasoning_effort:w.reasoningEffort,service_tier:w.serviceTier,prompt_cache_key:w.promptCacheKey,prompt_cache_retention:w.promptCacheRetention,safety_identifier:w.safetyIdentifier,messages:C};k?((w.reasoningEffort!=="none"||!S.supportsNonReasoningParameters)&&(B.temperature!=null&&(B.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),B.top_p!=null&&(B.top_p=void 0,b.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),B.logprobs!=null&&(B.logprobs=void 0,b.push({type:"other",message:"logprobs is not supported for reasoning models"}))),B.frequency_penalty!=null&&(B.frequency_penalty=void 0,b.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),B.presence_penalty!=null&&(B.presence_penalty=void 0,b.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),B.logit_bias!=null&&(B.logit_bias=void 0,b.push({type:"other",message:"logitBias is not supported for reasoning models"})),B.top_logprobs!=null&&(B.top_logprobs=void 0,b.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),B.max_tokens!=null&&(B.max_completion_tokens==null&&(B.max_completion_tokens=B.max_tokens),B.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&B.temperature!=null&&(B.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),w.serviceTier==="flex"&&!S.supportsFlexProcessing&&(b.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),B.service_tier=void 0),w.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(b.push({type:"unsupported",feature:"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"}),B.service_tier=void 0);const{tools:R,toolChoice:O,toolWarnings:j}=mE({tools:m,toolChoice:h});return{args:{...B,tools:R,tool_choice:O},warnings:[...b,...j]}}async doGenerate(t){var n,r,a,s,o,u,l;const{args:c,warnings:d}=await this.getArgs(t),{responseHeaders:m,value:h,rawValue:D}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:c,failedResponseHandler:pt,successfulResponseHandler:Pe(cE),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=h.choices[0],v=[],y=f.message.content;y!=null&&y.length>0&&v.push({type:"text",text:y});for(const b of(n=f.message.tool_calls)!=null?n:[])v.push({type:"tool-call",toolCallId:(r=b.id)!=null?r:Be(),toolName:b.function.name,input:b.function.arguments});for(const b of(a=f.message.annotations)!=null?a:[])v.push({type:"source",sourceType:"url",id:Be(),url:b.url_citation.url,title:b.url_citation.title});const F=(s=h.usage)==null?void 0:s.completion_tokens_details;(o=h.usage)==null||o.prompt_tokens_details;const E={openai:{}};return F?.accepted_prediction_tokens!=null&&(E.openai.acceptedPredictionTokens=F?.accepted_prediction_tokens),F?.rejected_prediction_tokens!=null&&(E.openai.rejectedPredictionTokens=F?.rejected_prediction_tokens),((u=f.logprobs)==null?void 0:u.content)!=null&&(E.openai.logprobs=f.logprobs.content),{content:v,finishReason:{unified:Xd(f.finish_reason),raw:(l=f.finish_reason)!=null?l:void 0},usage:Yd(h.usage),request:{body:c},response:{...xs(h),headers:m,body:D},warnings:d,providerMetadata:E}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),a={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:a,failedResponseHandler:pt,successfulResponseHandler:fn(pE),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=[];let l={unified:"other",raw:void 0},c,d=!1,m=!1;const h={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:r})},transform(D,f){var v,y,F,E,b,w,S,k,C,z,W,B,R,O,j,L,P;if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){l={unified:"error",raw:void 0},f.enqueue({type:"error",error:D.error});return}const Z=D.value;if("error"in Z){l={unified:"error",raw:void 0},f.enqueue({type:"error",error:Z.error});return}if(!d){const K=xs(Z);Object.values(K).some(Boolean)&&(d=!0,f.enqueue({type:"response-metadata",...xs(Z)}))}Z.usage!=null&&(c=Z.usage,((v=Z.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(y=Z.usage.completion_tokens_details)==null?void 0:y.accepted_prediction_tokens),((F=Z.usage.completion_tokens_details)==null?void 0:F.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(E=Z.usage.completion_tokens_details)==null?void 0:E.rejected_prediction_tokens));const X=Z.choices[0];if(X?.finish_reason!=null&&(l={unified:Xd(X.finish_reason),raw:X.finish_reason}),((b=X?.logprobs)==null?void 0:b.content)!=null&&(h.openai.logprobs=X.logprobs.content),X?.delta==null)return;const ce=X.delta;if(ce.content!=null&&(m||(f.enqueue({type:"text-start",id:"0"}),m=!0),f.enqueue({type:"text-delta",id:"0",delta:ce.content})),ce.tool_calls!=null)for(const K of ce.tool_calls){const Q=K.index;if(u[Q]==null){if(K.type!=="function")throw new _r({data:K,message:"Expected 'function' type."});if(K.id==null)throw new _r({data:K,message:"Expected 'id' to be a string."});if(((w=K.function)==null?void 0:w.name)==null)throw new _r({data:K,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:K.id,toolName:K.function.name}),u[Q]={id:K.id,type:"function",function:{name:K.function.name,arguments:(S=K.function.arguments)!=null?S:""},hasFinished:!1};const oe=u[Q];((k=oe.function)==null?void 0:k.name)!=null&&((C=oe.function)==null?void 0:C.arguments)!=null&&(oe.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:oe.id,delta:oe.function.arguments}),bo(oe.function.arguments)&&(f.enqueue({type:"tool-input-end",id:oe.id}),f.enqueue({type:"tool-call",toolCallId:(z=oe.id)!=null?z:Be(),toolName:oe.function.name,input:oe.function.arguments}),oe.hasFinished=!0));continue}const ee=u[Q];ee.hasFinished||(((W=K.function)==null?void 0:W.arguments)!=null&&(ee.function.arguments+=(R=(B=K.function)==null?void 0:B.arguments)!=null?R:""),f.enqueue({type:"tool-input-delta",id:ee.id,delta:(O=K.function.arguments)!=null?O:""}),((j=ee.function)==null?void 0:j.name)!=null&&((L=ee.function)==null?void 0:L.arguments)!=null&&bo(ee.function.arguments)&&(f.enqueue({type:"tool-input-end",id:ee.id}),f.enqueue({type:"tool-call",toolCallId:(P=ee.id)!=null?P:Be(),toolName:ee.function.name,input:ee.function.arguments}),ee.hasFinished=!0))}if(ce.annotations!=null)for(const K of ce.annotations)f.enqueue({type:"source",sourceType:"url",id:Be(),url:K.url_citation.url,title:K.url_citation.title})},flush(D){m&&D.enqueue({type:"text-end",id:"0"}),D.enqueue({type:"finish",finishReason:l,usage:Yd(c),...h!=null?{providerMetadata:h}:{}})}})),request:{body:a},response:{headers:s}}}},i(Yn,"OpenAIChatLanguageModel"),Yn);function Qd(e){var t,n,r,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,o=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:(r=e.prompt_tokens)!=null?r:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(a=e.completion_tokens)!=null?a:void 0,text:o,reasoning:void 0},raw:e}}i(Qd,"convertOpenAICompletionUsage");function hE({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
150
+ `)}})}},xr({prefix:"aitxt",size:24}),xr({prefix:"aiobj",size:24}),xr({prefix:"aiobj",size:24});var Is=g({error:g({message:p(),type:p().nullish(),param:qe().nullish(),code:H([p(),A()]).nullish()})}),pt=nt({errorSchema:Is,errorToMessage:i(e=>e.error.message,"errorToMessage")});function Xd(e){const 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=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),a=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?"developer":"system",supportsNonReasoningParameters:a}}i(Xd,"getOpenAILanguageModelCapabilities");function Qd(e){var t,n,r,a,s,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(a=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?a:0,d=(o=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?o:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(Qd,"convertOpenAIChatUsage");function pE({prompt:e,systemMessageMode:t="system"}){var n;const r=[],a=[];for(const{role:s,content:o}of e)switch(s){case"system":{switch(t){case"system":{r.push({role:"system",content:o});break}case"developer":{r.push({role:"developer",content:o});break}case"remove":{a.push({type:"other",message:"system messages are removed for this model"});break}default:{const u=t;throw new Error(`Unsupported system message mode: ${u}`)}}break}case"user":{if(o.length===1&&o[0].type==="text"){r.push({role:"user",content:o[0].text});break}r.push({role:"user",content:o.map((u,l)=>{var c,d,m;switch(u.type){case"text":return{type:"text",text:u.text};case"file":if(u.mediaType.startsWith("image/")){const h=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${h};base64,${Vt(u.data)}`,detail:(d=(c=u.providerOptions)==null?void 0:c.openai)==null?void 0:d.imageDetail}}}else if(u.mediaType.startsWith("audio/")){if(u.data instanceof URL)throw new He({functionality:"audio file parts with URLs"});switch(u.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Vt(u.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Vt(u.data),format:"mp3"}};default:throw new He({functionality:`audio content parts with media type ${u.mediaType}`})}}else if(u.mediaType==="application/pdf"){if(u.data instanceof URL)throw new He({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof u.data=="string"&&u.data.startsWith("file-")?{file_id:u.data}:{filename:(m=u.filename)!=null?m:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Vt(u.data)}`}}}else throw new He({functionality:`file part media type ${u.mediaType}`})}})});break}case"assistant":{let u="";const l=[];for(const c of o)switch(c.type){case"text":{u+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}r.push({role:"assistant",content:u,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const u of o){if(u.type==="tool-approval-response")continue;const l=u.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(n=l.reason)!=null?n:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}r.push({role:"tool",tool_call_id:u.toolCallId,content:c})}break}default:{const u=s;throw new Error(`Unsupported role: ${u}`)}}return{messages:r,warnings:a}}i(pE,"convertToOpenAIChatMessages");function xs({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}i(xs,"getResponseMetadata$1");function em(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"other"}}i(em,"mapOpenAIFinishReason");var dE=J(()=>G(g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({message:g({role:I("assistant").nullish(),content:p().nullish(),tool_calls:T(g({id:p().nullish(),type:I("function"),function:g({name:p(),arguments:p()})})).nullish(),annotations:T(g({type:I("url_citation"),url_citation:g({start_index:A(),end_index:A(),url:p(),title:p()})})).nullish()}),index:A(),logprobs:g({content:T(g({token:p(),logprob:A(),top_logprobs:T(g({token:p(),logprob:A()}))})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:g({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:g({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}))),mE=J(()=>G(H([g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({delta:g({role:re(["assistant"]).nullish(),content:p().nullish(),tool_calls:T(g({index:A(),id:p().nullish(),type:I("function").nullish(),function:g({name:p().nullish(),arguments:p().nullish()})})).nullish(),annotations:T(g({type:I("url_citation"),url_citation:g({start_index:A(),end_index:A(),url:p(),title:p()})})).nullish()}).nullish(),logprobs:g({content:T(g({token:p(),logprob:A(),top_logprobs:T(g({token:p(),logprob:A()}))})).nullish()}).nullish(),finish_reason:p().nullish(),index:A()})),usage:g({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:g({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}),Is]))),fE=J(()=>G(g({logitBias:me(mF(),A()).optional(),logprobs:H([Ae(),A()]).optional(),parallelToolCalls:Ae().optional(),user:p().optional(),reasoningEffort:re(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:A().optional(),store:Ae().optional(),metadata:me(p().max(64),p().max(512)).optional(),prediction:me(p(),qe()).optional(),serviceTier:re(["auto","flex","priority","default"]).optional(),strictJsonSchema:Ae().optional(),textVerbosity:re(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:re(["in_memory","24h"]).optional(),safetyIdentifier:p().optional(),systemMessageMode:re(["system","developer","remove"]).optional(),forceReasoning:Ae().optional()})));function hE({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:n.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:r,toolChoice:a,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=a;throw new He({functionality:`tool choice type: ${s}`})}}}i(hE,"prepareChatTools");var DE=(Yn=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:s,frequencyPenalty:o,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,tools:m,toolChoice:h,providerOptions:D}){var f,v,y,F,E;const b=[],w=(f=await Le({provider:"openai",providerOptions:D,schema:fE}))!=null?f:{},S=Xd(this.modelId),k=(v=w.forceReasoning)!=null?v:S.isReasoningModel;s!=null&&b.push({type:"unsupported",feature:"topK"});const{messages:C,warnings:z}=pE({prompt:t,systemMessageMode:(y=w.systemMessageMode)!=null?y:k?"developer":S.systemMessageMode});b.push(...z);const W=(F=w.strictJsonSchema)!=null?F:!0,B={model:this.modelId,logit_bias:w.logitBias,logprobs:w.logprobs===!0||typeof w.logprobs=="number"?!0:void 0,top_logprobs:typeof w.logprobs=="number"?w.logprobs:typeof w.logprobs=="boolean"&&w.logprobs?0:void 0,user:w.user,parallel_tool_calls:w.parallelToolCalls,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,response_format:c?.type==="json"?c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:W,name:(E=c.name)!=null?E:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,verbosity:w.textVerbosity,max_completion_tokens:w.maxCompletionTokens,store:w.store,metadata:w.metadata,prediction:w.prediction,reasoning_effort:w.reasoningEffort,service_tier:w.serviceTier,prompt_cache_key:w.promptCacheKey,prompt_cache_retention:w.promptCacheRetention,safety_identifier:w.safetyIdentifier,messages:C};k?((w.reasoningEffort!=="none"||!S.supportsNonReasoningParameters)&&(B.temperature!=null&&(B.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),B.top_p!=null&&(B.top_p=void 0,b.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),B.logprobs!=null&&(B.logprobs=void 0,b.push({type:"other",message:"logprobs is not supported for reasoning models"}))),B.frequency_penalty!=null&&(B.frequency_penalty=void 0,b.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),B.presence_penalty!=null&&(B.presence_penalty=void 0,b.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),B.logit_bias!=null&&(B.logit_bias=void 0,b.push({type:"other",message:"logitBias is not supported for reasoning models"})),B.top_logprobs!=null&&(B.top_logprobs=void 0,b.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),B.max_tokens!=null&&(B.max_completion_tokens==null&&(B.max_completion_tokens=B.max_tokens),B.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&B.temperature!=null&&(B.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),w.serviceTier==="flex"&&!S.supportsFlexProcessing&&(b.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),B.service_tier=void 0),w.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(b.push({type:"unsupported",feature:"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"}),B.service_tier=void 0);const{tools:R,toolChoice:O,toolWarnings:j}=hE({tools:m,toolChoice:h});return{args:{...B,tools:R,tool_choice:O},warnings:[...b,...j]}}async doGenerate(t){var n,r,a,s,o,u,l;const{args:c,warnings:d}=await this.getArgs(t),{responseHeaders:m,value:h,rawValue:D}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:c,failedResponseHandler:pt,successfulResponseHandler:Pe(dE),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=h.choices[0],v=[],y=f.message.content;y!=null&&y.length>0&&v.push({type:"text",text:y});for(const b of(n=f.message.tool_calls)!=null?n:[])v.push({type:"tool-call",toolCallId:(r=b.id)!=null?r:Be(),toolName:b.function.name,input:b.function.arguments});for(const b of(a=f.message.annotations)!=null?a:[])v.push({type:"source",sourceType:"url",id:Be(),url:b.url_citation.url,title:b.url_citation.title});const F=(s=h.usage)==null?void 0:s.completion_tokens_details;(o=h.usage)==null||o.prompt_tokens_details;const E={openai:{}};return F?.accepted_prediction_tokens!=null&&(E.openai.acceptedPredictionTokens=F?.accepted_prediction_tokens),F?.rejected_prediction_tokens!=null&&(E.openai.rejectedPredictionTokens=F?.rejected_prediction_tokens),((u=f.logprobs)==null?void 0:u.content)!=null&&(E.openai.logprobs=f.logprobs.content),{content:v,finishReason:{unified:em(f.finish_reason),raw:(l=f.finish_reason)!=null?l:void 0},usage:Qd(h.usage),request:{body:c},response:{...xs(h),headers:m,body:D},warnings:d,providerMetadata:E}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),a={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:a,failedResponseHandler:pt,successfulResponseHandler:fn(mE),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=[];let l={unified:"other",raw:void 0},c,d=!1,m=!1;const h={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:r})},transform(D,f){var v,y,F,E,b,w,S,k,C,z,W,B,R,O,j,U,P;if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){l={unified:"error",raw:void 0},f.enqueue({type:"error",error:D.error});return}const Z=D.value;if("error"in Z){l={unified:"error",raw:void 0},f.enqueue({type:"error",error:Z.error});return}if(!d){const K=xs(Z);Object.values(K).some(Boolean)&&(d=!0,f.enqueue({type:"response-metadata",...xs(Z)}))}Z.usage!=null&&(c=Z.usage,((v=Z.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(y=Z.usage.completion_tokens_details)==null?void 0:y.accepted_prediction_tokens),((F=Z.usage.completion_tokens_details)==null?void 0:F.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(E=Z.usage.completion_tokens_details)==null?void 0:E.rejected_prediction_tokens));const X=Z.choices[0];if(X?.finish_reason!=null&&(l={unified:em(X.finish_reason),raw:X.finish_reason}),((b=X?.logprobs)==null?void 0:b.content)!=null&&(h.openai.logprobs=X.logprobs.content),X?.delta==null)return;const ce=X.delta;if(ce.content!=null&&(m||(f.enqueue({type:"text-start",id:"0"}),m=!0),f.enqueue({type:"text-delta",id:"0",delta:ce.content})),ce.tool_calls!=null)for(const K of ce.tool_calls){const Q=K.index;if(u[Q]==null){if(K.type!=="function")throw new _r({data:K,message:"Expected 'function' type."});if(K.id==null)throw new _r({data:K,message:"Expected 'id' to be a string."});if(((w=K.function)==null?void 0:w.name)==null)throw new _r({data:K,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:K.id,toolName:K.function.name}),u[Q]={id:K.id,type:"function",function:{name:K.function.name,arguments:(S=K.function.arguments)!=null?S:""},hasFinished:!1};const oe=u[Q];((k=oe.function)==null?void 0:k.name)!=null&&((C=oe.function)==null?void 0:C.arguments)!=null&&(oe.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:oe.id,delta:oe.function.arguments}),wo(oe.function.arguments)&&(f.enqueue({type:"tool-input-end",id:oe.id}),f.enqueue({type:"tool-call",toolCallId:(z=oe.id)!=null?z:Be(),toolName:oe.function.name,input:oe.function.arguments}),oe.hasFinished=!0));continue}const ee=u[Q];ee.hasFinished||(((W=K.function)==null?void 0:W.arguments)!=null&&(ee.function.arguments+=(R=(B=K.function)==null?void 0:B.arguments)!=null?R:""),f.enqueue({type:"tool-input-delta",id:ee.id,delta:(O=K.function.arguments)!=null?O:""}),((j=ee.function)==null?void 0:j.name)!=null&&((U=ee.function)==null?void 0:U.arguments)!=null&&wo(ee.function.arguments)&&(f.enqueue({type:"tool-input-end",id:ee.id}),f.enqueue({type:"tool-call",toolCallId:(P=ee.id)!=null?P:Be(),toolName:ee.function.name,input:ee.function.arguments}),ee.hasFinished=!0))}if(ce.annotations!=null)for(const K of ce.annotations)f.enqueue({type:"source",sourceType:"url",id:Be(),url:K.url_citation.url,title:K.url_citation.title})},flush(D){m&&D.enqueue({type:"text-end",id:"0"}),D.enqueue({type:"finish",finishReason:l,usage:Qd(c),...h!=null?{providerMetadata:h}:{}})}})),request:{body:a},response:{headers:s}}}},i(Yn,"OpenAIChatLanguageModel"),Yn);function tm(e){var t,n,r,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,o=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:(r=e.prompt_tokens)!=null?r:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(a=e.completion_tokens)!=null?a:void 0,text:o,reasoning:void 0},raw:e}}i(tm,"convertOpenAICompletionUsage");function gE({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
151
151
 
152
152
  `,e=e.slice(1));for(const{role:a,content:s}of e)switch(a){case"system":throw new At({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const o=s.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
153
153
  ${o}
@@ -157,7 +157,7 @@ ${o}
157
157
 
158
158
  `;break}case"tool":throw new He({functionality:"tool messages"});default:{const o=a;throw new Error(`Unsupported role: ${o}`)}}return r+=`${n}:
159
159
  `,{prompt:r,stopSequences:[`
160
- ${t}:`]}}i(hE,"convertToOpenAICompletionPrompt");function em({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(em,"getResponseMetadata2$1");function tm(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"other"}}i(tm,"mapOpenAIFinishReason2");var DE=J(()=>G(g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({text:p(),finish_reason:p(),logprobs:g({tokens:T(p()),token_logprobs:T(A()),top_logprobs:T(me(p(),A())).nullish()}).nullish()})),usage:g({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}))),gE=J(()=>G(H([g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({text:p(),finish_reason:p().nullish(),index:A(),logprobs:g({tokens:T(p()),token_logprobs:T(A()),top_logprobs:T(me(p(),A())).nullish()}).nullish()})),usage:g({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}),Is]))),nm=J(()=>G(g({echo:Ae().optional(),logitBias:me(p(),A()).optional(),suffix:p().optional(),user:p().optional(),logprobs:H([Ae(),A()]).optional()}))),vE=(Xn=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=n}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:s,frequencyPenalty:o,presencePenalty:u,stopSequences:l,responseFormat:c,tools:d,toolChoice:m,seed:h,providerOptions:D}){const f=[],v={...await Ue({provider:"openai",providerOptions:D,schema:nm}),...await Ue({provider:this.providerOptionsName,providerOptions:D,schema:nm})};s!=null&&f.push({type:"unsupported",feature:"topK"}),d?.length&&f.push({type:"unsupported",feature:"tools"}),m!=null&&f.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&f.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:F}=hE({prompt:t}),E=[...F??[],...l??[]];return{args:{model:this.modelId,echo:v.echo,logit_bias:v.logitBias,logprobs:v?.logprobs===!0?0:v?.logprobs===!1?void 0:v?.logprobs,suffix:v.suffix,user:v.user,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,seed:h,prompt:y,stop:E.length>0?E:void 0},warnings:f}}async doGenerate(t){var n;const{args:r,warnings:a}=await this.getArgs(t),{responseHeaders:s,value:o,rawValue:u}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:r,failedResponseHandler:pt,successfulResponseHandler:Pe(DE),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=o.choices[0],c={openai:{}};return l.logprobs!=null&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:Qd(o.usage),finishReason:{unified:tm(l.finish_reason),raw:(n=l.finish_reason)!=null?n:void 0},request:{body:r},response:{...em(o),headers:s,body:u},providerMetadata:c,warnings:a}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),a={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:a,failedResponseHandler:pt,successfulResponseHandler:fn(gE),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0};const l={openai:{}};let c,d=!0;return{stream:o.pipeThrough(new TransformStream({start(m){m.enqueue({type:"stream-start",warnings:r})},transform(m,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:m.rawValue}),!m.success){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:m.error});return}const D=m.value;if("error"in D){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:D.error});return}d&&(d=!1,h.enqueue({type:"response-metadata",...em(D)}),h.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(c=D.usage);const f=D.choices[0];f?.finish_reason!=null&&(u={unified:tm(f.finish_reason),raw:f.finish_reason}),f?.logprobs!=null&&(l.openai.logprobs=f.logprobs),f?.text!=null&&f.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(m){d||m.enqueue({type:"text-end",id:"0"}),m.enqueue({type:"finish",finishReason:u,providerMetadata:l,usage:Qd(c)})}})),request:{body:a},response:{headers:s}}}},i(Xn,"OpenAICompletionLanguageModel"),Xn),yE=J(()=>G(g({dimensions:A().optional(),user:p().optional()}))),_E=J(()=>G(g({data:T(g({embedding:T(A())})),usage:g({prompt_tokens:A()}).nullish()}))),FE=(Qn=class{constructor(t,n){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=n}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:a}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new jl({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const o=(s=await Ue({provider:"openai",providerOptions:a,schema:yE}))!=null?s:{},{responseHeaders:u,value:l,rawValue:c}=await Se({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:xe(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:pt,successfulResponseHandler:Pe(_E),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.data.map(d=>d.embedding),usage:l.usage?{tokens:l.usage.prompt_tokens}:void 0,response:{headers:u,body:c}}}},i(Qn,"OpenAIEmbeddingModel"),Qn),rm=J(()=>G(g({created:A().nullish(),data:T(g({b64_json:p(),revised_prompt:p().nullish()})),background:p().nullish(),output_format:p().nullish(),size:p().nullish(),quality:p().nullish(),usage:g({input_tokens:A().nullish(),output_tokens:A().nullish(),total_tokens:A().nullish(),input_tokens_details:g({image_tokens:A().nullish(),text_tokens:A().nullish()}).nullish()}).nullish()}))),CE={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},bE=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),EE=(er=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=CE[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:n,mask:r,n:a,size:s,aspectRatio:o,seed:u,providerOptions:l,headers:c,abortSignal:d}){var m,h,D,f,v,y,F,E,b,w,S;const k=[];o!=null&&k.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),u!=null&&k.push({type:"unsupported",feature:"seed"});const C=(D=(h=(m=this.config._internal)==null?void 0:m.currentDate)==null?void 0:h.call(m))!=null?D:new Date;if(n!=null){const{value:B,responseHeaders:R}=await as({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:xe(this.config.headers(),c),formData:jc({model:this.modelId,prompt:t,image:await Promise.all(n.map(O=>O.type==="file"?new Blob([O.data instanceof Uint8Array?new Blob([O.data],{type:O.mediaType}):new Blob([Ut(O.data)],{type:O.mediaType})],{type:O.mediaType}):Xa(O.url))),mask:r!=null?await wE(r):void 0,n:a,size:s,...(f=l.openai)!=null?f:{}}),failedResponseHandler:pt,successfulResponseHandler:Pe(rm),abortSignal:d,fetch:this.config.fetch});return{images:B.data.map(O=>O.b64_json),warnings:k,usage:B.usage!=null?{inputTokens:(v=B.usage.input_tokens)!=null?v:void 0,outputTokens:(y=B.usage.output_tokens)!=null?y:void 0,totalTokens:(F=B.usage.total_tokens)!=null?F:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:R},providerMetadata:{openai:{images:B.data.map(O=>{var j,L,P,Z,X;return{...O.revised_prompt?{revisedPrompt:O.revised_prompt}:{},created:(j=B.created)!=null?j:void 0,size:(L=B.size)!=null?L:void 0,quality:(P=B.quality)!=null?P:void 0,background:(Z=B.background)!=null?Z:void 0,outputFormat:(X=B.output_format)!=null?X:void 0}})}}}}const{value:z,responseHeaders:W}=await Se({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:xe(this.config.headers(),c),body:{model:this.modelId,prompt:t,n:a,size:s,...(E=l.openai)!=null?E:{},...bE.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:pt,successfulResponseHandler:Pe(rm),abortSignal:d,fetch:this.config.fetch});return{images:z.data.map(B=>B.b64_json),warnings:k,usage:z.usage!=null?{inputTokens:(b=z.usage.input_tokens)!=null?b:void 0,outputTokens:(w=z.usage.output_tokens)!=null?w:void 0,totalTokens:(S=z.usage.total_tokens)!=null?S:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:W},providerMetadata:{openai:{images:z.data.map(B=>{var R,O,j,L,P;return{...B.revised_prompt?{revisedPrompt:B.revised_prompt}:{},created:(R=z.created)!=null?R:void 0,size:(O=z.size)!=null?O:void 0,quality:(j=z.quality)!=null?j:void 0,background:(L=z.background)!=null?L:void 0,outputFormat:(P=z.output_format)!=null?P:void 0}})}}}}},i(er,"OpenAIImageModel"),er);async function wE(e){if(!e)return;if(e.type==="url")return Xa(e.url);const t=e.data instanceof Uint8Array?e.data:Ut(e.data);return new Blob([t],{type:e.mediaType})}i(wE,"fileToBlob$1");var AE=J(()=>G(g({callId:p(),operation:Ie("type",[g({type:I("create_file"),path:p(),diff:p()}),g({type:I("delete_file"),path:p()}),g({type:I("update_file"),path:p(),diff:p()})])}))),om=J(()=>G(g({status:re(["completed","failed"]),output:p().optional()}))),IE=yt({id:"openai.apply_patch",inputSchema:AE,outputSchema:om}),xE=IE,kE=J(()=>G(g({code:p().nullish(),containerId:p()}))),$E=J(()=>G(g({outputs:T(Ie("type",[g({type:I("logs"),logs:p()}),g({type:I("image"),url:p()})])).nullish()}))),TE=J(()=>G(g({container:H([p(),g({fileIds:T(p()).optional()})]).optional()}))),BE=yt({id:"openai.code_interpreter",inputSchema:kE,outputSchema:$E}),SE=i((e={})=>BE(e),"codeInterpreter"),am=g({key:p(),type:re(["eq","ne","gt","gte","lt","lte","in","nin"]),value:H([p(),A(),Ae(),T(p())])}),sm=g({type:re(["and","or"]),filters:T(H([am,Ha(()=>sm)]))}),OE=J(()=>G(g({vectorStoreIds:T(p()),maxNumResults:A().optional(),ranking:g({ranker:p().optional(),scoreThreshold:A().optional()}).optional(),filters:H([am,sm]).optional()}))),RE=J(()=>G(g({queries:T(p()),results:T(g({attributes:me(p(),gt()),fileId:p(),filename:p(),score:A(),text:p()})).nullable()}))),NE=yt({id:"openai.file_search",inputSchema:g({}),outputSchema:RE}),PE=J(()=>G(g({background:re(["auto","opaque","transparent"]).optional(),inputFidelity:re(["low","high"]).optional(),inputImageMask:g({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:re(["auto"]).optional(),outputCompression:A().int().min(0).max(100).optional(),outputFormat:re(["png","jpeg","webp"]).optional(),partialImages:A().int().min(0).max(3).optional(),quality:re(["auto","low","medium","high"]).optional(),size:re(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),ME=J(()=>G(g({}))),jE=J(()=>G(g({result:p()}))),zE=yt({id:"openai.image_generation",inputSchema:ME,outputSchema:jE}),qE=i((e={})=>zE(e),"imageGeneration"),im=J(()=>G(g({action:g({type:I("exec"),command:T(p()),timeoutMs:A().optional(),user:p().optional(),workingDirectory:p().optional(),env:me(p(),p()).optional()})}))),um=J(()=>G(g({output:p()}))),ZE=yt({id:"openai.local_shell",inputSchema:im,outputSchema:um}),lm=J(()=>G(g({action:g({commands:T(p()),timeoutMs:A().optional(),maxOutputLength:A().optional()})}))),cm=J(()=>G(g({output:T(g({stdout:p(),stderr:p(),outcome:Ie("type",[g({type:I("timeout")}),g({type:I("exit"),exitCode:A()})])}))}))),LE=yt({id:"openai.shell",inputSchema:lm,outputSchema:cm}),UE=J(()=>G(g({externalWebAccess:Ae().optional(),filters:g({allowedDomains:T(p()).optional()}).optional(),searchContextSize:re(["low","medium","high"]).optional(),userLocation:g({type:I("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),VE=J(()=>G(g({}))),GE=J(()=>G(g({action:Ie("type",[g({type:I("search"),query:p().optional()}),g({type:I("openPage"),url:p().nullish()}),g({type:I("findInPage"),url:p().nullish(),pattern:p().nullish()})]),sources:T(Ie("type",[g({type:I("url"),url:p()}),g({type:I("api"),name:p()})])).optional()}))),WE=yt({id:"openai.web_search",inputSchema:VE,outputSchema:GE}),HE=i((e={})=>WE(e),"webSearch"),JE=J(()=>G(g({searchContextSize:re(["low","medium","high"]).optional(),userLocation:g({type:I("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),KE=J(()=>G(g({}))),YE=J(()=>G(g({action:Ie("type",[g({type:I("search"),query:p().optional()}),g({type:I("openPage"),url:p().nullish()}),g({type:I("findInPage"),url:p().nullish(),pattern:p().nullish()})])}))),XE=yt({id:"openai.web_search_preview",inputSchema:KE,outputSchema:YE}),ks=Ha(()=>H([p(),A(),Ae(),Tc(),T(ks),me(p(),ks)])),QE=J(()=>G(g({serverLabel:p(),allowedTools:H([T(p()),g({readOnly:Ae().optional(),toolNames:T(p()).optional()})]).optional(),authorization:p().optional(),connectorId:p().optional(),headers:me(p(),p()).optional(),requireApproval:H([re(["always","never"]),g({never:g({toolNames:T(p()).optional()}).optional()})]).optional(),serverDescription:p().optional(),serverUrl:p().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),ew=J(()=>G(g({}))),tw=J(()=>G(g({type:I("call"),serverLabel:p(),name:p(),arguments:p(),output:p().nullish(),error:H([p(),ks]).optional()}))),nw=yt({id:"openai.mcp",inputSchema:ew,outputSchema:tw}),rw=i(e=>nw(e),"mcp"),ow={applyPatch:xE,codeInterpreter:SE,fileSearch:NE,imageGeneration:qE,localShell:ZE,shell:LE,webSearchPreview:XE,webSearch:HE,mcp:rw};function pm(e){var t,n,r,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,o=e.output_tokens,u=(n=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?n:0,l=(a=(r=e.output_tokens_details)==null?void 0:r.reasoning_tokens)!=null?a:0;return{inputTokens:{total:s,noCache:s-u,cacheRead:u,cacheWrite:void 0},outputTokens:{total:o,text:o-l,reasoning:l},raw:e}}i(pm,"convertOpenAIResponsesUsage");function dm(e,t){return t?t.some(n=>e.startsWith(n)):!1}i(dm,"isFileId");async function aw({prompt:e,toolNameMapping:t,systemMessageMode:n,providerOptionsName:r,fileIdPrefixes:a,store:s,hasLocalShellTool:o=!1,hasShellTool:u=!1,hasApplyPatchTool:l=!1}){var c,d,m,h,D,f,v,y,F,E,b,w,S;const k=[],C=[],z=new Set;for(const{role:W,content:B}of e)switch(W){case"system":{switch(n){case"system":{k.push({role:"system",content:B});break}case"developer":{k.push({role:"developer",content:B});break}case"remove":{C.push({type:"other",message:"system messages are removed for this model"});break}default:{const R=n;throw new Error(`Unsupported system message mode: ${R}`)}}break}case"user":{k.push({role:"user",content:B.map((R,O)=>{var j,L,P;switch(R.type){case"text":return{type:"input_text",text:R.text};case"file":if(R.mediaType.startsWith("image/")){const Z=R.mediaType==="image/*"?"image/jpeg":R.mediaType;return{type:"input_image",...R.data instanceof URL?{image_url:R.data.toString()}:typeof R.data=="string"&&dm(R.data,a)?{file_id:R.data}:{image_url:`data:${Z};base64,${Vt(R.data)}`},detail:(L=(j=R.providerOptions)==null?void 0:j[r])==null?void 0:L.imageDetail}}else{if(R.mediaType==="application/pdf")return R.data instanceof URL?{type:"input_file",file_url:R.data.toString()}:{type:"input_file",...typeof R.data=="string"&&dm(R.data,a)?{file_id:R.data}:{filename:(P=R.filename)!=null?P:`part-${O}.pdf`,file_data:`data:application/pdf;base64,${Vt(R.data)}`}};throw new He({functionality:`file part media type ${R.mediaType}`})}}})});break}case"assistant":{const R={};for(const O of B)switch(O.type){case"text":{const j=(d=(c=O.providerOptions)==null?void 0:c[r])==null?void 0:d.itemId;if(s&&j!=null){k.push({type:"item_reference",id:j});break}k.push({role:"assistant",content:[{type:"output_text",text:O.text}],id:j});break}case"tool-call":{const j=(v=(h=(m=O.providerOptions)==null?void 0:m[r])==null?void 0:h.itemId)!=null?v:(f=(D=O.providerMetadata)==null?void 0:D[r])==null?void 0:f.itemId;if(O.providerExecuted){s&&j!=null&&k.push({type:"item_reference",id:j});break}if(s&&j!=null){k.push({type:"item_reference",id:j});break}const L=t.toProviderToolName(O.toolName);if(o&&L==="local_shell"){const P=await et({value:O.input,schema:im});k.push({type:"local_shell_call",call_id:O.toolCallId,id:j,action:{type:"exec",command:P.action.command,timeout_ms:P.action.timeoutMs,user:P.action.user,working_directory:P.action.workingDirectory,env:P.action.env}});break}if(u&&L==="shell"){const P=await et({value:O.input,schema:lm});k.push({type:"shell_call",call_id:O.toolCallId,id:j,status:"completed",action:{commands:P.action.commands,timeout_ms:P.action.timeoutMs,max_output_length:P.action.maxOutputLength}});break}k.push({type:"function_call",call_id:O.toolCallId,name:L,arguments:JSON.stringify(O.input),id:j});break}case"tool-result":{if(O.output.type==="execution-denied"||O.output.type==="json"&&typeof O.output.value=="object"&&O.output.value!=null&&"type"in O.output.value&&O.output.value.type==="execution-denied")break;if(s){const j=(E=(F=(y=O.providerMetadata)==null?void 0:y[r])==null?void 0:F.itemId)!=null?E:O.toolCallId;k.push({type:"item_reference",id:j})}else C.push({type:"other",message:`Results for OpenAI tool ${O.toolName} are not sent to the API when store is false`});break}case"reasoning":{const j=await Ue({provider:r,providerOptions:O.providerOptions,schema:sw}),L=j?.itemId;if(L!=null){const P=R[L];if(s)P===void 0&&(k.push({type:"item_reference",id:L}),R[L]={type:"reasoning",id:L,summary:[]});else{const Z=[];O.text.length>0?Z.push({type:"summary_text",text:O.text}):P!==void 0&&C.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(O)}.`}),P===void 0?(R[L]={type:"reasoning",id:L,encrypted_content:j?.reasoningEncryptedContent,summary:Z},k.push(R[L])):(P.summary.push(...Z),j?.reasoningEncryptedContent!=null&&(P.encrypted_content=j.reasoningEncryptedContent))}}else C.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(O)}.`});break}}break}case"tool":{for(const R of B){if(R.type==="tool-approval-response"){const P=R;if(z.has(P.approvalId))continue;z.add(P.approvalId),s&&k.push({type:"item_reference",id:P.approvalId}),k.push({type:"mcp_approval_response",approval_request_id:P.approvalId,approve:P.approved});continue}const O=R.output;if(O.type==="execution-denied"&&((w=(b=O.providerOptions)==null?void 0:b.openai)==null?void 0:w.approvalId))continue;const j=t.toProviderToolName(R.toolName);if(o&&j==="local_shell"&&O.type==="json"){const P=await et({value:O.value,schema:um});k.push({type:"local_shell_call_output",call_id:R.toolCallId,output:P.output});continue}if(u&&j==="shell"&&O.type==="json"){const P=await et({value:O.value,schema:cm});k.push({type:"shell_call_output",call_id:R.toolCallId,output:P.output.map(Z=>({stdout:Z.stdout,stderr:Z.stderr,outcome:Z.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Z.outcome.exitCode}}))});continue}if(l&&R.toolName==="apply_patch"&&O.type==="json"){const P=await et({value:O.value,schema:om});k.push({type:"apply_patch_call_output",call_id:R.toolCallId,status:P.status,output:P.output});continue}let L;switch(O.type){case"text":case"error-text":L=O.value;break;case"execution-denied":L=(S=O.reason)!=null?S:"Tool execution denied.";break;case"json":case"error-json":L=JSON.stringify(O.value);break;case"content":L=O.value.map(P=>{var Z;switch(P.type){case"text":return{type:"input_text",text:P.text};case"image-data":return{type:"input_image",image_url:`data:${P.mediaType};base64,${P.data}`};case"file-data":return{type:"input_file",filename:(Z=P.filename)!=null?Z:"data",file_data:`data:${P.mediaType};base64,${P.data}`};default:{C.push({type:"other",message:`unsupported tool content part type: ${P.type}`});return}}}).filter(CF);break}k.push({type:"function_call_output",call_id:R.toolCallId,output:L})}break}default:{const R=W;throw new Error(`Unsupported role: ${R}`)}}return{input:k,warnings:C}}i(aw,"convertToOpenAIResponsesInput");var sw=g({itemId:p().nullish(),reasoningEncryptedContent:p().nullish()});function mm({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":"other"}}i(mm,"mapOpenAIResponseFinishReason");var iw=J(()=>G(H([g({type:I("response.output_text.delta"),item_id:p(),delta:p(),logprobs:T(g({token:p(),logprob:A(),top_logprobs:T(g({token:p(),logprob:A()}))})).nullish()}),g({type:re(["response.completed","response.incomplete"]),response:g({incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:A(),input_tokens_details:g({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:g({reasoning_tokens:A().nullish()}).nullish()}),service_tier:p().nullish()})}),g({type:I("response.created"),response:g({id:p(),created_at:A(),model:p(),service_tier:p().nullish()})}),g({type:I("response.output_item.added"),output_index:A(),item:Ie("type",[g({type:I("message"),id:p()}),g({type:I("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:I("function_call"),id:p(),call_id:p(),name:p(),arguments:p()}),g({type:I("web_search_call"),id:p(),status:p()}),g({type:I("computer_call"),id:p(),status:p()}),g({type:I("file_search_call"),id:p()}),g({type:I("image_generation_call"),id:p()}),g({type:I("code_interpreter_call"),id:p(),container_id:p(),code:p().nullable(),outputs:T(Ie("type",[g({type:I("logs"),logs:p()}),g({type:I("image"),url:p()})])).nullable(),status:p()}),g({type:I("mcp_call"),id:p(),status:p(),approval_request_id:p().nullish()}),g({type:I("mcp_list_tools"),id:p()}),g({type:I("mcp_approval_request"),id:p()}),g({type:I("apply_patch_call"),id:p(),call_id:p(),status:re(["in_progress","completed"]),operation:Ie("type",[g({type:I("create_file"),path:p(),diff:p()}),g({type:I("delete_file"),path:p()}),g({type:I("update_file"),path:p(),diff:p()})])}),g({type:I("shell_call"),id:p(),call_id:p(),status:re(["in_progress","completed","incomplete"]),action:g({commands:T(p())})})])}),g({type:I("response.output_item.done"),output_index:A(),item:Ie("type",[g({type:I("message"),id:p()}),g({type:I("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:I("function_call"),id:p(),call_id:p(),name:p(),arguments:p(),status:I("completed")}),g({type:I("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:T(Ie("type",[g({type:I("logs"),logs:p()}),g({type:I("image"),url:p()})])).nullable()}),g({type:I("image_generation_call"),id:p(),result:p()}),g({type:I("web_search_call"),id:p(),status:p(),action:Ie("type",[g({type:I("search"),query:p().nullish(),sources:T(Ie("type",[g({type:I("url"),url:p()}),g({type:I("api"),name:p()})])).nullish()}),g({type:I("open_page"),url:p().nullish()}),g({type:I("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:I("file_search_call"),id:p(),queries:T(p()),results:T(g({attributes:me(p(),H([p(),A(),Ae()])),file_id:p(),filename:p(),score:A(),text:p()})).nullish()}),g({type:I("local_shell_call"),id:p(),call_id:p(),action:g({type:I("exec"),command:T(p()),timeout_ms:A().optional(),user:p().optional(),working_directory:p().optional(),env:me(p(),p()).optional()})}),g({type:I("computer_call"),id:p(),status:I("completed")}),g({type:I("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:H([p(),g({type:p().optional(),code:H([A(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:I("mcp_list_tools"),id:p(),server_label:p(),tools:T(g({name:p(),description:p().optional(),input_schema:qe(),annotations:me(p(),gt()).optional()})),error:H([p(),g({type:p().optional(),code:H([A(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:I("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:I("apply_patch_call"),id:p(),call_id:p(),status:re(["in_progress","completed"]),operation:Ie("type",[g({type:I("create_file"),path:p(),diff:p()}),g({type:I("delete_file"),path:p()}),g({type:I("update_file"),path:p(),diff:p()})])}),g({type:I("shell_call"),id:p(),call_id:p(),status:re(["in_progress","completed","incomplete"]),action:g({commands:T(p())})})])}),g({type:I("response.function_call_arguments.delta"),item_id:p(),output_index:A(),delta:p()}),g({type:I("response.image_generation_call.partial_image"),item_id:p(),output_index:A(),partial_image_b64:p()}),g({type:I("response.code_interpreter_call_code.delta"),item_id:p(),output_index:A(),delta:p()}),g({type:I("response.code_interpreter_call_code.done"),item_id:p(),output_index:A(),code:p()}),g({type:I("response.output_text.annotation.added"),annotation:Ie("type",[g({type:I("url_citation"),start_index:A(),end_index:A(),url:p(),title:p()}),g({type:I("file_citation"),file_id:p(),filename:p().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:p().nullish()}),g({type:I("container_file_citation"),container_id:p(),file_id:p(),filename:p().nullish(),start_index:A().nullish(),end_index:A().nullish(),index:A().nullish()}),g({type:I("file_path"),file_id:p(),index:A().nullish()})])}),g({type:I("response.reasoning_summary_part.added"),item_id:p(),summary_index:A()}),g({type:I("response.reasoning_summary_text.delta"),item_id:p(),summary_index:A(),delta:p()}),g({type:I("response.reasoning_summary_part.done"),item_id:p(),summary_index:A()}),g({type:I("response.apply_patch_call_operation_diff.delta"),item_id:p(),output_index:A(),delta:p(),obfuscation:p().nullish()}),g({type:I("response.apply_patch_call_operation_diff.done"),item_id:p(),output_index:A(),diff:p()}),g({type:I("error"),sequence_number:A(),error:g({type:p(),code:p(),message:p(),param:p().nullish()})}),g({type:p()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),uw=J(()=>G(g({id:p().optional(),created_at:A().optional(),error:g({message:p(),type:p(),param:p().nullish(),code:p()}).nullish(),model:p().optional(),output:T(Ie("type",[g({type:I("message"),role:I("assistant"),id:p(),content:T(g({type:I("output_text"),text:p(),logprobs:T(g({token:p(),logprob:A(),top_logprobs:T(g({token:p(),logprob:A()}))})).nullish(),annotations:T(Ie("type",[g({type:I("url_citation"),start_index:A(),end_index:A(),url:p(),title:p()}),g({type:I("file_citation"),file_id:p(),filename:p().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:p().nullish()}),g({type:I("container_file_citation"),container_id:p(),file_id:p(),filename:p().nullish(),start_index:A().nullish(),end_index:A().nullish(),index:A().nullish()}),g({type:I("file_path"),file_id:p(),index:A().nullish()})]))}))}),g({type:I("web_search_call"),id:p(),status:p(),action:Ie("type",[g({type:I("search"),query:p().nullish(),sources:T(Ie("type",[g({type:I("url"),url:p()}),g({type:I("api"),name:p()})])).nullish()}),g({type:I("open_page"),url:p().nullish()}),g({type:I("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:I("file_search_call"),id:p(),queries:T(p()),results:T(g({attributes:me(p(),H([p(),A(),Ae()])),file_id:p(),filename:p(),score:A(),text:p()})).nullish()}),g({type:I("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:T(Ie("type",[g({type:I("logs"),logs:p()}),g({type:I("image"),url:p()})])).nullable()}),g({type:I("image_generation_call"),id:p(),result:p()}),g({type:I("local_shell_call"),id:p(),call_id:p(),action:g({type:I("exec"),command:T(p()),timeout_ms:A().optional(),user:p().optional(),working_directory:p().optional(),env:me(p(),p()).optional()})}),g({type:I("function_call"),call_id:p(),name:p(),arguments:p(),id:p()}),g({type:I("computer_call"),id:p(),status:p().optional()}),g({type:I("reasoning"),id:p(),encrypted_content:p().nullish(),summary:T(g({type:I("summary_text"),text:p()}))}),g({type:I("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:H([p(),g({type:p().optional(),code:H([A(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:I("mcp_list_tools"),id:p(),server_label:p(),tools:T(g({name:p(),description:p().optional(),input_schema:qe(),annotations:me(p(),gt()).optional()})),error:H([p(),g({type:p().optional(),code:H([A(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:I("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:I("apply_patch_call"),id:p(),call_id:p(),status:re(["in_progress","completed"]),operation:Ie("type",[g({type:I("create_file"),path:p(),diff:p()}),g({type:I("delete_file"),path:p()}),g({type:I("update_file"),path:p(),diff:p()})])}),g({type:I("shell_call"),id:p(),call_id:p(),status:re(["in_progress","completed","incomplete"]),action:g({commands:T(p())})})])).optional(),service_tier:p().nullish(),incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:A(),input_tokens_details:g({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:g({reasoning_tokens:A().nullish()}).nullish()}).optional()}))),fm=20,hm=J(()=>G(g({conversation:p().nullish(),include:T(re(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:H([Ae(),A().min(1).max(fm)]).optional(),maxToolCalls:A().nullish(),metadata:qe().nullish(),parallelToolCalls:Ae().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:re(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:re(["auto","flex","priority","default"]).nullish(),store:Ae().nullish(),strictJsonSchema:Ae().nullish(),textVerbosity:re(["low","medium","high"]).nullish(),truncation:re(["auto","disabled"]).nullish(),user:p().nullish(),systemMessageMode:re(["system","developer","remove"]).optional(),forceReasoning:Ae().optional()})));async function lw({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const o=await et({value:s.args,schema:OE});r.push({type:"file_search",vector_store_ids:o.vectorStoreIds,max_num_results:o.maxNumResults,ranking_options:o.ranking?{ranker:o.ranking.ranker,score_threshold:o.ranking.scoreThreshold}:void 0,filters:o.filters});break}case"openai.local_shell":{r.push({type:"local_shell"});break}case"openai.shell":{r.push({type:"shell"});break}case"openai.apply_patch":{r.push({type:"apply_patch"});break}case"openai.web_search_preview":{const o=await et({value:s.args,schema:JE});r.push({type:"web_search_preview",search_context_size:o.searchContextSize,user_location:o.userLocation});break}case"openai.web_search":{const o=await et({value:s.args,schema:UE});r.push({type:"web_search",filters:o.filters!=null?{allowed_domains:o.filters.allowedDomains}:void 0,external_web_access:o.externalWebAccess,search_context_size:o.searchContextSize,user_location:o.userLocation});break}case"openai.code_interpreter":{const o=await et({value:s.args,schema:TE});r.push({type:"code_interpreter",container:o.container==null?{type:"auto",file_ids:void 0}:typeof o.container=="string"?o.container:{type:"auto",file_ids:o.container.fileIds}});break}case"openai.image_generation":{const o=await et({value:s.args,schema:PE});r.push({type:"image_generation",background:o.background,input_fidelity:o.inputFidelity,input_image_mask:o.inputImageMask?{file_id:o.inputImageMask.fileId,image_url:o.inputImageMask.imageUrl}:void 0,model:o.model,moderation:o.moderation,partial_images:o.partialImages,quality:o.quality,output_compression:o.outputCompression,output_format:o.outputFormat,size:o.size});break}case"openai.mcp":{const o=await et({value:s.args,schema:QE}),u=i(d=>({tool_names:d.toolNames}),"mapApprovalFilter"),l=o.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:u(l.never)}:void 0;r.push({type:"mcp",server_label:o.serverLabel,allowed_tools:Array.isArray(o.allowedTools)?o.allowedTools:o.allowedTools?{read_only:o.allowedTools.readOnly,tool_names:o.allowedTools.toolNames}:void 0,authorization:o.authorization,connector_id:o.connectorId,headers:o.headers,require_approval:c??"never",server_description:o.serverDescription,server_url:o.serverUrl});break}}break}default:n.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:r,toolChoice:a,toolWarnings:n};case"tool":return{tools:r,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const s=a;throw new He({functionality:`tool choice type: ${s}`})}}}i(lw,"prepareResponsesTools");function Dm(e){var t,n;const r={};for(const a of e)if(a.role==="assistant")for(const s of a.content){if(s.type!=="tool-call")continue;const o=(n=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:n.approvalRequestId;o!=null&&(r[o]=s.toolCallId)}return r}i(Dm,"extractApprovalRequestIdToToolCallIdMapping");var cw=(tr=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:n,stopSequences:r,topP:a,topK:s,presencePenalty:o,frequencyPenalty:u,seed:l,prompt:c,providerOptions:d,tools:m,toolChoice:h,responseFormat:D}){var f,v,y,F,E,b;const w=[],S=Kd(this.modelId);s!=null&&w.push({type:"unsupported",feature:"topK"}),l!=null&&w.push({type:"unsupported",feature:"seed"}),o!=null&&w.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&w.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&w.push({type:"unsupported",feature:"stopSequences"});const k=this.config.provider.includes("azure")?"azure":"openai";let C=await Ue({provider:k,providerOptions:d,schema:hm});C==null&&k!=="openai"&&(C=await Ue({provider:"openai",providerOptions:d,schema:hm}));const z=(f=C?.forceReasoning)!=null?f:S.isReasoningModel;C?.conversation&&C?.previousResponseId&&w.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const W=fF({tools:m,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:B,warnings:R}=await aw({prompt:c,toolNameMapping:W,systemMessageMode:(v=C?.systemMessageMode)!=null?v:z?"developer":S.systemMessageMode,providerOptionsName:k,fileIdPrefixes:this.config.fileIdPrefixes,store:(y=C?.store)!=null?y:!0,hasLocalShellTool:P("openai.local_shell"),hasShellTool:P("openai.shell"),hasApplyPatchTool:P("openai.apply_patch")});w.push(...R);const O=(F=C?.strictJsonSchema)!=null?F:!0;let j=C?.include;function L(ie){j==null?j=[ie]:j.includes(ie)||(j=[...j,ie])}i(L,"addInclude");function P(ie){return m?.find(rt=>rt.type==="provider"&&rt.id===ie)!=null}i(P,"hasOpenAITool");const Z=typeof C?.logprobs=="number"?C?.logprobs:C?.logprobs===!0?fm:void 0;Z&&L("message.output_text.logprobs");const X=(E=m?.find(ie=>ie.type==="provider"&&(ie.id==="openai.web_search"||ie.id==="openai.web_search_preview")))==null?void 0:E.name;X&&L("web_search_call.action.sources"),P("openai.code_interpreter")&&L("code_interpreter_call.outputs");const ce=C?.store;ce===!1&&z&&L("reasoning.encrypted_content");const K={model:this.modelId,input:B,temperature:n,top_p:a,max_output_tokens:t,...(D?.type==="json"||C?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:O,name:(b=D.name)!=null?b:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...C?.textVerbosity&&{verbosity:C.textVerbosity}}},conversation:C?.conversation,max_tool_calls:C?.maxToolCalls,metadata:C?.metadata,parallel_tool_calls:C?.parallelToolCalls,previous_response_id:C?.previousResponseId,store:ce,user:C?.user,instructions:C?.instructions,service_tier:C?.serviceTier,include:j,prompt_cache_key:C?.promptCacheKey,prompt_cache_retention:C?.promptCacheRetention,safety_identifier:C?.safetyIdentifier,top_logprobs:Z,truncation:C?.truncation,...z&&(C?.reasoningEffort!=null||C?.reasoningSummary!=null)&&{reasoning:{...C?.reasoningEffort!=null&&{effort:C.reasoningEffort},...C?.reasoningSummary!=null&&{summary:C.reasoningSummary}}}};z?C?.reasoningEffort==="none"&&S.supportsNonReasoningParameters||(K.temperature!=null&&(K.temperature=void 0,w.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),K.top_p!=null&&(K.top_p=void 0,w.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(C?.reasoningEffort!=null&&w.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),C?.reasoningSummary!=null&&w.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),C?.serviceTier==="flex"&&!S.supportsFlexProcessing&&(w.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete K.service_tier),C?.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(w.push({type:"unsupported",feature:"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 K.service_tier);const{tools:Q,toolChoice:ee,toolWarnings:oe}=await lw({tools:m,toolChoice:h});return{webSearchToolName:X,args:{...K,tools:Q,tool_choice:ee},warnings:[...w,...oe],store:ce,toolNameMapping:W,providerOptionsName:k}}async doGenerate(t){var n,r,a,s,o,u,l,c,d,m,h,D,f,v,y,F,E,b,w,S,k,C,z,W,B,R,O,j,L,P,Z;const{args:X,warnings:ce,webSearchToolName:K,toolNameMapping:Q,providerOptionsName:ee}=await this.getArgs(t),oe=this.config.url({path:"/responses",modelId:this.modelId}),ie=Dm(t.prompt),{responseHeaders:rt,value:Oe,rawValue:Ft}=await Se({url:oe,headers:xe(this.config.headers(),t.headers),body:X,failedResponseHandler:pt,successfulResponseHandler:Pe(uw),abortSignal:t.abortSignal,fetch:this.config.fetch});if(Oe.error)throw new Re({message:Oe.error.message,url:oe,requestBodyValues:X,statusCode:400,responseHeaders:rt,responseBody:Ft,isRetryable:!1});const ae=[],dt=[];let ot=!1;for(const M of Oe.output)switch(M.type){case"reasoning":{M.summary.length===0&&M.summary.push({type:"summary_text",text:""});for(const he of M.summary)ae.push({type:"reasoning",text:he.text,providerMetadata:{[ee]:{itemId:M.id,reasoningEncryptedContent:(n=M.encrypted_content)!=null?n:null}}});break}case"image_generation_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName("image_generation"),result:{result:M.result}});break}case"local_shell_call":{ae.push({type:"tool-call",toolCallId:M.call_id,toolName:Q.toCustomToolName("local_shell"),input:JSON.stringify({action:M.action}),providerMetadata:{[ee]:{itemId:M.id}}});break}case"shell_call":{ae.push({type:"tool-call",toolCallId:M.call_id,toolName:Q.toCustomToolName("shell"),input:JSON.stringify({action:{commands:M.action.commands}}),providerMetadata:{[ee]:{itemId:M.id}}});break}case"message":{for(const he of M.content){(a=(r=t.providerOptions)==null?void 0:r[ee])!=null&&a.logprobs&&he.logprobs&&dt.push(he.logprobs);const Xe={itemId:M.id,...he.annotations.length>0&&{annotations:he.annotations}};ae.push({type:"text",text:he.text,providerMetadata:{[ee]:Xe}});for(const U of he.annotations)U.type==="url_citation"?ae.push({type:"source",sourceType:"url",id:(u=(o=(s=this.config).generateId)==null?void 0:o.call(s))!=null?u:Be(),url:U.url,title:U.title}):U.type==="file_citation"?ae.push({type:"source",sourceType:"document",id:(d=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?d:Be(),mediaType:"text/plain",title:(h=(m=U.quote)!=null?m:U.filename)!=null?h:"Document",filename:(D=U.filename)!=null?D:U.file_id,...U.file_id?{providerMetadata:{[ee]:{fileId:U.file_id}}}:{}}):U.type==="container_file_citation"?ae.push({type:"source",sourceType:"document",id:(y=(v=(f=this.config).generateId)==null?void 0:v.call(f))!=null?y:Be(),mediaType:"text/plain",title:(E=(F=U.filename)!=null?F:U.file_id)!=null?E:"Document",filename:(b=U.filename)!=null?b:U.file_id,providerMetadata:{[ee]:{fileId:U.file_id,containerId:U.container_id,...U.index!=null?{index:U.index}:{}}}}):U.type==="file_path"&&ae.push({type:"source",sourceType:"document",id:(k=(S=(w=this.config).generateId)==null?void 0:S.call(w))!=null?k:Be(),mediaType:"application/octet-stream",title:U.file_id,filename:U.file_id,providerMetadata:{[ee]:{fileId:U.file_id,...U.index!=null?{index:U.index}:{}}}})}break}case"function_call":{ot=!0,ae.push({type:"tool-call",toolCallId:M.call_id,toolName:M.name,input:M.arguments,providerMetadata:{[ee]:{itemId:M.id}}});break}case"web_search_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName(K??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName(K??"web_search"),result:vm(M.action)});break}case"mcp_call":{const he=M.approval_request_id!=null&&(C=ie[M.approval_request_id])!=null?C:M.id,Xe=`mcp.${M.name}`;ae.push({type:"tool-call",toolCallId:he,toolName:Xe,input:M.arguments,providerExecuted:!0,dynamic:!0}),ae.push({type:"tool-result",toolCallId:he,toolName:Xe,result:{type:"call",serverLabel:M.server_label,name:M.name,arguments:M.arguments,...M.output!=null?{output:M.output}:{},...M.error!=null?{error:M.error}:{}},providerMetadata:{[ee]:{itemId:M.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const he=(z=M.approval_request_id)!=null?z:M.id,Xe=(R=(B=(W=this.config).generateId)==null?void 0:B.call(W))!=null?R:Be(),U=`mcp.${M.name}`;ae.push({type:"tool-call",toolCallId:Xe,toolName:U,input:M.arguments,providerExecuted:!0,dynamic:!0}),ae.push({type:"tool-approval-request",approvalId:he,toolCallId:Xe});break}case"computer_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:M.status||"completed"}});break}case"file_search_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName("file_search"),result:{queries:M.queries,results:(j=(O=M.results)==null?void 0:O.map(he=>({attributes:he.attributes,fileId:he.file_id,filename:he.filename,score:he.score,text:he.text})))!=null?j:null}});break}case"code_interpreter_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName("code_interpreter"),input:JSON.stringify({code:M.code,containerId:M.container_id}),providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName("code_interpreter"),result:{outputs:M.outputs}});break}case"apply_patch_call":{ae.push({type:"tool-call",toolCallId:M.call_id,toolName:Q.toCustomToolName("apply_patch"),input:JSON.stringify({callId:M.call_id,operation:M.operation}),providerMetadata:{[ee]:{itemId:M.id}}});break}}const vt={[ee]:{responseId:Oe.id}};dt.length>0&&(vt[ee].logprobs=dt),typeof Oe.service_tier=="string"&&(vt[ee].serviceTier=Oe.service_tier);const Ct=Oe.usage;return{content:ae,finishReason:{unified:mm({finishReason:(L=Oe.incomplete_details)==null?void 0:L.reason,hasFunctionCall:ot}),raw:(Z=(P=Oe.incomplete_details)==null?void 0:P.reason)!=null?Z:void 0},usage:pm(Ct),request:{body:X},response:{id:Oe.id,timestamp:new Date(Oe.created_at*1e3),modelId:Oe.model,headers:rt,body:Ft},providerMetadata:vt,warnings:ce}}async doStream(t){const{args:n,warnings:r,webSearchToolName:a,toolNameMapping:s,store:o,providerOptionsName:u}=await this.getArgs(t),{responseHeaders:l,value:c}=await Se({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:{...n,stream:!0},failedResponseHandler:pt,successfulResponseHandler:fn(iw),abortSignal:t.abortSignal,fetch:this.config.fetch}),d=this,m=Dm(t.prompt),h=new Map;let D={unified:"other",raw:void 0},f;const v=[];let y=null;const F={},E=[];let b=!1;const w={};let S;return{stream:c.pipeThrough(new TransformStream({start(k){k.enqueue({type:"stream-start",warnings:r})},transform(k,C){var z,W,B,R,O,j,L,P,Z,X,ce,K,Q,ee,oe,ie,rt,Oe,Ft,ae,dt,ot,vt,Ct,M,he,Xe,U,Bt,bt,Qe,Qt,pe,ur,lr,De;if(t.includeRawChunks&&C.enqueue({type:"raw",rawValue:k.rawValue}),!k.success){D={unified:"error",raw:void 0},C.enqueue({type:"error",error:k.error});return}const _=k.value;if(gm(_)){if(_.item.type==="function_call")F[_.output_index]={toolName:_.item.name,toolCallId:_.item.call_id},C.enqueue({type:"tool-input-start",id:_.item.call_id,toolName:_.item.name});else if(_.item.type==="web_search_call")F[_.output_index]={toolName:s.toCustomToolName(a??"web_search"),toolCallId:_.item.id},C.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName(a??"web_search"),providerExecuted:!0}),C.enqueue({type:"tool-input-end",id:_.item.id}),C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName(a??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(_.item.type==="computer_call")F[_.output_index]={toolName:s.toCustomToolName("computer_use"),toolCallId:_.item.id},C.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("computer_use"),providerExecuted:!0});else if(_.item.type==="code_interpreter_call")F[_.output_index]={toolName:s.toCustomToolName("code_interpreter"),toolCallId:_.item.id,codeInterpreter:{containerId:_.item.container_id}},C.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("code_interpreter"),providerExecuted:!0}),C.enqueue({type:"tool-input-delta",id:_.item.id,delta:`{"containerId":"${_.item.container_id}","code":"`});else if(_.item.type==="file_search_call")C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(_.item.type==="image_generation_call")C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(_.item.type==="mcp_call"||_.item.type==="mcp_list_tools"||_.item.type==="mcp_approval_request"))if(_.item.type==="apply_patch_call"){const{call_id:$,operation:be}=_.item;if(F[_.output_index]={toolName:s.toCustomToolName("apply_patch"),toolCallId:$,applyPatch:{hasDiff:be.type==="delete_file",endEmitted:be.type==="delete_file"}},C.enqueue({type:"tool-input-start",id:$,toolName:s.toCustomToolName("apply_patch")}),be.type==="delete_file"){const je=JSON.stringify({callId:$,operation:be});C.enqueue({type:"tool-input-delta",id:$,delta:je}),C.enqueue({type:"tool-input-end",id:$})}else C.enqueue({type:"tool-input-delta",id:$,delta:`{"callId":"${Jt($)}","operation":{"type":"${Jt(be.type)}","path":"${Jt(be.path)}","diff":"`})}else _.item.type==="shell_call"?F[_.output_index]={toolName:s.toCustomToolName("shell"),toolCallId:_.item.call_id}:_.item.type==="message"?(E.splice(0,E.length),C.enqueue({type:"text-start",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id}}})):gm(_)&&_.item.type==="reasoning"&&(w[_.item.id]={encryptedContent:_.item.encrypted_content,summaryParts:{0:"active"}},C.enqueue({type:"reasoning-start",id:`${_.item.id}:0`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(z=_.item.encrypted_content)!=null?z:null}}}))}else if(dw(_)){if(_.item.type==="message")C.enqueue({type:"text-end",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id,...E.length>0&&{annotations:E}}}});else if(_.item.type==="function_call")F[_.output_index]=void 0,b=!0,C.enqueue({type:"tool-input-end",id:_.item.call_id}),C.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:_.item.name,input:_.item.arguments,providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="web_search_call")F[_.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName(a??"web_search"),result:vm(_.item.action)});else if(_.item.type==="computer_call")F[_.output_index]=void 0,C.enqueue({type:"tool-input-end",id:_.item.id}),C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:_.item.status||"completed"}});else if(_.item.type==="file_search_call")F[_.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),result:{queries:_.item.queries,results:(B=(W=_.item.results)==null?void 0:W.map($=>({attributes:$.attributes,fileId:$.file_id,filename:$.filename,score:$.score,text:$.text})))!=null?B:null}});else if(_.item.type==="code_interpreter_call")F[_.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("code_interpreter"),result:{outputs:_.item.outputs}});else if(_.item.type==="image_generation_call")C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),result:{result:_.item.result}});else if(_.item.type==="mcp_call"){F[_.output_index]=void 0;const $=(R=_.item.approval_request_id)!=null?R:void 0,be=$!=null&&(j=(O=h.get($))!=null?O:m[$])!=null?j:_.item.id,je=`mcp.${_.item.name}`;C.enqueue({type:"tool-call",toolCallId:be,toolName:je,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),C.enqueue({type:"tool-result",toolCallId:be,toolName:je,result:{type:"call",serverLabel:_.item.server_label,name:_.item.name,arguments:_.item.arguments,..._.item.output!=null?{output:_.item.output}:{},..._.item.error!=null?{error:_.item.error}:{}},providerMetadata:{[u]:{itemId:_.item.id}}})}else if(_.item.type==="mcp_list_tools")F[_.output_index]=void 0;else if(_.item.type==="apply_patch_call"){const $=F[_.output_index];$?.applyPatch&&!$.applyPatch.endEmitted&&_.item.operation.type!=="delete_file"&&($.applyPatch.hasDiff||C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:Jt(_.item.operation.diff)}),C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:'"}}'}),C.enqueue({type:"tool-input-end",id:$.toolCallId}),$.applyPatch.endEmitted=!0),$&&_.item.status==="completed"&&C.enqueue({type:"tool-call",toolCallId:$.toolCallId,toolName:s.toCustomToolName("apply_patch"),input:JSON.stringify({callId:_.item.call_id,operation:_.item.operation}),providerMetadata:{[u]:{itemId:_.item.id}}}),F[_.output_index]=void 0}else if(_.item.type==="mcp_approval_request"){F[_.output_index]=void 0;const $=(Z=(P=(L=d.config).generateId)==null?void 0:P.call(L))!=null?Z:Be(),be=(X=_.item.approval_request_id)!=null?X:_.item.id;h.set(be,$);const je=`mcp.${_.item.name}`;C.enqueue({type:"tool-call",toolCallId:$,toolName:je,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),C.enqueue({type:"tool-approval-request",approvalId:be,toolCallId:$})}else if(_.item.type==="local_shell_call")F[_.output_index]=void 0,C.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:_.item.action.command,timeoutMs:_.item.action.timeout_ms,user:_.item.action.user,workingDirectory:_.item.action.working_directory,env:_.item.action.env}}),providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call")F[_.output_index]=void 0,C.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),input:JSON.stringify({action:{commands:_.item.action.commands}}),providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="reasoning"){const $=w[_.item.id],be=Object.entries($.summaryParts).filter(([je,en])=>en==="active"||en==="can-conclude").map(([je])=>je);for(const je of be)C.enqueue({type:"reasoning-end",id:`${_.item.id}:${je}`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(ce=_.item.encrypted_content)!=null?ce:null}}});delete w[_.item.id]}}else if(hw(_)){const $=F[_.output_index];$!=null&&C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:_.delta})}else if(yw(_)){const $=F[_.output_index];$?.applyPatch&&(C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:Jt(_.delta)}),$.applyPatch.hasDiff=!0)}else if(_w(_)){const $=F[_.output_index];$?.applyPatch&&!$.applyPatch.endEmitted&&($.applyPatch.hasDiff||(C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:Jt(_.diff)}),$.applyPatch.hasDiff=!0),C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:'"}}'}),C.enqueue({type:"tool-input-end",id:$.toolCallId}),$.applyPatch.endEmitted=!0)}else if(Dw(_))C.enqueue({type:"tool-result",toolCallId:_.item_id,toolName:s.toCustomToolName("image_generation"),result:{result:_.partial_image_b64},preliminary:!0});else if(gw(_)){const $=F[_.output_index];$!=null&&C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:Jt(_.delta)})}else if(vw(_)){const $=F[_.output_index];$!=null&&(C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:'"}'}),C.enqueue({type:"tool-input-end",id:$.toolCallId}),C.enqueue({type:"tool-call",toolCallId:$.toolCallId,toolName:s.toCustomToolName("code_interpreter"),input:JSON.stringify({code:_.code,containerId:$.codeInterpreter.containerId}),providerExecuted:!0}))}else if(fw(_))y=_.response.id,C.enqueue({type:"response-metadata",id:_.response.id,timestamp:new Date(_.response.created_at*1e3),modelId:_.response.model});else if(pw(_))C.enqueue({type:"text-delta",id:_.item_id,delta:_.delta}),(Q=(K=t.providerOptions)==null?void 0:K[u])!=null&&Q.logprobs&&_.logprobs&&v.push(_.logprobs);else if(_.type==="response.reasoning_summary_part.added"){if(_.summary_index>0){const $=w[_.item_id];$.summaryParts[_.summary_index]="active";for(const be of Object.keys($.summaryParts))$.summaryParts[be]==="can-conclude"&&(C.enqueue({type:"reasoning-end",id:`${_.item_id}:${be}`,providerMetadata:{[u]:{itemId:_.item_id}}}),$.summaryParts[be]="concluded");C.enqueue({type:"reasoning-start",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id,reasoningEncryptedContent:(oe=(ee=w[_.item_id])==null?void 0:ee.encryptedContent)!=null?oe:null}}})}}else _.type==="response.reasoning_summary_text.delta"?C.enqueue({type:"reasoning-delta",id:`${_.item_id}:${_.summary_index}`,delta:_.delta,providerMetadata:{[u]:{itemId:_.item_id}}}):_.type==="response.reasoning_summary_part.done"?o?(C.enqueue({type:"reasoning-end",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id}}}),w[_.item_id].summaryParts[_.summary_index]="concluded"):w[_.item_id].summaryParts[_.summary_index]="can-conclude":mw(_)?(D={unified:mm({finishReason:(ie=_.response.incomplete_details)==null?void 0:ie.reason,hasFunctionCall:b}),raw:(Oe=(rt=_.response.incomplete_details)==null?void 0:rt.reason)!=null?Oe:void 0},f=_.response.usage,typeof _.response.service_tier=="string"&&(S=_.response.service_tier)):Fw(_)?(E.push(_.annotation),_.annotation.type==="url_citation"?C.enqueue({type:"source",sourceType:"url",id:(dt=(ae=(Ft=d.config).generateId)==null?void 0:ae.call(Ft))!=null?dt:Be(),url:_.annotation.url,title:_.annotation.title}):_.annotation.type==="file_citation"?C.enqueue({type:"source",sourceType:"document",id:(Ct=(vt=(ot=d.config).generateId)==null?void 0:vt.call(ot))!=null?Ct:Be(),mediaType:"text/plain",title:(he=(M=_.annotation.quote)!=null?M:_.annotation.filename)!=null?he:"Document",filename:(Xe=_.annotation.filename)!=null?Xe:_.annotation.file_id,..._.annotation.file_id?{providerMetadata:{[u]:{fileId:_.annotation.file_id}}}:{}}):_.annotation.type==="container_file_citation"?C.enqueue({type:"source",sourceType:"document",id:(bt=(Bt=(U=d.config).generateId)==null?void 0:Bt.call(U))!=null?bt:Be(),mediaType:"text/plain",title:(Qt=(Qe=_.annotation.filename)!=null?Qe:_.annotation.file_id)!=null?Qt:"Document",filename:(pe=_.annotation.filename)!=null?pe:_.annotation.file_id,providerMetadata:{[u]:{fileId:_.annotation.file_id,containerId:_.annotation.container_id,..._.annotation.index!=null?{index:_.annotation.index}:{}}}}):_.annotation.type==="file_path"&&C.enqueue({type:"source",sourceType:"document",id:(De=(lr=(ur=d.config).generateId)==null?void 0:lr.call(ur))!=null?De:Be(),mediaType:"application/octet-stream",title:_.annotation.file_id,filename:_.annotation.file_id,providerMetadata:{[u]:{fileId:_.annotation.file_id,..._.annotation.index!=null?{index:_.annotation.index}:{}}}})):Cw(_)&&C.enqueue({type:"error",error:_})},flush(k){const C={[u]:{responseId:y}};v.length>0&&(C[u].logprobs=v),S!==void 0&&(C[u].serviceTier=S),k.enqueue({type:"finish",finishReason:D,usage:pm(f),providerMetadata:C})}})),request:{body:n},response:{headers:l}}}},i(tr,"OpenAIResponsesLanguageModel"),tr);function pw(e){return e.type==="response.output_text.delta"}i(pw,"isTextDeltaChunk");function dw(e){return e.type==="response.output_item.done"}i(dw,"isResponseOutputItemDoneChunk");function mw(e){return e.type==="response.completed"||e.type==="response.incomplete"}i(mw,"isResponseFinishedChunk");function fw(e){return e.type==="response.created"}i(fw,"isResponseCreatedChunk");function hw(e){return e.type==="response.function_call_arguments.delta"}i(hw,"isResponseFunctionCallArgumentsDeltaChunk");function Dw(e){return e.type==="response.image_generation_call.partial_image"}i(Dw,"isResponseImageGenerationCallPartialImageChunk");function gw(e){return e.type==="response.code_interpreter_call_code.delta"}i(gw,"isResponseCodeInterpreterCallCodeDeltaChunk");function vw(e){return e.type==="response.code_interpreter_call_code.done"}i(vw,"isResponseCodeInterpreterCallCodeDoneChunk");function yw(e){return e.type==="response.apply_patch_call_operation_diff.delta"}i(yw,"isResponseApplyPatchCallOperationDiffDeltaChunk");function _w(e){return e.type==="response.apply_patch_call_operation_diff.done"}i(_w,"isResponseApplyPatchCallOperationDiffDoneChunk");function gm(e){return e.type==="response.output_item.added"}i(gm,"isResponseOutputItemAddedChunk");function Fw(e){return e.type==="response.output_text.annotation.added"}i(Fw,"isResponseAnnotationAddedChunk");function Cw(e){return e.type==="error"}i(Cw,"isErrorChunk");function vm(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}i(vm,"mapWebSearchOutput");function Jt(e){return JSON.stringify(e).slice(1,-1)}i(Jt,"escapeJSONDelta");var bw=J(()=>G(g({instructions:p().nullish(),speed:A().min(.25).max(4).default(1).nullish()}))),Ew=(nr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:n="alloy",outputFormat:r="mp3",speed:a,instructions:s,language:o,providerOptions:u}){const l=[],c=await Ue({provider:"openai",providerOptions:u,schema:bw}),d={model:this.modelId,input:t,voice:n,response_format:"mp3",speed:a,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?d.response_format=r:l.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){const m={};for(const h in m){const D=m[h];D!==void 0&&(d[h]=D)}}return o&&l.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:d,warnings:l}}async doGenerate(t){var n,r,a;const s=(a=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?a:new Date,{requestBody:o,warnings:u}=await this.getArgs(t),{value:l,responseHeaders:c,rawValue:d}=await Se({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:o,failedResponseHandler:pt,successfulResponseHandler:b2(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:l,warnings:u,request:{body:JSON.stringify(o)},response:{timestamp:s,modelId:this.modelId,headers:c,body:d}}}},i(nr,"OpenAISpeechModel"),nr),ww=J(()=>G(g({text:p(),language:p().nullish(),duration:A().nullish(),words:T(g({word:p(),start:A(),end:A()})).nullish(),segments:T(g({id:A(),seek:A(),start:A(),end:A(),text:p(),tokens:T(A()),temperature:A(),avg_logprob:A(),compression_ratio:A(),no_speech_prob:A()})).nullish()}))),Aw=J(()=>G(g({include:T(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:A().min(0).max(1).default(0).optional(),timestampGranularities:T(re(["word","segment"])).default(["segment"]).optional()}))),ym={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"},Iw=(rr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:n,providerOptions:r}){const a=[],s=await Ue({provider:"openai",providerOptions:r,schema:Aw}),o=new FormData,u=t instanceof Uint8Array?new Blob([t]):new Blob([Ut(t)]);o.append("model",this.modelId);const l=wF(n);if(o.append("file",new File([u],"audio",{type:n}),`audio.${l}`),s){const c={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[d,m]of Object.entries(c))if(m!=null)if(Array.isArray(m))for(const h of m)o.append(`${d}[]`,String(h));else o.append(d,String(m))}return{formData:o,warnings:a}}async doGenerate(t){var n,r,a,s,o,u,l,c;const d=(a=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?a:new Date,{formData:m,warnings:h}=await this.getArgs(t),{value:D,responseHeaders:f,rawValue:v}=await as({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),formData:m,failedResponseHandler:pt,successfulResponseHandler:Pe(ww),abortSignal:t.abortSignal,fetch:this.config.fetch}),y=D.language!=null&&D.language in ym?ym[D.language]:void 0;return{text:D.text,segments:(l=(u=(s=D.segments)==null?void 0:s.map(F=>({text:F.text,startSecond:F.start,endSecond:F.end})))!=null?u:(o=D.words)==null?void 0:o.map(F=>({text:F.word,startSecond:F.start,endSecond:F.end})))!=null?l:[],language:y,durationInSeconds:(c=D.duration)!=null?c:void 0,warnings:h,response:{timestamp:d,modelId:this.modelId,headers:f,body:v}}}},i(rr,"OpenAITranscriptionModel"),rr),xw="3.0.5";function ko(e={}){var t,n;const r=(t=ss(kr({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",a=(n=e.name)!=null?n:"openai",s=i(()=>Gt({Authorization:`Bearer ${EF({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${xw}`),"getHeaders"),o=i(v=>new fE(v,{provider:`${a}.chat`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createChatModel"),u=i(v=>new vE(v,{provider:`${a}.completion`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createCompletionModel"),l=i(v=>new FE(v,{provider:`${a}.embedding`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createEmbeddingModel"),c=i(v=>new EE(v,{provider:`${a}.image`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createImageModel"),d=i(v=>new Iw(v,{provider:`${a}.transcription`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createTranscriptionModel"),m=i(v=>new Ew(v,{provider:`${a}.speech`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createSpeechModel"),h=i(v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return D(v)},"createLanguageModel"),D=i(v=>new cw(v,{provider:`${a}.responses`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),"createResponsesModel"),f=i(function(v){return h(v)},"provider");return f.specificationVersion="v3",f.languageModel=h,f.chat=o,f.completion=u,f.responses=D,f.embedding=l,f.embeddingModel=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=c,f.imageModel=c,f.transcription=d,f.transcriptionModel=d,f.speech=m,f.speechModel=m,f.tools=ow,f}i(ko,"createOpenAI"),ko();var kw=g({error:g({message:p(),type:p().nullish(),param:qe().nullish(),code:H([p(),A()]).nullish()})}),Pr={errorSchema:kw,errorToMessage:i(e=>e.error.message,"errorToMessage")};function _m(e){var t,n,r,a,s,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(a=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?a:0,d=(o=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?o:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(_m,"convertOpenAICompatibleChatUsage");function Mr(e){var t,n;return(n=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}i(Mr,"getOpenAIMetadata");function $w(e){var t;const n=[];for(const{role:r,content:a,...s}of e){const o=Mr({...s});switch(r){case"system":{n.push({role:"system",content:a,...o});break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text,...Mr(a[0])});break}n.push({role:"user",content:a.map(u=>{const l=Mr(u);switch(u.type){case"text":return{type:"text",text:u.text,...l};case"file":if(u.mediaType.startsWith("image/")){const c=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${c};base64,${Vt(u.data)}`},...l}}else throw new He({functionality:`file part media type ${u.mediaType}`})}}),...o});break}case"assistant":{let u="";const l=[];for(const c of a){const d=Mr(c);switch(c.type){case"text":{u+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)},...d});break}}}n.push({role:"assistant",content:u,tool_calls:l.length>0?l:void 0,...o});break}case"tool":{for(const u of a){if(u.type==="tool-approval-response")continue;const l=u.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(t=l.reason)!=null?t:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}const d=Mr(u);n.push({role:"tool",tool_call_id:u.toolCallId,content:c,...d})}break}default:{const u=r;throw new Error(`Unsupported role: ${u}`)}}}return n}i($w,"convertToOpenAICompatibleChatMessages");function Fm({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(Fm,"getResponseMetadata");function Cm(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"other"}}i(Cm,"mapOpenAICompatibleFinishReason");var $s=g({user:p().optional(),reasoningEffort:p().optional(),textVerbosity:p().optional()});function Tw({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider"?n.push({type:"unsupported",feature:`provider-defined tool ${s.id}`}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:r,toolChoice:a,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=a;throw new He({functionality:`tool choice type: ${s}`})}}}i(Tw,"prepareTools");var Bw=(or=class{constructor(t,n){this.specificationVersion="v3";var r,a;this.modelId=t,this.config=n;const s=(r=n.errorStructure)!=null?r:Pr;this.chunkSchema=Rw(s.errorSchema),this.failedResponseHandler=nt(s),this.supportsStructuredOutputs=(a=n.supportsStructuredOutputs)!=null?a:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:s,frequencyPenalty:o,presencePenalty:u,providerOptions:l,stopSequences:c,responseFormat:d,seed:m,toolChoice:h,tools:D}){var f,v,y,F;const E=[],b=Object.assign((f=await Ue({provider:"openai-compatible",providerOptions:l,schema:$s}))!=null?f:{},(v=await Ue({provider:this.providerOptionsName,providerOptions:l,schema:$s}))!=null?v:{});s!=null&&E.push({type:"unsupported",feature:"topK"}),d?.type==="json"&&d.schema!=null&&!this.supportsStructuredOutputs&&E.push({type:"unsupported",feature:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:w,toolChoice:S,toolWarnings:k}=Tw({tools:D,toolChoice:h});return{args:{model:this.modelId,user:b.user,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,response_format:d?.type==="json"?this.supportsStructuredOutputs===!0&&d.schema!=null?{type:"json_schema",json_schema:{schema:d.schema,name:(y=d.name)!=null?y:"response",description:d.description}}:{type:"json_object"}:void 0,stop:c,seed:m,...Object.fromEntries(Object.entries((F=l?.[this.providerOptionsName])!=null?F:{}).filter(([C])=>!Object.keys($s.shape).includes(C))),reasoning_effort:b.reasoningEffort,verbosity:b.textVerbosity,messages:$w(t),tools:w,tool_choice:S},warnings:[...E,...k]}}async doGenerate(t){var n,r,a,s,o,u;const{args:l,warnings:c}=await this.getArgs({...t}),d=JSON.stringify(l),{responseHeaders:m,value:h,rawValue:D}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:l,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Pe(Sw),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=h.choices[0],v=[],y=f.message.content;y!=null&&y.length>0&&v.push({type:"text",text:y});const F=(n=f.message.reasoning_content)!=null?n:f.message.reasoning;if(F!=null&&F.length>0&&v.push({type:"reasoning",text:F}),f.message.tool_calls!=null)for(const w of f.message.tool_calls)v.push({type:"tool-call",toolCallId:(r=w.id)!=null?r:Be(),toolName:w.function.name,input:w.function.arguments});const E={[this.providerOptionsName]:{},...await((s=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:s.call(a,{parsedBody:D}))},b=(o=h.usage)==null?void 0:o.completion_tokens_details;return b?.accepted_prediction_tokens!=null&&(E[this.providerOptionsName].acceptedPredictionTokens=b?.accepted_prediction_tokens),b?.rejected_prediction_tokens!=null&&(E[this.providerOptionsName].rejectedPredictionTokens=b?.rejected_prediction_tokens),{content:v,finishReason:{unified:Cm(f.finish_reason),raw:(u=f.finish_reason)!=null?u:void 0},usage:_m(h.usage),providerMetadata:E,request:{body:d},response:{...Fm(h),headers:m,body:D},warnings:c}}async doStream(t){var n;const{args:r,warnings:a}=await this.getArgs({...t}),s={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},o=(n=this.config.metadataExtractor)==null?void 0:n.createStreamExtractor(),{responseHeaders:u,value:l}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:fn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let d={unified:"other",raw:void 0},m,h=!0;const D=this.providerOptionsName;let f=!1,v=!1;return{stream:l.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:a})},transform(y,F){var E,b,w,S,k,C,z,W,B,R,O,j,L,P;if(t.includeRawChunks&&F.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){d={unified:"error",raw:void 0},F.enqueue({type:"error",error:y.error});return}if(o?.processChunk(y.rawValue),"error"in y.value){d={unified:"error",raw:void 0},F.enqueue({type:"error",error:y.value.error.message});return}const Z=y.value;h&&(h=!1,F.enqueue({type:"response-metadata",...Fm(Z)})),Z.usage!=null&&(m=Z.usage);const X=Z.choices[0];if(X?.finish_reason!=null&&(d={unified:Cm(X.finish_reason),raw:(E=X.finish_reason)!=null?E:void 0}),X?.delta==null)return;const ce=X.delta,K=(b=ce.reasoning_content)!=null?b:ce.reasoning;if(K&&(f||(F.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),F.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:K})),ce.content&&(v||(F.enqueue({type:"text-start",id:"txt-0"}),v=!0),F.enqueue({type:"text-delta",id:"txt-0",delta:ce.content})),ce.tool_calls!=null)for(const Q of ce.tool_calls){const ee=Q.index;if(c[ee]==null){if(Q.id==null)throw new _r({data:Q,message:"Expected 'id' to be a string."});if(((w=Q.function)==null?void 0:w.name)==null)throw new _r({data:Q,message:"Expected 'function.name' to be a string."});F.enqueue({type:"tool-input-start",id:Q.id,toolName:Q.function.name}),c[ee]={id:Q.id,type:"function",function:{name:Q.function.name,arguments:(S=Q.function.arguments)!=null?S:""},hasFinished:!1};const ie=c[ee];((k=ie.function)==null?void 0:k.name)!=null&&((C=ie.function)==null?void 0:C.arguments)!=null&&(ie.function.arguments.length>0&&F.enqueue({type:"tool-input-delta",id:ie.id,delta:ie.function.arguments}),bo(ie.function.arguments)&&(F.enqueue({type:"tool-input-end",id:ie.id}),F.enqueue({type:"tool-call",toolCallId:(z=ie.id)!=null?z:Be(),toolName:ie.function.name,input:ie.function.arguments}),ie.hasFinished=!0));continue}const oe=c[ee];oe.hasFinished||(((W=Q.function)==null?void 0:W.arguments)!=null&&(oe.function.arguments+=(R=(B=Q.function)==null?void 0:B.arguments)!=null?R:""),F.enqueue({type:"tool-input-delta",id:oe.id,delta:(O=Q.function.arguments)!=null?O:""}),((j=oe.function)==null?void 0:j.name)!=null&&((L=oe.function)==null?void 0:L.arguments)!=null&&bo(oe.function.arguments)&&(F.enqueue({type:"tool-input-end",id:oe.id}),F.enqueue({type:"tool-call",toolCallId:(P=oe.id)!=null?P:Be(),toolName:oe.function.name,input:oe.function.arguments}),oe.hasFinished=!0))}},flush(y){var F,E,b,w,S;f&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),v&&y.enqueue({type:"text-end",id:"txt-0"});for(const C of c.filter(z=>!z.hasFinished))y.enqueue({type:"tool-input-end",id:C.id}),y.enqueue({type:"tool-call",toolCallId:(F=C.id)!=null?F:Be(),toolName:C.function.name,input:C.function.arguments});const k={[D]:{},...o?.buildMetadata()};((E=m?.completion_tokens_details)==null?void 0:E.accepted_prediction_tokens)!=null&&(k[D].acceptedPredictionTokens=(b=m?.completion_tokens_details)==null?void 0:b.accepted_prediction_tokens),((w=m?.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens)!=null&&(k[D].rejectedPredictionTokens=(S=m?.completion_tokens_details)==null?void 0:S.rejected_prediction_tokens),y.enqueue({type:"finish",finishReason:d,usage:_m(m),providerMetadata:k})}})),request:{body:s},response:{headers:u}}}},i(or,"OpenAICompatibleChatLanguageModel"),or),bm=g({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:g({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish(),Sw=g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({message:g({role:I("assistant").nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:T(g({id:p().nullish(),function:g({name:p(),arguments:p()})})).nullish()}),finish_reason:p().nullish()})),usage:bm}),Ow=g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({delta:g({role:re(["assistant"]).nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:T(g({index:A(),id:p().nullish(),function:g({name:p().nullish(),arguments:p().nullish()})})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:bm}),Rw=i(e=>H([Ow,e]),"createOpenAICompatibleChatChunkSchema");function Em(e){var t,n;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const r=(t=e.prompt_tokens)!=null?t:0,a=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:r,noCache:r,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:a,text:a,reasoning:void 0},raw:e}}i(Em,"convertOpenAICompatibleCompletionUsage");function Nw({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
160
+ ${t}:`]}}i(gE,"convertToOpenAICompletionPrompt");function nm({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(nm,"getResponseMetadata2$1");function rm(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"other"}}i(rm,"mapOpenAIFinishReason2");var vE=J(()=>G(g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({text:p(),finish_reason:p(),logprobs:g({tokens:T(p()),token_logprobs:T(A()),top_logprobs:T(me(p(),A())).nullish()}).nullish()})),usage:g({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}))),yE=J(()=>G(H([g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({text:p(),finish_reason:p().nullish(),index:A(),logprobs:g({tokens:T(p()),token_logprobs:T(A()),top_logprobs:T(me(p(),A())).nullish()}).nullish()})),usage:g({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}),Is]))),om=J(()=>G(g({echo:Ae().optional(),logitBias:me(p(),A()).optional(),suffix:p().optional(),user:p().optional(),logprobs:H([Ae(),A()]).optional()}))),_E=(Xn=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=n}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:s,frequencyPenalty:o,presencePenalty:u,stopSequences:l,responseFormat:c,tools:d,toolChoice:m,seed:h,providerOptions:D}){const f=[],v={...await Le({provider:"openai",providerOptions:D,schema:om}),...await Le({provider:this.providerOptionsName,providerOptions:D,schema:om})};s!=null&&f.push({type:"unsupported",feature:"topK"}),d?.length&&f.push({type:"unsupported",feature:"tools"}),m!=null&&f.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&f.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:F}=gE({prompt:t}),E=[...F??[],...l??[]];return{args:{model:this.modelId,echo:v.echo,logit_bias:v.logitBias,logprobs:v?.logprobs===!0?0:v?.logprobs===!1?void 0:v?.logprobs,suffix:v.suffix,user:v.user,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,seed:h,prompt:y,stop:E.length>0?E:void 0},warnings:f}}async doGenerate(t){var n;const{args:r,warnings:a}=await this.getArgs(t),{responseHeaders:s,value:o,rawValue:u}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:r,failedResponseHandler:pt,successfulResponseHandler:Pe(vE),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=o.choices[0],c={openai:{}};return l.logprobs!=null&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:tm(o.usage),finishReason:{unified:rm(l.finish_reason),raw:(n=l.finish_reason)!=null?n:void 0},request:{body:r},response:{...nm(o),headers:s,body:u},providerMetadata:c,warnings:a}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),a={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:a,failedResponseHandler:pt,successfulResponseHandler:fn(yE),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0};const l={openai:{}};let c,d=!0;return{stream:o.pipeThrough(new TransformStream({start(m){m.enqueue({type:"stream-start",warnings:r})},transform(m,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:m.rawValue}),!m.success){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:m.error});return}const D=m.value;if("error"in D){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:D.error});return}d&&(d=!1,h.enqueue({type:"response-metadata",...nm(D)}),h.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(c=D.usage);const f=D.choices[0];f?.finish_reason!=null&&(u={unified:rm(f.finish_reason),raw:f.finish_reason}),f?.logprobs!=null&&(l.openai.logprobs=f.logprobs),f?.text!=null&&f.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(m){d||m.enqueue({type:"text-end",id:"0"}),m.enqueue({type:"finish",finishReason:u,providerMetadata:l,usage:tm(c)})}})),request:{body:a},response:{headers:s}}}},i(Xn,"OpenAICompletionLanguageModel"),Xn),FE=J(()=>G(g({dimensions:A().optional(),user:p().optional()}))),CE=J(()=>G(g({data:T(g({embedding:T(A())})),usage:g({prompt_tokens:A()}).nullish()}))),bE=(Qn=class{constructor(t,n){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=n}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:a}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new ql({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const o=(s=await Le({provider:"openai",providerOptions:a,schema:FE}))!=null?s:{},{responseHeaders:u,value:l,rawValue:c}=await Se({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:xe(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:pt,successfulResponseHandler:Pe(CE),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.data.map(d=>d.embedding),usage:l.usage?{tokens:l.usage.prompt_tokens}:void 0,response:{headers:u,body:c}}}},i(Qn,"OpenAIEmbeddingModel"),Qn),am=J(()=>G(g({created:A().nullish(),data:T(g({b64_json:p(),revised_prompt:p().nullish()})),background:p().nullish(),output_format:p().nullish(),size:p().nullish(),quality:p().nullish(),usage:g({input_tokens:A().nullish(),output_tokens:A().nullish(),total_tokens:A().nullish(),input_tokens_details:g({image_tokens:A().nullish(),text_tokens:A().nullish()}).nullish()}).nullish()}))),EE={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},wE=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),AE=(er=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=EE[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:n,mask:r,n:a,size:s,aspectRatio:o,seed:u,providerOptions:l,headers:c,abortSignal:d}){var m,h,D,f,v,y,F,E,b,w,S;const k=[];o!=null&&k.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),u!=null&&k.push({type:"unsupported",feature:"seed"});const C=(D=(h=(m=this.config._internal)==null?void 0:m.currentDate)==null?void 0:h.call(m))!=null?D:new Date;if(n!=null){const{value:B,responseHeaders:R}=await as({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:xe(this.config.headers(),c),formData:qc({model:this.modelId,prompt:t,image:await Promise.all(n.map(O=>O.type==="file"?new Blob([O.data instanceof Uint8Array?new Blob([O.data],{type:O.mediaType}):new Blob([Lt(O.data)],{type:O.mediaType})],{type:O.mediaType}):Xa(O.url))),mask:r!=null?await IE(r):void 0,n:a,size:s,...(f=l.openai)!=null?f:{}}),failedResponseHandler:pt,successfulResponseHandler:Pe(am),abortSignal:d,fetch:this.config.fetch});return{images:B.data.map(O=>O.b64_json),warnings:k,usage:B.usage!=null?{inputTokens:(v=B.usage.input_tokens)!=null?v:void 0,outputTokens:(y=B.usage.output_tokens)!=null?y:void 0,totalTokens:(F=B.usage.total_tokens)!=null?F:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:R},providerMetadata:{openai:{images:B.data.map(O=>{var j,U,P,Z,X;return{...O.revised_prompt?{revisedPrompt:O.revised_prompt}:{},created:(j=B.created)!=null?j:void 0,size:(U=B.size)!=null?U:void 0,quality:(P=B.quality)!=null?P:void 0,background:(Z=B.background)!=null?Z:void 0,outputFormat:(X=B.output_format)!=null?X:void 0}})}}}}const{value:z,responseHeaders:W}=await Se({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:xe(this.config.headers(),c),body:{model:this.modelId,prompt:t,n:a,size:s,...(E=l.openai)!=null?E:{},...wE.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:pt,successfulResponseHandler:Pe(am),abortSignal:d,fetch:this.config.fetch});return{images:z.data.map(B=>B.b64_json),warnings:k,usage:z.usage!=null?{inputTokens:(b=z.usage.input_tokens)!=null?b:void 0,outputTokens:(w=z.usage.output_tokens)!=null?w:void 0,totalTokens:(S=z.usage.total_tokens)!=null?S:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:W},providerMetadata:{openai:{images:z.data.map(B=>{var R,O,j,U,P;return{...B.revised_prompt?{revisedPrompt:B.revised_prompt}:{},created:(R=z.created)!=null?R:void 0,size:(O=z.size)!=null?O:void 0,quality:(j=z.quality)!=null?j:void 0,background:(U=z.background)!=null?U:void 0,outputFormat:(P=z.output_format)!=null?P:void 0}})}}}}},i(er,"OpenAIImageModel"),er);async function IE(e){if(!e)return;if(e.type==="url")return Xa(e.url);const t=e.data instanceof Uint8Array?e.data:Lt(e.data);return new Blob([t],{type:e.mediaType})}i(IE,"fileToBlob$1");var xE=J(()=>G(g({callId:p(),operation:Ie("type",[g({type:I("create_file"),path:p(),diff:p()}),g({type:I("delete_file"),path:p()}),g({type:I("update_file"),path:p(),diff:p()})])}))),sm=J(()=>G(g({status:re(["completed","failed"]),output:p().optional()}))),kE=yt({id:"openai.apply_patch",inputSchema:xE,outputSchema:sm}),$E=kE,TE=J(()=>G(g({code:p().nullish(),containerId:p()}))),BE=J(()=>G(g({outputs:T(Ie("type",[g({type:I("logs"),logs:p()}),g({type:I("image"),url:p()})])).nullish()}))),SE=J(()=>G(g({container:H([p(),g({fileIds:T(p()).optional()})]).optional()}))),OE=yt({id:"openai.code_interpreter",inputSchema:TE,outputSchema:BE}),RE=i((e={})=>OE(e),"codeInterpreter"),im=g({key:p(),type:re(["eq","ne","gt","gte","lt","lte","in","nin"]),value:H([p(),A(),Ae(),T(p())])}),um=g({type:re(["and","or"]),filters:T(H([im,Ha(()=>um)]))}),NE=J(()=>G(g({vectorStoreIds:T(p()),maxNumResults:A().optional(),ranking:g({ranker:p().optional(),scoreThreshold:A().optional()}).optional(),filters:H([im,um]).optional()}))),PE=J(()=>G(g({queries:T(p()),results:T(g({attributes:me(p(),gt()),fileId:p(),filename:p(),score:A(),text:p()})).nullable()}))),ME=yt({id:"openai.file_search",inputSchema:g({}),outputSchema:PE}),jE=J(()=>G(g({background:re(["auto","opaque","transparent"]).optional(),inputFidelity:re(["low","high"]).optional(),inputImageMask:g({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:re(["auto"]).optional(),outputCompression:A().int().min(0).max(100).optional(),outputFormat:re(["png","jpeg","webp"]).optional(),partialImages:A().int().min(0).max(3).optional(),quality:re(["auto","low","medium","high"]).optional(),size:re(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),zE=J(()=>G(g({}))),qE=J(()=>G(g({result:p()}))),ZE=yt({id:"openai.image_generation",inputSchema:zE,outputSchema:qE}),UE=i((e={})=>ZE(e),"imageGeneration"),lm=J(()=>G(g({action:g({type:I("exec"),command:T(p()),timeoutMs:A().optional(),user:p().optional(),workingDirectory:p().optional(),env:me(p(),p()).optional()})}))),cm=J(()=>G(g({output:p()}))),LE=yt({id:"openai.local_shell",inputSchema:lm,outputSchema:cm}),pm=J(()=>G(g({action:g({commands:T(p()),timeoutMs:A().optional(),maxOutputLength:A().optional()})}))),dm=J(()=>G(g({output:T(g({stdout:p(),stderr:p(),outcome:Ie("type",[g({type:I("timeout")}),g({type:I("exit"),exitCode:A()})])}))}))),VE=yt({id:"openai.shell",inputSchema:pm,outputSchema:dm}),GE=J(()=>G(g({externalWebAccess:Ae().optional(),filters:g({allowedDomains:T(p()).optional()}).optional(),searchContextSize:re(["low","medium","high"]).optional(),userLocation:g({type:I("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),WE=J(()=>G(g({}))),HE=J(()=>G(g({action:Ie("type",[g({type:I("search"),query:p().optional()}),g({type:I("openPage"),url:p().nullish()}),g({type:I("findInPage"),url:p().nullish(),pattern:p().nullish()})]),sources:T(Ie("type",[g({type:I("url"),url:p()}),g({type:I("api"),name:p()})])).optional()}))),JE=yt({id:"openai.web_search",inputSchema:WE,outputSchema:HE}),KE=i((e={})=>JE(e),"webSearch"),YE=J(()=>G(g({searchContextSize:re(["low","medium","high"]).optional(),userLocation:g({type:I("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),XE=J(()=>G(g({}))),QE=J(()=>G(g({action:Ie("type",[g({type:I("search"),query:p().optional()}),g({type:I("openPage"),url:p().nullish()}),g({type:I("findInPage"),url:p().nullish(),pattern:p().nullish()})])}))),ew=yt({id:"openai.web_search_preview",inputSchema:XE,outputSchema:QE}),ks=Ha(()=>H([p(),A(),Ae(),Sc(),T(ks),me(p(),ks)])),tw=J(()=>G(g({serverLabel:p(),allowedTools:H([T(p()),g({readOnly:Ae().optional(),toolNames:T(p()).optional()})]).optional(),authorization:p().optional(),connectorId:p().optional(),headers:me(p(),p()).optional(),requireApproval:H([re(["always","never"]),g({never:g({toolNames:T(p()).optional()}).optional()})]).optional(),serverDescription:p().optional(),serverUrl:p().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),nw=J(()=>G(g({}))),rw=J(()=>G(g({type:I("call"),serverLabel:p(),name:p(),arguments:p(),output:p().nullish(),error:H([p(),ks]).optional()}))),ow=yt({id:"openai.mcp",inputSchema:nw,outputSchema:rw}),aw=i(e=>ow(e),"mcp"),sw={applyPatch:$E,codeInterpreter:RE,fileSearch:ME,imageGeneration:UE,localShell:LE,shell:VE,webSearchPreview:ew,webSearch:KE,mcp:aw};function mm(e){var t,n,r,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,o=e.output_tokens,u=(n=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?n:0,l=(a=(r=e.output_tokens_details)==null?void 0:r.reasoning_tokens)!=null?a:0;return{inputTokens:{total:s,noCache:s-u,cacheRead:u,cacheWrite:void 0},outputTokens:{total:o,text:o-l,reasoning:l},raw:e}}i(mm,"convertOpenAIResponsesUsage");function fm(e,t){return t?t.some(n=>e.startsWith(n)):!1}i(fm,"isFileId");async function iw({prompt:e,toolNameMapping:t,systemMessageMode:n,providerOptionsName:r,fileIdPrefixes:a,store:s,hasLocalShellTool:o=!1,hasShellTool:u=!1,hasApplyPatchTool:l=!1}){var c,d,m,h,D,f,v,y,F,E,b,w,S;const k=[],C=[],z=new Set;for(const{role:W,content:B}of e)switch(W){case"system":{switch(n){case"system":{k.push({role:"system",content:B});break}case"developer":{k.push({role:"developer",content:B});break}case"remove":{C.push({type:"other",message:"system messages are removed for this model"});break}default:{const R=n;throw new Error(`Unsupported system message mode: ${R}`)}}break}case"user":{k.push({role:"user",content:B.map((R,O)=>{var j,U,P;switch(R.type){case"text":return{type:"input_text",text:R.text};case"file":if(R.mediaType.startsWith("image/")){const Z=R.mediaType==="image/*"?"image/jpeg":R.mediaType;return{type:"input_image",...R.data instanceof URL?{image_url:R.data.toString()}:typeof R.data=="string"&&fm(R.data,a)?{file_id:R.data}:{image_url:`data:${Z};base64,${Vt(R.data)}`},detail:(U=(j=R.providerOptions)==null?void 0:j[r])==null?void 0:U.imageDetail}}else{if(R.mediaType==="application/pdf")return R.data instanceof URL?{type:"input_file",file_url:R.data.toString()}:{type:"input_file",...typeof R.data=="string"&&fm(R.data,a)?{file_id:R.data}:{filename:(P=R.filename)!=null?P:`part-${O}.pdf`,file_data:`data:application/pdf;base64,${Vt(R.data)}`}};throw new He({functionality:`file part media type ${R.mediaType}`})}}})});break}case"assistant":{const R={};for(const O of B)switch(O.type){case"text":{const j=(d=(c=O.providerOptions)==null?void 0:c[r])==null?void 0:d.itemId;if(s&&j!=null){k.push({type:"item_reference",id:j});break}k.push({role:"assistant",content:[{type:"output_text",text:O.text}],id:j});break}case"tool-call":{const j=(v=(h=(m=O.providerOptions)==null?void 0:m[r])==null?void 0:h.itemId)!=null?v:(f=(D=O.providerMetadata)==null?void 0:D[r])==null?void 0:f.itemId;if(O.providerExecuted){s&&j!=null&&k.push({type:"item_reference",id:j});break}if(s&&j!=null){k.push({type:"item_reference",id:j});break}const U=t.toProviderToolName(O.toolName);if(o&&U==="local_shell"){const P=await et({value:O.input,schema:lm});k.push({type:"local_shell_call",call_id:O.toolCallId,id:j,action:{type:"exec",command:P.action.command,timeout_ms:P.action.timeoutMs,user:P.action.user,working_directory:P.action.workingDirectory,env:P.action.env}});break}if(u&&U==="shell"){const P=await et({value:O.input,schema:pm});k.push({type:"shell_call",call_id:O.toolCallId,id:j,status:"completed",action:{commands:P.action.commands,timeout_ms:P.action.timeoutMs,max_output_length:P.action.maxOutputLength}});break}k.push({type:"function_call",call_id:O.toolCallId,name:U,arguments:JSON.stringify(O.input),id:j});break}case"tool-result":{if(O.output.type==="execution-denied"||O.output.type==="json"&&typeof O.output.value=="object"&&O.output.value!=null&&"type"in O.output.value&&O.output.value.type==="execution-denied")break;if(s){const j=(E=(F=(y=O.providerMetadata)==null?void 0:y[r])==null?void 0:F.itemId)!=null?E:O.toolCallId;k.push({type:"item_reference",id:j})}else C.push({type:"other",message:`Results for OpenAI tool ${O.toolName} are not sent to the API when store is false`});break}case"reasoning":{const j=await Le({provider:r,providerOptions:O.providerOptions,schema:uw}),U=j?.itemId;if(U!=null){const P=R[U];if(s)P===void 0&&(k.push({type:"item_reference",id:U}),R[U]={type:"reasoning",id:U,summary:[]});else{const Z=[];O.text.length>0?Z.push({type:"summary_text",text:O.text}):P!==void 0&&C.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(O)}.`}),P===void 0?(R[U]={type:"reasoning",id:U,encrypted_content:j?.reasoningEncryptedContent,summary:Z},k.push(R[U])):(P.summary.push(...Z),j?.reasoningEncryptedContent!=null&&(P.encrypted_content=j.reasoningEncryptedContent))}}else C.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(O)}.`});break}}break}case"tool":{for(const R of B){if(R.type==="tool-approval-response"){const P=R;if(z.has(P.approvalId))continue;z.add(P.approvalId),s&&k.push({type:"item_reference",id:P.approvalId}),k.push({type:"mcp_approval_response",approval_request_id:P.approvalId,approve:P.approved});continue}const O=R.output;if(O.type==="execution-denied"&&((w=(b=O.providerOptions)==null?void 0:b.openai)==null?void 0:w.approvalId))continue;const j=t.toProviderToolName(R.toolName);if(o&&j==="local_shell"&&O.type==="json"){const P=await et({value:O.value,schema:cm});k.push({type:"local_shell_call_output",call_id:R.toolCallId,output:P.output});continue}if(u&&j==="shell"&&O.type==="json"){const P=await et({value:O.value,schema:dm});k.push({type:"shell_call_output",call_id:R.toolCallId,output:P.output.map(Z=>({stdout:Z.stdout,stderr:Z.stderr,outcome:Z.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Z.outcome.exitCode}}))});continue}if(l&&R.toolName==="apply_patch"&&O.type==="json"){const P=await et({value:O.value,schema:sm});k.push({type:"apply_patch_call_output",call_id:R.toolCallId,status:P.status,output:P.output});continue}let U;switch(O.type){case"text":case"error-text":U=O.value;break;case"execution-denied":U=(S=O.reason)!=null?S:"Tool execution denied.";break;case"json":case"error-json":U=JSON.stringify(O.value);break;case"content":U=O.value.map(P=>{var Z;switch(P.type){case"text":return{type:"input_text",text:P.text};case"image-data":return{type:"input_image",image_url:`data:${P.mediaType};base64,${P.data}`};case"file-data":return{type:"input_file",filename:(Z=P.filename)!=null?Z:"data",file_data:`data:${P.mediaType};base64,${P.data}`};default:{C.push({type:"other",message:`unsupported tool content part type: ${P.type}`});return}}}).filter(EF);break}k.push({type:"function_call_output",call_id:R.toolCallId,output:U})}break}default:{const R=W;throw new Error(`Unsupported role: ${R}`)}}return{input:k,warnings:C}}i(iw,"convertToOpenAIResponsesInput");var uw=g({itemId:p().nullish(),reasoningEncryptedContent:p().nullish()});function hm({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":"other"}}i(hm,"mapOpenAIResponseFinishReason");var lw=J(()=>G(H([g({type:I("response.output_text.delta"),item_id:p(),delta:p(),logprobs:T(g({token:p(),logprob:A(),top_logprobs:T(g({token:p(),logprob:A()}))})).nullish()}),g({type:re(["response.completed","response.incomplete"]),response:g({incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:A(),input_tokens_details:g({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:g({reasoning_tokens:A().nullish()}).nullish()}),service_tier:p().nullish()})}),g({type:I("response.created"),response:g({id:p(),created_at:A(),model:p(),service_tier:p().nullish()})}),g({type:I("response.output_item.added"),output_index:A(),item:Ie("type",[g({type:I("message"),id:p()}),g({type:I("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:I("function_call"),id:p(),call_id:p(),name:p(),arguments:p()}),g({type:I("web_search_call"),id:p(),status:p()}),g({type:I("computer_call"),id:p(),status:p()}),g({type:I("file_search_call"),id:p()}),g({type:I("image_generation_call"),id:p()}),g({type:I("code_interpreter_call"),id:p(),container_id:p(),code:p().nullable(),outputs:T(Ie("type",[g({type:I("logs"),logs:p()}),g({type:I("image"),url:p()})])).nullable(),status:p()}),g({type:I("mcp_call"),id:p(),status:p(),approval_request_id:p().nullish()}),g({type:I("mcp_list_tools"),id:p()}),g({type:I("mcp_approval_request"),id:p()}),g({type:I("apply_patch_call"),id:p(),call_id:p(),status:re(["in_progress","completed"]),operation:Ie("type",[g({type:I("create_file"),path:p(),diff:p()}),g({type:I("delete_file"),path:p()}),g({type:I("update_file"),path:p(),diff:p()})])}),g({type:I("shell_call"),id:p(),call_id:p(),status:re(["in_progress","completed","incomplete"]),action:g({commands:T(p())})})])}),g({type:I("response.output_item.done"),output_index:A(),item:Ie("type",[g({type:I("message"),id:p()}),g({type:I("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:I("function_call"),id:p(),call_id:p(),name:p(),arguments:p(),status:I("completed")}),g({type:I("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:T(Ie("type",[g({type:I("logs"),logs:p()}),g({type:I("image"),url:p()})])).nullable()}),g({type:I("image_generation_call"),id:p(),result:p()}),g({type:I("web_search_call"),id:p(),status:p(),action:Ie("type",[g({type:I("search"),query:p().nullish(),sources:T(Ie("type",[g({type:I("url"),url:p()}),g({type:I("api"),name:p()})])).nullish()}),g({type:I("open_page"),url:p().nullish()}),g({type:I("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:I("file_search_call"),id:p(),queries:T(p()),results:T(g({attributes:me(p(),H([p(),A(),Ae()])),file_id:p(),filename:p(),score:A(),text:p()})).nullish()}),g({type:I("local_shell_call"),id:p(),call_id:p(),action:g({type:I("exec"),command:T(p()),timeout_ms:A().optional(),user:p().optional(),working_directory:p().optional(),env:me(p(),p()).optional()})}),g({type:I("computer_call"),id:p(),status:I("completed")}),g({type:I("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:H([p(),g({type:p().optional(),code:H([A(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:I("mcp_list_tools"),id:p(),server_label:p(),tools:T(g({name:p(),description:p().optional(),input_schema:qe(),annotations:me(p(),gt()).optional()})),error:H([p(),g({type:p().optional(),code:H([A(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:I("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:I("apply_patch_call"),id:p(),call_id:p(),status:re(["in_progress","completed"]),operation:Ie("type",[g({type:I("create_file"),path:p(),diff:p()}),g({type:I("delete_file"),path:p()}),g({type:I("update_file"),path:p(),diff:p()})])}),g({type:I("shell_call"),id:p(),call_id:p(),status:re(["in_progress","completed","incomplete"]),action:g({commands:T(p())})})])}),g({type:I("response.function_call_arguments.delta"),item_id:p(),output_index:A(),delta:p()}),g({type:I("response.image_generation_call.partial_image"),item_id:p(),output_index:A(),partial_image_b64:p()}),g({type:I("response.code_interpreter_call_code.delta"),item_id:p(),output_index:A(),delta:p()}),g({type:I("response.code_interpreter_call_code.done"),item_id:p(),output_index:A(),code:p()}),g({type:I("response.output_text.annotation.added"),annotation:Ie("type",[g({type:I("url_citation"),start_index:A(),end_index:A(),url:p(),title:p()}),g({type:I("file_citation"),file_id:p(),filename:p().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:p().nullish()}),g({type:I("container_file_citation"),container_id:p(),file_id:p(),filename:p().nullish(),start_index:A().nullish(),end_index:A().nullish(),index:A().nullish()}),g({type:I("file_path"),file_id:p(),index:A().nullish()})])}),g({type:I("response.reasoning_summary_part.added"),item_id:p(),summary_index:A()}),g({type:I("response.reasoning_summary_text.delta"),item_id:p(),summary_index:A(),delta:p()}),g({type:I("response.reasoning_summary_part.done"),item_id:p(),summary_index:A()}),g({type:I("response.apply_patch_call_operation_diff.delta"),item_id:p(),output_index:A(),delta:p(),obfuscation:p().nullish()}),g({type:I("response.apply_patch_call_operation_diff.done"),item_id:p(),output_index:A(),diff:p()}),g({type:I("error"),sequence_number:A(),error:g({type:p(),code:p(),message:p(),param:p().nullish()})}),g({type:p()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),cw=J(()=>G(g({id:p().optional(),created_at:A().optional(),error:g({message:p(),type:p(),param:p().nullish(),code:p()}).nullish(),model:p().optional(),output:T(Ie("type",[g({type:I("message"),role:I("assistant"),id:p(),content:T(g({type:I("output_text"),text:p(),logprobs:T(g({token:p(),logprob:A(),top_logprobs:T(g({token:p(),logprob:A()}))})).nullish(),annotations:T(Ie("type",[g({type:I("url_citation"),start_index:A(),end_index:A(),url:p(),title:p()}),g({type:I("file_citation"),file_id:p(),filename:p().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:p().nullish()}),g({type:I("container_file_citation"),container_id:p(),file_id:p(),filename:p().nullish(),start_index:A().nullish(),end_index:A().nullish(),index:A().nullish()}),g({type:I("file_path"),file_id:p(),index:A().nullish()})]))}))}),g({type:I("web_search_call"),id:p(),status:p(),action:Ie("type",[g({type:I("search"),query:p().nullish(),sources:T(Ie("type",[g({type:I("url"),url:p()}),g({type:I("api"),name:p()})])).nullish()}),g({type:I("open_page"),url:p().nullish()}),g({type:I("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:I("file_search_call"),id:p(),queries:T(p()),results:T(g({attributes:me(p(),H([p(),A(),Ae()])),file_id:p(),filename:p(),score:A(),text:p()})).nullish()}),g({type:I("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:T(Ie("type",[g({type:I("logs"),logs:p()}),g({type:I("image"),url:p()})])).nullable()}),g({type:I("image_generation_call"),id:p(),result:p()}),g({type:I("local_shell_call"),id:p(),call_id:p(),action:g({type:I("exec"),command:T(p()),timeout_ms:A().optional(),user:p().optional(),working_directory:p().optional(),env:me(p(),p()).optional()})}),g({type:I("function_call"),call_id:p(),name:p(),arguments:p(),id:p()}),g({type:I("computer_call"),id:p(),status:p().optional()}),g({type:I("reasoning"),id:p(),encrypted_content:p().nullish(),summary:T(g({type:I("summary_text"),text:p()}))}),g({type:I("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:H([p(),g({type:p().optional(),code:H([A(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:I("mcp_list_tools"),id:p(),server_label:p(),tools:T(g({name:p(),description:p().optional(),input_schema:qe(),annotations:me(p(),gt()).optional()})),error:H([p(),g({type:p().optional(),code:H([A(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:I("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:I("apply_patch_call"),id:p(),call_id:p(),status:re(["in_progress","completed"]),operation:Ie("type",[g({type:I("create_file"),path:p(),diff:p()}),g({type:I("delete_file"),path:p()}),g({type:I("update_file"),path:p(),diff:p()})])}),g({type:I("shell_call"),id:p(),call_id:p(),status:re(["in_progress","completed","incomplete"]),action:g({commands:T(p())})})])).optional(),service_tier:p().nullish(),incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:A(),input_tokens_details:g({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:g({reasoning_tokens:A().nullish()}).nullish()}).optional()}))),Dm=20,gm=J(()=>G(g({conversation:p().nullish(),include:T(re(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:H([Ae(),A().min(1).max(Dm)]).optional(),maxToolCalls:A().nullish(),metadata:qe().nullish(),parallelToolCalls:Ae().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:re(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:re(["auto","flex","priority","default"]).nullish(),store:Ae().nullish(),strictJsonSchema:Ae().nullish(),textVerbosity:re(["low","medium","high"]).nullish(),truncation:re(["auto","disabled"]).nullish(),user:p().nullish(),systemMessageMode:re(["system","developer","remove"]).optional(),forceReasoning:Ae().optional()})));async function pw({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const o=await et({value:s.args,schema:NE});r.push({type:"file_search",vector_store_ids:o.vectorStoreIds,max_num_results:o.maxNumResults,ranking_options:o.ranking?{ranker:o.ranking.ranker,score_threshold:o.ranking.scoreThreshold}:void 0,filters:o.filters});break}case"openai.local_shell":{r.push({type:"local_shell"});break}case"openai.shell":{r.push({type:"shell"});break}case"openai.apply_patch":{r.push({type:"apply_patch"});break}case"openai.web_search_preview":{const o=await et({value:s.args,schema:YE});r.push({type:"web_search_preview",search_context_size:o.searchContextSize,user_location:o.userLocation});break}case"openai.web_search":{const o=await et({value:s.args,schema:GE});r.push({type:"web_search",filters:o.filters!=null?{allowed_domains:o.filters.allowedDomains}:void 0,external_web_access:o.externalWebAccess,search_context_size:o.searchContextSize,user_location:o.userLocation});break}case"openai.code_interpreter":{const o=await et({value:s.args,schema:SE});r.push({type:"code_interpreter",container:o.container==null?{type:"auto",file_ids:void 0}:typeof o.container=="string"?o.container:{type:"auto",file_ids:o.container.fileIds}});break}case"openai.image_generation":{const o=await et({value:s.args,schema:jE});r.push({type:"image_generation",background:o.background,input_fidelity:o.inputFidelity,input_image_mask:o.inputImageMask?{file_id:o.inputImageMask.fileId,image_url:o.inputImageMask.imageUrl}:void 0,model:o.model,moderation:o.moderation,partial_images:o.partialImages,quality:o.quality,output_compression:o.outputCompression,output_format:o.outputFormat,size:o.size});break}case"openai.mcp":{const o=await et({value:s.args,schema:tw}),u=i(d=>({tool_names:d.toolNames}),"mapApprovalFilter"),l=o.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:u(l.never)}:void 0;r.push({type:"mcp",server_label:o.serverLabel,allowed_tools:Array.isArray(o.allowedTools)?o.allowedTools:o.allowedTools?{read_only:o.allowedTools.readOnly,tool_names:o.allowedTools.toolNames}:void 0,authorization:o.authorization,connector_id:o.connectorId,headers:o.headers,require_approval:c??"never",server_description:o.serverDescription,server_url:o.serverUrl});break}}break}default:n.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:r,toolChoice:a,toolWarnings:n};case"tool":return{tools:r,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const s=a;throw new He({functionality:`tool choice type: ${s}`})}}}i(pw,"prepareResponsesTools");function vm(e){var t,n;const r={};for(const a of e)if(a.role==="assistant")for(const s of a.content){if(s.type!=="tool-call")continue;const o=(n=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:n.approvalRequestId;o!=null&&(r[o]=s.toolCallId)}return r}i(vm,"extractApprovalRequestIdToToolCallIdMapping");var dw=(tr=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:n,stopSequences:r,topP:a,topK:s,presencePenalty:o,frequencyPenalty:u,seed:l,prompt:c,providerOptions:d,tools:m,toolChoice:h,responseFormat:D}){var f,v,y,F,E,b;const w=[],S=Xd(this.modelId);s!=null&&w.push({type:"unsupported",feature:"topK"}),l!=null&&w.push({type:"unsupported",feature:"seed"}),o!=null&&w.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&w.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&w.push({type:"unsupported",feature:"stopSequences"});const k=this.config.provider.includes("azure")?"azure":"openai";let C=await Le({provider:k,providerOptions:d,schema:gm});C==null&&k!=="openai"&&(C=await Le({provider:"openai",providerOptions:d,schema:gm}));const z=(f=C?.forceReasoning)!=null?f:S.isReasoningModel;C?.conversation&&C?.previousResponseId&&w.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const W=DF({tools:m,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:B,warnings:R}=await iw({prompt:c,toolNameMapping:W,systemMessageMode:(v=C?.systemMessageMode)!=null?v:z?"developer":S.systemMessageMode,providerOptionsName:k,fileIdPrefixes:this.config.fileIdPrefixes,store:(y=C?.store)!=null?y:!0,hasLocalShellTool:P("openai.local_shell"),hasShellTool:P("openai.shell"),hasApplyPatchTool:P("openai.apply_patch")});w.push(...R);const O=(F=C?.strictJsonSchema)!=null?F:!0;let j=C?.include;function U(ie){j==null?j=[ie]:j.includes(ie)||(j=[...j,ie])}i(U,"addInclude");function P(ie){return m?.find(rt=>rt.type==="provider"&&rt.id===ie)!=null}i(P,"hasOpenAITool");const Z=typeof C?.logprobs=="number"?C?.logprobs:C?.logprobs===!0?Dm:void 0;Z&&U("message.output_text.logprobs");const X=(E=m?.find(ie=>ie.type==="provider"&&(ie.id==="openai.web_search"||ie.id==="openai.web_search_preview")))==null?void 0:E.name;X&&U("web_search_call.action.sources"),P("openai.code_interpreter")&&U("code_interpreter_call.outputs");const ce=C?.store;ce===!1&&z&&U("reasoning.encrypted_content");const K={model:this.modelId,input:B,temperature:n,top_p:a,max_output_tokens:t,...(D?.type==="json"||C?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:O,name:(b=D.name)!=null?b:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...C?.textVerbosity&&{verbosity:C.textVerbosity}}},conversation:C?.conversation,max_tool_calls:C?.maxToolCalls,metadata:C?.metadata,parallel_tool_calls:C?.parallelToolCalls,previous_response_id:C?.previousResponseId,store:ce,user:C?.user,instructions:C?.instructions,service_tier:C?.serviceTier,include:j,prompt_cache_key:C?.promptCacheKey,prompt_cache_retention:C?.promptCacheRetention,safety_identifier:C?.safetyIdentifier,top_logprobs:Z,truncation:C?.truncation,...z&&(C?.reasoningEffort!=null||C?.reasoningSummary!=null)&&{reasoning:{...C?.reasoningEffort!=null&&{effort:C.reasoningEffort},...C?.reasoningSummary!=null&&{summary:C.reasoningSummary}}}};z?C?.reasoningEffort==="none"&&S.supportsNonReasoningParameters||(K.temperature!=null&&(K.temperature=void 0,w.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),K.top_p!=null&&(K.top_p=void 0,w.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(C?.reasoningEffort!=null&&w.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),C?.reasoningSummary!=null&&w.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),C?.serviceTier==="flex"&&!S.supportsFlexProcessing&&(w.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete K.service_tier),C?.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(w.push({type:"unsupported",feature:"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 K.service_tier);const{tools:Q,toolChoice:ee,toolWarnings:oe}=await pw({tools:m,toolChoice:h});return{webSearchToolName:X,args:{...K,tools:Q,tool_choice:ee},warnings:[...w,...oe],store:ce,toolNameMapping:W,providerOptionsName:k}}async doGenerate(t){var n,r,a,s,o,u,l,c,d,m,h,D,f,v,y,F,E,b,w,S,k,C,z,W,B,R,O,j,U,P,Z;const{args:X,warnings:ce,webSearchToolName:K,toolNameMapping:Q,providerOptionsName:ee}=await this.getArgs(t),oe=this.config.url({path:"/responses",modelId:this.modelId}),ie=vm(t.prompt),{responseHeaders:rt,value:Oe,rawValue:Ft}=await Se({url:oe,headers:xe(this.config.headers(),t.headers),body:X,failedResponseHandler:pt,successfulResponseHandler:Pe(cw),abortSignal:t.abortSignal,fetch:this.config.fetch});if(Oe.error)throw new Re({message:Oe.error.message,url:oe,requestBodyValues:X,statusCode:400,responseHeaders:rt,responseBody:Ft,isRetryable:!1});const ae=[],dt=[];let ot=!1;for(const M of Oe.output)switch(M.type){case"reasoning":{M.summary.length===0&&M.summary.push({type:"summary_text",text:""});for(const he of M.summary)ae.push({type:"reasoning",text:he.text,providerMetadata:{[ee]:{itemId:M.id,reasoningEncryptedContent:(n=M.encrypted_content)!=null?n:null}}});break}case"image_generation_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName("image_generation"),result:{result:M.result}});break}case"local_shell_call":{ae.push({type:"tool-call",toolCallId:M.call_id,toolName:Q.toCustomToolName("local_shell"),input:JSON.stringify({action:M.action}),providerMetadata:{[ee]:{itemId:M.id}}});break}case"shell_call":{ae.push({type:"tool-call",toolCallId:M.call_id,toolName:Q.toCustomToolName("shell"),input:JSON.stringify({action:{commands:M.action.commands}}),providerMetadata:{[ee]:{itemId:M.id}}});break}case"message":{for(const he of M.content){(a=(r=t.providerOptions)==null?void 0:r[ee])!=null&&a.logprobs&&he.logprobs&&dt.push(he.logprobs);const Xe={itemId:M.id,...he.annotations.length>0&&{annotations:he.annotations}};ae.push({type:"text",text:he.text,providerMetadata:{[ee]:Xe}});for(const L of he.annotations)L.type==="url_citation"?ae.push({type:"source",sourceType:"url",id:(u=(o=(s=this.config).generateId)==null?void 0:o.call(s))!=null?u:Be(),url:L.url,title:L.title}):L.type==="file_citation"?ae.push({type:"source",sourceType:"document",id:(d=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?d:Be(),mediaType:"text/plain",title:(h=(m=L.quote)!=null?m:L.filename)!=null?h:"Document",filename:(D=L.filename)!=null?D:L.file_id,...L.file_id?{providerMetadata:{[ee]:{fileId:L.file_id}}}:{}}):L.type==="container_file_citation"?ae.push({type:"source",sourceType:"document",id:(y=(v=(f=this.config).generateId)==null?void 0:v.call(f))!=null?y:Be(),mediaType:"text/plain",title:(E=(F=L.filename)!=null?F:L.file_id)!=null?E:"Document",filename:(b=L.filename)!=null?b:L.file_id,providerMetadata:{[ee]:{fileId:L.file_id,containerId:L.container_id,...L.index!=null?{index:L.index}:{}}}}):L.type==="file_path"&&ae.push({type:"source",sourceType:"document",id:(k=(S=(w=this.config).generateId)==null?void 0:S.call(w))!=null?k:Be(),mediaType:"application/octet-stream",title:L.file_id,filename:L.file_id,providerMetadata:{[ee]:{fileId:L.file_id,...L.index!=null?{index:L.index}:{}}}})}break}case"function_call":{ot=!0,ae.push({type:"tool-call",toolCallId:M.call_id,toolName:M.name,input:M.arguments,providerMetadata:{[ee]:{itemId:M.id}}});break}case"web_search_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName(K??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName(K??"web_search"),result:_m(M.action)});break}case"mcp_call":{const he=M.approval_request_id!=null&&(C=ie[M.approval_request_id])!=null?C:M.id,Xe=`mcp.${M.name}`;ae.push({type:"tool-call",toolCallId:he,toolName:Xe,input:M.arguments,providerExecuted:!0,dynamic:!0}),ae.push({type:"tool-result",toolCallId:he,toolName:Xe,result:{type:"call",serverLabel:M.server_label,name:M.name,arguments:M.arguments,...M.output!=null?{output:M.output}:{},...M.error!=null?{error:M.error}:{}},providerMetadata:{[ee]:{itemId:M.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const he=(z=M.approval_request_id)!=null?z:M.id,Xe=(R=(B=(W=this.config).generateId)==null?void 0:B.call(W))!=null?R:Be(),L=`mcp.${M.name}`;ae.push({type:"tool-call",toolCallId:Xe,toolName:L,input:M.arguments,providerExecuted:!0,dynamic:!0}),ae.push({type:"tool-approval-request",approvalId:he,toolCallId:Xe});break}case"computer_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:M.status||"completed"}});break}case"file_search_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName("file_search"),result:{queries:M.queries,results:(j=(O=M.results)==null?void 0:O.map(he=>({attributes:he.attributes,fileId:he.file_id,filename:he.filename,score:he.score,text:he.text})))!=null?j:null}});break}case"code_interpreter_call":{ae.push({type:"tool-call",toolCallId:M.id,toolName:Q.toCustomToolName("code_interpreter"),input:JSON.stringify({code:M.code,containerId:M.container_id}),providerExecuted:!0}),ae.push({type:"tool-result",toolCallId:M.id,toolName:Q.toCustomToolName("code_interpreter"),result:{outputs:M.outputs}});break}case"apply_patch_call":{ae.push({type:"tool-call",toolCallId:M.call_id,toolName:Q.toCustomToolName("apply_patch"),input:JSON.stringify({callId:M.call_id,operation:M.operation}),providerMetadata:{[ee]:{itemId:M.id}}});break}}const vt={[ee]:{responseId:Oe.id}};dt.length>0&&(vt[ee].logprobs=dt),typeof Oe.service_tier=="string"&&(vt[ee].serviceTier=Oe.service_tier);const Ct=Oe.usage;return{content:ae,finishReason:{unified:hm({finishReason:(U=Oe.incomplete_details)==null?void 0:U.reason,hasFunctionCall:ot}),raw:(Z=(P=Oe.incomplete_details)==null?void 0:P.reason)!=null?Z:void 0},usage:mm(Ct),request:{body:X},response:{id:Oe.id,timestamp:new Date(Oe.created_at*1e3),modelId:Oe.model,headers:rt,body:Ft},providerMetadata:vt,warnings:ce}}async doStream(t){const{args:n,warnings:r,webSearchToolName:a,toolNameMapping:s,store:o,providerOptionsName:u}=await this.getArgs(t),{responseHeaders:l,value:c}=await Se({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:{...n,stream:!0},failedResponseHandler:pt,successfulResponseHandler:fn(lw),abortSignal:t.abortSignal,fetch:this.config.fetch}),d=this,m=vm(t.prompt),h=new Map;let D={unified:"other",raw:void 0},f;const v=[];let y=null;const F={},E=[];let b=!1;const w={};let S;return{stream:c.pipeThrough(new TransformStream({start(k){k.enqueue({type:"stream-start",warnings:r})},transform(k,C){var z,W,B,R,O,j,U,P,Z,X,ce,K,Q,ee,oe,ie,rt,Oe,Ft,ae,dt,ot,vt,Ct,M,he,Xe,L,Bt,bt,Qe,Qt,pe,ur,lr,De;if(t.includeRawChunks&&C.enqueue({type:"raw",rawValue:k.rawValue}),!k.success){D={unified:"error",raw:void 0},C.enqueue({type:"error",error:k.error});return}const _=k.value;if(ym(_)){if(_.item.type==="function_call")F[_.output_index]={toolName:_.item.name,toolCallId:_.item.call_id},C.enqueue({type:"tool-input-start",id:_.item.call_id,toolName:_.item.name});else if(_.item.type==="web_search_call")F[_.output_index]={toolName:s.toCustomToolName(a??"web_search"),toolCallId:_.item.id},C.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName(a??"web_search"),providerExecuted:!0}),C.enqueue({type:"tool-input-end",id:_.item.id}),C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName(a??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(_.item.type==="computer_call")F[_.output_index]={toolName:s.toCustomToolName("computer_use"),toolCallId:_.item.id},C.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("computer_use"),providerExecuted:!0});else if(_.item.type==="code_interpreter_call")F[_.output_index]={toolName:s.toCustomToolName("code_interpreter"),toolCallId:_.item.id,codeInterpreter:{containerId:_.item.container_id}},C.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("code_interpreter"),providerExecuted:!0}),C.enqueue({type:"tool-input-delta",id:_.item.id,delta:`{"containerId":"${_.item.container_id}","code":"`});else if(_.item.type==="file_search_call")C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(_.item.type==="image_generation_call")C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(_.item.type==="mcp_call"||_.item.type==="mcp_list_tools"||_.item.type==="mcp_approval_request"))if(_.item.type==="apply_patch_call"){const{call_id:$,operation:be}=_.item;if(F[_.output_index]={toolName:s.toCustomToolName("apply_patch"),toolCallId:$,applyPatch:{hasDiff:be.type==="delete_file",endEmitted:be.type==="delete_file"}},C.enqueue({type:"tool-input-start",id:$,toolName:s.toCustomToolName("apply_patch")}),be.type==="delete_file"){const je=JSON.stringify({callId:$,operation:be});C.enqueue({type:"tool-input-delta",id:$,delta:je}),C.enqueue({type:"tool-input-end",id:$})}else C.enqueue({type:"tool-input-delta",id:$,delta:`{"callId":"${Jt($)}","operation":{"type":"${Jt(be.type)}","path":"${Jt(be.path)}","diff":"`})}else _.item.type==="shell_call"?F[_.output_index]={toolName:s.toCustomToolName("shell"),toolCallId:_.item.call_id}:_.item.type==="message"?(E.splice(0,E.length),C.enqueue({type:"text-start",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id}}})):ym(_)&&_.item.type==="reasoning"&&(w[_.item.id]={encryptedContent:_.item.encrypted_content,summaryParts:{0:"active"}},C.enqueue({type:"reasoning-start",id:`${_.item.id}:0`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(z=_.item.encrypted_content)!=null?z:null}}}))}else if(fw(_)){if(_.item.type==="message")C.enqueue({type:"text-end",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id,...E.length>0&&{annotations:E}}}});else if(_.item.type==="function_call")F[_.output_index]=void 0,b=!0,C.enqueue({type:"tool-input-end",id:_.item.call_id}),C.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:_.item.name,input:_.item.arguments,providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="web_search_call")F[_.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName(a??"web_search"),result:_m(_.item.action)});else if(_.item.type==="computer_call")F[_.output_index]=void 0,C.enqueue({type:"tool-input-end",id:_.item.id}),C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:_.item.status||"completed"}});else if(_.item.type==="file_search_call")F[_.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),result:{queries:_.item.queries,results:(B=(W=_.item.results)==null?void 0:W.map($=>({attributes:$.attributes,fileId:$.file_id,filename:$.filename,score:$.score,text:$.text})))!=null?B:null}});else if(_.item.type==="code_interpreter_call")F[_.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("code_interpreter"),result:{outputs:_.item.outputs}});else if(_.item.type==="image_generation_call")C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),result:{result:_.item.result}});else if(_.item.type==="mcp_call"){F[_.output_index]=void 0;const $=(R=_.item.approval_request_id)!=null?R:void 0,be=$!=null&&(j=(O=h.get($))!=null?O:m[$])!=null?j:_.item.id,je=`mcp.${_.item.name}`;C.enqueue({type:"tool-call",toolCallId:be,toolName:je,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),C.enqueue({type:"tool-result",toolCallId:be,toolName:je,result:{type:"call",serverLabel:_.item.server_label,name:_.item.name,arguments:_.item.arguments,..._.item.output!=null?{output:_.item.output}:{},..._.item.error!=null?{error:_.item.error}:{}},providerMetadata:{[u]:{itemId:_.item.id}}})}else if(_.item.type==="mcp_list_tools")F[_.output_index]=void 0;else if(_.item.type==="apply_patch_call"){const $=F[_.output_index];$?.applyPatch&&!$.applyPatch.endEmitted&&_.item.operation.type!=="delete_file"&&($.applyPatch.hasDiff||C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:Jt(_.item.operation.diff)}),C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:'"}}'}),C.enqueue({type:"tool-input-end",id:$.toolCallId}),$.applyPatch.endEmitted=!0),$&&_.item.status==="completed"&&C.enqueue({type:"tool-call",toolCallId:$.toolCallId,toolName:s.toCustomToolName("apply_patch"),input:JSON.stringify({callId:_.item.call_id,operation:_.item.operation}),providerMetadata:{[u]:{itemId:_.item.id}}}),F[_.output_index]=void 0}else if(_.item.type==="mcp_approval_request"){F[_.output_index]=void 0;const $=(Z=(P=(U=d.config).generateId)==null?void 0:P.call(U))!=null?Z:Be(),be=(X=_.item.approval_request_id)!=null?X:_.item.id;h.set(be,$);const je=`mcp.${_.item.name}`;C.enqueue({type:"tool-call",toolCallId:$,toolName:je,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),C.enqueue({type:"tool-approval-request",approvalId:be,toolCallId:$})}else if(_.item.type==="local_shell_call")F[_.output_index]=void 0,C.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:_.item.action.command,timeoutMs:_.item.action.timeout_ms,user:_.item.action.user,workingDirectory:_.item.action.working_directory,env:_.item.action.env}}),providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call")F[_.output_index]=void 0,C.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),input:JSON.stringify({action:{commands:_.item.action.commands}}),providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="reasoning"){const $=w[_.item.id],be=Object.entries($.summaryParts).filter(([je,en])=>en==="active"||en==="can-conclude").map(([je])=>je);for(const je of be)C.enqueue({type:"reasoning-end",id:`${_.item.id}:${je}`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(ce=_.item.encrypted_content)!=null?ce:null}}});delete w[_.item.id]}}else if(gw(_)){const $=F[_.output_index];$!=null&&C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:_.delta})}else if(Fw(_)){const $=F[_.output_index];$?.applyPatch&&(C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:Jt(_.delta)}),$.applyPatch.hasDiff=!0)}else if(Cw(_)){const $=F[_.output_index];$?.applyPatch&&!$.applyPatch.endEmitted&&($.applyPatch.hasDiff||(C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:Jt(_.diff)}),$.applyPatch.hasDiff=!0),C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:'"}}'}),C.enqueue({type:"tool-input-end",id:$.toolCallId}),$.applyPatch.endEmitted=!0)}else if(vw(_))C.enqueue({type:"tool-result",toolCallId:_.item_id,toolName:s.toCustomToolName("image_generation"),result:{result:_.partial_image_b64},preliminary:!0});else if(yw(_)){const $=F[_.output_index];$!=null&&C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:Jt(_.delta)})}else if(_w(_)){const $=F[_.output_index];$!=null&&(C.enqueue({type:"tool-input-delta",id:$.toolCallId,delta:'"}'}),C.enqueue({type:"tool-input-end",id:$.toolCallId}),C.enqueue({type:"tool-call",toolCallId:$.toolCallId,toolName:s.toCustomToolName("code_interpreter"),input:JSON.stringify({code:_.code,containerId:$.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Dw(_))y=_.response.id,C.enqueue({type:"response-metadata",id:_.response.id,timestamp:new Date(_.response.created_at*1e3),modelId:_.response.model});else if(mw(_))C.enqueue({type:"text-delta",id:_.item_id,delta:_.delta}),(Q=(K=t.providerOptions)==null?void 0:K[u])!=null&&Q.logprobs&&_.logprobs&&v.push(_.logprobs);else if(_.type==="response.reasoning_summary_part.added"){if(_.summary_index>0){const $=w[_.item_id];$.summaryParts[_.summary_index]="active";for(const be of Object.keys($.summaryParts))$.summaryParts[be]==="can-conclude"&&(C.enqueue({type:"reasoning-end",id:`${_.item_id}:${be}`,providerMetadata:{[u]:{itemId:_.item_id}}}),$.summaryParts[be]="concluded");C.enqueue({type:"reasoning-start",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id,reasoningEncryptedContent:(oe=(ee=w[_.item_id])==null?void 0:ee.encryptedContent)!=null?oe:null}}})}}else _.type==="response.reasoning_summary_text.delta"?C.enqueue({type:"reasoning-delta",id:`${_.item_id}:${_.summary_index}`,delta:_.delta,providerMetadata:{[u]:{itemId:_.item_id}}}):_.type==="response.reasoning_summary_part.done"?o?(C.enqueue({type:"reasoning-end",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id}}}),w[_.item_id].summaryParts[_.summary_index]="concluded"):w[_.item_id].summaryParts[_.summary_index]="can-conclude":hw(_)?(D={unified:hm({finishReason:(ie=_.response.incomplete_details)==null?void 0:ie.reason,hasFunctionCall:b}),raw:(Oe=(rt=_.response.incomplete_details)==null?void 0:rt.reason)!=null?Oe:void 0},f=_.response.usage,typeof _.response.service_tier=="string"&&(S=_.response.service_tier)):bw(_)?(E.push(_.annotation),_.annotation.type==="url_citation"?C.enqueue({type:"source",sourceType:"url",id:(dt=(ae=(Ft=d.config).generateId)==null?void 0:ae.call(Ft))!=null?dt:Be(),url:_.annotation.url,title:_.annotation.title}):_.annotation.type==="file_citation"?C.enqueue({type:"source",sourceType:"document",id:(Ct=(vt=(ot=d.config).generateId)==null?void 0:vt.call(ot))!=null?Ct:Be(),mediaType:"text/plain",title:(he=(M=_.annotation.quote)!=null?M:_.annotation.filename)!=null?he:"Document",filename:(Xe=_.annotation.filename)!=null?Xe:_.annotation.file_id,..._.annotation.file_id?{providerMetadata:{[u]:{fileId:_.annotation.file_id}}}:{}}):_.annotation.type==="container_file_citation"?C.enqueue({type:"source",sourceType:"document",id:(bt=(Bt=(L=d.config).generateId)==null?void 0:Bt.call(L))!=null?bt:Be(),mediaType:"text/plain",title:(Qt=(Qe=_.annotation.filename)!=null?Qe:_.annotation.file_id)!=null?Qt:"Document",filename:(pe=_.annotation.filename)!=null?pe:_.annotation.file_id,providerMetadata:{[u]:{fileId:_.annotation.file_id,containerId:_.annotation.container_id,..._.annotation.index!=null?{index:_.annotation.index}:{}}}}):_.annotation.type==="file_path"&&C.enqueue({type:"source",sourceType:"document",id:(De=(lr=(ur=d.config).generateId)==null?void 0:lr.call(ur))!=null?De:Be(),mediaType:"application/octet-stream",title:_.annotation.file_id,filename:_.annotation.file_id,providerMetadata:{[u]:{fileId:_.annotation.file_id,..._.annotation.index!=null?{index:_.annotation.index}:{}}}})):Ew(_)&&C.enqueue({type:"error",error:_})},flush(k){const C={[u]:{responseId:y}};v.length>0&&(C[u].logprobs=v),S!==void 0&&(C[u].serviceTier=S),k.enqueue({type:"finish",finishReason:D,usage:mm(f),providerMetadata:C})}})),request:{body:n},response:{headers:l}}}},i(tr,"OpenAIResponsesLanguageModel"),tr);function mw(e){return e.type==="response.output_text.delta"}i(mw,"isTextDeltaChunk");function fw(e){return e.type==="response.output_item.done"}i(fw,"isResponseOutputItemDoneChunk");function hw(e){return e.type==="response.completed"||e.type==="response.incomplete"}i(hw,"isResponseFinishedChunk");function Dw(e){return e.type==="response.created"}i(Dw,"isResponseCreatedChunk");function gw(e){return e.type==="response.function_call_arguments.delta"}i(gw,"isResponseFunctionCallArgumentsDeltaChunk");function vw(e){return e.type==="response.image_generation_call.partial_image"}i(vw,"isResponseImageGenerationCallPartialImageChunk");function yw(e){return e.type==="response.code_interpreter_call_code.delta"}i(yw,"isResponseCodeInterpreterCallCodeDeltaChunk");function _w(e){return e.type==="response.code_interpreter_call_code.done"}i(_w,"isResponseCodeInterpreterCallCodeDoneChunk");function Fw(e){return e.type==="response.apply_patch_call_operation_diff.delta"}i(Fw,"isResponseApplyPatchCallOperationDiffDeltaChunk");function Cw(e){return e.type==="response.apply_patch_call_operation_diff.done"}i(Cw,"isResponseApplyPatchCallOperationDiffDoneChunk");function ym(e){return e.type==="response.output_item.added"}i(ym,"isResponseOutputItemAddedChunk");function bw(e){return e.type==="response.output_text.annotation.added"}i(bw,"isResponseAnnotationAddedChunk");function Ew(e){return e.type==="error"}i(Ew,"isErrorChunk");function _m(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}i(_m,"mapWebSearchOutput");function Jt(e){return JSON.stringify(e).slice(1,-1)}i(Jt,"escapeJSONDelta");var ww=J(()=>G(g({instructions:p().nullish(),speed:A().min(.25).max(4).default(1).nullish()}))),Aw=(nr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:n="alloy",outputFormat:r="mp3",speed:a,instructions:s,language:o,providerOptions:u}){const l=[],c=await Le({provider:"openai",providerOptions:u,schema:ww}),d={model:this.modelId,input:t,voice:n,response_format:"mp3",speed:a,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?d.response_format=r:l.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){const m={};for(const h in m){const D=m[h];D!==void 0&&(d[h]=D)}}return o&&l.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:d,warnings:l}}async doGenerate(t){var n,r,a;const s=(a=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?a:new Date,{requestBody:o,warnings:u}=await this.getArgs(t),{value:l,responseHeaders:c,rawValue:d}=await Se({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:o,failedResponseHandler:pt,successfulResponseHandler:w2(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:l,warnings:u,request:{body:JSON.stringify(o)},response:{timestamp:s,modelId:this.modelId,headers:c,body:d}}}},i(nr,"OpenAISpeechModel"),nr),Iw=J(()=>G(g({text:p(),language:p().nullish(),duration:A().nullish(),words:T(g({word:p(),start:A(),end:A()})).nullish(),segments:T(g({id:A(),seek:A(),start:A(),end:A(),text:p(),tokens:T(A()),temperature:A(),avg_logprob:A(),compression_ratio:A(),no_speech_prob:A()})).nullish()}))),xw=J(()=>G(g({include:T(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:A().min(0).max(1).default(0).optional(),timestampGranularities:T(re(["word","segment"])).default(["segment"]).optional()}))),Fm={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"},kw=(rr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:n,providerOptions:r}){const a=[],s=await Le({provider:"openai",providerOptions:r,schema:xw}),o=new FormData,u=t instanceof Uint8Array?new Blob([t]):new Blob([Lt(t)]);o.append("model",this.modelId);const l=IF(n);if(o.append("file",new File([u],"audio",{type:n}),`audio.${l}`),s){const c={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[d,m]of Object.entries(c))if(m!=null)if(Array.isArray(m))for(const h of m)o.append(`${d}[]`,String(h));else o.append(d,String(m))}return{formData:o,warnings:a}}async doGenerate(t){var n,r,a,s,o,u,l,c;const d=(a=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?a:new Date,{formData:m,warnings:h}=await this.getArgs(t),{value:D,responseHeaders:f,rawValue:v}=await as({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),formData:m,failedResponseHandler:pt,successfulResponseHandler:Pe(Iw),abortSignal:t.abortSignal,fetch:this.config.fetch}),y=D.language!=null&&D.language in Fm?Fm[D.language]:void 0;return{text:D.text,segments:(l=(u=(s=D.segments)==null?void 0:s.map(F=>({text:F.text,startSecond:F.start,endSecond:F.end})))!=null?u:(o=D.words)==null?void 0:o.map(F=>({text:F.word,startSecond:F.start,endSecond:F.end})))!=null?l:[],language:y,durationInSeconds:(c=D.duration)!=null?c:void 0,warnings:h,response:{timestamp:d,modelId:this.modelId,headers:f,body:v}}}},i(rr,"OpenAITranscriptionModel"),rr),$w="3.0.5";function To(e={}){var t,n;const r=(t=ss(kr({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",a=(n=e.name)!=null?n:"openai",s=i(()=>Gt({Authorization:`Bearer ${AF({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${$w}`),"getHeaders"),o=i(v=>new DE(v,{provider:`${a}.chat`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createChatModel"),u=i(v=>new _E(v,{provider:`${a}.completion`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createCompletionModel"),l=i(v=>new bE(v,{provider:`${a}.embedding`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createEmbeddingModel"),c=i(v=>new AE(v,{provider:`${a}.image`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createImageModel"),d=i(v=>new kw(v,{provider:`${a}.transcription`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createTranscriptionModel"),m=i(v=>new Aw(v,{provider:`${a}.speech`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createSpeechModel"),h=i(v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return D(v)},"createLanguageModel"),D=i(v=>new dw(v,{provider:`${a}.responses`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),"createResponsesModel"),f=i(function(v){return h(v)},"provider");return f.specificationVersion="v3",f.languageModel=h,f.chat=o,f.completion=u,f.responses=D,f.embedding=l,f.embeddingModel=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=c,f.imageModel=c,f.transcription=d,f.transcriptionModel=d,f.speech=m,f.speechModel=m,f.tools=sw,f}i(To,"createOpenAI"),To();var Tw=g({error:g({message:p(),type:p().nullish(),param:qe().nullish(),code:H([p(),A()]).nullish()})}),Pr={errorSchema:Tw,errorToMessage:i(e=>e.error.message,"errorToMessage")};function Cm(e){var t,n,r,a,s,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(a=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?a:0,d=(o=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?o:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(Cm,"convertOpenAICompatibleChatUsage");function Mr(e){var t,n;return(n=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}i(Mr,"getOpenAIMetadata");function Bw(e){var t;const n=[];for(const{role:r,content:a,...s}of e){const o=Mr({...s});switch(r){case"system":{n.push({role:"system",content:a,...o});break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text,...Mr(a[0])});break}n.push({role:"user",content:a.map(u=>{const l=Mr(u);switch(u.type){case"text":return{type:"text",text:u.text,...l};case"file":if(u.mediaType.startsWith("image/")){const c=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${c};base64,${Vt(u.data)}`},...l}}else throw new He({functionality:`file part media type ${u.mediaType}`})}}),...o});break}case"assistant":{let u="";const l=[];for(const c of a){const d=Mr(c);switch(c.type){case"text":{u+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)},...d});break}}}n.push({role:"assistant",content:u,tool_calls:l.length>0?l:void 0,...o});break}case"tool":{for(const u of a){if(u.type==="tool-approval-response")continue;const l=u.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(t=l.reason)!=null?t:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}const d=Mr(u);n.push({role:"tool",tool_call_id:u.toolCallId,content:c,...d})}break}default:{const u=r;throw new Error(`Unsupported role: ${u}`)}}}return n}i(Bw,"convertToOpenAICompatibleChatMessages");function bm({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(bm,"getResponseMetadata");function Em(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"other"}}i(Em,"mapOpenAICompatibleFinishReason");var $s=g({user:p().optional(),reasoningEffort:p().optional(),textVerbosity:p().optional()});function Sw({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider"?n.push({type:"unsupported",feature:`provider-defined tool ${s.id}`}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:r,toolChoice:a,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=a;throw new He({functionality:`tool choice type: ${s}`})}}}i(Sw,"prepareTools");var Ow=(or=class{constructor(t,n){this.specificationVersion="v3";var r,a;this.modelId=t,this.config=n;const s=(r=n.errorStructure)!=null?r:Pr;this.chunkSchema=Pw(s.errorSchema),this.failedResponseHandler=nt(s),this.supportsStructuredOutputs=(a=n.supportsStructuredOutputs)!=null?a:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:s,frequencyPenalty:o,presencePenalty:u,providerOptions:l,stopSequences:c,responseFormat:d,seed:m,toolChoice:h,tools:D}){var f,v,y,F;const E=[],b=Object.assign((f=await Le({provider:"openai-compatible",providerOptions:l,schema:$s}))!=null?f:{},(v=await Le({provider:this.providerOptionsName,providerOptions:l,schema:$s}))!=null?v:{});s!=null&&E.push({type:"unsupported",feature:"topK"}),d?.type==="json"&&d.schema!=null&&!this.supportsStructuredOutputs&&E.push({type:"unsupported",feature:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:w,toolChoice:S,toolWarnings:k}=Sw({tools:D,toolChoice:h});return{args:{model:this.modelId,user:b.user,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,response_format:d?.type==="json"?this.supportsStructuredOutputs===!0&&d.schema!=null?{type:"json_schema",json_schema:{schema:d.schema,name:(y=d.name)!=null?y:"response",description:d.description}}:{type:"json_object"}:void 0,stop:c,seed:m,...Object.fromEntries(Object.entries((F=l?.[this.providerOptionsName])!=null?F:{}).filter(([C])=>!Object.keys($s.shape).includes(C))),reasoning_effort:b.reasoningEffort,verbosity:b.textVerbosity,messages:Bw(t),tools:w,tool_choice:S},warnings:[...E,...k]}}async doGenerate(t){var n,r,a,s,o,u;const{args:l,warnings:c}=await this.getArgs({...t}),d=JSON.stringify(l),{responseHeaders:m,value:h,rawValue:D}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:l,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Pe(Rw),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=h.choices[0],v=[],y=f.message.content;y!=null&&y.length>0&&v.push({type:"text",text:y});const F=(n=f.message.reasoning_content)!=null?n:f.message.reasoning;if(F!=null&&F.length>0&&v.push({type:"reasoning",text:F}),f.message.tool_calls!=null)for(const w of f.message.tool_calls)v.push({type:"tool-call",toolCallId:(r=w.id)!=null?r:Be(),toolName:w.function.name,input:w.function.arguments});const E={[this.providerOptionsName]:{},...await((s=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:s.call(a,{parsedBody:D}))},b=(o=h.usage)==null?void 0:o.completion_tokens_details;return b?.accepted_prediction_tokens!=null&&(E[this.providerOptionsName].acceptedPredictionTokens=b?.accepted_prediction_tokens),b?.rejected_prediction_tokens!=null&&(E[this.providerOptionsName].rejectedPredictionTokens=b?.rejected_prediction_tokens),{content:v,finishReason:{unified:Em(f.finish_reason),raw:(u=f.finish_reason)!=null?u:void 0},usage:Cm(h.usage),providerMetadata:E,request:{body:d},response:{...bm(h),headers:m,body:D},warnings:c}}async doStream(t){var n;const{args:r,warnings:a}=await this.getArgs({...t}),s={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},o=(n=this.config.metadataExtractor)==null?void 0:n.createStreamExtractor(),{responseHeaders:u,value:l}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:fn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let d={unified:"other",raw:void 0},m,h=!0;const D=this.providerOptionsName;let f=!1,v=!1;return{stream:l.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:a})},transform(y,F){var E,b,w,S,k,C,z,W,B,R,O,j,U,P;if(t.includeRawChunks&&F.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){d={unified:"error",raw:void 0},F.enqueue({type:"error",error:y.error});return}if(o?.processChunk(y.rawValue),"error"in y.value){d={unified:"error",raw:void 0},F.enqueue({type:"error",error:y.value.error.message});return}const Z=y.value;h&&(h=!1,F.enqueue({type:"response-metadata",...bm(Z)})),Z.usage!=null&&(m=Z.usage);const X=Z.choices[0];if(X?.finish_reason!=null&&(d={unified:Em(X.finish_reason),raw:(E=X.finish_reason)!=null?E:void 0}),X?.delta==null)return;const ce=X.delta,K=(b=ce.reasoning_content)!=null?b:ce.reasoning;if(K&&(f||(F.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),F.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:K})),ce.content&&(v||(F.enqueue({type:"text-start",id:"txt-0"}),v=!0),F.enqueue({type:"text-delta",id:"txt-0",delta:ce.content})),ce.tool_calls!=null)for(const Q of ce.tool_calls){const ee=Q.index;if(c[ee]==null){if(Q.id==null)throw new _r({data:Q,message:"Expected 'id' to be a string."});if(((w=Q.function)==null?void 0:w.name)==null)throw new _r({data:Q,message:"Expected 'function.name' to be a string."});F.enqueue({type:"tool-input-start",id:Q.id,toolName:Q.function.name}),c[ee]={id:Q.id,type:"function",function:{name:Q.function.name,arguments:(S=Q.function.arguments)!=null?S:""},hasFinished:!1};const ie=c[ee];((k=ie.function)==null?void 0:k.name)!=null&&((C=ie.function)==null?void 0:C.arguments)!=null&&(ie.function.arguments.length>0&&F.enqueue({type:"tool-input-delta",id:ie.id,delta:ie.function.arguments}),wo(ie.function.arguments)&&(F.enqueue({type:"tool-input-end",id:ie.id}),F.enqueue({type:"tool-call",toolCallId:(z=ie.id)!=null?z:Be(),toolName:ie.function.name,input:ie.function.arguments}),ie.hasFinished=!0));continue}const oe=c[ee];oe.hasFinished||(((W=Q.function)==null?void 0:W.arguments)!=null&&(oe.function.arguments+=(R=(B=Q.function)==null?void 0:B.arguments)!=null?R:""),F.enqueue({type:"tool-input-delta",id:oe.id,delta:(O=Q.function.arguments)!=null?O:""}),((j=oe.function)==null?void 0:j.name)!=null&&((U=oe.function)==null?void 0:U.arguments)!=null&&wo(oe.function.arguments)&&(F.enqueue({type:"tool-input-end",id:oe.id}),F.enqueue({type:"tool-call",toolCallId:(P=oe.id)!=null?P:Be(),toolName:oe.function.name,input:oe.function.arguments}),oe.hasFinished=!0))}},flush(y){var F,E,b,w,S;f&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),v&&y.enqueue({type:"text-end",id:"txt-0"});for(const C of c.filter(z=>!z.hasFinished))y.enqueue({type:"tool-input-end",id:C.id}),y.enqueue({type:"tool-call",toolCallId:(F=C.id)!=null?F:Be(),toolName:C.function.name,input:C.function.arguments});const k={[D]:{},...o?.buildMetadata()};((E=m?.completion_tokens_details)==null?void 0:E.accepted_prediction_tokens)!=null&&(k[D].acceptedPredictionTokens=(b=m?.completion_tokens_details)==null?void 0:b.accepted_prediction_tokens),((w=m?.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens)!=null&&(k[D].rejectedPredictionTokens=(S=m?.completion_tokens_details)==null?void 0:S.rejected_prediction_tokens),y.enqueue({type:"finish",finishReason:d,usage:Cm(m),providerMetadata:k})}})),request:{body:s},response:{headers:u}}}},i(or,"OpenAICompatibleChatLanguageModel"),or),wm=g({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:g({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish(),Rw=g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({message:g({role:I("assistant").nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:T(g({id:p().nullish(),function:g({name:p(),arguments:p()})})).nullish()}),finish_reason:p().nullish()})),usage:wm}),Nw=g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({delta:g({role:re(["assistant"]).nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:T(g({index:A(),id:p().nullish(),function:g({name:p().nullish(),arguments:p().nullish()})})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:wm}),Pw=i(e=>H([Nw,e]),"createOpenAICompatibleChatChunkSchema");function Am(e){var t,n;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const r=(t=e.prompt_tokens)!=null?t:0,a=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:r,noCache:r,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:a,text:a,reasoning:void 0},raw:e}}i(Am,"convertOpenAICompatibleCompletionUsage");function Mw({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
161
161
 
162
162
  `,e=e.slice(1));for(const{role:a,content:s}of e)switch(a){case"system":throw new At({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const o=s.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
163
163
  ${o}
@@ -167,37 +167,37 @@ ${o}
167
167
 
168
168
  `;break}case"tool":throw new He({functionality:"tool messages"});default:{const o=a;throw new Error(`Unsupported role: ${o}`)}}return r+=`${n}:
169
169
  `,{prompt:r,stopSequences:[`
170
- ${t}:`]}}i(Nw,"convertToOpenAICompatibleCompletionPrompt");function wm({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(wm,"getResponseMetadata2");function Am(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"other"}}i(Am,"mapOpenAICompatibleFinishReason2");var Pw=g({echo:Ae().optional(),logitBias:me(p(),A()).optional(),suffix:p().optional(),user:p().optional()}),Mw=(ar=class{constructor(t,n){this.specificationVersion="v3";var r;this.modelId=t,this.config=n;const a=(r=n.errorStructure)!=null?r:Pr;this.chunkSchema=zw(a.errorSchema),this.failedResponseHandler=nt(a)}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:s,frequencyPenalty:o,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,providerOptions:m,tools:h,toolChoice:D}){var f;const v=[],y=(f=await Ue({provider:this.providerOptionsName,providerOptions:m,schema:Pw}))!=null?f:{};s!=null&&v.push({type:"unsupported",feature:"topK"}),h?.length&&v.push({type:"unsupported",feature:"tools"}),D!=null&&v.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&v.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:F,stopSequences:E}=Nw({prompt:t}),b=[...E??[],...l??[]];return{args:{model:this.modelId,echo:y.echo,logit_bias:y.logitBias,suffix:y.suffix,user:y.user,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,seed:d,...m?.[this.providerOptionsName],prompt:F,stop:b.length>0?b:void 0},warnings:v}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{responseHeaders:a,value:s,rawValue:o}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Pe(jw),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=s.choices[0],l=[];return u.text!=null&&u.text.length>0&&l.push({type:"text",text:u.text}),{content:l,usage:Em(s.usage),finishReason:{unified:Am(u.finish_reason),raw:u.finish_reason},request:{body:n},response:{...wm(s),headers:a,body:o},warnings:r}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),a={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},{responseHeaders:s,value:o}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:a,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:fn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0},l,c=!0;return{stream:o.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,m){var h;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){u={unified:"error",raw:void 0},m.enqueue({type:"error",error:d.error});return}const D=d.value;if("error"in D){u={unified:"error",raw:void 0},m.enqueue({type:"error",error:D.error});return}c&&(c=!1,m.enqueue({type:"response-metadata",...wm(D)}),m.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(l=D.usage);const f=D.choices[0];f?.finish_reason!=null&&(u={unified:Am(f.finish_reason),raw:(h=f.finish_reason)!=null?h:void 0}),f?.text!=null&&m.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(d){c||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:u,usage:Em(l)})}})),request:{body:a},response:{headers:s}}}},i(ar,"OpenAICompatibleCompletionLanguageModel"),ar),Im=g({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}),jw=g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({text:p(),finish_reason:p()})),usage:Im.nullish()}),zw=i(e=>H([g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({text:p(),finish_reason:p().nullish(),index:A()})),usage:Im.nullish()}),e]),"createOpenAICompatibleCompletionChunkSchema"),xm=g({dimensions:A().optional(),user:p().optional()}),qw=(sr=class{constructor(t,n){this.specificationVersion="v3",this.modelId=t,this.config=n}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var t;return(t=this.config.maxEmbeddingsPerCall)!=null?t:2048}get supportsParallelCalls(){var t;return(t=this.config.supportsParallelCalls)!=null?t:!0}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:a}){var s,o,u;const l=Object.assign((s=await Ue({provider:"openai-compatible",providerOptions:a,schema:xm}))!=null?s:{},(o=await Ue({provider:this.providerOptionsName,providerOptions:a,schema:xm}))!=null?o:{});if(t.length>this.maxEmbeddingsPerCall)throw new jl({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:c,value:d,rawValue:m}=await Se({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:xe(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:l.dimensions,user:l.user},failedResponseHandler:nt((u=this.config.errorStructure)!=null?u:Pr),successfulResponseHandler:Pe(Zw),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:d.data.map(h=>h.embedding),usage:d.usage?{tokens:d.usage.prompt_tokens}:void 0,providerMetadata:d.providerMetadata,response:{headers:c,body:m}}}},i(sr,"OpenAICompatibleEmbeddingModel"),sr),Zw=g({data:T(g({embedding:T(A())})),usage:g({prompt_tokens:A()}).nullish(),providerMetadata:me(p(),me(p(),qe())).optional()}),Lw=(ir=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:t,n,size:r,aspectRatio:a,seed:s,providerOptions:o,headers:u,abortSignal:l,files:c,mask:d}){var m,h,D,f,v,y,F;const E=[];a!=null&&E.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&E.push({type:"unsupported",feature:"seed"});const b=(D=(h=(m=this.config._internal)==null?void 0:m.currentDate)==null?void 0:h.call(m))!=null?D:new Date;if(c!=null&&c.length>0){const{value:k,responseHeaders:C}=await as({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:xe(this.config.headers(),u),formData:jc({model:this.modelId,prompt:t,image:await Promise.all(c.map(z=>$m(z))),mask:d!=null?await $m(d):void 0,n,size:r,...(f=o.openai)!=null?f:{}}),failedResponseHandler:nt((v=this.config.errorStructure)!=null?v:Pr),successfulResponseHandler:Pe(km),abortSignal:l,fetch:this.config.fetch});return{images:k.data.map(z=>z.b64_json),warnings:E,response:{timestamp:b,modelId:this.modelId,headers:C}}}const{value:w,responseHeaders:S}=await Se({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:xe(this.config.headers(),u),body:{model:this.modelId,prompt:t,n,size:r,...(y=o.openai)!=null?y:{},response_format:"b64_json"},failedResponseHandler:nt((F=this.config.errorStructure)!=null?F:Pr),successfulResponseHandler:Pe(km),abortSignal:l,fetch:this.config.fetch});return{images:w.data.map(k=>k.b64_json),warnings:E,response:{timestamp:b,modelId:this.modelId,headers:S}}}},i(ir,"OpenAICompatibleImageModel"),ir),km=g({data:T(g({b64_json:p()}))});async function $m(e){if(e.type==="url")return Xa(e.url);const t=e.data instanceof Uint8Array?e.data:Ut(e.data);return new Blob([t],{type:e.mediaType})}i($m,"fileToBlob");var Uw="2.0.4";function Ts(e){const t=ss(e.baseURL),n=e.name,r={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},a=i(()=>Gt(r,`ai-sdk/openai-compatible/${Uw}`),"getHeaders"),s=i(h=>({provider:`${n}.${h}`,url:i(({path:D})=>{const f=new URL(`${t}${D}`);return e.queryParams&&(f.search=new URLSearchParams(e.queryParams).toString()),f.toString()},"url"),headers:a,fetch:e.fetch}),"getCommonModelConfig"),o=i(h=>u(h),"createLanguageModel"),u=i(h=>new Bw(h,{...s("chat"),includeUsage:e.includeUsage,supportsStructuredOutputs:e.supportsStructuredOutputs}),"createChatModel"),l=i(h=>new Mw(h,{...s("completion"),includeUsage:e.includeUsage}),"createCompletionModel"),c=i(h=>new qw(h,{...s("embedding")}),"createEmbeddingModel"),d=i(h=>new Lw(h,s("image")),"createImageModel"),m=i(h=>o(h),"provider");return m.specificationVersion="v3",m.languageModel=o,m.chatModel=u,m.completionModel=l,m.embeddingModel=c,m.textEmbeddingModel=c,m.imageModel=d,m}i(Ts,"createOpenAICompatible");const Vw={"":"<commit message>",conventional:"<type>[optional (<scope>)]: <commit message>",gitmoji:":emoji: <commit message>"},Gw=i(e=>`The output response must be in format:
171
- ${Vw[e]}`,"specifyCommitFormat"),Ww={"":"",conventional:`Choose a type from the type-to-description JSON below that best describes the git diff:
170
+ ${t}:`]}}i(Mw,"convertToOpenAICompatibleCompletionPrompt");function Im({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(Im,"getResponseMetadata2");function xm(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"other"}}i(xm,"mapOpenAICompatibleFinishReason2");var jw=g({echo:Ae().optional(),logitBias:me(p(),A()).optional(),suffix:p().optional(),user:p().optional()}),zw=(ar=class{constructor(t,n){this.specificationVersion="v3";var r;this.modelId=t,this.config=n;const a=(r=n.errorStructure)!=null?r:Pr;this.chunkSchema=Zw(a.errorSchema),this.failedResponseHandler=nt(a)}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:s,frequencyPenalty:o,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,providerOptions:m,tools:h,toolChoice:D}){var f;const v=[],y=(f=await Le({provider:this.providerOptionsName,providerOptions:m,schema:jw}))!=null?f:{};s!=null&&v.push({type:"unsupported",feature:"topK"}),h?.length&&v.push({type:"unsupported",feature:"tools"}),D!=null&&v.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&v.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:F,stopSequences:E}=Mw({prompt:t}),b=[...E??[],...l??[]];return{args:{model:this.modelId,echo:y.echo,logit_bias:y.logitBias,suffix:y.suffix,user:y.user,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,seed:d,...m?.[this.providerOptionsName],prompt:F,stop:b.length>0?b:void 0},warnings:v}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{responseHeaders:a,value:s,rawValue:o}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Pe(qw),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=s.choices[0],l=[];return u.text!=null&&u.text.length>0&&l.push({type:"text",text:u.text}),{content:l,usage:Am(s.usage),finishReason:{unified:xm(u.finish_reason),raw:u.finish_reason},request:{body:n},response:{...Im(s),headers:a,body:o},warnings:r}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),a={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},{responseHeaders:s,value:o}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:a,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:fn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0},l,c=!0;return{stream:o.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,m){var h;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){u={unified:"error",raw:void 0},m.enqueue({type:"error",error:d.error});return}const D=d.value;if("error"in D){u={unified:"error",raw:void 0},m.enqueue({type:"error",error:D.error});return}c&&(c=!1,m.enqueue({type:"response-metadata",...Im(D)}),m.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(l=D.usage);const f=D.choices[0];f?.finish_reason!=null&&(u={unified:xm(f.finish_reason),raw:(h=f.finish_reason)!=null?h:void 0}),f?.text!=null&&m.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(d){c||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:u,usage:Am(l)})}})),request:{body:a},response:{headers:s}}}},i(ar,"OpenAICompatibleCompletionLanguageModel"),ar),km=g({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}),qw=g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({text:p(),finish_reason:p()})),usage:km.nullish()}),Zw=i(e=>H([g({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:T(g({text:p(),finish_reason:p().nullish(),index:A()})),usage:km.nullish()}),e]),"createOpenAICompatibleCompletionChunkSchema"),$m=g({dimensions:A().optional(),user:p().optional()}),Uw=(sr=class{constructor(t,n){this.specificationVersion="v3",this.modelId=t,this.config=n}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var t;return(t=this.config.maxEmbeddingsPerCall)!=null?t:2048}get supportsParallelCalls(){var t;return(t=this.config.supportsParallelCalls)!=null?t:!0}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:a}){var s,o,u;const l=Object.assign((s=await Le({provider:"openai-compatible",providerOptions:a,schema:$m}))!=null?s:{},(o=await Le({provider:this.providerOptionsName,providerOptions:a,schema:$m}))!=null?o:{});if(t.length>this.maxEmbeddingsPerCall)throw new ql({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:c,value:d,rawValue:m}=await Se({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:xe(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:l.dimensions,user:l.user},failedResponseHandler:nt((u=this.config.errorStructure)!=null?u:Pr),successfulResponseHandler:Pe(Lw),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:d.data.map(h=>h.embedding),usage:d.usage?{tokens:d.usage.prompt_tokens}:void 0,providerMetadata:d.providerMetadata,response:{headers:c,body:m}}}},i(sr,"OpenAICompatibleEmbeddingModel"),sr),Lw=g({data:T(g({embedding:T(A())})),usage:g({prompt_tokens:A()}).nullish(),providerMetadata:me(p(),me(p(),qe())).optional()}),Vw=(ir=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:t,n,size:r,aspectRatio:a,seed:s,providerOptions:o,headers:u,abortSignal:l,files:c,mask:d}){var m,h,D,f,v,y,F;const E=[];a!=null&&E.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&E.push({type:"unsupported",feature:"seed"});const b=(D=(h=(m=this.config._internal)==null?void 0:m.currentDate)==null?void 0:h.call(m))!=null?D:new Date;if(c!=null&&c.length>0){const{value:k,responseHeaders:C}=await as({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:xe(this.config.headers(),u),formData:qc({model:this.modelId,prompt:t,image:await Promise.all(c.map(z=>Bm(z))),mask:d!=null?await Bm(d):void 0,n,size:r,...(f=o.openai)!=null?f:{}}),failedResponseHandler:nt((v=this.config.errorStructure)!=null?v:Pr),successfulResponseHandler:Pe(Tm),abortSignal:l,fetch:this.config.fetch});return{images:k.data.map(z=>z.b64_json),warnings:E,response:{timestamp:b,modelId:this.modelId,headers:C}}}const{value:w,responseHeaders:S}=await Se({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:xe(this.config.headers(),u),body:{model:this.modelId,prompt:t,n,size:r,...(y=o.openai)!=null?y:{},response_format:"b64_json"},failedResponseHandler:nt((F=this.config.errorStructure)!=null?F:Pr),successfulResponseHandler:Pe(Tm),abortSignal:l,fetch:this.config.fetch});return{images:w.data.map(k=>k.b64_json),warnings:E,response:{timestamp:b,modelId:this.modelId,headers:S}}}},i(ir,"OpenAICompatibleImageModel"),ir),Tm=g({data:T(g({b64_json:p()}))});async function Bm(e){if(e.type==="url")return Xa(e.url);const t=e.data instanceof Uint8Array?e.data:Lt(e.data);return new Blob([t],{type:e.mediaType})}i(Bm,"fileToBlob");var Gw="2.0.4";function Ts(e){const t=ss(e.baseURL),n=e.name,r={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},a=i(()=>Gt(r,`ai-sdk/openai-compatible/${Gw}`),"getHeaders"),s=i(h=>({provider:`${n}.${h}`,url:i(({path:D})=>{const f=new URL(`${t}${D}`);return e.queryParams&&(f.search=new URLSearchParams(e.queryParams).toString()),f.toString()},"url"),headers:a,fetch:e.fetch}),"getCommonModelConfig"),o=i(h=>u(h),"createLanguageModel"),u=i(h=>new Ow(h,{...s("chat"),includeUsage:e.includeUsage,supportsStructuredOutputs:e.supportsStructuredOutputs}),"createChatModel"),l=i(h=>new zw(h,{...s("completion"),includeUsage:e.includeUsage}),"createCompletionModel"),c=i(h=>new Uw(h,{...s("embedding")}),"createEmbeddingModel"),d=i(h=>new Vw(h,s("image")),"createImageModel"),m=i(h=>o(h),"provider");return m.specificationVersion="v3",m.languageModel=o,m.chatModel=u,m.completionModel=l,m.embeddingModel=c,m.textEmbeddingModel=c,m.imageModel=d,m}i(Ts,"createOpenAICompatible");const Ww={"":"<commit message>",conventional:"<type>[optional (<scope>)]: <commit message>",gitmoji:":emoji: <commit message>"},Hw=i(e=>`The output response must be in format:
171
+ ${Ww[e]}`,"specifyCommitFormat"),Jw={"":"",conventional:`Choose a type from the type-to-description JSON below that best describes the git diff:
172
172
  ${JSON.stringify({docs:"Documentation only changes",style:"Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",refactor:"A code change that improves code structure without changing functionality (renaming, restructuring classes/methods, extracting functions, etc)",perf:"A code change that improves performance",test:"Adding missing tests or correcting existing tests",build:"Changes that affect the build system or external dependencies",ci:"Changes to our CI configuration files and scripts",chore:"Other changes that don't modify src or test files",revert:"Reverts a previous commit",feat:"A new feature",fix:"A bug fix"},null,2)}`,gitmoji:`Choose an emoji from the emoji-to-description JSON below that best describes the git diff:
173
- ${JSON.stringify({"\u{1F3A8}":"Improve structure / format of the code","\u26A1":"Improve performance","\u{1F525}":"Remove code or files","\u{1F41B}":"Fix a bug","\u{1F691}":"Critical hotfix","\u2728":"Introduce new features","\u{1F4DD}":"Add or update documentation","\u{1F680}":"Deploy stuff","\u{1F484}":"Add or update the UI and style files","\u{1F389}":"Begin a project","\u2705":"Add, update, or pass tests","\u{1F512}":"Fix security or privacy issues","\u{1F510}":"Add or update secrets","\u{1F516}":"Release / Version tags","\u{1F6A8}":"Fix compiler / linter warnings","\u{1F6A7}":"Work in progress","\u{1F49A}":"Fix CI Build","\u2B07\uFE0F":"Downgrade dependencies","\u2B06\uFE0F":"Upgrade dependencies","\u{1F4CC}":"Pin dependencies to specific versions","\u{1F477}":"Add or update CI build system","\u{1F4C8}":"Add or update analytics or track code","\u267B\uFE0F":"Refactor code","\u2795":"Add a dependency","\u2796":"Remove a dependency","\u{1F527}":"Add or update configuration files","\u{1F528}":"Add or update development scripts","\u{1F310}":"Internationalization and localization","\u270F\uFE0F":"Fix typos","\u{1F4A9}":"Write bad code that needs to be improved","\u23EA":"Revert changes","\u{1F500}":"Merge branches","\u{1F4E6}":"Add or update compiled files or packages","\u{1F47D}":"Update code due to external API changes","\u{1F69A}":"Move or rename resources (e.g.: files, paths, routes)","\u{1F4C4}":"Add or update license","\u{1F4A5}":"Introduce breaking changes","\u{1F371}":"Add or update assets","\u267F":"Improve accessibility","\u{1F4A1}":"Add or update comments in source code","\u{1F37B}":"Write code drunkenly","\u{1F4AC}":"Add or update text and literals","\u{1F5C3}":"Perform database related changes","\u{1F50A}":"Add or update logs","\u{1F507}":"Remove logs","\u{1F465}":"Add or update contributor(s)","\u{1F6B8}":"Improve user experience / usability","\u{1F3D7}":"Make architectural changes","\u{1F4F1}":"Work on responsive design","\u{1F921}":"Mock things","\u{1F95A}":"Add or update an easter egg","\u{1F648}":"Add or update a .gitignore file","\u{1F4F8}":"Add or update snapshots","\u2697":"Perform experiments","\u{1F50D}":"Improve SEO","\u{1F3F7}":"Add or update types","\u{1F331}":"Add or update seed files","\u{1F6A9}":"Add, update, or remove feature flags","\u{1F945}":"Catch errors","\u{1F4AB}":"Add or update animations and transitions","\u{1F5D1}":"Deprecate code that needs to be cleaned up","\u{1F6C2}":"Work on code related to authorization, roles and permissions","\u{1FA79}":"Simple fix for a non-critical issue","\u{1F9D0}":"Data exploration/inspection","\u26B0":"Remove dead code","\u{1F9EA}":"Add a failing test","\u{1F454}":"Add or update business logic","\u{1FA7A}":"Add or update healthcheck","\u{1F9F1}":"Infrastructure related changes","\u{1F9D1}\u200D\u{1F4BB}":"Improve developer experience","\u{1F4B8}":"Add sponsorships or money related infrastructure","\u{1F9F5}":"Add or update code related to multithreading or concurrency","\u{1F9BA}":"Add or update code related to validation"},null,2)}`},Hw=i((e,t,n)=>["Generate a concise git commit message title in present tense that precisely describes the key changes in the following code diff. Focus on what was changed, not just file names. Provide only the title, no description or body.",`Message language: ${e}`,`Commit message must be a maximum of ${t} characters.`,"Exclude anything unnecessary such as translation. Your entire response will be passed directly into git commit.",`IMPORTANT: Do not include any explanations, introductions, or additional text. Do not wrap the commit message in quotes or any other formatting. The commit message must not exceed ${t} characters. Respond with ONLY the commit message text.`,"Be specific: include concrete details (package names, versions, functionality) rather than generic statements.",Ww[n],Gw(n)].filter(Boolean).join(`
174
- `),"generatePrompt"),Jw=i(e=>{const t=/<think>[\s\S]*?<\/think>/gi;let n=e.replace(t,"");return n=n.trim(),n},"extractResponseFromReasoning"),Bs=i(e=>Jw(e).trim().split(`
175
- `)[0].replace(/(\w)\.$/,"$1").replace(/^["'`]|["'`]$/g,"").replace(/^<[^>]*>\s*/,""),"sanitizeMessage"),Tm=i(e=>Array.from(new Set(e)),"deduplicateMessages"),Bm=i(async(e,t,n,r,a)=>{const s=new AbortController,o=setTimeout(()=>s.abort(),a);try{const u=await Nr({model:e(t),system:`You are a tool that shortens git commit messages. Given a commit message, make it shorter while preserving the key information and format. The shortened message must be ${r} characters or less. Respond with ONLY the shortened commit message.`,prompt:n,temperature:.2,maxRetries:2,maxOutputTokens:500});return clearTimeout(o),Bs(u.text)}catch(u){throw clearTimeout(o),u}},"shortenCommitMessage"),Ss=i(async(e,t,n,r,a,s,o,u,l)=>{process.env.DEBUG&&(console.log("Diff being sent to AI:"),console.log(a));try{const c=e==="https://api.openai.com/v1"?ko({apiKey:t}):Ts({name:"custom",apiKey:t,baseURL:e}),d=new AbortController,m=setTimeout(()=>d.abort(),l),h=Array.from({length:s},()=>Nr({model:c(n),system:Hw(r,o,u),prompt:a,temperature:.4,maxRetries:2,maxOutputTokens:2e3}).finally(()=>clearTimeout(m))),D=await Promise.all(h);let f=D.map(E=>E.text),v=Tm(f.map(E=>Bs(E)));const y=3;for(let E=0;E<y;E++){let b=!1;const w=await Promise.all(v.map(async S=>{if(S.length<=o)return S;b=!0;try{return await Bm(c,n,S,o,l)}catch{return S}}));if(v=Tm(w),!b)break}const F={prompt_tokens:D.reduce((E,b)=>E+(b.usage.promptTokens||0),0),completion_tokens:D.reduce((E,b)=>E+(b.usage.completionTokens||0),0),total_tokens:D.reduce((E,b)=>E+(b.usage.totalTokens||0),0)};return{messages:v,usage:F}}catch(c){const d=c;if(console.log(d),d.code==="ENOTFOUND")throw new ue(`Error connecting to ${d.hostname} (${d.syscall}). Are you connected to the internet?`);if(d.status===429){const m=d.headers?.get("x-ratelimit-reset");let h="Rate limit exceeded";if(m){const D=parseInt(m),f=Date.now(),v=D-f,y=Math.ceil(v/1e3);if(y>0){let F;if(y<60)F=`${y} second${y===1?"":"s"}`;else if(y<3600){const E=Math.ceil(y/60);F=`${E} minute${E===1?"":"s"}`}else{const E=Math.ceil(y/3600);F=`${E} hour${E===1?"":"s"}`}h+=`. Retry in ${F}.`}}throw new ue(h)}throw d}},"generateCommitMessage"),Kw=i(async(e,t,n,r,a,s,o,u)=>{try{const l=t==="https://api.openai.com/v1"?ko({apiKey:n}):Ts({name:"custom",apiKey:n,baseURL:t}),c=new AbortController,d=setTimeout(()=>c.abort(),u),h=await Nr({model:l(r),system:`You are a tool that generates git commit messages. Your task is to combine multiple commit messages into one.
173
+ ${JSON.stringify({"\u{1F3A8}":"Improve structure / format of the code","\u26A1":"Improve performance","\u{1F525}":"Remove code or files","\u{1F41B}":"Fix a bug","\u{1F691}":"Critical hotfix","\u2728":"Introduce new features","\u{1F4DD}":"Add or update documentation","\u{1F680}":"Deploy stuff","\u{1F484}":"Add or update the UI and style files","\u{1F389}":"Begin a project","\u2705":"Add, update, or pass tests","\u{1F512}":"Fix security or privacy issues","\u{1F510}":"Add or update secrets","\u{1F516}":"Release / Version tags","\u{1F6A8}":"Fix compiler / linter warnings","\u{1F6A7}":"Work in progress","\u{1F49A}":"Fix CI Build","\u2B07\uFE0F":"Downgrade dependencies","\u2B06\uFE0F":"Upgrade dependencies","\u{1F4CC}":"Pin dependencies to specific versions","\u{1F477}":"Add or update CI build system","\u{1F4C8}":"Add or update analytics or track code","\u267B\uFE0F":"Refactor code","\u2795":"Add a dependency","\u2796":"Remove a dependency","\u{1F527}":"Add or update configuration files","\u{1F528}":"Add or update development scripts","\u{1F310}":"Internationalization and localization","\u270F\uFE0F":"Fix typos","\u{1F4A9}":"Write bad code that needs to be improved","\u23EA":"Revert changes","\u{1F500}":"Merge branches","\u{1F4E6}":"Add or update compiled files or packages","\u{1F47D}":"Update code due to external API changes","\u{1F69A}":"Move or rename resources (e.g.: files, paths, routes)","\u{1F4C4}":"Add or update license","\u{1F4A5}":"Introduce breaking changes","\u{1F371}":"Add or update assets","\u267F":"Improve accessibility","\u{1F4A1}":"Add or update comments in source code","\u{1F37B}":"Write code drunkenly","\u{1F4AC}":"Add or update text and literals","\u{1F5C3}":"Perform database related changes","\u{1F50A}":"Add or update logs","\u{1F507}":"Remove logs","\u{1F465}":"Add or update contributor(s)","\u{1F6B8}":"Improve user experience / usability","\u{1F3D7}":"Make architectural changes","\u{1F4F1}":"Work on responsive design","\u{1F921}":"Mock things","\u{1F95A}":"Add or update an easter egg","\u{1F648}":"Add or update a .gitignore file","\u{1F4F8}":"Add or update snapshots","\u2697":"Perform experiments","\u{1F50D}":"Improve SEO","\u{1F3F7}":"Add or update types","\u{1F331}":"Add or update seed files","\u{1F6A9}":"Add, update, or remove feature flags","\u{1F945}":"Catch errors","\u{1F4AB}":"Add or update animations and transitions","\u{1F5D1}":"Deprecate code that needs to be cleaned up","\u{1F6C2}":"Work on code related to authorization, roles and permissions","\u{1FA79}":"Simple fix for a non-critical issue","\u{1F9D0}":"Data exploration/inspection","\u26B0":"Remove dead code","\u{1F9EA}":"Add a failing test","\u{1F454}":"Add or update business logic","\u{1FA7A}":"Add or update healthcheck","\u{1F9F1}":"Infrastructure related changes","\u{1F9D1}\u200D\u{1F4BB}":"Improve developer experience","\u{1F4B8}":"Add sponsorships or money related infrastructure","\u{1F9F5}":"Add or update code related to multithreading or concurrency","\u{1F9BA}":"Add or update code related to validation"},null,2)}`},Kw=i((e,t,n)=>["Generate a concise git commit message title in present tense that precisely describes the key changes in the following code diff. Focus on what was changed, not just file names. Provide only the title, no description or body.",`Message language: ${e}`,`Commit message must be a maximum of ${t} characters.`,"Exclude anything unnecessary such as translation. Your entire response will be passed directly into git commit.",`IMPORTANT: Do not include any explanations, introductions, or additional text. Do not wrap the commit message in quotes or any other formatting. The commit message must not exceed ${t} characters. Respond with ONLY the commit message text.`,"Be specific: include concrete details (package names, versions, functionality) rather than generic statements.",Jw[n],Hw(n)].filter(Boolean).join(`
174
+ `),"generatePrompt"),Yw=i(e=>{const t=/<think>[\s\S]*?<\/think>/gi;let n=e.replace(t,"");return n=n.trim(),n},"extractResponseFromReasoning"),Bs=i(e=>Yw(e).trim().split(`
175
+ `)[0].replace(/(\w)\.$/,"$1").replace(/^["'`]|["'`]$/g,"").replace(/^<[^>]*>\s*/,""),"sanitizeMessage"),Sm=i(e=>Array.from(new Set(e)),"deduplicateMessages"),Om=i(async(e,t,n,r,a)=>{const s=new AbortController,o=setTimeout(()=>s.abort(),a);try{const u=await Nr({model:e(t),system:`You are a tool that shortens git commit messages. Given a commit message, make it shorter while preserving the key information and format. The shortened message must be ${r} characters or less. Respond with ONLY the shortened commit message.`,prompt:n,temperature:.2,maxRetries:2,maxOutputTokens:500});return clearTimeout(o),Bs(u.text)}catch(u){throw clearTimeout(o),u}},"shortenCommitMessage"),Ss=i(async(e,t,n,r,a,s,o,u,l)=>{process.env.DEBUG&&(console.log("Diff being sent to AI:"),console.log(a));try{const c=e==="https://api.openai.com/v1"?To({apiKey:t}):Ts({name:"custom",apiKey:t,baseURL:e}),d=new AbortController,m=setTimeout(()=>d.abort(),l),h=Array.from({length:s},()=>Nr({model:c(n),system:Kw(r,o,u),prompt:a,temperature:.4,maxRetries:2,maxOutputTokens:2e3}).finally(()=>clearTimeout(m))),D=await Promise.all(h);let f=D.map(E=>E.text),v=Sm(f.map(E=>Bs(E)));const y=3;for(let E=0;E<y;E++){let b=!1;const w=await Promise.all(v.map(async S=>{if(S.length<=o)return S;b=!0;try{return await Om(c,n,S,o,l)}catch{return S}}));if(v=Sm(w),!b)break}const F={prompt_tokens:D.reduce((E,b)=>E+(b.usage.promptTokens||0),0),completion_tokens:D.reduce((E,b)=>E+(b.usage.completionTokens||0),0),total_tokens:D.reduce((E,b)=>E+(b.usage.totalTokens||0),0)};return{messages:v,usage:F}}catch(c){const d=c;if(console.log(d),d.code==="ENOTFOUND")throw new ue(`Error connecting to ${d.hostname} (${d.syscall}). Are you connected to the internet?`);if(d.status===429){const m=d.headers?.get("x-ratelimit-reset");let h="Rate limit exceeded";if(m){const D=parseInt(m),f=Date.now(),v=D-f,y=Math.ceil(v/1e3);if(y>0){let F;if(y<60)F=`${y} second${y===1?"":"s"}`;else if(y<3600){const E=Math.ceil(y/60);F=`${E} minute${E===1?"":"s"}`}else{const E=Math.ceil(y/3600);F=`${E} hour${E===1?"":"s"}`}h+=`. Retry in ${F}.`}}throw new ue(h)}throw d}},"generateCommitMessage"),Xw=i(async(e,t,n,r,a,s,o,u)=>{try{const l=t==="https://api.openai.com/v1"?To({apiKey:n}):Ts({name:"custom",apiKey:n,baseURL:t}),c=new AbortController,d=setTimeout(()=>c.abort(),u),h=await Nr({model:l(r),system:`You are a tool that generates git commit messages. Your task is to combine multiple commit messages into one.
176
176
 
177
177
  Input: Several commit messages separated by newlines.
178
178
  Output: A single commit message starting with type like 'feat:' or 'fix:'.
179
179
 
180
180
  Do not add thanks, explanations, or any text outside the commit message.`,prompt:e.join(`
181
- `),temperature:.4,maxRetries:2,maxOutputTokens:2e3});clearTimeout(d);let D=Bs(h.text);if(D.length>s)try{D=await Bm(l,r,D,s,u)}catch{}return{messages:[D],usage:h.usage}}catch(l){const c=l;throw console.log(c),c}},"combineCommitMessages"),Yw=i(async(e,t)=>{const{select:n,confirm:r,isCancel:a}=await Promise.resolve().then(function(){return gr}),{dim:s}=await Promise.resolve().then(function(){return zD}),o=process.stdout.isTTY&&!process.env.CI;if(e.length===1){const[l]=e;if(t)return l;if(!o)throw new ue("Interactive terminal required for commit message confirmation. Use --confirm flag to skip confirmation.");console.log(`
181
+ `),temperature:.4,maxRetries:2,maxOutputTokens:2e3});clearTimeout(d);let D=Bs(h.text);if(D.length>s)try{D=await Om(l,r,D,s,u)}catch{}return{messages:[D],usage:h.usage}}catch(l){const c=l;throw console.log(c),c}},"combineCommitMessages"),Qw=i(async(e,t)=>{const{select:n,confirm:r,isCancel:a}=await Promise.resolve().then(function(){return gr}),{dim:s}=await Promise.resolve().then(function(){return ZD}),o=process.stdout.isTTY&&!process.env.CI;if(e.length===1){const[l]=e;if(t)return l;if(!o)throw new ue("Interactive terminal required for commit message confirmation. Use --confirm flag to skip confirmation.");console.log(`
182
182
  \x1B[1m${l}\x1B[0m
183
- `);const c=await r({message:"Use this commit message?"});return c&&!a(c)?l:null}if(t)return e[0];if(!o)throw new ue("Interactive terminal required for commit message selection. Use --confirm flag to skip selection and use the first message.");const u=await n({message:`Pick a commit message to use: ${s("(Ctrl+c to exit)")}`,options:e.map(l=>({label:l,value:l}))});return a(u)?null:u},"getCommitMessage");var Xw=i(async(e,t,n,r,a,s,o,u)=>(async()=>{ro(Yr(Kr(" aicommits "))),await xa();const l=Mt();n&&await Ge("git",["add","--update"]),l.start("Detecting staged files");const c=await Wu(t);if(!c)throw l.stop("Detecting staged files"),new ue("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");c.files.length<=10?l.stop(`\u{1F4C1} ${Hu(c.files)}:
183
+ `);const c=await r({message:"Use this commit message?"});return c&&!a(c)?l:null}if(t)return e[0];if(!o)throw new ue("Interactive terminal required for commit message selection. Use --confirm flag to skip selection and use the first message.");const u=await n({message:`Pick a commit message to use: ${s("(Ctrl+c to exit)")}`,options:e.map(l=>({label:l,value:l}))});return a(u)?null:u},"getCommitMessage");var e1=i(async(e,t,n,r,a,s,o,u)=>(async()=>{ao(Qr(Xr(" aicommits "))),await xa();const l=Mt();n&&await Ge("git",["add","--update"]),l.start("Detecting staged files");const c=await Ju(t);if(!c)throw l.stop("Detecting staged files"),new ue("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");c.files.length<=10?l.stop(`\u{1F4C1} ${Ku(c.files)}:
184
184
  ${c.files.map(C=>` ${C}`).join(`
185
- `)}`):l.stop(`\u{1F4C1} ${Hu(c.files)}`);const{env:d}=process,m=await jt({generate:e?.toString(),type:r?.toString()}),h=ln(m);if(!h)if(process.stdout.isTTY&&!process.env.CI){console.log("Welcome to aicommits! Let's set up your AI provider."),console.log("Run `aicommits setup` to configure your provider."),ve("Setup required. Please run: aicommits setup");return}else throw new ue("No configuration found. Run `aicommits setup` in an interactive terminal, or set environment variables (OPENAI_API_KEY, etc.)");const D=m.timeout||(h.name==="ollama"?3e4:1e4),f=h.validateConfig();if(!f.valid)throw new ue(`Provider configuration issues: ${f.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);m.model=m.OPENAI_MODEL||h.getDefaultModel();const v=50,y=10;let F=!1;c.files.length>v&&(F=!0);const E=Mt();E.start(`\u{1F50D} Analyzing changes in ${c.files.length} file${c.files.length===1?"":"s"}`);const b=Date.now();let w,S;try{const C=h.getBaseUrl(),z=h.getApiKey()||"";if(F){const W=[];for(let j=0;j<c.files.length;j+=y)W.push(c.files.slice(j,j+y));const B=[];let R={promptTokens:0,completionTokens:0,totalTokens:0};for(const j of W){const L=await Eg(j,t);if(L&&L.diff){let Z=L.diff;Z.length>3e4&&(Z=Z.substring(Z.length-3e4)+`
185
+ `)}`):l.stop(`\u{1F4C1} ${Ku(c.files)}`);const{env:d}=process,m=await jt({generate:e?.toString(),type:r?.toString()}),h=ln(m);if(!h)if(process.stdout.isTTY&&!process.env.CI){console.log("Welcome to aicommits! Let's set up your AI provider."),console.log("Run `aicommits setup` to configure your provider."),ve("Setup required. Please run: aicommits setup");return}else throw new ue("No configuration found. Run `aicommits setup` in an interactive terminal, or set environment variables (OPENAI_API_KEY, etc.)");const D=m.timeout||(h.name==="ollama"?3e4:1e4),f=h.validateConfig();if(!f.valid)throw new ue(`Provider configuration issues: ${f.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);m.model=m.OPENAI_MODEL||h.getDefaultModel();const v=50,y=10;let F=!1;c.files.length>v&&(F=!0);const E=Mt();E.start(`\u{1F50D} Analyzing changes in ${c.files.length} file${c.files.length===1?"":"s"}`);const b=Date.now();let w,S;try{const C=h.getBaseUrl(),z=h.getApiKey()||"";if(F){const W=[];for(let j=0;j<c.files.length;j+=y)W.push(c.files.slice(j,j+y));const B=[];let R={promptTokens:0,completionTokens:0,totalTokens:0};for(const j of W){const U=await Ag(j,t);if(U&&U.diff){let Z=U.diff;Z.length>3e4&&(Z=Z.substring(Z.length-3e4)+`
186
186
 
187
- [Diff truncated due to size]`);const X=await Ss(C,z,m.model,m.locale,Z,m.generate,m["max-length"],m.type,D);B.push(...X.messages),X.usage&&(R.promptTokens+=X.usage.promptTokens||0,R.completionTokens+=X.usage.completionTokens||0,R.totalTokens+=X.usage.totalTokens||0)}}const O=await Kw(B,C,z,m.model,m.locale,m["max-length"],m.type,D);w=O.messages,O.usage&&(R.promptTokens+=O.usage.promptTokens||0,R.completionTokens+=O.usage.completionTokens||0,R.totalTokens+=O.usage.totalTokens||0),S=R}else{let B=c.diff;B.length>3e4&&(B=B.substring(B.length-3e4)+`
187
+ [Diff truncated due to size]`);const X=await Ss(C,z,m.model,m.locale,Z,m.generate,m["max-length"],m.type,D);B.push(...X.messages),X.usage&&(R.promptTokens+=X.usage.promptTokens||0,R.completionTokens+=X.usage.completionTokens||0,R.totalTokens+=X.usage.totalTokens||0)}}const O=await Xw(B,C,z,m.model,m.locale,m["max-length"],m.type,D);w=O.messages,O.usage&&(R.promptTokens+=O.usage.promptTokens||0,R.completionTokens+=O.usage.completionTokens||0,R.totalTokens+=O.usage.totalTokens||0),S=R}else{let B=c.diff;B.length>3e4&&(B=B.substring(B.length-3e4)+`
188
188
 
189
- [Diff truncated due to size]`);const R=await Ss(C,z,m.model,m.locale,B,m.generate,m["max-length"],m.type,D);w=R.messages,S=R.usage}}finally{const C=Date.now()-b;let z="";if(S?.total_tokens){const W=S.total_tokens,B=W>=1e3?`${(W/1e3).toFixed(0)}k`:W.toString(),R=Math.round(W/(C/1e3));z=`, ${B} tokens (${R} tokens/s)`}E.stop(`\u2705 Changes analyzed in ${(C/1e3).toFixed(1)}s${z}`)}if(w.length===0)throw new ue("No commit messages were generated. Try again.");const k=await Yw(w,a);if(!k){ve("Commit cancelled");return}if(s){await bu(k)&&ve(`${ft("\u2714")} Message copied to clipboard`);return}try{const C=["-m",k];o&&C.push("--no-verify"),await Ge("git",["commit",...C,...u],{stdio:"inherit",cleanup:!0,timeout:1e4}),ve(`${ft("\u2714")} Successfully committed!`)}catch(C){if(C.timedOut){const z=await bu(k);ve(z?`${da("\u26A0")} Commit timed out after 10 seconds. Message copied to clipboard.`:`${da("\u26A0")} Commit timed out after 10 seconds. Could not copy to clipboard.`);return}throw C}})().catch(oo),"aicommits");const[$o,Qw]=process.argv.slice(2);var e1=i(()=>(async()=>{if(!$o)throw new ue('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(Qw)return;const e=await Wu();if(!e)return;ro(Yr(Kr(" aicommits ")));const t=await jt({}),n=ln(t);if(!n)throw new ue("Invalid provider configuration. Run `aicommits setup` to reconfigure.");const r=n.validateConfig();if(!r.valid)throw new ue(`Provider configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);const a=n.getBaseUrl(),s=n.getApiKey()||"",o=t.timeout||(n.name==="ollama"?3e4:1e4);let u=t.OPENAI_MODEL||n.getDefaultModel();const l=Mt();l.start("The AI is analyzing your changes");let c;try{c=(await Ss(a,s,u,t.locale,e.diff,t.generate,t["max-length"],t.type,o)).messages}finally{l.stop("Changes analyzed")}const m=await Ne.readFile($o,"utf8")!=="",h=c.length>1;let D="";m&&(D=`# \u{1F916} AI generated commit${h?"s":""}
189
+ [Diff truncated due to size]`);const R=await Ss(C,z,m.model,m.locale,B,m.generate,m["max-length"],m.type,D);w=R.messages,S=R.usage}}finally{const C=Date.now()-b;let z="";if(S?.total_tokens){const W=S.total_tokens,B=W>=1e3?`${(W/1e3).toFixed(0)}k`:W.toString(),R=Math.round(W/(C/1e3));z=`, ${B} tokens (${R} tokens/s)`}E.stop(`\u2705 Changes analyzed in ${(C/1e3).toFixed(1)}s${z}`)}if(w.length===0)throw new ue("No commit messages were generated. Try again.");const k=await Qw(w,a);if(!k){ve("Commit cancelled");return}if(s){await wu(k)&&ve(`${ft("\u2714")} Message copied to clipboard`);return}try{const C=["-m",k];o&&C.push("--no-verify"),await Ge("git",["commit",...C,...u],{stdio:"inherit",cleanup:!0,timeout:1e4}),ve(`${ft("\u2714")} Successfully committed!`)}catch(C){if(C.timedOut){const z=await wu(k);ve(z?`${da("\u26A0")} Commit timed out after 10 seconds. Message copied to clipboard.`:`${da("\u26A0")} Commit timed out after 10 seconds. Could not copy to clipboard.`);return}throw C}})().catch(so),"aicommits");const[Bo,t1]=process.argv.slice(2);var n1=i(()=>(async()=>{if(!Bo)throw new ue('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(t1)return;const e=await Ju();if(!e)return;ao(Qr(Xr(" aicommits ")));const t=await jt({}),n=ln(t);if(!n)throw new ue("Invalid provider configuration. Run `aicommits setup` to reconfigure.");const r=n.validateConfig();if(!r.valid)throw new ue(`Provider configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);const a=n.getBaseUrl(),s=n.getApiKey()||"",o=t.timeout||(n.name==="ollama"?3e4:1e4);let u=t.OPENAI_MODEL||n.getDefaultModel();const l=Mt();l.start("The AI is analyzing your changes");let c;try{c=(await Ss(a,s,u,t.locale,e.diff,t.generate,t["max-length"],t.type,o)).messages}finally{l.stop("Changes analyzed")}const m=await Ne.readFile(Bo,"utf8")!=="",h=c.length>1;let D="";m&&(D=`# \u{1F916} AI generated commit${h?"s":""}
190
190
  `),h?(m&&(D+=`# Select one of the following messages by uncommenting:
191
191
  `),D+=`
192
192
  ${c.map(y=>`# ${y}`).join(`
193
193
  `)}`):(m&&(D+=`# Edit the message below and commit:
194
194
  `),D+=`
195
195
  ${c[0]}
196
- `);const f=await Ne.readFile($o,"utf8"),v=D+`
197
- `+f;await Ne.writeFile($o,v),ve(`${ft("\u2714")} Saved commit message!`)})().catch(oo),"prepareCommitMessageHook"),t1=rn({name:"config",description:"View or modify configuration settings",help:{description:"View or modify configuration settings"},parameters:["[mode]","[key=value...]"]},e=>{(async()=>{const[t,...n]=e._;if(!t){const r=await jt({},{},!0);console.log("Provider:",r.provider),r.OPENAI_API_KEY&&console.log("API Key:",`${r.OPENAI_API_KEY.substring(0,4)}****`),r.OPENAI_BASE_URL&&console.log("Base URL:",r.OPENAI_BASE_URL),r.OPENAI_MODEL&&console.log("Model:",r.OPENAI_MODEL);return}if(t==="get"){const r=await jt({},{},!0),a=["OPENAI_API_KEY","TOGETHER_API_KEY","api-key"];for(const s of n)if(Ta(r,s)){const o=r[s],u=a.includes(s)?`${String(o).substring(0,4)}****`:String(o);console.log(`${s}=${u}`)}return}if(t==="set"){await Sa(n.map(r=>r.split("=")));return}throw new ue(`Invalid mode: ${t}`)})().catch(oo)}),n1=rn({name:"setup",description:"Configure your AI provider and settings",help:{description:"Configure your AI provider and settings"}},e=>{(async()=>{let t=await jt();const n=Hg(),r=await Lu({message:"Choose your AI provider:",options:n,initialValue:t.provider});if(Dr(r)){ve("Setup cancelled");return}const a=r;let s="";if(a==="custom"){const h=await Zu({message:"Enter your custom API endpoint:",validate:i(D=>{if(!D)return"Endpoint is required";try{new URL(D)}catch{return"Invalid URL format"}},"validate")});if(Dr(h)){ve("Setup cancelled");return}s=h}let o=s||Jg(a);t.OPENAI_BASE_URL=o,t.OPENAI_API_KEY="",t.OPENAI_MODEL="";let u=ln({...t,provider:a});if(!u){ve("Invalid provider selected");return}try{const h=await u.setup();for(const[D,f]of h)t[D]=f}catch(h){if(h instanceof Error&&h.message==="Setup cancelled"){ve("Setup cancelled");return}throw h}if(u=ln({...t,provider:a}),!u){ve("Invalid provider selected");return}const l=u.validateConfig();if(!l.valid){ve(`Setup cancelled: ${l.errors.join(", ")}`);return}const{selectModel:c}=await Promise.resolve().then(function(){return Vg}),d=await c(u.getBaseUrl(),u.getApiKey()||"",void 0,u.getDefinition());if(d)t.OPENAI_MODEL=d,console.log(`Model selected: ${d}`);else{ve("Model selection cancelled.");return}const m=Object.entries(t).filter(([h,D])=>h!=="provider"&&h!=="model"&&D!==void 0&&D!==""&&typeof D=="string");await Sa(m),ve(`\u2705 Setup complete! You're now using ${u.displayName}.`)})().catch(t=>{console.error(`\u274C Setup failed: ${t.message}`),process.exit(1)})}),r1=rn({name:"model",description:"Select or change your AI model",help:{description:"Select or change your AI model"},alias:["-m","models"]},()=>{(async()=>{const e=await jt();if(!e.provider){ve("No provider configured. Run `aicommits setup` first.");return}const t=ln(e);if(!t){ve("Invalid provider configured. Run `aicommits setup` to reconfigure.");return}console.log(`Current provider: ${t.displayName}`);const n=e.OPENAI_MODEL;console.log(`Current model: ${n&&n!=="undefined"?n:"not set"}`);const r=t.validateConfig();if(!r.valid){ve(`Configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);return}const a=await tl(t.getBaseUrl(),t.getApiKey()||"",n,t.getDefinition());a?(await Sa([["OPENAI_MODEL",a]]),ve(`\u2705 Model updated to: ${a}`)):ve("Model selection cancelled")})().catch(e=>{console.error(`\u274C Model selection failed: ${e.message}`),process.exit(1)})});const Sm="prepare-commit-msg",Om=`.git/hooks/${Sm}`,To=nf(new URL("cli.mjs",import.meta.url)),o1=process.argv[1].replace(/\\/g,"/").endsWith(`/${Om}`),Rm=process.platform==="win32",Nm=`
196
+ `);const f=await Ne.readFile(Bo,"utf8"),v=D+`
197
+ `+f;await Ne.writeFile(Bo,v),ve(`${ft("\u2714")} Saved commit message!`)})().catch(so),"prepareCommitMessageHook"),r1=rn({name:"config",description:"View or modify configuration settings",help:{description:"View or modify configuration settings"},parameters:["[mode]","[key=value...]"]},e=>{(async()=>{const[t,...n]=e._;if(!t){const r=await jt({},{},!0);console.log("Provider:",r.provider),r.OPENAI_API_KEY&&console.log("API Key:",`${r.OPENAI_API_KEY.substring(0,4)}****`),r.OPENAI_BASE_URL&&console.log("Base URL:",r.OPENAI_BASE_URL),r.OPENAI_MODEL&&console.log("Model:",r.OPENAI_MODEL);return}if(t==="get"){const r=await jt({},{},!0),a=["OPENAI_API_KEY","TOGETHER_API_KEY","api-key"];for(const s of n)if(Ta(r,s)){const o=r[s],u=a.includes(s)?`${String(o).substring(0,4)}****`:String(o);console.log(`${s}=${u}`)}return}if(t==="set"){await Sa(n.map(r=>r.split("=")));return}throw new ue(`Invalid mode: ${t}`)})().catch(so)}),o1=rn({name:"setup",description:"Configure your AI provider and settings",help:{description:"Configure your AI provider and settings"}},e=>{(async()=>{let t=await jt();const n=Kg(),r=await Vu({message:"Choose your AI provider:",options:n,initialValue:t.provider});if(Dr(r)){ve("Setup cancelled");return}const a=r;let s="";if(a==="custom"){const h=await Lu({message:"Enter your custom API endpoint:",validate:i(D=>{if(!D)return"Endpoint is required";try{new URL(D)}catch{return"Invalid URL format"}},"validate")});if(Dr(h)){ve("Setup cancelled");return}s=h}let o=s||Yg(a);t.OPENAI_BASE_URL=o,t.OPENAI_API_KEY="",t.OPENAI_MODEL="";let u=ln({...t,provider:a});if(!u){ve("Invalid provider selected");return}try{const h=await u.setup();for(const[D,f]of h)t[D]=f}catch(h){if(h instanceof Error&&h.message==="Setup cancelled"){ve("Setup cancelled");return}throw h}if(u=ln({...t,provider:a}),!u){ve("Invalid provider selected");return}const l=u.validateConfig();if(!l.valid){ve(`Setup cancelled: ${l.errors.join(", ")}`);return}const{selectModel:c}=await Promise.resolve().then(function(){return Wg}),d=await c(u.getBaseUrl(),u.getApiKey()||"",void 0,u.getDefinition());if(d)t.OPENAI_MODEL=d,console.log(`Model selected: ${d}`);else{ve("Model selection cancelled.");return}const m=Object.entries(t).filter(([h,D])=>h!=="provider"&&h!=="model"&&D!==void 0&&D!==""&&typeof D=="string");await Sa(m),ve(`\u2705 Setup complete! You're now using ${u.displayName}.`)})().catch(t=>{console.error(`\u274C Setup failed: ${t.message}`),process.exit(1)})}),a1=rn({name:"model",description:"Select or change your AI model",help:{description:"Select or change your AI model"},alias:["-m","models"]},()=>{(async()=>{const e=await jt();if(!e.provider){ve("No provider configured. Run `aicommits setup` first.");return}const t=ln(e);if(!t){ve("Invalid provider configured. Run `aicommits setup` to reconfigure.");return}console.log(`Current provider: ${t.displayName}`);const n=e.OPENAI_MODEL;console.log(`Current model: ${n&&n!=="undefined"?n:"not set"}`);const r=t.validateConfig();if(!r.valid){ve(`Configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);return}const a=await rl(t.getBaseUrl(),t.getApiKey()||"",n,t.getDefinition());a?(await Sa([["OPENAI_MODEL",a]]),ve(`\u2705 Model updated to: ${a}`)):ve("Model selection cancelled")})().catch(e=>{console.error(`\u274C Model selection failed: ${e.message}`),process.exit(1)})});const Rm="prepare-commit-msg",Nm=`.git/hooks/${Rm}`,So=of(new URL("cli.mjs",import.meta.url)),s1=process.argv[1].replace(/\\/g,"/").endsWith(`/${Nm}`),Pm=process.platform==="win32",Mm=`
198
198
  #!/usr/bin/env node
199
- import(${JSON.stringify(rf(To))})
200
- `.trim();var a1=rn({name:"hook",description:"Install or uninstall the Git hook for automatic commit messages",help:{description:"Install or uninstall the Git hook for automatic commit messages"},parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await xa(),{installUninstall:n}=e._,r=at.join(t,Om),a=await $a(r);if(n==="install"){if(a){if(await Ne.realpath(r).catch(()=>{})===To){console.warn("The hook is already installed");return}throw new ue(`A different ${Sm} hook seems to be installed. Please remove it before installing aicommits.`)}await Ne.mkdir(at.dirname(r),{recursive:!0}),Rm?await Ne.writeFile(r,Nm):(await Ne.symlink(To,r,"file"),await Ne.chmod(r,493)),console.log(`${ft("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!a){console.warn("Hook is not installed");return}if(Rm){if(await Ne.readFile(r,"utf8")!==Nm){console.warn("Hook is not installed");return}}else if(await Ne.realpath(r)!==To){console.warn("Hook is not installed");return}await Ne.rm(r),console.log(`${ft("\u2714")} Hook uninstalled`);return}throw new ue(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${pa("\u2716")} ${t.message}`),Uu(t),process.exit(1)})}),s1=rn({name:"pr",description:"[beta \u{1F6A7}] Generate and create a PR on GitHub based on branch diff",help:{description:"[beta \u{1F6A7}] Generate and create a PR on GitHub based on branch diff"}},()=>{(async()=>{ro(Yr(Kr(" aicommits pr "))),await xa();const{stdout:e}=await Ge("git",["branch","--show-current"]);if(!e.trim())throw new ue("Not on a branch");const{stdout:t}=await Ge("git",["remote","get-url","origin"]),n=t.match(/github\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(!n)throw new ue("Could not determine GitHub repository from remote URL");const[,r,a]=n;let s="main";try{const{stdout:B}=await Ge("git",["symbolic-ref","refs/remotes/origin/HEAD"]);s=B.trim().replace("refs/remotes/origin/","")}catch{}if(e.trim()===s)throw new ue("PR creation requires being on a feature branch, not the default branch. Please switch to a feature branch with changes.");let o;try{const{stdout:B}=await Ge("git",["diff",`origin/${s}..HEAD`]);o=B}catch{throw new ue(`Could not get diff from origin/${s}`)}if(!o)throw new ue("No changes to create PR from");const u=o.split(`
199
+ import(${JSON.stringify(af(So))})
200
+ `.trim();var i1=rn({name:"hook",description:"Install or uninstall the Git hook for automatic commit messages",help:{description:"Install or uninstall the Git hook for automatic commit messages"},parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await xa(),{installUninstall:n}=e._,r=at.join(t,Nm),a=await $a(r);if(n==="install"){if(a){if(await Ne.realpath(r).catch(()=>{})===So){console.warn("The hook is already installed");return}throw new ue(`A different ${Rm} hook seems to be installed. Please remove it before installing aicommits.`)}await Ne.mkdir(at.dirname(r),{recursive:!0}),Pm?await Ne.writeFile(r,Mm):(await Ne.symlink(So,r,"file"),await Ne.chmod(r,493)),console.log(`${ft("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!a){console.warn("Hook is not installed");return}if(Pm){if(await Ne.readFile(r,"utf8")!==Mm){console.warn("Hook is not installed");return}}else if(await Ne.realpath(r)!==So){console.warn("Hook is not installed");return}await Ne.rm(r),console.log(`${ft("\u2714")} Hook uninstalled`);return}throw new ue(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${pa("\u2716")} ${t.message}`),Gu(t),process.exit(1)})}),u1=rn({name:"pr",description:"[beta \u{1F6A7}] Generate and create a PR on GitHub based on branch diff",help:{description:"[beta \u{1F6A7}] Generate and create a PR on GitHub based on branch diff"}},()=>{(async()=>{ao(Qr(Xr(" aicommits pr "))),await xa();const{stdout:e}=await Ge("git",["branch","--show-current"]);if(!e.trim())throw new ue("Not on a branch");const{stdout:t}=await Ge("git",["remote","get-url","origin"]),n=t.match(/github\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(!n)throw new ue("Could not determine GitHub repository from remote URL");const[,r,a]=n;let s="main";try{const{stdout:B}=await Ge("git",["symbolic-ref","refs/remotes/origin/HEAD"]);s=B.trim().replace("refs/remotes/origin/","")}catch{}if(e.trim()===s)throw new ue("PR creation requires being on a feature branch, not the default branch. Please switch to a feature branch with changes.");let o;try{const{stdout:B}=await Ge("git",["diff",`origin/${s}..HEAD`]);o=B}catch{throw new ue(`Could not get diff from origin/${s}`)}if(!o)throw new ue("No changes to create PR from");const u=o.split(`
201
201
  `).filter(B=>B.startsWith("diff --git")).length,l=3e4;o.length>l&&(o=o.substring(0,l)+`
202
202
 
203
- [Diff truncated due to size]`);const c=await jt(),d=await ln(c);if(!d)throw new ue("No provider configured");let m=d.getBaseUrl();if(!m||m==="")throw new ue("Base URL not configured. Please run `aicommits setup` to configure your provider.");m.endsWith("/v1")||(m+="/v1");const h=d.getApiKey();if(!h)throw new ue("API key not configured. Please run `aicommits setup` to configure your provider.");const D=m==="https://api.openai.com/v1"?ko({apiKey:h}):Ts({name:"custom",apiKey:h,baseURL:m}),f=Mt();f.start(`Generating PR title and description (${u} files changed)`);const v=Date.now(),F=(await Nr({model:D(c.model),system:"Generate a concise PR title based on the following git diff. The title should be under 72 characters.",prompt:o,maxRetries:2})).text,b=(await Nr({model:D(c.model),system:"Generate a concise PR description based on the following git diff. Format using Markdown with headings like ### Summary, ### Changes, ### Review Notes. Provide a high-level summary of the changes, what was implemented or fixed, and any specific details reviewers should consider. Avoid listing individual files.",prompt:o,maxRetries:2})).text,w=Date.now(),S=Math.round((w-v)/1e3);f.stop(`Generated PR content for ${u} files in ${S}s`),console.log(`${ft("Title:")} ${F.replace(/\n/g," ")}`),console.log(`${ft("Body:")} ${b.length>100?b.substring(0,100)+"...":b}`);const{text:k}=await Promise.resolve().then(function(){return gr}),C=await k({message:"Press Enter to open PR creation in browser, or Ctrl+C to cancel",placeholder:"Press Enter"});if(Dr(C)){ve("PR creation cancelled");return}const z=`https://github.com/${r}/${a}/compare/${s}...${e.trim()}?expand=1&title=${encodeURIComponent(F)}&body=${encodeURIComponent(b)}`,W=Mt();W.start("Opening PR creation page in browser");try{const B=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";await Ge(B,[z]),W.stop("PR creation page opened in browser"),ve(ft("PR creation page opened! Please review and submit the PR."))}catch{W.stop("Failed to open browser"),ve(`${ft("PR URL:")} ${z}`),ve("Please open the URL above in your browser to create the PR.")}})().catch(e=>{oo(e)})});const{description:i1,version:Bo}=Vo,u1=Zm({pkg:Vo,distTag:Bo.includes("-")?"develop":"latest"});Bo!=="0.0.0-semantic-release"&&Bo.includes("-")&&u1.notify();const Pm=process.argv.slice(2);Wi({name:"aicommits",flags:{generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Git commit message format (default: conventional). Supports conventional and gitmoji",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard instead of committing (default: false)",alias:"c",default:!1},noVerify:{type:Boolean,description:"Bypass pre-commit hooks while committing (default: false)",alias:"n",default:!1},version:{type:Boolean,description:"Show version number",alias:"v"}},commands:[t1,n1,r1,a1,s1],help:{description:i1},ignoreArgv:i(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{e.flags.version&&(console.log(Bo),process.exit(0)),o1?e1():Xw(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.confirm,e.flags.clipboard,e.flags.noVerify,Pm)},Pm);export{St as g,sp as r};
203
+ [Diff truncated due to size]`);const c=await jt(),d=await ln(c);if(!d)throw new ue("No provider configured");let m=d.getBaseUrl();if(!m||m==="")throw new ue("Base URL not configured. Please run `aicommits setup` to configure your provider.");m.endsWith("/v1")||(m+="/v1");const h=d.getApiKey();if(!h)throw new ue("API key not configured. Please run `aicommits setup` to configure your provider.");const D=m==="https://api.openai.com/v1"?To({apiKey:h}):Ts({name:"custom",apiKey:h,baseURL:m}),f=Mt();f.start(`Generating PR title and description (${u} files changed)`);const v=Date.now(),F=(await Nr({model:D(c.model),system:"Generate a concise PR title based on the following git diff. The title should be under 72 characters.",prompt:o,maxRetries:2})).text,b=(await Nr({model:D(c.model),system:"Generate a concise PR description based on the following git diff. Format using Markdown with headings like ### Summary, ### Changes, ### Review Notes. Provide a high-level summary of the changes, what was implemented or fixed, and any specific details reviewers should consider. Avoid listing individual files.",prompt:o,maxRetries:2})).text,w=Date.now(),S=Math.round((w-v)/1e3);f.stop(`Generated PR content for ${u} files in ${S}s`),console.log(`${ft("Title:")} ${F.replace(/\n/g," ")}`),console.log(`${ft("Body:")} ${b.length>100?b.substring(0,100)+"...":b}`);const{text:k}=await Promise.resolve().then(function(){return gr}),C=await k({message:"Press Enter to open PR creation in browser, or Ctrl+C to cancel",placeholder:"Press Enter"});if(Dr(C)){ve("PR creation cancelled");return}const z=`https://github.com/${r}/${a}/compare/${s}...${e.trim()}?expand=1&title=${encodeURIComponent(F)}&body=${encodeURIComponent(b)}`,W=Mt();W.start("Opening PR creation page in browser");try{const B=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";await Ge(B,[z]),W.stop("PR creation page opened in browser"),ve(ft("PR creation page opened! Please review and submit the PR."))}catch{W.stop("Failed to open browser"),ve(`${ft("PR URL:")} ${z}`),ve("Please open the URL above in your browser to create the PR.")}})().catch(e=>{so(e)})});const l1=ef(si);async function c1(e){const{pkg:t,distTag:n="latest",autoUpdate:r=!0}=e;if(t.version==="0.0.0-semantic-release")return;const a=ni({pkg:t,distTag:t.version.includes("-")?"develop":n}),s=a.update;if(!s||!r){s&&!r&&a.notify();return}if(!await p1(t.name)){a.notify();return}console.log(`Updating ${t.name} from v${s.current} to v${s.latest}...`);try{await d1(t.name),console.log(`\u2713 ${t.name} updated to v${s.latest}`),console.log("Please restart to use the new version.")}catch{console.log("Auto-update failed. You can manually update with:"),console.log(` npm update -g ${t.name}`),a.notify()}}i(c1,"checkAndAutoUpdate");async function p1(e){try{const{stdout:t}=await l1(`npm list -g ${e} --depth=0`);return t.includes(e)}catch{return!1}}i(p1,"checkIfGlobalInstallation");async function d1(e){return new Promise((t,n)=>{const r=si(`npm update -g ${e}`,{timeout:6e4,env:{...process.env,NPM_CONFIG_PROGRESS:"false"}});r.on("error",a=>{n(a)}),r.on("exit",a=>{a===0||a===null?t():n(new Error(`npm update exited with code ${a}`))})})}i(d1,"runBackgroundUpdate");const{description:m1,version:jr}=Gr,f1=ni({pkg:Gr,distTag:jr.includes("-")?"develop":"latest"});jr!=="0.0.0-semantic-release"&&jr.includes("-")&&c1({pkg:Gr,distTag:jr.includes("-")?"develop":"latest",autoUpdate:!0}).catch(()=>{f1.notify()});const jm=process.argv.slice(2);Ji({name:"aicommits",flags:{generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Git commit message format (default: conventional). Supports conventional and gitmoji",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard instead of committing (default: false)",alias:"c",default:!1},noVerify:{type:Boolean,description:"Bypass pre-commit hooks while committing (default: false)",alias:"n",default:!1},version:{type:Boolean,description:"Show version number",alias:"v"}},commands:[r1,o1,a1,i1,u1],help:{description:m1},ignoreArgv:i(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{e.flags.version&&(console.log(jr),process.exit(0)),s1?n1():e1(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.confirm,e.flags.clipboard,e.flags.noVerify,jm)},jm);export{St as g,up as r};