goatchain-cli 0.0.5-beta.9 → 0.0.6-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/goatchain +79 -0
- package/package.json +12 -52
- package/postinstall.mjs +37 -0
- package/cli.mjs +0 -2
- package/dist/cli.mjs +0 -1016
package/dist/cli.mjs
DELETED
|
@@ -1,1016 +0,0 @@
|
|
|
1
|
-
import{createRequire as Xb}from"node:module";var Ub=Object.create;var{getPrototypeOf:_b,defineProperty:CX,getOwnPropertyNames:Qb}=Object;var Gb=Object.prototype.hasOwnProperty;var U4=($,J,U)=>{U=$!=null?Ub(_b($)):{};let Q=J||!$||!$.__esModule?CX(U,"default",{value:$,enumerable:!0}):U;for(let _ of Qb($))if(!Gb.call(Q,_))CX(Q,_,{get:()=>$[_],enumerable:!0});return Q};var J$=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var F1=($,J)=>{for(var U in J)CX($,U,{get:J[U],enumerable:!0,configurable:!0,set:(Q)=>J[U]=()=>Q})};var Vb=($,J)=>()=>($&&(J=$($=0)),J);var E$=Xb(import.meta.url);var vE=J$((SE)=>{Object.defineProperty(SE,"__esModule",{value:!0});SE.splitWhen=SE.flatten=void 0;function Ox($){return $.reduce((J,U)=>[].concat(J,U),[])}SE.flatten=Ox;function jx($,J){let U=[[]],Q=0;for(let _ of $)if(J(_))Q++,U[Q]=[];else U[Q].push(_);return U}SE.splitWhen=jx});var yE=J$((CE)=>{Object.defineProperty(CE,"__esModule",{value:!0});CE.isEnoentCodeError=void 0;function Ex($){return $.code==="ENOENT"}CE.isEnoentCodeError=Ex});var uE=J$((xE)=>{Object.defineProperty(xE,"__esModule",{value:!0});xE.createDirentFromStats=void 0;class gE{constructor($,J){this.name=$,this.isBlockDevice=J.isBlockDevice.bind(J),this.isCharacterDevice=J.isCharacterDevice.bind(J),this.isDirectory=J.isDirectory.bind(J),this.isFIFO=J.isFIFO.bind(J),this.isFile=J.isFile.bind(J),this.isSocket=J.isSocket.bind(J),this.isSymbolicLink=J.isSymbolicLink.bind(J)}}function Px($,J){return new gE($,J)}xE.createDirentFromStats=Px});var rE=J$((lE)=>{Object.defineProperty(lE,"__esModule",{value:!0});lE.convertPosixPathToPattern=lE.convertWindowsPathToPattern=lE.convertPathToPattern=lE.escapePosixPath=lE.escapeWindowsPath=lE.escape=lE.removeLeadingDotSegment=lE.makeAbsolute=lE.unixify=void 0;var Mx=E$("os"),Lx=E$("path"),mE=Mx.platform()==="win32",zx=2,Rx=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,Ax=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,wx=/^\\\\([.?])/,fx=/\\(?![!()+@[\]{}])/g;function kx($){return $.replace(/\\/g,"/")}lE.unixify=kx;function Ix($,J){return Lx.resolve($,J)}lE.makeAbsolute=Ix;function Sx($){if($.charAt(0)==="."){let J=$.charAt(1);if(J==="/"||J==="\\")return $.slice(zx)}return $}lE.removeLeadingDotSegment=Sx;lE.escape=mE?cY:dY;function cY($){return $.replace(Ax,"\\$2")}lE.escapeWindowsPath=cY;function dY($){return $.replace(Rx,"\\$2")}lE.escapePosixPath=dY;lE.convertPathToPattern=mE?cE:dE;function cE($){return cY($).replace(wx,"//$1").replace(fx,"/")}lE.convertWindowsPathToPattern=cE;function dE($){return dY($)}lE.convertPosixPathToPattern=dE});var pE=J$((RV$,nE)=>{/*!
|
|
2
|
-
* is-extglob <https://github.com/jonschlinkert/is-extglob>
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) 2014-2016, Jon Schlinkert.
|
|
5
|
-
* Licensed under the MIT License.
|
|
6
|
-
*/nE.exports=function(J){if(typeof J!=="string"||J==="")return!1;var U;while(U=/(\\).|([@?!+*]\(.*\))/g.exec(J)){if(U[2])return!0;J=J.slice(U.index+U[0].length)}return!1}});var tE=J$((AV$,oE)=>{/*!
|
|
7
|
-
* is-glob <https://github.com/jonschlinkert/is-glob>
|
|
8
|
-
*
|
|
9
|
-
* Copyright (c) 2014-2017, Jon Schlinkert.
|
|
10
|
-
* Released under the MIT License.
|
|
11
|
-
*/var ux=pE(),aE={"{":"}","(":")","[":"]"},mx=function($){if($[0]==="!")return!0;var J=0,U=-2,Q=-2,_=-2,G=-2,V=-2;while(J<$.length){if($[J]==="*")return!0;if($[J+1]==="?"&&/[\].+)]/.test($[J]))return!0;if(Q!==-1&&$[J]==="["&&$[J+1]!=="]"){if(Q<J)Q=$.indexOf("]",J);if(Q>J){if(V===-1||V>Q)return!0;if(V=$.indexOf("\\",J),V===-1||V>Q)return!0}}if(_!==-1&&$[J]==="{"&&$[J+1]!=="}"){if(_=$.indexOf("}",J),_>J){if(V=$.indexOf("\\",J),V===-1||V>_)return!0}}if(G!==-1&&$[J]==="("&&$[J+1]==="?"&&/[:!=]/.test($[J+2])&&$[J+3]!==")"){if(G=$.indexOf(")",J),G>J){if(V=$.indexOf("\\",J),V===-1||V>G)return!0}}if(U!==-1&&$[J]==="("&&$[J+1]!=="|"){if(U<J)U=$.indexOf("|",J);if(U!==-1&&$[U+1]!==")"){if(G=$.indexOf(")",U),G>U){if(V=$.indexOf("\\",U),V===-1||V>G)return!0}}}if($[J]==="\\"){var X=$[J+1];J+=2;var Z=aE[X];if(Z){var Y=$.indexOf(Z,J);if(Y!==-1)J=Y+1}if($[J]==="!")return!0}else J++}return!1},cx=function($){if($[0]==="!")return!0;var J=0;while(J<$.length){if(/[*?{}()[\]]/.test($[J]))return!0;if($[J]==="\\"){var U=$[J+1];J+=2;var Q=aE[U];if(Q){var _=$.indexOf(Q,J);if(_!==-1)J=_+1}if($[J]==="!")return!0}else J++}return!1};oE.exports=function(J,U){if(typeof J!=="string"||J==="")return!1;if(ux(J))return!0;var Q=mx;if(U&&U.strict===!1)Q=cx;return Q(J)}});var eE=J$((wV$,sE)=>{var dx=tE(),lx=E$("path").posix.dirname,ix=E$("os").platform()==="win32",lY="/",rx=/\\/g,nx=/[\{\[].*[\}\]]$/,px=/(^|[^\\])([\{\[]|\([^\)]+$)/,ax=/\\([\!\*\?\|\[\]\(\)\{\}])/g;sE.exports=function(J,U){var Q=Object.assign({flipBackslashes:!0},U);if(Q.flipBackslashes&&ix&&J.indexOf(lY)<0)J=J.replace(rx,lY);if(nx.test(J))J+=lY;J+="a";do J=lx(J);while(dx(J)||px.test(J));return J.replace(ax,"$1")}});var PQ=J$((ox)=>{ox.isInteger=($)=>{if(typeof $==="number")return Number.isInteger($);if(typeof $==="string"&&$.trim()!=="")return Number.isInteger(Number($));return!1};ox.find=($,J)=>$.nodes.find((U)=>U.type===J);ox.exceedsLimit=($,J,U=1,Q)=>{if(Q===!1)return!1;if(!ox.isInteger($)||!ox.isInteger(J))return!1;return(Number(J)-Number($))/Number(U)>=Q};ox.escapeNode=($,J=0,U)=>{let Q=$.nodes[J];if(!Q)return;if(U&&Q.type===U||Q.type==="open"||Q.type==="close"){if(Q.escaped!==!0)Q.value="\\"+Q.value,Q.escaped=!0}};ox.encloseBrace=($)=>{if($.type!=="brace")return!1;if($.commas>>0+$.ranges>>0===0)return $.invalid=!0,!0;return!1};ox.isInvalidBrace=($)=>{if($.type!=="brace")return!1;if($.invalid===!0||$.dollar)return!0;if($.commas>>0+$.ranges>>0===0)return $.invalid=!0,!0;if($.open!==!0||$.close!==!0)return $.invalid=!0,!0;return!1};ox.isOpenOrClose=($)=>{if($.type==="open"||$.type==="close")return!0;return $.open===!0||$.close===!0};ox.reduce=($)=>$.reduce((J,U)=>{if(U.type==="text")J.push(U.value);if(U.type==="range")U.type="text";return J},[]);ox.flatten=(...$)=>{let J=[],U=(Q)=>{for(let _=0;_<Q.length;_++){let G=Q[_];if(Array.isArray(G)){U(G);continue}if(G!==void 0)J.push(G)}return J};return U($),J}});var MQ=J$((kV$,JP)=>{var $P=PQ();JP.exports=($,J={})=>{let U=(Q,_={})=>{let G=J.escapeInvalid&&$P.isInvalidBrace(_),V=Q.invalid===!0&&J.escapeInvalid===!0,X="";if(Q.value){if((G||V)&&$P.isOpenOrClose(Q))return"\\"+Q.value;return Q.value}if(Q.value)return Q.value;if(Q.nodes)for(let Z of Q.nodes)X+=U(Z);return X};return U($)}});var _P=J$((IV$,UP)=>{/*!
|
|
12
|
-
* is-number <https://github.com/jonschlinkert/is-number>
|
|
13
|
-
*
|
|
14
|
-
* Copyright (c) 2014-present, Jon Schlinkert.
|
|
15
|
-
* Released under the MIT License.
|
|
16
|
-
*/UP.exports=function($){if(typeof $==="number")return $-$===0;if(typeof $==="string"&&$.trim()!=="")return Number.isFinite?Number.isFinite(+$):isFinite(+$);return!1}});var FP=J$((SV$,NP)=>{/*!
|
|
17
|
-
* to-regex-range <https://github.com/micromatch/to-regex-range>
|
|
18
|
-
*
|
|
19
|
-
* Copyright (c) 2015-present, Jon Schlinkert.
|
|
20
|
-
* Released under the MIT License.
|
|
21
|
-
*/var QP=_P(),aJ=($,J,U)=>{if(QP($)===!1)throw TypeError("toRegexRange: expected the first argument to be a number");if(J===void 0||$===J)return String($);if(QP(J)===!1)throw TypeError("toRegexRange: expected the second argument to be a number.");let Q={relaxZeros:!0,...U};if(typeof Q.strictZeros==="boolean")Q.relaxZeros=Q.strictZeros===!1;let _=String(Q.relaxZeros),G=String(Q.shorthand),V=String(Q.capture),X=String(Q.wrap),Z=$+":"+J+"="+_+G+V+X;if(aJ.cache.hasOwnProperty(Z))return aJ.cache[Z].result;let Y=Math.min($,J),K=Math.max($,J);if(Math.abs(Y-K)===1){let E=$+"|"+J;if(Q.capture)return`(${E})`;if(Q.wrap===!1)return E;return`(?:${E})`}let F=KP($)||KP(J),N={min:$,max:J,a:Y,b:K},q=[],H=[];if(F)N.isPadded=F,N.maxLen=String(N.max).length;if(Y<0){let E=K<0?Math.abs(K):1;H=GP(E,Math.abs(Y),N,Q),Y=N.a=0}if(K>=0)q=GP(Y,K,N,Q);if(N.negatives=H,N.positives=q,N.result=Gh(H,q,Q),Q.capture===!0)N.result=`(${N.result})`;else if(Q.wrap!==!1&&q.length+H.length>1)N.result=`(?:${N.result})`;return aJ.cache[Z]=N,N.result};function Gh($,J,U){let Q=rY($,J,"-",!1,U)||[],_=rY(J,$,"",!1,U)||[],G=rY($,J,"-?",!0,U)||[];return Q.concat(G).concat(_).join("|")}function Vh($,J){let U=1,Q=1,_=XP($,U),G=new Set([J]);while($<=_&&_<=J)G.add(_),U+=1,_=XP($,U);_=YP(J+1,Q)-1;while($<_&&_<=J)G.add(_),Q+=1,_=YP(J+1,Q)-1;return G=[...G],G.sort(Zh),G}function Xh($,J,U){if($===J)return{pattern:$,count:[],digits:0};let Q=Yh($,J),_=Q.length,G="",V=0;for(let X=0;X<_;X++){let[Z,Y]=Q[X];if(Z===Y)G+=Z;else if(Z!=="0"||Y!=="9")G+=Kh(Z,Y,U);else V++}if(V)G+=U.shorthand===!0?"\\d":"[0-9]";return{pattern:G,count:[V],digits:_}}function GP($,J,U,Q){let _=Vh($,J),G=[],V=$,X;for(let Z=0;Z<_.length;Z++){let Y=_[Z],K=Xh(String(V),String(Y),Q),F="";if(!U.isPadded&&X&&X.pattern===K.pattern){if(X.count.length>1)X.count.pop();X.count.push(K.count[0]),X.string=X.pattern+ZP(X.count),V=Y+1;continue}if(U.isPadded)F=Nh(Y,U,Q);K.string=F+K.pattern+ZP(K.count),G.push(K),V=Y+1,X=K}return G}function rY($,J,U,Q,_){let G=[];for(let V of $){let{string:X}=V;if(!Q&&!VP(J,"string",X))G.push(U+X);if(Q&&VP(J,"string",X))G.push(U+X)}return G}function Yh($,J){let U=[];for(let Q=0;Q<$.length;Q++)U.push([$[Q],J[Q]]);return U}function Zh($,J){return $>J?1:J>$?-1:0}function VP($,J,U){return $.some((Q)=>Q[J]===U)}function XP($,J){return Number(String($).slice(0,-J)+"9".repeat(J))}function YP($,J){return $-$%Math.pow(10,J)}function ZP($){let[J=0,U=""]=$;if(U||J>1)return`{${J+(U?","+U:"")}}`;return""}function Kh($,J,U){return`[${$}${J-$===1?"":"-"}${J}]`}function KP($){return/^-?(0+)\d/.test($)}function Nh($,J,U){if(!J.isPadded)return $;let Q=Math.abs(J.maxLen-String($).length),_=U.relaxZeros!==!1;switch(Q){case 0:return"";case 1:return _?"0?":"0";case 2:return _?"0{0,2}":"00";default:return _?`0{0,${Q}}`:`0{${Q}}`}}aJ.cache={};aJ.clearCache=()=>aJ.cache={};NP.exports=aJ});var aY=J$((TV$,DP)=>{/*!
|
|
22
|
-
* fill-range <https://github.com/jonschlinkert/fill-range>
|
|
23
|
-
*
|
|
24
|
-
* Copyright (c) 2014-present, Jon Schlinkert.
|
|
25
|
-
* Licensed under the MIT License.
|
|
26
|
-
*/var Fh=E$("util"),qP=FP(),WP=($)=>$!==null&&typeof $==="object"&&!Array.isArray($),Wh=($)=>{return(J)=>$===!0?Number(J):String(J)},nY=($)=>{return typeof $==="number"||typeof $==="string"&&$!==""},n5=($)=>Number.isInteger(+$),pY=($)=>{let J=`${$}`,U=-1;if(J[0]==="-")J=J.slice(1);if(J==="0")return!1;while(J[++U]==="0");return U>0},qh=($,J,U)=>{if(typeof $==="string"||typeof J==="string")return!0;return U.stringify===!0},Hh=($,J,U)=>{if(J>0){let Q=$[0]==="-"?"-":"";if(Q)$=$.slice(1);$=Q+$.padStart(Q?J-1:J,"0")}if(U===!1)return String($);return $},zQ=($,J)=>{let U=$[0]==="-"?"-":"";if(U)$=$.slice(1),J--;while($.length<J)$="0"+$;return U?"-"+$:$},Bh=($,J,U)=>{$.negatives.sort((X,Z)=>X<Z?-1:X>Z?1:0),$.positives.sort((X,Z)=>X<Z?-1:X>Z?1:0);let Q=J.capture?"":"?:",_="",G="",V;if($.positives.length)_=$.positives.map((X)=>zQ(String(X),U)).join("|");if($.negatives.length)G=`-(${Q}${$.negatives.map((X)=>zQ(String(X),U)).join("|")})`;if(_&&G)V=`${_}|${G}`;else V=_||G;if(J.wrap)return`(${Q}${V})`;return V},HP=($,J,U,Q)=>{if(U)return qP($,J,{wrap:!1,...Q});let _=String.fromCharCode($);if($===J)return _;let G=String.fromCharCode(J);return`[${_}-${G}]`},BP=($,J,U)=>{if(Array.isArray($)){let Q=U.wrap===!0,_=U.capture?"":"?:";return Q?`(${_}${$.join("|")})`:$.join("|")}return qP($,J,U)},OP=(...$)=>{return RangeError("Invalid range arguments: "+Fh.inspect(...$))},jP=($,J,U)=>{if(U.strictRanges===!0)throw OP([$,J]);return[]},Oh=($,J)=>{if(J.strictRanges===!0)throw TypeError(`Expected step "${$}" to be a number`);return[]},jh=($,J,U=1,Q={})=>{let _=Number($),G=Number(J);if(!Number.isInteger(_)||!Number.isInteger(G)){if(Q.strictRanges===!0)throw OP([$,J]);return[]}if(_===0)_=0;if(G===0)G=0;let V=_>G,X=String($),Z=String(J),Y=String(U);U=Math.max(Math.abs(U),1);let K=pY(X)||pY(Z)||pY(Y),F=K?Math.max(X.length,Z.length,Y.length):0,N=K===!1&&qh($,J,Q)===!1,q=Q.transform||Wh(N);if(Q.toRegex&&U===1)return HP(zQ($,F),zQ(J,F),!0,Q);let H={negatives:[],positives:[]},E=(j)=>H[j<0?"negatives":"positives"].push(Math.abs(j)),D=[],B=0;while(V?_>=G:_<=G){if(Q.toRegex===!0&&U>1)E(_);else D.push(Hh(q(_,B),F,N));_=V?_-U:_+U,B++}if(Q.toRegex===!0)return U>1?Bh(H,Q,F):BP(D,null,{wrap:!1,...Q});return D},Dh=($,J,U=1,Q={})=>{if(!n5($)&&$.length>1||!n5(J)&&J.length>1)return jP($,J,Q);let _=Q.transform||((N)=>String.fromCharCode(N)),G=`${$}`.charCodeAt(0),V=`${J}`.charCodeAt(0),X=G>V,Z=Math.min(G,V),Y=Math.max(G,V);if(Q.toRegex&&U===1)return HP(Z,Y,!1,Q);let K=[],F=0;while(X?G>=V:G<=V)K.push(_(G,F)),G=X?G-U:G+U,F++;if(Q.toRegex===!0)return BP(K,null,{wrap:!1,options:Q});return K},LQ=($,J,U,Q={})=>{if(J==null&&nY($))return[$];if(!nY($)||!nY(J))return jP($,J,Q);if(typeof U==="function")return LQ($,J,1,{transform:U});if(WP(U))return LQ($,J,0,U);let _={...Q};if(_.capture===!0)_.wrap=!0;if(U=U||_.step||1,!n5(U)){if(U!=null&&!WP(U))return Oh(U,_);return LQ($,J,1,U)}if(n5($)&&n5(J))return jh($,J,U,_);return Dh($,J,Math.max(Math.abs(U),1),_)};DP.exports=LQ});var MP=J$((vV$,PP)=>{var Eh=aY(),EP=PQ(),Ph=($,J={})=>{let U=(Q,_={})=>{let G=EP.isInvalidBrace(_),V=Q.invalid===!0&&J.escapeInvalid===!0,X=G===!0||V===!0,Z=J.escapeInvalid===!0?"\\":"",Y="";if(Q.isOpen===!0)return Z+Q.value;if(Q.isClose===!0)return console.log("node.isClose",Z,Q.value),Z+Q.value;if(Q.type==="open")return X?Z+Q.value:"(";if(Q.type==="close")return X?Z+Q.value:")";if(Q.type==="comma")return Q.prev.type==="comma"?"":X?Q.value:"|";if(Q.value)return Q.value;if(Q.nodes&&Q.ranges>0){let K=EP.reduce(Q.nodes),F=Eh(...K,{...J,wrap:!1,toRegex:!0,strictZeros:!0});if(F.length!==0)return K.length>1&&F.length>1?`(${F})`:F}if(Q.nodes)for(let K of Q.nodes)Y+=U(K,Q);return Y};return U($)};PP.exports=Ph});var RP=J$((CV$,zP)=>{var Mh=aY(),LP=MQ(),F9=PQ(),oJ=($="",J="",U=!1)=>{let Q=[];if($=[].concat($),J=[].concat(J),!J.length)return $;if(!$.length)return U?F9.flatten(J).map((_)=>`{${_}}`):J;for(let _ of $)if(Array.isArray(_))for(let G of _)Q.push(oJ(G,J,U));else for(let G of J){if(U===!0&&typeof G==="string")G=`{${G}}`;Q.push(Array.isArray(G)?oJ(_,G,U):_+G)}return F9.flatten(Q)},Lh=($,J={})=>{let U=J.rangeLimit===void 0?1000:J.rangeLimit,Q=(_,G={})=>{_.queue=[];let V=G,X=G.queue;while(V.type!=="brace"&&V.type!=="root"&&V.parent)V=V.parent,X=V.queue;if(_.invalid||_.dollar){X.push(oJ(X.pop(),LP(_,J)));return}if(_.type==="brace"&&_.invalid!==!0&&_.nodes.length===2){X.push(oJ(X.pop(),["{}"]));return}if(_.nodes&&_.ranges>0){let F=F9.reduce(_.nodes);if(F9.exceedsLimit(...F,J.step,U))throw RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let N=Mh(...F,J);if(N.length===0)N=LP(_,J);X.push(oJ(X.pop(),N)),_.nodes=[];return}let Z=F9.encloseBrace(_),Y=_.queue,K=_;while(K.type!=="brace"&&K.type!=="root"&&K.parent)K=K.parent,Y=K.queue;for(let F=0;F<_.nodes.length;F++){let N=_.nodes[F];if(N.type==="comma"&&_.type==="brace"){if(F===1)Y.push("");Y.push("");continue}if(N.type==="close"){X.push(oJ(X.pop(),Y,Z));continue}if(N.value&&N.type!=="open"){Y.push(oJ(Y.pop(),N.value));continue}if(N.nodes)Q(N,_)}return Y};return F9.flatten(Q($))};zP.exports=Lh});var wP=J$((bV$,AP)=>{AP.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
|
|
27
|
-
`,CHAR_NO_BREAK_SPACE:" ",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var TP=J$((yV$,SP)=>{var zh=MQ(),{MAX_LENGTH:fP,CHAR_BACKSLASH:oY,CHAR_BACKTICK:Rh,CHAR_COMMA:Ah,CHAR_DOT:wh,CHAR_LEFT_PARENTHESES:fh,CHAR_RIGHT_PARENTHESES:kh,CHAR_LEFT_CURLY_BRACE:Ih,CHAR_RIGHT_CURLY_BRACE:Sh,CHAR_LEFT_SQUARE_BRACKET:kP,CHAR_RIGHT_SQUARE_BRACKET:IP,CHAR_DOUBLE_QUOTE:Th,CHAR_SINGLE_QUOTE:vh,CHAR_NO_BREAK_SPACE:Ch,CHAR_ZERO_WIDTH_NOBREAK_SPACE:bh}=wP(),yh=($,J={})=>{if(typeof $!=="string")throw TypeError("Expected a string");let U=J||{},Q=typeof U.maxLength==="number"?Math.min(fP,U.maxLength):fP;if($.length>Q)throw SyntaxError(`Input length (${$.length}), exceeds max characters (${Q})`);let _={type:"root",input:$,nodes:[]},G=[_],V=_,X=_,Z=0,Y=$.length,K=0,F=0,N,q=()=>$[K++],H=(E)=>{if(E.type==="text"&&X.type==="dot")X.type="text";if(X&&X.type==="text"&&E.type==="text"){X.value+=E.value;return}return V.nodes.push(E),E.parent=V,E.prev=X,X=E,E};H({type:"bos"});while(K<Y){if(V=G[G.length-1],N=q(),N===bh||N===Ch)continue;if(N===oY){H({type:"text",value:(J.keepEscaping?N:"")+q()});continue}if(N===IP){H({type:"text",value:"\\"+N});continue}if(N===kP){Z++;let E;while(K<Y&&(E=q())){if(N+=E,E===kP){Z++;continue}if(E===oY){N+=q();continue}if(E===IP){if(Z--,Z===0)break}}H({type:"text",value:N});continue}if(N===fh){V=H({type:"paren",nodes:[]}),G.push(V),H({type:"text",value:N});continue}if(N===kh){if(V.type!=="paren"){H({type:"text",value:N});continue}V=G.pop(),H({type:"text",value:N}),V=G[G.length-1];continue}if(N===Th||N===vh||N===Rh){let E=N,D;if(J.keepQuotes!==!0)N="";while(K<Y&&(D=q())){if(D===oY){N+=D+q();continue}if(D===E){if(J.keepQuotes===!0)N+=D;break}N+=D}H({type:"text",value:N});continue}if(N===Ih){F++;let D={type:"brace",open:!0,close:!1,dollar:X.value&&X.value.slice(-1)==="$"||V.dollar===!0,depth:F,commas:0,ranges:0,nodes:[]};V=H(D),G.push(V),H({type:"open",value:N});continue}if(N===Sh){if(V.type!=="brace"){H({type:"text",value:N});continue}let E="close";V=G.pop(),V.close=!0,H({type:E,value:N}),F--,V=G[G.length-1];continue}if(N===Ah&&F>0){if(V.ranges>0){V.ranges=0;let E=V.nodes.shift();V.nodes=[E,{type:"text",value:zh(V)}]}H({type:"comma",value:N}),V.commas++;continue}if(N===wh&&F>0&&V.commas===0){let E=V.nodes;if(F===0||E.length===0){H({type:"text",value:N});continue}if(X.type==="dot"){if(V.range=[],X.value+=N,X.type="range",V.nodes.length!==3&&V.nodes.length!==5){V.invalid=!0,V.ranges=0,X.type="text";continue}V.ranges++,V.args=[];continue}if(X.type==="range"){E.pop();let D=E[E.length-1];D.value+=X.value+N,X=D,V.ranges--;continue}H({type:"dot",value:N});continue}H({type:"text",value:N})}do if(V=G.pop(),V.type!=="root"){V.nodes.forEach((B)=>{if(!B.nodes){if(B.type==="open")B.isOpen=!0;if(B.type==="close")B.isClose=!0;if(!B.nodes)B.type="text";B.invalid=!0}});let E=G[G.length-1],D=E.nodes.indexOf(V);E.nodes.splice(D,1,...V.nodes)}while(G.length>0);return H({type:"eos"}),_};SP.exports=yh});var bP=J$((gV$,CP)=>{var vP=MQ(),gh=MP(),xh=RP(),hh=TP(),z0=($,J={})=>{let U=[];if(Array.isArray($))for(let Q of $){let _=z0.create(Q,J);if(Array.isArray(_))U.push(..._);else U.push(_)}else U=[].concat(z0.create($,J));if(J&&J.expand===!0&&J.nodupes===!0)U=[...new Set(U)];return U};z0.parse=($,J={})=>hh($,J);z0.stringify=($,J={})=>{if(typeof $==="string")return vP(z0.parse($,J),J);return vP($,J)};z0.compile=($,J={})=>{if(typeof $==="string")$=z0.parse($,J);return gh($,J)};z0.expand=($,J={})=>{if(typeof $==="string")$=z0.parse($,J);let U=xh($,J);if(J.noempty===!0)U=U.filter(Boolean);if(J.nodupes===!0)U=[...new Set(U)];return U};z0.create=($,J={})=>{if($===""||$.length<3)return[$];return J.expand!==!0?z0.compile($,J):z0.expand($,J)};CP.exports=z0});var p5=J$((xV$,gP)=>{var uh=E$("path"),yP={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)"},mh={...yP,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)"},ch={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};gP.exports={MAX_LENGTH:65536,POSIX_REGEX_SOURCE:ch,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:uh.sep,extglobChars($){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${$.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars($){return $===!0?mh:yP}}});var a5=J$((ah)=>{var dh=E$("path"),lh=process.platform==="win32",{REGEX_BACKSLASH:ih,REGEX_REMOVE_BACKSLASH:rh,REGEX_SPECIAL_CHARS:nh,REGEX_SPECIAL_CHARS_GLOBAL:ph}=p5();ah.isObject=($)=>$!==null&&typeof $==="object"&&!Array.isArray($);ah.hasRegexChars=($)=>nh.test($);ah.isRegexChar=($)=>$.length===1&&ah.hasRegexChars($);ah.escapeRegex=($)=>$.replace(ph,"\\$1");ah.toPosixSlashes=($)=>$.replace(ih,"/");ah.removeBackslashes=($)=>{return $.replace(rh,(J)=>{return J==="\\"?"":J})};ah.supportsLookbehinds=()=>{let $=process.version.slice(1).split(".").map(Number);if($.length===3&&$[0]>=9||$[0]===8&&$[1]>=10)return!0;return!1};ah.isWindows=($)=>{if($&&typeof $.windows==="boolean")return $.windows;return lh===!0||dh.sep==="\\"};ah.escapeLast=($,J,U)=>{let Q=$.lastIndexOf(J,U);if(Q===-1)return $;if($[Q-1]==="\\")return ah.escapeLast($,J,Q-1);return`${$.slice(0,Q)}\\${$.slice(Q)}`};ah.removePrefix=($,J={})=>{let U=$;if(U.startsWith("./"))U=U.slice(2),J.prefix="./";return U};ah.wrapOutput=($,J={},U={})=>{let Q=U.contains?"":"^",_=U.contains?"":"$",G=`${Q}(?:${$})${_}`;if(J.negated===!0)G=`(?:^(?!${G}).*$)`;return G}});var nP=J$((uV$,rP)=>{var uP=a5(),{CHAR_ASTERISK:tY,CHAR_AT:Gu,CHAR_BACKWARD_SLASH:o5,CHAR_COMMA:Vu,CHAR_DOT:sY,CHAR_EXCLAMATION_MARK:eY,CHAR_FORWARD_SLASH:iP,CHAR_LEFT_CURLY_BRACE:$Z,CHAR_LEFT_PARENTHESES:JZ,CHAR_LEFT_SQUARE_BRACKET:Xu,CHAR_PLUS:Yu,CHAR_QUESTION_MARK:mP,CHAR_RIGHT_CURLY_BRACE:Zu,CHAR_RIGHT_PARENTHESES:cP,CHAR_RIGHT_SQUARE_BRACKET:Ku}=p5(),dP=($)=>{return $===iP||$===o5},lP=($)=>{if($.isPrefix!==!0)$.depth=$.isGlobstar?1/0:1},Nu=($,J)=>{let U=J||{},Q=$.length-1,_=U.parts===!0||U.scanToEnd===!0,G=[],V=[],X=[],Z=$,Y=-1,K=0,F=0,N=!1,q=!1,H=!1,E=!1,D=!1,B=!1,j=!1,f=!1,R=!1,I=!1,w=0,T,z,S={value:"",depth:0,isGlob:!1},O=()=>Y>=Q,M=()=>Z.charCodeAt(Y+1),P=()=>{return T=z,Z.charCodeAt(++Y)};while(Y<Q){z=P();let C;if(z===o5){if(j=S.backslashes=!0,z=P(),z===$Z)B=!0;continue}if(B===!0||z===$Z){w++;while(O()!==!0&&(z=P())){if(z===o5){j=S.backslashes=!0,P();continue}if(z===$Z){w++;continue}if(B!==!0&&z===sY&&(z=P())===sY){if(N=S.isBrace=!0,H=S.isGlob=!0,I=!0,_===!0)continue;break}if(B!==!0&&z===Vu){if(N=S.isBrace=!0,H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===Zu){if(w--,w===0){B=!1,N=S.isBrace=!0,I=!0;break}}}if(_===!0)continue;break}if(z===iP){if(G.push(Y),V.push(S),S={value:"",depth:0,isGlob:!1},I===!0)continue;if(T===sY&&Y===K+1){K+=2;continue}F=Y+1;continue}if(U.noext!==!0){if((z===Yu||z===Gu||z===tY||z===mP||z===eY)===!0&&M()===JZ){if(H=S.isGlob=!0,E=S.isExtglob=!0,I=!0,z===eY&&Y===K)R=!0;if(_===!0){while(O()!==!0&&(z=P())){if(z===o5){j=S.backslashes=!0,z=P();continue}if(z===cP){H=S.isGlob=!0,I=!0;break}}continue}break}}if(z===tY){if(T===tY)D=S.isGlobstar=!0;if(H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===mP){if(H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===Xu){while(O()!==!0&&(C=P())){if(C===o5){j=S.backslashes=!0,P();continue}if(C===Ku){q=S.isBracket=!0,H=S.isGlob=!0,I=!0;break}}if(_===!0)continue;break}if(U.nonegate!==!0&&z===eY&&Y===K){f=S.negated=!0,K++;continue}if(U.noparen!==!0&&z===JZ){if(H=S.isGlob=!0,_===!0){while(O()!==!0&&(z=P())){if(z===JZ){j=S.backslashes=!0,z=P();continue}if(z===cP){I=!0;break}}continue}break}if(H===!0){if(I=!0,_===!0)continue;break}}if(U.noext===!0)E=!1,H=!1;let A=Z,k="",L="";if(K>0)k=Z.slice(0,K),Z=Z.slice(K),F-=K;if(A&&H===!0&&F>0)A=Z.slice(0,F),L=Z.slice(F);else if(H===!0)A="",L=Z;else A=Z;if(A&&A!==""&&A!=="/"&&A!==Z){if(dP(A.charCodeAt(A.length-1)))A=A.slice(0,-1)}if(U.unescape===!0){if(L)L=uP.removeBackslashes(L);if(A&&j===!0)A=uP.removeBackslashes(A)}let v={prefix:k,input:$,start:K,base:A,glob:L,isBrace:N,isBracket:q,isGlob:H,isExtglob:E,isGlobstar:D,negated:f,negatedExtglob:R};if(U.tokens===!0){if(v.maxDepth=0,!dP(z))V.push(S);v.tokens=V}if(U.parts===!0||U.tokens===!0){let C;for(let b=0;b<G.length;b++){let y=C?C+1:K,x=G[b],c=$.slice(y,x);if(U.tokens){if(b===0&&K!==0)V[b].isPrefix=!0,V[b].value=k;else V[b].value=c;lP(V[b]),v.maxDepth+=V[b].depth}if(b!==0||c!=="")X.push(c);C=x}if(C&&C+1<$.length){let b=$.slice(C+1);if(X.push(b),U.tokens)V[V.length-1].value=b,lP(V[V.length-1]),v.maxDepth+=V[V.length-1].depth}v.slashes=G,v.parts=X}return v};rP.exports=Nu});var oP=J$((mV$,aP)=>{var RQ=p5(),R0=a5(),{MAX_LENGTH:AQ,POSIX_REGEX_SOURCE:Fu,REGEX_NON_SPECIAL_CHARS:Wu,REGEX_SPECIAL_CHARS_BACKREF:qu,REPLACEMENTS:pP}=RQ,Hu=($,J)=>{if(typeof J.expandRange==="function")return J.expandRange(...$,J);$.sort();let U=`[${$.join("-")}]`;try{new RegExp(U)}catch(Q){return $.map((_)=>R0.escapeRegex(_)).join("..")}return U},W9=($,J)=>{return`Missing ${$}: "${J}" - use "\\\\${J}" to match literal characters`},UZ=($,J)=>{if(typeof $!=="string")throw TypeError("Expected a string");$=pP[$]||$;let U={...J},Q=typeof U.maxLength==="number"?Math.min(AQ,U.maxLength):AQ,_=$.length;if(_>Q)throw SyntaxError(`Input length: ${_}, exceeds maximum allowed length: ${Q}`);let G={type:"bos",value:"",output:U.prepend||""},V=[G],X=U.capture?"":"?:",Z=R0.isWindows(J),Y=RQ.globChars(Z),K=RQ.extglobChars(Y),{DOT_LITERAL:F,PLUS_LITERAL:N,SLASH_LITERAL:q,ONE_CHAR:H,DOTS_SLASH:E,NO_DOT:D,NO_DOT_SLASH:B,NO_DOTS_SLASH:j,QMARK:f,QMARK_NO_DOT:R,STAR:I,START_ANCHOR:w}=Y,T=(n)=>{return`(${X}(?:(?!${w}${n.dot?E:F}).)*?)`},z=U.dot?"":D,S=U.dot?f:R,O=U.bash===!0?T(U):I;if(U.capture)O=`(${O})`;if(typeof U.noext==="boolean")U.noextglob=U.noext;let M={input:$,index:-1,start:0,dot:U.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:V};$=R0.removePrefix($,M),_=$.length;let P=[],A=[],k=[],L=G,v,C=()=>M.index===_-1,b=M.peek=(n=1)=>$[M.index+n],y=M.advance=()=>$[++M.index]||"",x=()=>$.slice(M.index+1),c=(n="",a=0)=>{M.consumed+=n,M.index+=a},s=(n)=>{M.output+=n.output!=null?n.output:n.value,c(n.value)},F$=()=>{let n=1;while(b()==="!"&&(b(2)!=="("||b(3)==="?"))y(),M.start++,n++;if(n%2===0)return!1;return M.negated=!0,M.start++,!0},K$=(n)=>{M[n]++,k.push(n)},V$=(n)=>{M[n]--,k.pop()},Y$=(n)=>{if(L.type==="globstar"){let a=M.braces>0&&(n.type==="comma"||n.type==="brace"),m=n.extglob===!0||P.length&&(n.type==="pipe"||n.type==="paren");if(n.type!=="slash"&&n.type!=="paren"&&!a&&!m)M.output=M.output.slice(0,-L.output.length),L.type="star",L.value="*",L.output=O,M.output+=L.output}if(P.length&&n.type!=="paren")P[P.length-1].inner+=n.value;if(n.value||n.output)s(n);if(L&&L.type==="text"&&n.type==="text"){L.value+=n.value,L.output=(L.output||"")+n.value;return}n.prev=L,V.push(n),L=n},u$=(n,a)=>{let m={...K[a],conditions:1,inner:""};m.prev=L,m.parens=M.parens,m.output=M.output;let G$=(U.capture?"(":"")+m.open;K$("parens"),Y$({type:n,value:a,output:M.output?"":H}),Y$({type:"paren",extglob:!0,value:y(),output:G$}),P.push(m)},_$=(n)=>{let a=n.close+(U.capture?")":""),m;if(n.type==="negate"){let G$=O;if(n.inner&&n.inner.length>1&&n.inner.includes("/"))G$=T(U);if(G$!==O||C()||/^\)+$/.test(x()))a=n.close=`)$))${G$}`;if(n.inner.includes("*")&&(m=x())&&/^\.[^\\/.]+$/.test(m)){let L$=UZ(m,{...J,fastpaths:!1}).output;a=n.close=`)${L$})${G$})`}if(n.prev.type==="bos")M.negatedExtglob=!0}Y$({type:"paren",extglob:!0,value:v,output:a}),V$("parens")};if(U.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test($)){let n=!1,a=$.replace(qu,(m,G$,L$,P$,f$,V4)=>{if(P$==="\\")return n=!0,m;if(P$==="?"){if(G$)return G$+P$+(f$?f.repeat(f$.length):"");if(V4===0)return S+(f$?f.repeat(f$.length):"");return f.repeat(L$.length)}if(P$===".")return F.repeat(L$.length);if(P$==="*"){if(G$)return G$+P$+(f$?O:"");return O}return G$?m:`\\${m}`});if(n===!0)if(U.unescape===!0)a=a.replace(/\\/g,"");else a=a.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(a===$&&U.contains===!0)return M.output=$,M;return M.output=R0.wrapOutput(a,M,J),M}while(!C()){if(v=y(),v==="\x00")continue;if(v==="\\"){let m=b();if(m==="/"&&U.bash!==!0)continue;if(m==="."||m===";")continue;if(!m){v+="\\",Y$({type:"text",value:v});continue}let G$=/^\\+/.exec(x()),L$=0;if(G$&&G$[0].length>2){if(L$=G$[0].length,M.index+=L$,L$%2!==0)v+="\\"}if(U.unescape===!0)v=y();else v+=y();if(M.brackets===0){Y$({type:"text",value:v});continue}}if(M.brackets>0&&(v!=="]"||L.value==="["||L.value==="[^")){if(U.posix!==!1&&v===":"){let m=L.value.slice(1);if(m.includes("[")){if(L.posix=!0,m.includes(":")){let G$=L.value.lastIndexOf("["),L$=L.value.slice(0,G$),P$=L.value.slice(G$+2),f$=Fu[P$];if(f$){if(L.value=L$+f$,M.backtrack=!0,y(),!G.output&&V.indexOf(L)===1)G.output=H;continue}}}}if(v==="["&&b()!==":"||v==="-"&&b()==="]")v=`\\${v}`;if(v==="]"&&(L.value==="["||L.value==="[^"))v=`\\${v}`;if(U.posix===!0&&v==="!"&&L.value==="[")v="^";L.value+=v,s({value:v});continue}if(M.quotes===1&&v!=='"'){v=R0.escapeRegex(v),L.value+=v,s({value:v});continue}if(v==='"'){if(M.quotes=M.quotes===1?0:1,U.keepQuotes===!0)Y$({type:"text",value:v});continue}if(v==="("){K$("parens"),Y$({type:"paren",value:v});continue}if(v===")"){if(M.parens===0&&U.strictBrackets===!0)throw SyntaxError(W9("opening","("));let m=P[P.length-1];if(m&&M.parens===m.parens+1){_$(P.pop());continue}Y$({type:"paren",value:v,output:M.parens?")":"\\)"}),V$("parens");continue}if(v==="["){if(U.nobracket===!0||!x().includes("]")){if(U.nobracket!==!0&&U.strictBrackets===!0)throw SyntaxError(W9("closing","]"));v=`\\${v}`}else K$("brackets");Y$({type:"bracket",value:v});continue}if(v==="]"){if(U.nobracket===!0||L&&L.type==="bracket"&&L.value.length===1){Y$({type:"text",value:v,output:`\\${v}`});continue}if(M.brackets===0){if(U.strictBrackets===!0)throw SyntaxError(W9("opening","["));Y$({type:"text",value:v,output:`\\${v}`});continue}V$("brackets");let m=L.value.slice(1);if(L.posix!==!0&&m[0]==="^"&&!m.includes("/"))v=`/${v}`;if(L.value+=v,s({value:v}),U.literalBrackets===!1||R0.hasRegexChars(m))continue;let G$=R0.escapeRegex(L.value);if(M.output=M.output.slice(0,-L.value.length),U.literalBrackets===!0){M.output+=G$,L.value=G$;continue}L.value=`(${X}${G$}|${L.value})`,M.output+=L.value;continue}if(v==="{"&&U.nobrace!==!0){K$("braces");let m={type:"brace",value:v,output:"(",outputIndex:M.output.length,tokensIndex:M.tokens.length};A.push(m),Y$(m);continue}if(v==="}"){let m=A[A.length-1];if(U.nobrace===!0||!m){Y$({type:"text",value:v,output:v});continue}let G$=")";if(m.dots===!0){let L$=V.slice(),P$=[];for(let f$=L$.length-1;f$>=0;f$--){if(V.pop(),L$[f$].type==="brace")break;if(L$[f$].type!=="dots")P$.unshift(L$[f$].value)}G$=Hu(P$,U),M.backtrack=!0}if(m.comma!==!0&&m.dots!==!0){let L$=M.output.slice(0,m.outputIndex),P$=M.tokens.slice(m.tokensIndex);m.value=m.output="\\{",v=G$="\\}",M.output=L$;for(let f$ of P$)M.output+=f$.output||f$.value}Y$({type:"brace",value:v,output:G$}),V$("braces"),A.pop();continue}if(v==="|"){if(P.length>0)P[P.length-1].conditions++;Y$({type:"text",value:v});continue}if(v===","){let m=v,G$=A[A.length-1];if(G$&&k[k.length-1]==="braces")G$.comma=!0,m="|";Y$({type:"comma",value:v,output:m});continue}if(v==="/"){if(L.type==="dot"&&M.index===M.start+1){M.start=M.index+1,M.consumed="",M.output="",V.pop(),L=G;continue}Y$({type:"slash",value:v,output:q});continue}if(v==="."){if(M.braces>0&&L.type==="dot"){if(L.value===".")L.output=F;let m=A[A.length-1];L.type="dots",L.output+=v,L.value+=v,m.dots=!0;continue}if(M.braces+M.parens===0&&L.type!=="bos"&&L.type!=="slash"){Y$({type:"text",value:v,output:F});continue}Y$({type:"dot",value:v,output:F});continue}if(v==="?"){if(!(L&&L.value==="(")&&U.noextglob!==!0&&b()==="("&&b(2)!=="?"){u$("qmark",v);continue}if(L&&L.type==="paren"){let G$=b(),L$=v;if(G$==="<"&&!R0.supportsLookbehinds())throw Error("Node.js v10 or higher is required for regex lookbehinds");if(L.value==="("&&!/[!=<:]/.test(G$)||G$==="<"&&!/<([!=]|\w+>)/.test(x()))L$=`\\${v}`;Y$({type:"text",value:v,output:L$});continue}if(U.dot!==!0&&(L.type==="slash"||L.type==="bos")){Y$({type:"qmark",value:v,output:R});continue}Y$({type:"qmark",value:v,output:f});continue}if(v==="!"){if(U.noextglob!==!0&&b()==="("){if(b(2)!=="?"||!/[!=<:]/.test(b(3))){u$("negate",v);continue}}if(U.nonegate!==!0&&M.index===0){F$();continue}}if(v==="+"){if(U.noextglob!==!0&&b()==="("&&b(2)!=="?"){u$("plus",v);continue}if(L&&L.value==="("||U.regex===!1){Y$({type:"plus",value:v,output:N});continue}if(L&&(L.type==="bracket"||L.type==="paren"||L.type==="brace")||M.parens>0){Y$({type:"plus",value:v});continue}Y$({type:"plus",value:N});continue}if(v==="@"){if(U.noextglob!==!0&&b()==="("&&b(2)!=="?"){Y$({type:"at",extglob:!0,value:v,output:""});continue}Y$({type:"text",value:v});continue}if(v!=="*"){if(v==="$"||v==="^")v=`\\${v}`;let m=Wu.exec(x());if(m)v+=m[0],M.index+=m[0].length;Y$({type:"text",value:v});continue}if(L&&(L.type==="globstar"||L.star===!0)){L.type="star",L.star=!0,L.value+=v,L.output=O,M.backtrack=!0,M.globstar=!0,c(v);continue}let n=x();if(U.noextglob!==!0&&/^\([^?]/.test(n)){u$("star",v);continue}if(L.type==="star"){if(U.noglobstar===!0){c(v);continue}let m=L.prev,G$=m.prev,L$=m.type==="slash"||m.type==="bos",P$=G$&&(G$.type==="star"||G$.type==="globstar");if(U.bash===!0&&(!L$||n[0]&&n[0]!=="/")){Y$({type:"star",value:v,output:""});continue}let f$=M.braces>0&&(m.type==="comma"||m.type==="brace"),V4=P.length&&(m.type==="pipe"||m.type==="paren");if(!L$&&m.type!=="paren"&&!f$&&!V4){Y$({type:"star",value:v,output:""});continue}while(n.slice(0,3)==="/**"){let s4=$[M.index+4];if(s4&&s4!=="/")break;n=n.slice(3),c("/**",3)}if(m.type==="bos"&&C()){L.type="globstar",L.value+=v,L.output=T(U),M.output=L.output,M.globstar=!0,c(v);continue}if(m.type==="slash"&&m.prev.type!=="bos"&&!P$&&C()){M.output=M.output.slice(0,-(m.output+L.output).length),m.output=`(?:${m.output}`,L.type="globstar",L.output=T(U)+(U.strictSlashes?")":"|$)"),L.value+=v,M.globstar=!0,M.output+=m.output+L.output,c(v);continue}if(m.type==="slash"&&m.prev.type!=="bos"&&n[0]==="/"){let s4=n[1]!==void 0?"|$":"";M.output=M.output.slice(0,-(m.output+L.output).length),m.output=`(?:${m.output}`,L.type="globstar",L.output=`${T(U)}${q}|${q}${s4})`,L.value+=v,M.output+=m.output+L.output,M.globstar=!0,c(v+y()),Y$({type:"slash",value:"/",output:""});continue}if(m.type==="bos"&&n[0]==="/"){L.type="globstar",L.value+=v,L.output=`(?:^|${q}|${T(U)}${q})`,M.output=L.output,M.globstar=!0,c(v+y()),Y$({type:"slash",value:"/",output:""});continue}M.output=M.output.slice(0,-L.output.length),L.type="globstar",L.output=T(U),L.value+=v,M.output+=L.output,M.globstar=!0,c(v);continue}let a={type:"star",value:v,output:O};if(U.bash===!0){if(a.output=".*?",L.type==="bos"||L.type==="slash")a.output=z+a.output;Y$(a);continue}if(L&&(L.type==="bracket"||L.type==="paren")&&U.regex===!0){a.output=v,Y$(a);continue}if(M.index===M.start||L.type==="slash"||L.type==="dot"){if(L.type==="dot")M.output+=B,L.output+=B;else if(U.dot===!0)M.output+=j,L.output+=j;else M.output+=z,L.output+=z;if(b()!=="*")M.output+=H,L.output+=H}Y$(a)}while(M.brackets>0){if(U.strictBrackets===!0)throw SyntaxError(W9("closing","]"));M.output=R0.escapeLast(M.output,"["),V$("brackets")}while(M.parens>0){if(U.strictBrackets===!0)throw SyntaxError(W9("closing",")"));M.output=R0.escapeLast(M.output,"("),V$("parens")}while(M.braces>0){if(U.strictBrackets===!0)throw SyntaxError(W9("closing","}"));M.output=R0.escapeLast(M.output,"{"),V$("braces")}if(U.strictSlashes!==!0&&(L.type==="star"||L.type==="bracket"))Y$({type:"maybe_slash",value:"",output:`${q}?`});if(M.backtrack===!0){M.output="";for(let n of M.tokens)if(M.output+=n.output!=null?n.output:n.value,n.suffix)M.output+=n.suffix}return M};UZ.fastpaths=($,J)=>{let U={...J},Q=typeof U.maxLength==="number"?Math.min(AQ,U.maxLength):AQ,_=$.length;if(_>Q)throw SyntaxError(`Input length: ${_}, exceeds maximum allowed length: ${Q}`);$=pP[$]||$;let G=R0.isWindows(J),{DOT_LITERAL:V,SLASH_LITERAL:X,ONE_CHAR:Z,DOTS_SLASH:Y,NO_DOT:K,NO_DOTS:F,NO_DOTS_SLASH:N,STAR:q,START_ANCHOR:H}=RQ.globChars(G),E=U.dot?F:K,D=U.dot?N:K,B=U.capture?"":"?:",j={negated:!1,prefix:""},f=U.bash===!0?".*?":q;if(U.capture)f=`(${f})`;let R=(z)=>{if(z.noglobstar===!0)return f;return`(${B}(?:(?!${H}${z.dot?Y:V}).)*?)`},I=(z)=>{switch(z){case"*":return`${E}${Z}${f}`;case".*":return`${V}${Z}${f}`;case"*.*":return`${E}${f}${V}${Z}${f}`;case"*/*":return`${E}${f}${X}${Z}${D}${f}`;case"**":return E+R(U);case"**/*":return`(?:${E}${R(U)}${X})?${D}${Z}${f}`;case"**/*.*":return`(?:${E}${R(U)}${X})?${D}${f}${V}${Z}${f}`;case"**/.*":return`(?:${E}${R(U)}${X})?${V}${Z}${f}`;default:{let S=/^(.*?)\.(\w+)$/.exec(z);if(!S)return;let O=I(S[1]);if(!O)return;return O+V+S[2]}}},w=R0.removePrefix($,j),T=I(w);if(T&&U.strictSlashes!==!0)T+=`${X}?`;return T};aP.exports=UZ});var sP=J$((cV$,tP)=>{var Bu=E$("path"),Ou=nP(),_Z=oP(),QZ=a5(),ju=p5(),Du=($)=>$&&typeof $==="object"&&!Array.isArray($),V6=($,J,U=!1)=>{if(Array.isArray($)){let K=$.map((N)=>V6(N,J,U));return(N)=>{for(let q of K){let H=q(N);if(H)return H}return!1}}let Q=Du($)&&$.tokens&&$.input;if($===""||typeof $!=="string"&&!Q)throw TypeError("Expected pattern to be a non-empty string");let _=J||{},G=QZ.isWindows(J),V=Q?V6.compileRe($,J):V6.makeRe($,J,!1,!0),X=V.state;delete V.state;let Z=()=>!1;if(_.ignore){let K={...J,ignore:null,onMatch:null,onResult:null};Z=V6(_.ignore,K,U)}let Y=(K,F=!1)=>{let{isMatch:N,match:q,output:H}=V6.test(K,V,J,{glob:$,posix:G}),E={glob:$,state:X,regex:V,posix:G,input:K,output:H,match:q,isMatch:N};if(typeof _.onResult==="function")_.onResult(E);if(N===!1)return E.isMatch=!1,F?E:!1;if(Z(K)){if(typeof _.onIgnore==="function")_.onIgnore(E);return E.isMatch=!1,F?E:!1}if(typeof _.onMatch==="function")_.onMatch(E);return F?E:!0};if(U)Y.state=X;return Y};V6.test=($,J,U,{glob:Q,posix:_}={})=>{if(typeof $!=="string")throw TypeError("Expected input to be a string");if($==="")return{isMatch:!1,output:""};let G=U||{},V=G.format||(_?QZ.toPosixSlashes:null),X=$===Q,Z=X&&V?V($):$;if(X===!1)Z=V?V($):$,X=Z===Q;if(X===!1||G.capture===!0)if(G.matchBase===!0||G.basename===!0)X=V6.matchBase($,J,U,_);else X=J.exec(Z);return{isMatch:Boolean(X),match:X,output:Z}};V6.matchBase=($,J,U,Q=QZ.isWindows(U))=>{return(J instanceof RegExp?J:V6.makeRe(J,U)).test(Bu.basename($))};V6.isMatch=($,J,U)=>V6(J,U)($);V6.parse=($,J)=>{if(Array.isArray($))return $.map((U)=>V6.parse(U,J));return _Z($,{...J,fastpaths:!1})};V6.scan=($,J)=>Ou($,J);V6.compileRe=($,J,U=!1,Q=!1)=>{if(U===!0)return $.output;let _=J||{},G=_.contains?"":"^",V=_.contains?"":"$",X=`${G}(?:${$.output})${V}`;if($&&$.negated===!0)X=`^(?!${X}).*$`;let Z=V6.toRegex(X,J);if(Q===!0)Z.state=$;return Z};V6.makeRe=($,J={},U=!1,Q=!1)=>{if(!$||typeof $!=="string")throw TypeError("Expected a non-empty string");let _={negated:!1,fastpaths:!0};if(J.fastpaths!==!1&&($[0]==="."||$[0]==="*"))_.output=_Z.fastpaths($,J);if(!_.output)_=_Z($,J);return V6.compileRe(_,J,U,Q)};V6.toRegex=($,J)=>{try{let U=J||{};return new RegExp($,U.flags||(U.nocase?"i":""))}catch(U){if(J&&J.debug===!0)throw U;return/$^/}};V6.constants=ju;tP.exports=V6});var QM=J$((dV$,_M)=>{var $M=E$("util"),JM=bP(),P1=sP(),GZ=a5(),eP=($)=>$===""||$==="./",UM=($)=>{let J=$.indexOf("{");return J>-1&&$.indexOf("}",J)>-1},l4=($,J,U)=>{J=[].concat(J),$=[].concat($);let Q=new Set,_=new Set,G=new Set,V=0,X=(K)=>{if(G.add(K.output),U&&U.onResult)U.onResult(K)};for(let K=0;K<J.length;K++){let F=P1(String(J[K]),{...U,onResult:X},!0),N=F.state.negated||F.state.negatedExtglob;if(N)V++;for(let q of $){let H=F(q,!0);if(!(N?!H.isMatch:H.isMatch))continue;if(N)Q.add(H.output);else Q.delete(H.output),_.add(H.output)}}let Y=(V===J.length?[...G]:[..._]).filter((K)=>!Q.has(K));if(U&&Y.length===0){if(U.failglob===!0)throw Error(`No matches found for "${J.join(", ")}"`);if(U.nonull===!0||U.nullglob===!0)return U.unescape?J.map((K)=>K.replace(/\\/g,"")):J}return Y};l4.match=l4;l4.matcher=($,J)=>P1($,J);l4.isMatch=($,J,U)=>P1(J,U)($);l4.any=l4.isMatch;l4.not=($,J,U={})=>{J=[].concat(J).map(String);let Q=new Set,_=[],V=new Set(l4($,J,{...U,onResult:(X)=>{if(U.onResult)U.onResult(X);_.push(X.output)}}));for(let X of _)if(!V.has(X))Q.add(X);return[...Q]};l4.contains=($,J,U)=>{if(typeof $!=="string")throw TypeError(`Expected a string: "${$M.inspect($)}"`);if(Array.isArray(J))return J.some((Q)=>l4.contains($,Q,U));if(typeof J==="string"){if(eP($)||eP(J))return!1;if($.includes(J)||$.startsWith("./")&&$.slice(2).includes(J))return!0}return l4.isMatch($,J,{...U,contains:!0})};l4.matchKeys=($,J,U)=>{if(!GZ.isObject($))throw TypeError("Expected the first argument to be an object");let Q=l4(Object.keys($),J,U),_={};for(let G of Q)_[G]=$[G];return _};l4.some=($,J,U)=>{let Q=[].concat($);for(let _ of[].concat(J)){let G=P1(String(_),U);if(Q.some((V)=>G(V)))return!0}return!1};l4.every=($,J,U)=>{let Q=[].concat($);for(let _ of[].concat(J)){let G=P1(String(_),U);if(!Q.every((V)=>G(V)))return!1}return!0};l4.all=($,J,U)=>{if(typeof $!=="string")throw TypeError(`Expected a string: "${$M.inspect($)}"`);return[].concat(J).every((Q)=>P1(Q,U)($))};l4.capture=($,J,U)=>{let Q=GZ.isWindows(U),G=P1.makeRe(String($),{...U,capture:!0}).exec(Q?GZ.toPosixSlashes(J):J);if(G)return G.slice(1).map((V)=>V===void 0?"":V)};l4.makeRe=(...$)=>P1.makeRe(...$);l4.scan=(...$)=>P1.scan(...$);l4.parse=($,J)=>{let U=[];for(let Q of[].concat($||[]))for(let _ of JM(String(Q),J))U.push(P1.parse(_,J));return U};l4.braces=($,J)=>{if(typeof $!=="string")throw TypeError("Expected a string");if(J&&J.nobrace===!0||!UM($))return[$];return JM($,J)};l4.braceExpand=($,J)=>{if(typeof $!=="string")throw TypeError("Expected a string");return l4.braces($,{...J,expand:!0})};l4.hasBraces=UM;_M.exports=l4});var BM=J$((qM)=>{Object.defineProperty(qM,"__esModule",{value:!0});qM.isAbsolute=qM.partitionAbsoluteAndRelative=qM.removeDuplicateSlashes=qM.matchAny=qM.convertPatternsToRe=qM.makeRe=qM.getPatternParts=qM.expandBraceExpansion=qM.expandPatternsWithBraceExpansion=qM.isAffectDepthOfReadingPattern=qM.endsWithSlashGlobStar=qM.hasGlobStar=qM.getBaseDirectory=qM.isPatternRelatedToParentDirectory=qM.getPatternsOutsideCurrentDirectory=qM.getPatternsInsideCurrentDirectory=qM.getPositivePatterns=qM.getNegativePatterns=qM.isPositivePattern=qM.isNegativePattern=qM.convertToNegativePattern=qM.convertToPositivePattern=qM.isDynamicPattern=qM.isStaticPattern=void 0;var GM=E$("path"),Eu=eE(),VZ=QM(),VM="**",Pu="\\",Mu=/[*?]|^!/,Lu=/\[[^[]*]/,zu=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,Ru=/[!*+?@]\([^(]*\)/,Au=/,|\.\./,wu=/(?!^)\/{2,}/g;function XM($,J={}){return!YM($,J)}qM.isStaticPattern=XM;function YM($,J={}){if($==="")return!1;if(J.caseSensitiveMatch===!1||$.includes(Pu))return!0;if(Mu.test($)||Lu.test($)||zu.test($))return!0;if(J.extglob!==!1&&Ru.test($))return!0;if(J.braceExpansion!==!1&&fu($))return!0;return!1}qM.isDynamicPattern=YM;function fu($){let J=$.indexOf("{");if(J===-1)return!1;let U=$.indexOf("}",J+1);if(U===-1)return!1;let Q=$.slice(J,U);return Au.test(Q)}function ku($){return wQ($)?$.slice(1):$}qM.convertToPositivePattern=ku;function Iu($){return"!"+$}qM.convertToNegativePattern=Iu;function wQ($){return $.startsWith("!")&&$[1]!=="("}qM.isNegativePattern=wQ;function ZM($){return!wQ($)}qM.isPositivePattern=ZM;function Su($){return $.filter(wQ)}qM.getNegativePatterns=Su;function Tu($){return $.filter(ZM)}qM.getPositivePatterns=Tu;function vu($){return $.filter((J)=>!XZ(J))}qM.getPatternsInsideCurrentDirectory=vu;function Cu($){return $.filter(XZ)}qM.getPatternsOutsideCurrentDirectory=Cu;function XZ($){return $.startsWith("..")||$.startsWith("./..")}qM.isPatternRelatedToParentDirectory=XZ;function bu($){return Eu($,{flipBackslashes:!1})}qM.getBaseDirectory=bu;function yu($){return $.includes(VM)}qM.hasGlobStar=yu;function KM($){return $.endsWith("/"+VM)}qM.endsWithSlashGlobStar=KM;function gu($){let J=GM.basename($);return KM($)||XM(J)}qM.isAffectDepthOfReadingPattern=gu;function xu($){return $.reduce((J,U)=>{return J.concat(NM(U))},[])}qM.expandPatternsWithBraceExpansion=xu;function NM($){let J=VZ.braces($,{expand:!0,nodupes:!0,keepEscaping:!0});return J.sort((U,Q)=>U.length-Q.length),J.filter((U)=>U!=="")}qM.expandBraceExpansion=NM;function hu($,J){let{parts:U}=VZ.scan($,Object.assign(Object.assign({},J),{parts:!0}));if(U.length===0)U=[$];if(U[0].startsWith("/"))U[0]=U[0].slice(1),U.unshift("");return U}qM.getPatternParts=hu;function FM($,J){return VZ.makeRe($,J)}qM.makeRe=FM;function uu($,J){return $.map((U)=>FM(U,J))}qM.convertPatternsToRe=uu;function mu($,J){return J.some((U)=>U.test($))}qM.matchAny=mu;function cu($){return $.replace(wu,"/")}qM.removeDuplicateSlashes=cu;function du($){let J=[],U=[];for(let Q of $)if(WM(Q))J.push(Q);else U.push(Q);return[J,U]}qM.partitionAbsoluteAndRelative=du;function WM($){return GM.isAbsolute($)}qM.isAbsolute=WM});var EM=J$((iV$,DM)=>{var Wm=E$("stream"),OM=Wm.PassThrough,qm=Array.prototype.slice;DM.exports=Hm;function Hm(){let $=[],J=qm.call(arguments),U=!1,Q=J[J.length-1];if(Q&&!Array.isArray(Q)&&Q.pipe==null)J.pop();else Q={};let _=Q.end!==!1,G=Q.pipeError===!0;if(Q.objectMode==null)Q.objectMode=!0;if(Q.highWaterMark==null)Q.highWaterMark=65536;let V=OM(Q);function X(){for(let K=0,F=arguments.length;K<F;K++)$.push(jM(arguments[K],Q));return Z(),this}function Z(){if(U)return;U=!0;let K=$.shift();if(!K){process.nextTick(Y);return}if(!Array.isArray(K))K=[K];let F=K.length+1;function N(){if(--F>0)return;U=!1,Z()}function q(H){function E(){if(H.removeListener("merge2UnpipeEnd",E),H.removeListener("end",E),G)H.removeListener("error",D);N()}function D(B){V.emit("error",B)}if(H._readableState.endEmitted)return N();if(H.on("merge2UnpipeEnd",E),H.on("end",E),G)H.on("error",D);H.pipe(V,{end:!1}),H.resume()}for(let H=0;H<K.length;H++)q(K[H]);N()}function Y(){if(U=!1,V.emit("queueDrain"),_)V.end()}if(V.setMaxListeners(0),V.add=X,V.on("unpipe",function(K){K.emit("merge2UnpipeEnd")}),J.length)X.apply(null,J);return V}function jM($,J){if(!Array.isArray($)){if(!$._readableState&&$.pipe)$=$.pipe(OM(J));if(!$._readableState||!$.pause||!$.pipe)throw Error("Only readable stream can be merged.");$.pause()}else for(let U=0,Q=$.length;U<Q;U++)$[U]=jM($[U],J);return $}});var zM=J$((MM)=>{Object.defineProperty(MM,"__esModule",{value:!0});MM.merge=void 0;var Bm=EM();function Om($){let J=Bm($);return $.forEach((U)=>{U.once("error",(Q)=>J.emit("error",Q))}),J.once("close",()=>PM($)),J.once("end",()=>PM($)),J}MM.merge=Om;function PM($){$.forEach((J)=>J.emit("close"))}});var wM=J$((RM)=>{Object.defineProperty(RM,"__esModule",{value:!0});RM.isEmpty=RM.isString=void 0;function jm($){return typeof $==="string"}RM.isString=jm;function Dm($){return $===""}RM.isEmpty=Dm});var a1=J$((fM)=>{Object.defineProperty(fM,"__esModule",{value:!0});fM.string=fM.stream=fM.pattern=fM.path=fM.fs=fM.errno=fM.array=void 0;var Pm=vE();fM.array=Pm;var Mm=yE();fM.errno=Mm;var Lm=uE();fM.fs=Lm;var zm=rE();fM.path=zm;var Rm=BM();fM.pattern=Rm;var Am=zM();fM.stream=Am;var wm=wM();fM.string=wm});var bM=J$((vM)=>{Object.defineProperty(vM,"__esModule",{value:!0});vM.convertPatternGroupToTask=vM.convertPatternGroupsToTasks=vM.groupPatternsByBaseDirectory=vM.getNegativePatternsAsPositive=vM.getPositivePatterns=vM.convertPatternsToTasks=vM.generate=void 0;var o0=a1();function Cm($,J){let U=IM($,J),Q=IM(J.ignore,J),_=SM(U),G=TM(U,Q),V=_.filter((K)=>o0.pattern.isStaticPattern(K,J)),X=_.filter((K)=>o0.pattern.isDynamicPattern(K,J)),Z=YZ(V,G,!1),Y=YZ(X,G,!0);return Z.concat(Y)}vM.generate=Cm;function IM($,J){let U=$;if(J.braceExpansion)U=o0.pattern.expandPatternsWithBraceExpansion(U);if(J.baseNameMatch)U=U.map((Q)=>Q.includes("/")?Q:`**/${Q}`);return U.map((Q)=>o0.pattern.removeDuplicateSlashes(Q))}function YZ($,J,U){let Q=[],_=o0.pattern.getPatternsOutsideCurrentDirectory($),G=o0.pattern.getPatternsInsideCurrentDirectory($),V=ZZ(_),X=ZZ(G);if(Q.push(...KZ(V,J,U)),"."in X)Q.push(NZ(".",G,J,U));else Q.push(...KZ(X,J,U));return Q}vM.convertPatternsToTasks=YZ;function SM($){return o0.pattern.getPositivePatterns($)}vM.getPositivePatterns=SM;function TM($,J){return o0.pattern.getNegativePatterns($).concat(J).map(o0.pattern.convertToPositivePattern)}vM.getNegativePatternsAsPositive=TM;function ZZ($){let J={};return $.reduce((U,Q)=>{let _=o0.pattern.getBaseDirectory(Q);if(_ in U)U[_].push(Q);else U[_]=[Q];return U},J)}vM.groupPatternsByBaseDirectory=ZZ;function KZ($,J,U){return Object.keys($).map((Q)=>{return NZ(Q,$[Q],J,U)})}vM.convertPatternGroupsToTasks=KZ;function NZ($,J,U,Q){return{dynamic:Q,positive:J,negative:U,base:$,patterns:[].concat(J,U.map(o0.pattern.convertToNegativePattern))}}vM.convertPatternGroupToTask=NZ});var hM=J$((gM)=>{Object.defineProperty(gM,"__esModule",{value:!0});gM.read=void 0;function mm($,J,U){J.fs.lstat($,(Q,_)=>{if(Q!==null){yM(U,Q);return}if(!_.isSymbolicLink()||!J.followSymbolicLink){FZ(U,_);return}J.fs.stat($,(G,V)=>{if(G!==null){if(J.throwErrorOnBrokenSymbolicLink){yM(U,G);return}FZ(U,_);return}if(J.markSymbolicLink)V.isSymbolicLink=()=>!0;FZ(U,V)})})}gM.read=mm;function yM($,J){$(J)}function FZ($,J){$(null,J)}});var cM=J$((uM)=>{Object.defineProperty(uM,"__esModule",{value:!0});uM.read=void 0;function cm($,J){let U=J.fs.lstatSync($);if(!U.isSymbolicLink()||!J.followSymbolicLink)return U;try{let Q=J.fs.statSync($);if(J.markSymbolicLink)Q.isSymbolicLink=()=>!0;return Q}catch(Q){if(!J.throwErrorOnBrokenSymbolicLink)return U;throw Q}}uM.read=cm});var iM=J$((dM)=>{Object.defineProperty(dM,"__esModule",{value:!0});dM.createFileSystemAdapter=dM.FILE_SYSTEM_ADAPTER=void 0;var fQ=E$("fs");dM.FILE_SYSTEM_ADAPTER={lstat:fQ.lstat,stat:fQ.stat,lstatSync:fQ.lstatSync,statSync:fQ.statSync};function dm($){if($===void 0)return dM.FILE_SYSTEM_ADAPTER;return Object.assign(Object.assign({},dM.FILE_SYSTEM_ADAPTER),$)}dM.createFileSystemAdapter=dm});var pM=J$((nM)=>{Object.defineProperty(nM,"__esModule",{value:!0});var lm=iM();class rM{constructor($={}){this._options=$,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=lm.createFileSystemAdapter(this._options.fs),this.markSymbolicLink=this._getValue(this._options.markSymbolicLink,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0)}_getValue($,J){return $!==null&&$!==void 0?$:J}}nM.default=rM});var tJ=J$((oM)=>{Object.defineProperty(oM,"__esModule",{value:!0});oM.statSync=oM.stat=oM.Settings=void 0;var aM=hM(),rm=cM(),qZ=pM();oM.Settings=qZ.default;function nm($,J,U){if(typeof J==="function"){aM.read($,HZ(),J);return}aM.read($,HZ(J),U)}oM.stat=nm;function pm($,J){let U=HZ(J);return rm.read($,U)}oM.statSync=pm;function HZ($={}){if($ instanceof qZ.default)return $;return new qZ.default($)}});var $L=J$((JX$,eM)=>{/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var sM;eM.exports=typeof queueMicrotask==="function"?queueMicrotask.bind(typeof window<"u"?window:global):($)=>(sM||(sM=Promise.resolve())).then($).catch((J)=>setTimeout(()=>{throw J},0))});var UL=J$((UX$,JL)=>{/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */JL.exports=sm;var tm=$L();function sm($,J){let U,Q,_,G=!0;if(Array.isArray($))U=[],Q=$.length;else _=Object.keys($),U={},Q=_.length;function V(Z){function Y(){if(J)J(Z,U);J=null}if(G)tm(Y);else Y()}function X(Z,Y,K){if(U[Z]=K,--Q===0||Y)V(Y)}if(!Q)V(null);else if(_)_.forEach(function(Z){$[Z](function(Y,K){X(Z,Y,K)})});else $.forEach(function(Z,Y){Z(function(K,F){X(Y,K,F)})});G=!1}});var BZ=J$((GL)=>{Object.defineProperty(GL,"__esModule",{value:!0});GL.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var kQ=process.versions.node.split(".");if(kQ[0]===void 0||kQ[1]===void 0)throw Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var _L=Number.parseInt(kQ[0],10),em=Number.parseInt(kQ[1],10),QL=10,$c=10,Jc=_L>QL,Uc=_L===QL&&em>=$c;GL.IS_SUPPORT_READDIR_WITH_FILE_TYPES=Jc||Uc});var KL=J$((YL)=>{Object.defineProperty(YL,"__esModule",{value:!0});YL.createDirentFromStats=void 0;class XL{constructor($,J){this.name=$,this.isBlockDevice=J.isBlockDevice.bind(J),this.isCharacterDevice=J.isCharacterDevice.bind(J),this.isDirectory=J.isDirectory.bind(J),this.isFIFO=J.isFIFO.bind(J),this.isFile=J.isFile.bind(J),this.isSocket=J.isSocket.bind(J),this.isSymbolicLink=J.isSymbolicLink.bind(J)}}function _c($,J){return new XL($,J)}YL.createDirentFromStats=_c});var OZ=J$((NL)=>{Object.defineProperty(NL,"__esModule",{value:!0});NL.fs=void 0;var Qc=KL();NL.fs=Qc});var jZ=J$((WL)=>{Object.defineProperty(WL,"__esModule",{value:!0});WL.joinPathSegments=void 0;function Gc($,J,U){if($.endsWith(U))return $+J;return $+U+J}WL.joinPathSegments=Gc});var ML=J$((EL)=>{Object.defineProperty(EL,"__esModule",{value:!0});EL.readdir=EL.readdirWithFileTypes=EL.read=void 0;var Vc=tJ(),HL=UL(),Xc=BZ(),BL=OZ(),OL=jZ();function Yc($,J,U){if(!J.stats&&Xc.IS_SUPPORT_READDIR_WITH_FILE_TYPES){jL($,J,U);return}DL($,J,U)}EL.read=Yc;function jL($,J,U){J.fs.readdir($,{withFileTypes:!0},(Q,_)=>{if(Q!==null){IQ(U,Q);return}let G=_.map((X)=>({dirent:X,name:X.name,path:OL.joinPathSegments($,X.name,J.pathSegmentSeparator)}));if(!J.followSymbolicLinks){DZ(U,G);return}let V=G.map((X)=>Zc(X,J));HL(V,(X,Z)=>{if(X!==null){IQ(U,X);return}DZ(U,Z)})})}EL.readdirWithFileTypes=jL;function Zc($,J){return(U)=>{if(!$.dirent.isSymbolicLink()){U(null,$);return}J.fs.stat($.path,(Q,_)=>{if(Q!==null){if(J.throwErrorOnBrokenSymbolicLink){U(Q);return}U(null,$);return}$.dirent=BL.fs.createDirentFromStats($.name,_),U(null,$)})}}function DL($,J,U){J.fs.readdir($,(Q,_)=>{if(Q!==null){IQ(U,Q);return}let G=_.map((V)=>{let X=OL.joinPathSegments($,V,J.pathSegmentSeparator);return(Z)=>{Vc.stat(X,J.fsStatSettings,(Y,K)=>{if(Y!==null){Z(Y);return}let F={name:V,path:X,dirent:BL.fs.createDirentFromStats(V,K)};if(J.stats)F.stats=K;Z(null,F)})}});HL(G,(V,X)=>{if(V!==null){IQ(U,V);return}DZ(U,X)})})}EL.readdir=DL;function IQ($,J){$(J)}function DZ($,J){$(null,J)}});var kL=J$((wL)=>{Object.defineProperty(wL,"__esModule",{value:!0});wL.readdir=wL.readdirWithFileTypes=wL.read=void 0;var Fc=tJ(),Wc=BZ(),LL=OZ(),zL=jZ();function qc($,J){if(!J.stats&&Wc.IS_SUPPORT_READDIR_WITH_FILE_TYPES)return RL($,J);return AL($,J)}wL.read=qc;function RL($,J){return J.fs.readdirSync($,{withFileTypes:!0}).map((Q)=>{let _={dirent:Q,name:Q.name,path:zL.joinPathSegments($,Q.name,J.pathSegmentSeparator)};if(_.dirent.isSymbolicLink()&&J.followSymbolicLinks)try{let G=J.fs.statSync(_.path);_.dirent=LL.fs.createDirentFromStats(_.name,G)}catch(G){if(J.throwErrorOnBrokenSymbolicLink)throw G}return _})}wL.readdirWithFileTypes=RL;function AL($,J){return J.fs.readdirSync($).map((Q)=>{let _=zL.joinPathSegments($,Q,J.pathSegmentSeparator),G=Fc.statSync(_,J.fsStatSettings),V={name:Q,path:_,dirent:LL.fs.createDirentFromStats(Q,G)};if(J.stats)V.stats=G;return V})}wL.readdir=AL});var TL=J$((IL)=>{Object.defineProperty(IL,"__esModule",{value:!0});IL.createFileSystemAdapter=IL.FILE_SYSTEM_ADAPTER=void 0;var q9=E$("fs");IL.FILE_SYSTEM_ADAPTER={lstat:q9.lstat,stat:q9.stat,lstatSync:q9.lstatSync,statSync:q9.statSync,readdir:q9.readdir,readdirSync:q9.readdirSync};function Oc($){if($===void 0)return IL.FILE_SYSTEM_ADAPTER;return Object.assign(Object.assign({},IL.FILE_SYSTEM_ADAPTER),$)}IL.createFileSystemAdapter=Oc});var bL=J$((CL)=>{Object.defineProperty(CL,"__esModule",{value:!0});var jc=E$("path"),Dc=tJ(),Ec=TL();class vL{constructor($={}){this._options=$,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=Ec.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,jc.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new Dc.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue($,J){return $!==null&&$!==void 0?$:J}}CL.default=vL});var SQ=J$((gL)=>{Object.defineProperty(gL,"__esModule",{value:!0});gL.Settings=gL.scandirSync=gL.scandir=void 0;var yL=ML(),Mc=kL(),PZ=bL();gL.Settings=PZ.default;function Lc($,J,U){if(typeof J==="function"){yL.read($,MZ(),J);return}yL.read($,MZ(J),U)}gL.scandir=Lc;function zc($,J){let U=MZ(J);return Mc.read($,U)}gL.scandirSync=zc;function MZ($={}){if($ instanceof PZ.default)return $;return new PZ.default($)}});var uL=J$((FX$,hL)=>{function wc($){var J=new $,U=J;function Q(){var G=J;if(G.next)J=G.next;else J=new $,U=J;return G.next=null,G}function _(G){U.next=G,U=G}return{get:Q,release:_}}hL.exports=wc});var cL=J$((WX$,LZ)=>{var fc=uL();function mL($,J,U){if(typeof $==="function")U=J,J=$,$=null;if(!(U>=1))throw Error("fastqueue concurrency must be equal to or greater than 1");var Q=fc(kc),_=null,G=null,V=0,X=null,Z={push:E,drain:G0,saturated:G0,pause:K,paused:!1,get concurrency(){return U},set concurrency(w){if(!(w>=1))throw Error("fastqueue concurrency must be equal to or greater than 1");if(U=w,Z.paused)return;for(;_&&V<U;)V++,B()},running:Y,resume:q,idle:H,length:F,getQueue:N,unshift:D,empty:G0,kill:j,killAndDrain:f,error:I,abort:R};return Z;function Y(){return V}function K(){Z.paused=!0}function F(){var w=_,T=0;while(w)w=w.next,T++;return T}function N(){var w=_,T=[];while(w)T.push(w.value),w=w.next;return T}function q(){if(!Z.paused)return;if(Z.paused=!1,_===null){V++,B();return}for(;_&&V<U;)V++,B()}function H(){return V===0&&Z.length()===0}function E(w,T){var z=Q.get();if(z.context=$,z.release=B,z.value=w,z.callback=T||G0,z.errorHandler=X,V>=U||Z.paused)if(G)G.next=z,G=z;else _=z,G=z,Z.saturated();else V++,J.call($,z.value,z.worked)}function D(w,T){var z=Q.get();if(z.context=$,z.release=B,z.value=w,z.callback=T||G0,z.errorHandler=X,V>=U||Z.paused)if(_)z.next=_,_=z;else _=z,G=z,Z.saturated();else V++,J.call($,z.value,z.worked)}function B(w){if(w)Q.release(w);var T=_;if(T&&V<=U)if(!Z.paused){if(G===_)G=null;if(_=T.next,T.next=null,J.call($,T.value,T.worked),G===null)Z.empty()}else V--;else if(--V===0)Z.drain()}function j(){_=null,G=null,Z.drain=G0}function f(){_=null,G=null,Z.drain(),Z.drain=G0}function R(){var w=_;_=null,G=null;while(w){var{next:T,callback:z,errorHandler:S,value:O,context:M}=w;if(w.value=null,w.callback=G0,w.errorHandler=null,S)S(Error("abort"),O);z.call(M,Error("abort")),w.release(w),w=T}Z.drain=G0}function I(w){X=w}}function G0(){}function kc(){this.value=null,this.callback=G0,this.next=null,this.release=G0,this.context=null,this.errorHandler=null;var $=this;this.worked=function(U,Q){var{callback:_,errorHandler:G,value:V}=$;if($.value=null,$.callback=G0,$.errorHandler)G(U,V);_.call($.context,U,Q),$.release($)}}function Ic($,J,U){if(typeof $==="function")U=J,J=$,$=null;function Q(K,F){J.call(this,K).then(function(N){F(null,N)},F)}var _=mL($,Q,U),G=_.push,V=_.unshift;return _.push=X,_.unshift=Z,_.drained=Y,_;function X(K){var F=new Promise(function(N,q){G(K,function(H,E){if(H){q(H);return}N(E)})});return F.catch(G0),F}function Z(K){var F=new Promise(function(N,q){V(K,function(H,E){if(H){q(H);return}N(E)})});return F.catch(G0),F}function Y(){var K=new Promise(function(F){process.nextTick(function(){if(_.idle())F();else{var N=_.drain;_.drain=function(){if(typeof N==="function")N();F(),_.drain=N}}})});return K}}LZ.exports=mL;LZ.exports.promise=Ic});var TQ=J$((dL)=>{Object.defineProperty(dL,"__esModule",{value:!0});dL.joinPathSegments=dL.replacePathSegmentSeparator=dL.isAppliedFilter=dL.isFatalError=void 0;function Sc($,J){if($.errorFilter===null)return!0;return!$.errorFilter(J)}dL.isFatalError=Sc;function Tc($,J){return $===null||$(J)}dL.isAppliedFilter=Tc;function vc($,J){return $.split(/[/\\]/).join(J)}dL.replacePathSegmentSeparator=vc;function Cc($,J,U){if($==="")return J;if($.endsWith(U))return $+J;return $+U+J}dL.joinPathSegments=Cc});var zZ=J$((rL)=>{Object.defineProperty(rL,"__esModule",{value:!0});var xc=TQ();class iL{constructor($,J){this._root=$,this._settings=J,this._root=xc.replacePathSegmentSeparator($,J.pathSegmentSeparator)}}rL.default=iL});var RZ=J$((pL)=>{Object.defineProperty(pL,"__esModule",{value:!0});var uc=E$("events"),mc=SQ(),cc=cL(),vQ=TQ(),dc=zZ();class nL extends dc.default{constructor($,J){super($,J);this._settings=J,this._scandir=mc.scandir,this._emitter=new uc.EventEmitter,this._queue=cc(this._worker.bind(this),this._settings.concurrency),this._isFatalError=!1,this._isDestroyed=!1,this._queue.drain=()=>{if(!this._isFatalError)this._emitter.emit("end")}}read(){return this._isFatalError=!1,this._isDestroyed=!1,setImmediate(()=>{this._pushToQueue(this._root,this._settings.basePath)}),this._emitter}get isDestroyed(){return this._isDestroyed}destroy(){if(this._isDestroyed)throw Error("The reader is already destroyed");this._isDestroyed=!0,this._queue.killAndDrain()}onEntry($){this._emitter.on("entry",$)}onError($){this._emitter.once("error",$)}onEnd($){this._emitter.once("end",$)}_pushToQueue($,J){let U={directory:$,base:J};this._queue.push(U,(Q)=>{if(Q!==null)this._handleError(Q)})}_worker($,J){this._scandir($.directory,this._settings.fsScandirSettings,(U,Q)=>{if(U!==null){J(U,void 0);return}for(let _ of Q)this._handleEntry(_,$.base);J(null,void 0)})}_handleError($){if(this._isDestroyed||!vQ.isFatalError(this._settings,$))return;this._isFatalError=!0,this._isDestroyed=!0,this._emitter.emit("error",$)}_handleEntry($,J){if(this._isDestroyed||this._isFatalError)return;let U=$.path;if(J!==void 0)$.path=vQ.joinPathSegments(J,$.name,this._settings.pathSegmentSeparator);if(vQ.isAppliedFilter(this._settings.entryFilter,$))this._emitEntry($);if($.dirent.isDirectory()&&vQ.isAppliedFilter(this._settings.deepFilter,$))this._pushToQueue(U,J===void 0?void 0:$.path)}_emitEntry($){this._emitter.emit("entry",$)}}pL.default=nL});var tL=J$((oL)=>{Object.defineProperty(oL,"__esModule",{value:!0});var ic=RZ();class aL{constructor($,J){this._root=$,this._settings=J,this._reader=new ic.default(this._root,this._settings),this._storage=[]}read($){this._reader.onError((J)=>{rc($,J)}),this._reader.onEntry((J)=>{this._storage.push(J)}),this._reader.onEnd(()=>{nc($,this._storage)}),this._reader.read()}}oL.default=aL;function rc($,J){$(J)}function nc($,J){$(null,J)}});var $z=J$((eL)=>{Object.defineProperty(eL,"__esModule",{value:!0});var ac=E$("stream"),oc=RZ();class sL{constructor($,J){this._root=$,this._settings=J,this._reader=new oc.default(this._root,this._settings),this._stream=new ac.Readable({objectMode:!0,read:()=>{},destroy:()=>{if(!this._reader.isDestroyed)this._reader.destroy()}})}read(){return this._reader.onError(($)=>{this._stream.emit("error",$)}),this._reader.onEntry(($)=>{this._stream.push($)}),this._reader.onEnd(()=>{this._stream.push(null)}),this._reader.read(),this._stream}}eL.default=sL});var _z=J$((Uz)=>{Object.defineProperty(Uz,"__esModule",{value:!0});var sc=SQ(),CQ=TQ(),ec=zZ();class Jz extends ec.default{constructor(){super(...arguments);this._scandir=sc.scandirSync,this._storage=[],this._queue=new Set}read(){return this._pushToQueue(this._root,this._settings.basePath),this._handleQueue(),this._storage}_pushToQueue($,J){this._queue.add({directory:$,base:J})}_handleQueue(){for(let $ of this._queue.values())this._handleDirectory($.directory,$.base)}_handleDirectory($,J){try{let U=this._scandir($,this._settings.fsScandirSettings);for(let Q of U)this._handleEntry(Q,J)}catch(U){this._handleError(U)}}_handleError($){if(!CQ.isFatalError(this._settings,$))return;throw $}_handleEntry($,J){let U=$.path;if(J!==void 0)$.path=CQ.joinPathSegments(J,$.name,this._settings.pathSegmentSeparator);if(CQ.isAppliedFilter(this._settings.entryFilter,$))this._pushToStorage($);if($.dirent.isDirectory()&&CQ.isAppliedFilter(this._settings.deepFilter,$))this._pushToQueue(U,J===void 0?void 0:$.path)}_pushToStorage($){this._storage.push($)}}Uz.default=Jz});var Vz=J$((Gz)=>{Object.defineProperty(Gz,"__esModule",{value:!0});var Jd=_z();class Qz{constructor($,J){this._root=$,this._settings=J,this._reader=new Jd.default(this._root,this._settings)}read(){return this._reader.read()}}Gz.default=Qz});var Zz=J$((Yz)=>{Object.defineProperty(Yz,"__esModule",{value:!0});var _d=E$("path"),Qd=SQ();class Xz{constructor($={}){this._options=$,this.basePath=this._getValue(this._options.basePath,void 0),this.concurrency=this._getValue(this._options.concurrency,Number.POSITIVE_INFINITY),this.deepFilter=this._getValue(this._options.deepFilter,null),this.entryFilter=this._getValue(this._options.entryFilter,null),this.errorFilter=this._getValue(this._options.errorFilter,null),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,_d.sep),this.fsScandirSettings=new Qd.Settings({followSymbolicLinks:this._options.followSymbolicLinks,fs:this._options.fs,pathSegmentSeparator:this._options.pathSegmentSeparator,stats:this._options.stats,throwErrorOnBrokenSymbolicLink:this._options.throwErrorOnBrokenSymbolicLink})}_getValue($,J){return $!==null&&$!==void 0?$:J}}Yz.default=Xz});var yQ=J$((Nz)=>{Object.defineProperty(Nz,"__esModule",{value:!0});Nz.Settings=Nz.walkStream=Nz.walkSync=Nz.walk=void 0;var Kz=tL(),Vd=$z(),Xd=Vz(),AZ=Zz();Nz.Settings=AZ.default;function Yd($,J,U){if(typeof J==="function"){new Kz.default($,bQ()).read(J);return}new Kz.default($,bQ(J)).read(U)}Nz.walk=Yd;function Zd($,J){let U=bQ(J);return new Xd.default($,U).read()}Nz.walkSync=Zd;function Kd($,J){let U=bQ(J);return new Vd.default($,U).read()}Nz.walkStream=Kd;function bQ($={}){if($ instanceof AZ.default)return $;return new AZ.default($)}});var gQ=J$((Hz)=>{Object.defineProperty(Hz,"__esModule",{value:!0});var qd=E$("path"),Hd=tJ(),Wz=a1();class qz{constructor($){this._settings=$,this._fsStatSettings=new Hd.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath($){return qd.resolve(this._settings.cwd,$)}_makeEntry($,J){let U={name:J,path:J,dirent:Wz.fs.createDirentFromStats(J,$)};if(this._settings.stats)U.stats=$;return U}_isFatalError($){return!Wz.errno.isEnoentCodeError($)&&!this._settings.suppressErrors}}Hz.default=qz});var wZ=J$((Oz)=>{Object.defineProperty(Oz,"__esModule",{value:!0});var Od=E$("stream"),jd=tJ(),Dd=yQ(),Ed=gQ();class Bz extends Ed.default{constructor(){super(...arguments);this._walkStream=Dd.walkStream,this._stat=jd.stat}dynamic($,J){return this._walkStream($,J)}static($,J){let U=$.map(this._getFullEntryPath,this),Q=new Od.PassThrough({objectMode:!0});Q._write=(_,G,V)=>{return this._getEntry(U[_],$[_],J).then((X)=>{if(X!==null&&J.entryFilter(X))Q.push(X);if(_===U.length-1)Q.end();V()}).catch(V)};for(let _=0;_<U.length;_++)Q.write(_);return Q}_getEntry($,J,U){return this._getStat($).then((Q)=>this._makeEntry(Q,J)).catch((Q)=>{if(U.errorFilter(Q))return null;throw Q})}_getStat($){return new Promise((J,U)=>{this._stat($,this._fsStatSettings,(Q,_)=>{return Q===null?J(_):U(Q)})})}}Oz.default=Bz});var Ez=J$((Dz)=>{Object.defineProperty(Dz,"__esModule",{value:!0});var Md=yQ(),Ld=gQ(),zd=wZ();class jz extends Ld.default{constructor(){super(...arguments);this._walkAsync=Md.walk,this._readerStream=new zd.default(this._settings)}dynamic($,J){return new Promise((U,Q)=>{this._walkAsync($,J,(_,G)=>{if(_===null)U(G);else Q(_)})})}async static($,J){let U=[],Q=this._readerStream.static($,J);return new Promise((_,G)=>{Q.once("error",G),Q.on("data",(V)=>U.push(V)),Q.once("end",()=>_(U))})}}Dz.default=jz});var Lz=J$((Mz)=>{Object.defineProperty(Mz,"__esModule",{value:!0});var t5=a1();class Pz{constructor($,J,U){this._patterns=$,this._settings=J,this._micromatchOptions=U,this._storage=[],this._fillStorage()}_fillStorage(){for(let $ of this._patterns){let J=this._getPatternSegments($),U=this._splitSegmentsIntoSections(J);this._storage.push({complete:U.length<=1,pattern:$,segments:J,sections:U})}}_getPatternSegments($){return t5.pattern.getPatternParts($,this._micromatchOptions).map((U)=>{if(!t5.pattern.isDynamicPattern(U,this._settings))return{dynamic:!1,pattern:U};return{dynamic:!0,pattern:U,patternRe:t5.pattern.makeRe(U,this._micromatchOptions)}})}_splitSegmentsIntoSections($){return t5.array.splitWhen($,(J)=>J.dynamic&&t5.pattern.hasGlobStar(J.pattern))}}Mz.default=Pz});var Az=J$((Rz)=>{Object.defineProperty(Rz,"__esModule",{value:!0});var wd=Lz();class zz extends wd.default{match($){let J=$.split("/"),U=J.length,Q=this._storage.filter((_)=>!_.complete||_.segments.length>U);for(let _ of Q){let G=_.sections[0];if(!_.complete&&U>G.length)return!0;if(J.every((X,Z)=>{let Y=_.segments[Z];if(Y.dynamic&&Y.patternRe.test(X))return!0;if(!Y.dynamic&&Y.pattern===X)return!0;return!1}))return!0}return!1}}Rz.default=zz});var kz=J$((fz)=>{Object.defineProperty(fz,"__esModule",{value:!0});var xQ=a1(),kd=Az();class wz{constructor($,J){this._settings=$,this._micromatchOptions=J}getFilter($,J,U){let Q=this._getMatcher(J),_=this._getNegativePatternsRe(U);return(G)=>this._filter($,G,Q,_)}_getMatcher($){return new kd.default($,this._settings,this._micromatchOptions)}_getNegativePatternsRe($){let J=$.filter(xQ.pattern.isAffectDepthOfReadingPattern);return xQ.pattern.convertPatternsToRe(J,this._micromatchOptions)}_filter($,J,U,Q){if(this._isSkippedByDeep($,J.path))return!1;if(this._isSkippedSymbolicLink(J))return!1;let _=xQ.path.removeLeadingDotSegment(J.path);if(this._isSkippedByPositivePatterns(_,U))return!1;return this._isSkippedByNegativePatterns(_,Q)}_isSkippedByDeep($,J){if(this._settings.deep===1/0)return!1;return this._getEntryLevel($,J)>=this._settings.deep}_getEntryLevel($,J){let U=J.split("/").length;if($==="")return U;let Q=$.split("/").length;return U-Q}_isSkippedSymbolicLink($){return!this._settings.followSymbolicLinks&&$.dirent.isSymbolicLink()}_isSkippedByPositivePatterns($,J){return!this._settings.baseNameMatch&&!J.match($)}_isSkippedByNegativePatterns($,J){return!xQ.pattern.matchAny($,J)}}fz.default=wz});var Tz=J$((Sz)=>{Object.defineProperty(Sz,"__esModule",{value:!0});var b2=a1();class Iz{constructor($,J){this._settings=$,this._micromatchOptions=J,this.index=new Map}getFilter($,J){let[U,Q]=b2.pattern.partitionAbsoluteAndRelative(J),_={positive:{all:b2.pattern.convertPatternsToRe($,this._micromatchOptions)},negative:{absolute:b2.pattern.convertPatternsToRe(U,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:b2.pattern.convertPatternsToRe(Q,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return(G)=>this._filter(G,_)}_filter($,J){let U=b2.path.removeLeadingDotSegment($.path);if(this._settings.unique&&this._isDuplicateEntry(U))return!1;if(this._onlyFileFilter($)||this._onlyDirectoryFilter($))return!1;let Q=this._isMatchToPatternsSet(U,J,$.dirent.isDirectory());if(this._settings.unique&&Q)this._createIndexRecord(U);return Q}_isDuplicateEntry($){return this.index.has($)}_createIndexRecord($){this.index.set($,void 0)}_onlyFileFilter($){return this._settings.onlyFiles&&!$.dirent.isFile()}_onlyDirectoryFilter($){return this._settings.onlyDirectories&&!$.dirent.isDirectory()}_isMatchToPatternsSet($,J,U){if(!this._isMatchToPatterns($,J.positive.all,U))return!1;if(this._isMatchToPatterns($,J.negative.relative,U))return!1;if(this._isMatchToAbsoluteNegative($,J.negative.absolute,U))return!1;return!0}_isMatchToAbsoluteNegative($,J,U){if(J.length===0)return!1;let Q=b2.path.makeAbsolute(this._settings.cwd,$);return this._isMatchToPatterns(Q,J,U)}_isMatchToPatterns($,J,U){if(J.length===0)return!1;let Q=b2.pattern.matchAny($,J);if(!Q&&U)return b2.pattern.matchAny($+"/",J);return Q}}Sz.default=Iz});var bz=J$((Cz)=>{Object.defineProperty(Cz,"__esModule",{value:!0});var Td=a1();class vz{constructor($){this._settings=$}getFilter(){return($)=>this._isNonFatalError($)}_isNonFatalError($){return Td.errno.isEnoentCodeError($)||this._settings.suppressErrors}}Cz.default=vz});var hz=J$((xz)=>{Object.defineProperty(xz,"__esModule",{value:!0});var yz=a1();class gz{constructor($){this._settings=$}getTransformer(){return($)=>this._transform($)}_transform($){let J=$.path;if(this._settings.absolute)J=yz.path.makeAbsolute(this._settings.cwd,J),J=yz.path.unixify(J);if(this._settings.markDirectories&&$.dirent.isDirectory())J+="/";if(!this._settings.objectMode)return J;return Object.assign(Object.assign({},$),{path:J})}}xz.default=gz});var hQ=J$((mz)=>{Object.defineProperty(mz,"__esModule",{value:!0});var bd=E$("path"),yd=kz(),gd=Tz(),xd=bz(),hd=hz();class uz{constructor($){this._settings=$,this.errorFilter=new xd.default(this._settings),this.entryFilter=new gd.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new yd.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new hd.default(this._settings)}_getRootDirectory($){return bd.resolve(this._settings.cwd,$.base)}_getReaderOptions($){let J=$.base==="."?"":$.base;return{basePath:J,pathSegmentSeparator:"/",concurrency:this._settings.concurrency,deepFilter:this.deepFilter.getFilter(J,$.positive,$.negative),entryFilter:this.entryFilter.getFilter($.positive,$.negative),errorFilter:this.errorFilter.getFilter(),followSymbolicLinks:this._settings.followSymbolicLinks,fs:this._settings.fs,stats:this._settings.stats,throwErrorOnBrokenSymbolicLink:this._settings.throwErrorOnBrokenSymbolicLink,transform:this.entryTransformer.getTransformer()}}_getMicromatchOptions(){return{dot:this._settings.dot,matchBase:this._settings.baseNameMatch,nobrace:!this._settings.braceExpansion,nocase:!this._settings.caseSensitiveMatch,noext:!this._settings.extglob,noglobstar:!this._settings.globstar,posix:!0,strictSlashes:!1}}}mz.default=uz});var lz=J$((dz)=>{Object.defineProperty(dz,"__esModule",{value:!0});var md=Ez(),cd=hQ();class cz extends cd.default{constructor(){super(...arguments);this._reader=new md.default(this._settings)}async read($){let J=this._getRootDirectory($),U=this._getReaderOptions($);return(await this.api(J,$,U)).map((_)=>U.transform(_))}api($,J,U){if(J.dynamic)return this._reader.dynamic($,U);return this._reader.static(J.patterns,U)}}dz.default=cz});var nz=J$((rz)=>{Object.defineProperty(rz,"__esModule",{value:!0});var ld=E$("stream"),id=wZ(),rd=hQ();class iz extends rd.default{constructor(){super(...arguments);this._reader=new id.default(this._settings)}read($){let J=this._getRootDirectory($),U=this._getReaderOptions($),Q=this.api(J,$,U),_=new ld.Readable({objectMode:!0,read:()=>{}});return Q.once("error",(G)=>_.emit("error",G)).on("data",(G)=>_.emit("data",U.transform(G))).once("end",()=>_.emit("end")),_.once("close",()=>Q.destroy()),_}api($,J,U){if(J.dynamic)return this._reader.dynamic($,U);return this._reader.static(J.patterns,U)}}rz.default=iz});var oz=J$((az)=>{Object.defineProperty(az,"__esModule",{value:!0});var pd=tJ(),ad=yQ(),od=gQ();class pz extends od.default{constructor(){super(...arguments);this._walkSync=ad.walkSync,this._statSync=pd.statSync}dynamic($,J){return this._walkSync($,J)}static($,J){let U=[];for(let Q of $){let _=this._getFullEntryPath(Q),G=this._getEntry(_,Q,J);if(G===null||!J.entryFilter(G))continue;U.push(G)}return U}_getEntry($,J,U){try{let Q=this._getStat($);return this._makeEntry(Q,J)}catch(Q){if(U.errorFilter(Q))return null;throw Q}}_getStat($){return this._statSync($,this._fsStatSettings)}}az.default=pz});var ez=J$((sz)=>{Object.defineProperty(sz,"__esModule",{value:!0});var sd=oz(),ed=hQ();class tz extends ed.default{constructor(){super(...arguments);this._reader=new sd.default(this._settings)}read($){let J=this._getRootDirectory($),U=this._getReaderOptions($);return this.api(J,$,U).map(U.transform)}api($,J,U){if(J.dynamic)return this._reader.dynamic($,U);return this._reader.static(J.patterns,U)}}sz.default=tz});var UR=J$((JR)=>{Object.defineProperty(JR,"__esModule",{value:!0});JR.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var H9=E$("fs"),Jl=E$("os"),Ul=Math.max(Jl.cpus().length,1);JR.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:H9.lstat,lstatSync:H9.lstatSync,stat:H9.stat,statSync:H9.statSync,readdir:H9.readdir,readdirSync:H9.readdirSync};class $R{constructor($={}){if(this._options=$,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,Ul),this.cwd=this._getValue(this._options.cwd,process.cwd()),this.deep=this._getValue(this._options.deep,1/0),this.dot=this._getValue(this._options.dot,!1),this.extglob=this._getValue(this._options.extglob,!0),this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!0),this.fs=this._getFileSystemMethods(this._options.fs),this.globstar=this._getValue(this._options.globstar,!0),this.ignore=this._getValue(this._options.ignore,[]),this.markDirectories=this._getValue(this._options.markDirectories,!1),this.objectMode=this._getValue(this._options.objectMode,!1),this.onlyDirectories=this._getValue(this._options.onlyDirectories,!1),this.onlyFiles=this._getValue(this._options.onlyFiles,!0),this.stats=this._getValue(this._options.stats,!1),this.suppressErrors=this._getValue(this._options.suppressErrors,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!1),this.unique=this._getValue(this._options.unique,!0),this.onlyDirectories)this.onlyFiles=!1;if(this.stats)this.objectMode=!0;this.ignore=[].concat(this.ignore)}_getValue($,J){return $===void 0?J:$}_getFileSystemMethods($={}){return Object.assign(Object.assign({},JR.DEFAULT_FILE_SYSTEM_ADAPTER),$)}}JR.default=$R});var GR=J$((xX$,QR)=>{var _R=bM(),Ql=lz(),Gl=nz(),Vl=ez(),kZ=UR(),y0=a1();async function IZ($,J){t0($);let U=SZ($,Ql.default,J),Q=await Promise.all(U);return y0.array.flatten(Q)}(function($){$.glob=$,$.globSync=J,$.globStream=U,$.async=$;function J(Y,K){t0(Y);let F=SZ(Y,Vl.default,K);return y0.array.flatten(F)}$.sync=J;function U(Y,K){t0(Y);let F=SZ(Y,Gl.default,K);return y0.stream.merge(F)}$.stream=U;function Q(Y,K){t0(Y);let F=[].concat(Y),N=new kZ.default(K);return _R.generate(F,N)}$.generateTasks=Q;function _(Y,K){t0(Y);let F=new kZ.default(K);return y0.pattern.isDynamicPattern(Y,F)}$.isDynamicPattern=_;function G(Y){return t0(Y),y0.path.escape(Y)}$.escapePath=G;function V(Y){return t0(Y),y0.path.convertPathToPattern(Y)}$.convertPathToPattern=V;let X;(function(Y){function K(N){return t0(N),y0.path.escapePosixPath(N)}Y.escapePath=K;function F(N){return t0(N),y0.path.convertPosixPathToPattern(N)}Y.convertPathToPattern=F})(X=$.posix||($.posix={}));let Z;(function(Y){function K(N){return t0(N),y0.path.escapeWindowsPath(N)}Y.escapePath=K;function F(N){return t0(N),y0.path.convertWindowsPathToPattern(N)}Y.convertPathToPattern=F})(Z=$.win32||($.win32={}))})(IZ||(IZ={}));function SZ($,J,U){let Q=[].concat($),_=new kZ.default(U),G=_R.generate(Q,_),V=new J(_);return G.map(V.read,V)}function t0($){if(![].concat($).every((Q)=>y0.string.isString(Q)&&!y0.string.isEmpty(Q)))throw TypeError("Patterns must be a string (non empty) or an array of strings")}QR.exports=IZ});var s5=J$((hX$,XR)=>{var VR={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},Xl={...VR,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},Yl={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};XR.exports={MAX_LENGTH:65536,POSIX_REGEX_SOURCE:Yl,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars($){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${$.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars($){return $===!0?Xl:VR}}});var e5=J$((Wl)=>{var{REGEX_BACKSLASH:Zl,REGEX_REMOVE_BACKSLASH:Kl,REGEX_SPECIAL_CHARS:Nl,REGEX_SPECIAL_CHARS_GLOBAL:Fl}=s5();Wl.isObject=($)=>$!==null&&typeof $==="object"&&!Array.isArray($);Wl.hasRegexChars=($)=>Nl.test($);Wl.isRegexChar=($)=>$.length===1&&Wl.hasRegexChars($);Wl.escapeRegex=($)=>$.replace(Fl,"\\$1");Wl.toPosixSlashes=($)=>$.replace(Zl,"/");Wl.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let $=navigator.platform.toLowerCase();return $==="win32"||$==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};Wl.removeBackslashes=($)=>{return $.replace(Kl,(J)=>{return J==="\\"?"":J})};Wl.escapeLast=($,J,U)=>{let Q=$.lastIndexOf(J,U);if(Q===-1)return $;if($[Q-1]==="\\")return Wl.escapeLast($,J,Q-1);return`${$.slice(0,Q)}\\${$.slice(Q)}`};Wl.removePrefix=($,J={})=>{let U=$;if(U.startsWith("./"))U=U.slice(2),J.prefix="./";return U};Wl.wrapOutput=($,J={},U={})=>{let Q=U.contains?"":"^",_=U.contains?"":"$",G=`${Q}(?:${$})${_}`;if(J.negated===!0)G=`(?:^(?!${G}).*$)`;return G};Wl.basename=($,{windows:J}={})=>{let U=$.split(J?/[\\/]/:"/"),Q=U[U.length-1];if(Q==="")return U[U.length-2];return Q}});var OR=J$((mX$,BR)=>{var KR=e5(),{CHAR_ASTERISK:TZ,CHAR_AT:Ll,CHAR_BACKWARD_SLASH:$7,CHAR_COMMA:zl,CHAR_DOT:vZ,CHAR_EXCLAMATION_MARK:CZ,CHAR_FORWARD_SLASH:HR,CHAR_LEFT_CURLY_BRACE:bZ,CHAR_LEFT_PARENTHESES:yZ,CHAR_LEFT_SQUARE_BRACKET:Rl,CHAR_PLUS:Al,CHAR_QUESTION_MARK:NR,CHAR_RIGHT_CURLY_BRACE:wl,CHAR_RIGHT_PARENTHESES:FR,CHAR_RIGHT_SQUARE_BRACKET:fl}=s5(),WR=($)=>{return $===HR||$===$7},qR=($)=>{if($.isPrefix!==!0)$.depth=$.isGlobstar?1/0:1},kl=($,J)=>{let U=J||{},Q=$.length-1,_=U.parts===!0||U.scanToEnd===!0,G=[],V=[],X=[],Z=$,Y=-1,K=0,F=0,N=!1,q=!1,H=!1,E=!1,D=!1,B=!1,j=!1,f=!1,R=!1,I=!1,w=0,T,z,S={value:"",depth:0,isGlob:!1},O=()=>Y>=Q,M=()=>Z.charCodeAt(Y+1),P=()=>{return T=z,Z.charCodeAt(++Y)};while(Y<Q){z=P();let C;if(z===$7){if(j=S.backslashes=!0,z=P(),z===bZ)B=!0;continue}if(B===!0||z===bZ){w++;while(O()!==!0&&(z=P())){if(z===$7){j=S.backslashes=!0,P();continue}if(z===bZ){w++;continue}if(B!==!0&&z===vZ&&(z=P())===vZ){if(N=S.isBrace=!0,H=S.isGlob=!0,I=!0,_===!0)continue;break}if(B!==!0&&z===zl){if(N=S.isBrace=!0,H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===wl){if(w--,w===0){B=!1,N=S.isBrace=!0,I=!0;break}}}if(_===!0)continue;break}if(z===HR){if(G.push(Y),V.push(S),S={value:"",depth:0,isGlob:!1},I===!0)continue;if(T===vZ&&Y===K+1){K+=2;continue}F=Y+1;continue}if(U.noext!==!0){if((z===Al||z===Ll||z===TZ||z===NR||z===CZ)===!0&&M()===yZ){if(H=S.isGlob=!0,E=S.isExtglob=!0,I=!0,z===CZ&&Y===K)R=!0;if(_===!0){while(O()!==!0&&(z=P())){if(z===$7){j=S.backslashes=!0,z=P();continue}if(z===FR){H=S.isGlob=!0,I=!0;break}}continue}break}}if(z===TZ){if(T===TZ)D=S.isGlobstar=!0;if(H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===NR){if(H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===Rl){while(O()!==!0&&(C=P())){if(C===$7){j=S.backslashes=!0,P();continue}if(C===fl){q=S.isBracket=!0,H=S.isGlob=!0,I=!0;break}}if(_===!0)continue;break}if(U.nonegate!==!0&&z===CZ&&Y===K){f=S.negated=!0,K++;continue}if(U.noparen!==!0&&z===yZ){if(H=S.isGlob=!0,_===!0){while(O()!==!0&&(z=P())){if(z===yZ){j=S.backslashes=!0,z=P();continue}if(z===FR){I=!0;break}}continue}break}if(H===!0){if(I=!0,_===!0)continue;break}}if(U.noext===!0)E=!1,H=!1;let A=Z,k="",L="";if(K>0)k=Z.slice(0,K),Z=Z.slice(K),F-=K;if(A&&H===!0&&F>0)A=Z.slice(0,F),L=Z.slice(F);else if(H===!0)A="",L=Z;else A=Z;if(A&&A!==""&&A!=="/"&&A!==Z){if(WR(A.charCodeAt(A.length-1)))A=A.slice(0,-1)}if(U.unescape===!0){if(L)L=KR.removeBackslashes(L);if(A&&j===!0)A=KR.removeBackslashes(A)}let v={prefix:k,input:$,start:K,base:A,glob:L,isBrace:N,isBracket:q,isGlob:H,isExtglob:E,isGlobstar:D,negated:f,negatedExtglob:R};if(U.tokens===!0){if(v.maxDepth=0,!WR(z))V.push(S);v.tokens=V}if(U.parts===!0||U.tokens===!0){let C;for(let b=0;b<G.length;b++){let y=C?C+1:K,x=G[b],c=$.slice(y,x);if(U.tokens){if(b===0&&K!==0)V[b].isPrefix=!0,V[b].value=k;else V[b].value=c;qR(V[b]),v.maxDepth+=V[b].depth}if(b!==0||c!=="")X.push(c);C=x}if(C&&C+1<$.length){let b=$.slice(C+1);if(X.push(b),U.tokens)V[V.length-1].value=b,qR(V[V.length-1]),v.maxDepth+=V[V.length-1].depth}v.slashes=G,v.parts=X}return v};BR.exports=kl});var ER=J$((cX$,DR)=>{var uQ=s5(),M1=e5(),{MAX_LENGTH:mQ,POSIX_REGEX_SOURCE:Il,REGEX_NON_SPECIAL_CHARS:Sl,REGEX_SPECIAL_CHARS_BACKREF:Tl,REPLACEMENTS:jR}=uQ,vl=($,J)=>{if(typeof J.expandRange==="function")return J.expandRange(...$,J);$.sort();let U=`[${$.join("-")}]`;try{new RegExp(U)}catch(Q){return $.map((_)=>M1.escapeRegex(_)).join("..")}return U},B9=($,J)=>{return`Missing ${$}: "${J}" - use "\\\\${J}" to match literal characters`},gZ=($,J)=>{if(typeof $!=="string")throw TypeError("Expected a string");$=jR[$]||$;let U={...J},Q=typeof U.maxLength==="number"?Math.min(mQ,U.maxLength):mQ,_=$.length;if(_>Q)throw SyntaxError(`Input length: ${_}, exceeds maximum allowed length: ${Q}`);let G={type:"bos",value:"",output:U.prepend||""},V=[G],X=U.capture?"":"?:",Z=uQ.globChars(U.windows),Y=uQ.extglobChars(Z),{DOT_LITERAL:K,PLUS_LITERAL:F,SLASH_LITERAL:N,ONE_CHAR:q,DOTS_SLASH:H,NO_DOT:E,NO_DOT_SLASH:D,NO_DOTS_SLASH:B,QMARK:j,QMARK_NO_DOT:f,STAR:R,START_ANCHOR:I}=Z,w=(_$)=>{return`(${X}(?:(?!${I}${_$.dot?H:K}).)*?)`},T=U.dot?"":E,z=U.dot?j:f,S=U.bash===!0?w(U):R;if(U.capture)S=`(${S})`;if(typeof U.noext==="boolean")U.noextglob=U.noext;let O={input:$,index:-1,start:0,dot:U.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:V};$=M1.removePrefix($,O),_=$.length;let M=[],P=[],A=[],k=G,L,v=()=>O.index===_-1,C=O.peek=(_$=1)=>$[O.index+_$],b=O.advance=()=>$[++O.index]||"",y=()=>$.slice(O.index+1),x=(_$="",n=0)=>{O.consumed+=_$,O.index+=n},c=(_$)=>{O.output+=_$.output!=null?_$.output:_$.value,x(_$.value)},s=()=>{let _$=1;while(C()==="!"&&(C(2)!=="("||C(3)==="?"))b(),O.start++,_$++;if(_$%2===0)return!1;return O.negated=!0,O.start++,!0},F$=(_$)=>{O[_$]++,A.push(_$)},K$=(_$)=>{O[_$]--,A.pop()},V$=(_$)=>{if(k.type==="globstar"){let n=O.braces>0&&(_$.type==="comma"||_$.type==="brace"),a=_$.extglob===!0||M.length&&(_$.type==="pipe"||_$.type==="paren");if(_$.type!=="slash"&&_$.type!=="paren"&&!n&&!a)O.output=O.output.slice(0,-k.output.length),k.type="star",k.value="*",k.output=S,O.output+=k.output}if(M.length&&_$.type!=="paren")M[M.length-1].inner+=_$.value;if(_$.value||_$.output)c(_$);if(k&&k.type==="text"&&_$.type==="text"){k.output=(k.output||k.value)+_$.value,k.value+=_$.value;return}_$.prev=k,V.push(_$),k=_$},Y$=(_$,n)=>{let a={...Y[n],conditions:1,inner:""};a.prev=k,a.parens=O.parens,a.output=O.output;let m=(U.capture?"(":"")+a.open;F$("parens"),V$({type:_$,value:n,output:O.output?"":q}),V$({type:"paren",extglob:!0,value:b(),output:m}),M.push(a)},u$=(_$)=>{let n=_$.close+(U.capture?")":""),a;if(_$.type==="negate"){let m=S;if(_$.inner&&_$.inner.length>1&&_$.inner.includes("/"))m=w(U);if(m!==S||v()||/^\)+$/.test(y()))n=_$.close=`)$))${m}`;if(_$.inner.includes("*")&&(a=y())&&/^\.[^\\/.]+$/.test(a)){let G$=gZ(a,{...J,fastpaths:!1}).output;n=_$.close=`)${G$})${m})`}if(_$.prev.type==="bos")O.negatedExtglob=!0}V$({type:"paren",extglob:!0,value:L,output:n}),K$("parens")};if(U.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test($)){let _$=!1,n=$.replace(Tl,(a,m,G$,L$,P$,f$)=>{if(L$==="\\")return _$=!0,a;if(L$==="?"){if(m)return m+L$+(P$?j.repeat(P$.length):"");if(f$===0)return z+(P$?j.repeat(P$.length):"");return j.repeat(G$.length)}if(L$===".")return K.repeat(G$.length);if(L$==="*"){if(m)return m+L$+(P$?S:"");return S}return m?a:`\\${a}`});if(_$===!0)if(U.unescape===!0)n=n.replace(/\\/g,"");else n=n.replace(/\\+/g,(a)=>{return a.length%2===0?"\\\\":a?"\\":""});if(n===$&&U.contains===!0)return O.output=$,O;return O.output=M1.wrapOutput(n,O,J),O}while(!v()){if(L=b(),L==="\x00")continue;if(L==="\\"){let a=C();if(a==="/"&&U.bash!==!0)continue;if(a==="."||a===";")continue;if(!a){L+="\\",V$({type:"text",value:L});continue}let m=/^\\+/.exec(y()),G$=0;if(m&&m[0].length>2){if(G$=m[0].length,O.index+=G$,G$%2!==0)L+="\\"}if(U.unescape===!0)L=b();else L+=b();if(O.brackets===0){V$({type:"text",value:L});continue}}if(O.brackets>0&&(L!=="]"||k.value==="["||k.value==="[^")){if(U.posix!==!1&&L===":"){let a=k.value.slice(1);if(a.includes("[")){if(k.posix=!0,a.includes(":")){let m=k.value.lastIndexOf("["),G$=k.value.slice(0,m),L$=k.value.slice(m+2),P$=Il[L$];if(P$){if(k.value=G$+P$,O.backtrack=!0,b(),!G.output&&V.indexOf(k)===1)G.output=q;continue}}}}if(L==="["&&C()!==":"||L==="-"&&C()==="]")L=`\\${L}`;if(L==="]"&&(k.value==="["||k.value==="[^"))L=`\\${L}`;if(U.posix===!0&&L==="!"&&k.value==="[")L="^";k.value+=L,c({value:L});continue}if(O.quotes===1&&L!=='"'){L=M1.escapeRegex(L),k.value+=L,c({value:L});continue}if(L==='"'){if(O.quotes=O.quotes===1?0:1,U.keepQuotes===!0)V$({type:"text",value:L});continue}if(L==="("){F$("parens"),V$({type:"paren",value:L});continue}if(L===")"){if(O.parens===0&&U.strictBrackets===!0)throw SyntaxError(B9("opening","("));let a=M[M.length-1];if(a&&O.parens===a.parens+1){u$(M.pop());continue}V$({type:"paren",value:L,output:O.parens?")":"\\)"}),K$("parens");continue}if(L==="["){if(U.nobracket===!0||!y().includes("]")){if(U.nobracket!==!0&&U.strictBrackets===!0)throw SyntaxError(B9("closing","]"));L=`\\${L}`}else F$("brackets");V$({type:"bracket",value:L});continue}if(L==="]"){if(U.nobracket===!0||k&&k.type==="bracket"&&k.value.length===1){V$({type:"text",value:L,output:`\\${L}`});continue}if(O.brackets===0){if(U.strictBrackets===!0)throw SyntaxError(B9("opening","["));V$({type:"text",value:L,output:`\\${L}`});continue}K$("brackets");let a=k.value.slice(1);if(k.posix!==!0&&a[0]==="^"&&!a.includes("/"))L=`/${L}`;if(k.value+=L,c({value:L}),U.literalBrackets===!1||M1.hasRegexChars(a))continue;let m=M1.escapeRegex(k.value);if(O.output=O.output.slice(0,-k.value.length),U.literalBrackets===!0){O.output+=m,k.value=m;continue}k.value=`(${X}${m}|${k.value})`,O.output+=k.value;continue}if(L==="{"&&U.nobrace!==!0){F$("braces");let a={type:"brace",value:L,output:"(",outputIndex:O.output.length,tokensIndex:O.tokens.length};P.push(a),V$(a);continue}if(L==="}"){let a=P[P.length-1];if(U.nobrace===!0||!a){V$({type:"text",value:L,output:L});continue}let m=")";if(a.dots===!0){let G$=V.slice(),L$=[];for(let P$=G$.length-1;P$>=0;P$--){if(V.pop(),G$[P$].type==="brace")break;if(G$[P$].type!=="dots")L$.unshift(G$[P$].value)}m=vl(L$,U),O.backtrack=!0}if(a.comma!==!0&&a.dots!==!0){let G$=O.output.slice(0,a.outputIndex),L$=O.tokens.slice(a.tokensIndex);a.value=a.output="\\{",L=m="\\}",O.output=G$;for(let P$ of L$)O.output+=P$.output||P$.value}V$({type:"brace",value:L,output:m}),K$("braces"),P.pop();continue}if(L==="|"){if(M.length>0)M[M.length-1].conditions++;V$({type:"text",value:L});continue}if(L===","){let a=L,m=P[P.length-1];if(m&&A[A.length-1]==="braces")m.comma=!0,a="|";V$({type:"comma",value:L,output:a});continue}if(L==="/"){if(k.type==="dot"&&O.index===O.start+1){O.start=O.index+1,O.consumed="",O.output="",V.pop(),k=G;continue}V$({type:"slash",value:L,output:N});continue}if(L==="."){if(O.braces>0&&k.type==="dot"){if(k.value===".")k.output=K;let a=P[P.length-1];k.type="dots",k.output+=L,k.value+=L,a.dots=!0;continue}if(O.braces+O.parens===0&&k.type!=="bos"&&k.type!=="slash"){V$({type:"text",value:L,output:K});continue}V$({type:"dot",value:L,output:K});continue}if(L==="?"){if(!(k&&k.value==="(")&&U.noextglob!==!0&&C()==="("&&C(2)!=="?"){Y$("qmark",L);continue}if(k&&k.type==="paren"){let m=C(),G$=L;if(k.value==="("&&!/[!=<:]/.test(m)||m==="<"&&!/<([!=]|\w+>)/.test(y()))G$=`\\${L}`;V$({type:"text",value:L,output:G$});continue}if(U.dot!==!0&&(k.type==="slash"||k.type==="bos")){V$({type:"qmark",value:L,output:f});continue}V$({type:"qmark",value:L,output:j});continue}if(L==="!"){if(U.noextglob!==!0&&C()==="("){if(C(2)!=="?"||!/[!=<:]/.test(C(3))){Y$("negate",L);continue}}if(U.nonegate!==!0&&O.index===0){s();continue}}if(L==="+"){if(U.noextglob!==!0&&C()==="("&&C(2)!=="?"){Y$("plus",L);continue}if(k&&k.value==="("||U.regex===!1){V$({type:"plus",value:L,output:F});continue}if(k&&(k.type==="bracket"||k.type==="paren"||k.type==="brace")||O.parens>0){V$({type:"plus",value:L});continue}V$({type:"plus",value:F});continue}if(L==="@"){if(U.noextglob!==!0&&C()==="("&&C(2)!=="?"){V$({type:"at",extglob:!0,value:L,output:""});continue}V$({type:"text",value:L});continue}if(L!=="*"){if(L==="$"||L==="^")L=`\\${L}`;let a=Sl.exec(y());if(a)L+=a[0],O.index+=a[0].length;V$({type:"text",value:L});continue}if(k&&(k.type==="globstar"||k.star===!0)){k.type="star",k.star=!0,k.value+=L,k.output=S,O.backtrack=!0,O.globstar=!0,x(L);continue}let _$=y();if(U.noextglob!==!0&&/^\([^?]/.test(_$)){Y$("star",L);continue}if(k.type==="star"){if(U.noglobstar===!0){x(L);continue}let a=k.prev,m=a.prev,G$=a.type==="slash"||a.type==="bos",L$=m&&(m.type==="star"||m.type==="globstar");if(U.bash===!0&&(!G$||_$[0]&&_$[0]!=="/")){V$({type:"star",value:L,output:""});continue}let P$=O.braces>0&&(a.type==="comma"||a.type==="brace"),f$=M.length&&(a.type==="pipe"||a.type==="paren");if(!G$&&a.type!=="paren"&&!P$&&!f$){V$({type:"star",value:L,output:""});continue}while(_$.slice(0,3)==="/**"){let V4=$[O.index+4];if(V4&&V4!=="/")break;_$=_$.slice(3),x("/**",3)}if(a.type==="bos"&&v()){k.type="globstar",k.value+=L,k.output=w(U),O.output=k.output,O.globstar=!0,x(L);continue}if(a.type==="slash"&&a.prev.type!=="bos"&&!L$&&v()){O.output=O.output.slice(0,-(a.output+k.output).length),a.output=`(?:${a.output}`,k.type="globstar",k.output=w(U)+(U.strictSlashes?")":"|$)"),k.value+=L,O.globstar=!0,O.output+=a.output+k.output,x(L);continue}if(a.type==="slash"&&a.prev.type!=="bos"&&_$[0]==="/"){let V4=_$[1]!==void 0?"|$":"";O.output=O.output.slice(0,-(a.output+k.output).length),a.output=`(?:${a.output}`,k.type="globstar",k.output=`${w(U)}${N}|${N}${V4})`,k.value+=L,O.output+=a.output+k.output,O.globstar=!0,x(L+b()),V$({type:"slash",value:"/",output:""});continue}if(a.type==="bos"&&_$[0]==="/"){k.type="globstar",k.value+=L,k.output=`(?:^|${N}|${w(U)}${N})`,O.output=k.output,O.globstar=!0,x(L+b()),V$({type:"slash",value:"/",output:""});continue}O.output=O.output.slice(0,-k.output.length),k.type="globstar",k.output=w(U),k.value+=L,O.output+=k.output,O.globstar=!0,x(L);continue}let n={type:"star",value:L,output:S};if(U.bash===!0){if(n.output=".*?",k.type==="bos"||k.type==="slash")n.output=T+n.output;V$(n);continue}if(k&&(k.type==="bracket"||k.type==="paren")&&U.regex===!0){n.output=L,V$(n);continue}if(O.index===O.start||k.type==="slash"||k.type==="dot"){if(k.type==="dot")O.output+=D,k.output+=D;else if(U.dot===!0)O.output+=B,k.output+=B;else O.output+=T,k.output+=T;if(C()!=="*")O.output+=q,k.output+=q}V$(n)}while(O.brackets>0){if(U.strictBrackets===!0)throw SyntaxError(B9("closing","]"));O.output=M1.escapeLast(O.output,"["),K$("brackets")}while(O.parens>0){if(U.strictBrackets===!0)throw SyntaxError(B9("closing",")"));O.output=M1.escapeLast(O.output,"("),K$("parens")}while(O.braces>0){if(U.strictBrackets===!0)throw SyntaxError(B9("closing","}"));O.output=M1.escapeLast(O.output,"{"),K$("braces")}if(U.strictSlashes!==!0&&(k.type==="star"||k.type==="bracket"))V$({type:"maybe_slash",value:"",output:`${N}?`});if(O.backtrack===!0){O.output="";for(let _$ of O.tokens)if(O.output+=_$.output!=null?_$.output:_$.value,_$.suffix)O.output+=_$.suffix}return O};gZ.fastpaths=($,J)=>{let U={...J},Q=typeof U.maxLength==="number"?Math.min(mQ,U.maxLength):mQ,_=$.length;if(_>Q)throw SyntaxError(`Input length: ${_}, exceeds maximum allowed length: ${Q}`);$=jR[$]||$;let{DOT_LITERAL:G,SLASH_LITERAL:V,ONE_CHAR:X,DOTS_SLASH:Z,NO_DOT:Y,NO_DOTS:K,NO_DOTS_SLASH:F,STAR:N,START_ANCHOR:q}=uQ.globChars(U.windows),H=U.dot?K:Y,E=U.dot?F:Y,D=U.capture?"":"?:",B={negated:!1,prefix:""},j=U.bash===!0?".*?":N;if(U.capture)j=`(${j})`;let f=(T)=>{if(T.noglobstar===!0)return j;return`(${D}(?:(?!${q}${T.dot?Z:G}).)*?)`},R=(T)=>{switch(T){case"*":return`${H}${X}${j}`;case".*":return`${G}${X}${j}`;case"*.*":return`${H}${j}${G}${X}${j}`;case"*/*":return`${H}${j}${V}${X}${E}${j}`;case"**":return H+f(U);case"**/*":return`(?:${H}${f(U)}${V})?${E}${X}${j}`;case"**/*.*":return`(?:${H}${f(U)}${V})?${E}${j}${G}${X}${j}`;case"**/.*":return`(?:${H}${f(U)}${V})?${G}${X}${j}`;default:{let z=/^(.*?)\.(\w+)$/.exec(T);if(!z)return;let S=R(z[1]);if(!S)return;return S+G+z[2]}}},I=M1.removePrefix($,B),w=R(I);if(w&&U.strictSlashes!==!0)w+=`${V}?`;return w};DR.exports=gZ});var LR=J$((dX$,MR)=>{var Cl=OR(),xZ=ER(),PR=e5(),bl=s5(),yl=($)=>$&&typeof $==="object"&&!Array.isArray($),X6=($,J,U=!1)=>{if(Array.isArray($)){let K=$.map((N)=>X6(N,J,U));return(N)=>{for(let q of K){let H=q(N);if(H)return H}return!1}}let Q=yl($)&&$.tokens&&$.input;if($===""||typeof $!=="string"&&!Q)throw TypeError("Expected pattern to be a non-empty string");let _=J||{},G=_.windows,V=Q?X6.compileRe($,J):X6.makeRe($,J,!1,!0),X=V.state;delete V.state;let Z=()=>!1;if(_.ignore){let K={...J,ignore:null,onMatch:null,onResult:null};Z=X6(_.ignore,K,U)}let Y=(K,F=!1)=>{let{isMatch:N,match:q,output:H}=X6.test(K,V,J,{glob:$,posix:G}),E={glob:$,state:X,regex:V,posix:G,input:K,output:H,match:q,isMatch:N};if(typeof _.onResult==="function")_.onResult(E);if(N===!1)return E.isMatch=!1,F?E:!1;if(Z(K)){if(typeof _.onIgnore==="function")_.onIgnore(E);return E.isMatch=!1,F?E:!1}if(typeof _.onMatch==="function")_.onMatch(E);return F?E:!0};if(U)Y.state=X;return Y};X6.test=($,J,U,{glob:Q,posix:_}={})=>{if(typeof $!=="string")throw TypeError("Expected input to be a string");if($==="")return{isMatch:!1,output:""};let G=U||{},V=G.format||(_?PR.toPosixSlashes:null),X=$===Q,Z=X&&V?V($):$;if(X===!1)Z=V?V($):$,X=Z===Q;if(X===!1||G.capture===!0)if(G.matchBase===!0||G.basename===!0)X=X6.matchBase($,J,U,_);else X=J.exec(Z);return{isMatch:Boolean(X),match:X,output:Z}};X6.matchBase=($,J,U)=>{return(J instanceof RegExp?J:X6.makeRe(J,U)).test(PR.basename($))};X6.isMatch=($,J,U)=>X6(J,U)($);X6.parse=($,J)=>{if(Array.isArray($))return $.map((U)=>X6.parse(U,J));return xZ($,{...J,fastpaths:!1})};X6.scan=($,J)=>Cl($,J);X6.compileRe=($,J,U=!1,Q=!1)=>{if(U===!0)return $.output;let _=J||{},G=_.contains?"":"^",V=_.contains?"":"$",X=`${G}(?:${$.output})${V}`;if($&&$.negated===!0)X=`^(?!${X}).*$`;let Z=X6.toRegex(X,J);if(Q===!0)Z.state=$;return Z};X6.makeRe=($,J={},U=!1,Q=!1)=>{if(!$||typeof $!=="string")throw TypeError("Expected a non-empty string");let _={negated:!1,fastpaths:!0};if(J.fastpaths!==!1&&($[0]==="."||$[0]==="*"))_.output=xZ.fastpaths($,J);if(!_.output)_=xZ($,J);return X6.compileRe(_,J,U,Q)};X6.toRegex=($,J)=>{try{let U=J||{};return new RegExp($,U.flags||(U.nocase?"i":""))}catch(U){if(J&&J.debug===!0)throw U;return/$^/}};X6.constants=bl;MR.exports=X6});var wR=J$((lX$,AR)=>{var zR=LR(),gl=e5();function RR($,J,U=!1){if(J&&(J.windows===null||J.windows===void 0))J={...J,windows:gl.isWindows()};return zR($,J,U)}Object.assign(RR,zR);AR.exports=RR});var Jf=J$((jF$,ua)=>{ua.exports={name:"dotenv",version:"17.2.3",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var Xf=J$((DF$,$2)=>{var FB=E$("fs"),CG=E$("path"),ma=E$("os"),ca=E$("crypto"),da=Jf(),WB=da.version,Uf=["\uD83D\uDD10 encrypt with Dotenvx: https://dotenvx.com","\uD83D\uDD10 prevent committing .env to code: https://dotenvx.com/precommit","\uD83D\uDD10 prevent building .env in docker: https://dotenvx.com/prebuild","\uD83D\uDCE1 add observability to secrets: https://dotenvx.com/ops","\uD83D\uDC65 sync secrets across teammates & machines: https://dotenvx.com/ops","\uD83D\uDDC2️ backup and recover secrets: https://dotenvx.com/ops","✅ audit secrets and track compliance: https://dotenvx.com/ops","\uD83D\uDD04 add secrets lifecycle management: https://dotenvx.com/ops","\uD83D\uDD11 add access controls to secrets: https://dotenvx.com/ops","\uD83D\uDEE0️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function la(){return Uf[Math.floor(Math.random()*Uf.length)]}function t9($){if(typeof $==="string")return!["false","0","no","off",""].includes($.toLowerCase());return Boolean($)}function ia(){return process.stdout.isTTY}function ra($){return ia()?`\x1B[2m${$}\x1B[0m`:$}var na=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function pa($){let J={},U=$.toString();U=U.replace(/\r\n?/mg,`
|
|
28
|
-
`);let Q;while((Q=na.exec(U))!=null){let _=Q[1],G=Q[2]||"";G=G.trim();let V=G[0];if(G=G.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),V==='"')G=G.replace(/\\n/g,`
|
|
29
|
-
`),G=G.replace(/\\r/g,"\r");J[_]=G}return J}function aa($){$=$||{};let J=Vf($);$.path=J;let U=L6.configDotenv($);if(!U.parsed){let V=Error(`MISSING_DATA: Cannot parse ${J} for an unknown reason`);throw V.code="MISSING_DATA",V}let Q=Gf($).split(","),_=Q.length,G;for(let V=0;V<_;V++)try{let X=Q[V].trim(),Z=ta(U,X);G=L6.decrypt(Z.ciphertext,Z.key);break}catch(X){if(V+1>=_)throw X}return L6.parse(G)}function oa($){console.error(`[dotenv@${WB}][WARN] ${$}`)}function u7($){console.log(`[dotenv@${WB}][DEBUG] ${$}`)}function Qf($){console.log(`[dotenv@${WB}] ${$}`)}function Gf($){if($&&$.DOTENV_KEY&&$.DOTENV_KEY.length>0)return $.DOTENV_KEY;if(process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0)return process.env.DOTENV_KEY;return""}function ta($,J){let U;try{U=new URL(J)}catch(X){if(X.code==="ERR_INVALID_URL"){let Z=Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw Z.code="INVALID_DOTENV_KEY",Z}throw X}let Q=U.password;if(!Q){let X=Error("INVALID_DOTENV_KEY: Missing key part");throw X.code="INVALID_DOTENV_KEY",X}let _=U.searchParams.get("environment");if(!_){let X=Error("INVALID_DOTENV_KEY: Missing environment part");throw X.code="INVALID_DOTENV_KEY",X}let G=`DOTENV_VAULT_${_.toUpperCase()}`,V=$.parsed[G];if(!V){let X=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${G} in your .env.vault file.`);throw X.code="NOT_FOUND_DOTENV_ENVIRONMENT",X}return{ciphertext:V,key:Q}}function Vf($){let J=null;if($&&$.path&&$.path.length>0)if(Array.isArray($.path)){for(let U of $.path)if(FB.existsSync(U))J=U.endsWith(".vault")?U:`${U}.vault`}else J=$.path.endsWith(".vault")?$.path:`${$.path}.vault`;else J=CG.resolve(process.cwd(),".env.vault");if(FB.existsSync(J))return J;return null}function _f($){return $[0]==="~"?CG.join(ma.homedir(),$.slice(1)):$}function sa($){let J=t9(process.env.DOTENV_CONFIG_DEBUG||$&&$.debug),U=t9(process.env.DOTENV_CONFIG_QUIET||$&&$.quiet);if(J||!U)Qf("Loading env from encrypted .env.vault");let Q=L6._parseVault($),_=process.env;if($&&$.processEnv!=null)_=$.processEnv;return L6.populate(_,Q,$),{parsed:Q}}function ea($){let J=CG.resolve(process.cwd(),".env"),U="utf8",Q=process.env;if($&&$.processEnv!=null)Q=$.processEnv;let _=t9(Q.DOTENV_CONFIG_DEBUG||$&&$.debug),G=t9(Q.DOTENV_CONFIG_QUIET||$&&$.quiet);if($&&$.encoding)U=$.encoding;else if(_)u7("No encoding is specified. UTF-8 is used by default");let V=[J];if($&&$.path)if(!Array.isArray($.path))V=[_f($.path)];else{V=[];for(let K of $.path)V.push(_f(K))}let X,Z={};for(let K of V)try{let F=L6.parse(FB.readFileSync(K,{encoding:U}));L6.populate(Z,F,$)}catch(F){if(_)u7(`Failed to load ${K} ${F.message}`);X=F}let Y=L6.populate(Q,Z,$);if(_=t9(Q.DOTENV_CONFIG_DEBUG||_),G=t9(Q.DOTENV_CONFIG_QUIET||G),_||!G){let K=Object.keys(Y).length,F=[];for(let N of V)try{let q=CG.relative(process.cwd(),N);F.push(q)}catch(q){if(_)u7(`Failed to load ${N} ${q.message}`);X=q}Qf(`injecting env (${K}) from ${F.join(",")} ${ra(`-- tip: ${la()}`)}`)}if(X)return{parsed:Z,error:X};else return{parsed:Z}}function $o($){if(Gf($).length===0)return L6.configDotenv($);let J=Vf($);if(!J)return oa(`You set DOTENV_KEY but you are missing a .env.vault file at ${J}. Did you forget to build it?`),L6.configDotenv($);return L6._configVault($)}function Jo($,J){let U=Buffer.from(J.slice(-64),"hex"),Q=Buffer.from($,"base64"),_=Q.subarray(0,12),G=Q.subarray(-16);Q=Q.subarray(12,-16);try{let V=ca.createDecipheriv("aes-256-gcm",U,_);return V.setAuthTag(G),`${V.update(Q)}${V.final()}`}catch(V){let X=V instanceof RangeError,Z=V.message==="Invalid key length",Y=V.message==="Unsupported state or unable to authenticate data";if(X||Z){let K=Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw K.code="INVALID_DOTENV_KEY",K}else if(Y){let K=Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw K.code="DECRYPTION_FAILED",K}else throw V}}function Uo($,J,U={}){let Q=Boolean(U&&U.debug),_=Boolean(U&&U.override),G={};if(typeof J!=="object"){let V=Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw V.code="OBJECT_REQUIRED",V}for(let V of Object.keys(J))if(Object.prototype.hasOwnProperty.call($,V)){if(_===!0)$[V]=J[V],G[V]=J[V];if(Q)if(_===!0)u7(`"${V}" is already defined and WAS overwritten`);else u7(`"${V}" is already defined and was NOT overwritten`)}else $[V]=J[V],G[V]=J[V];return G}var L6={configDotenv:ea,_configVault:sa,_parseVault:aa,config:$o,decrypt:Jo,parse:pa,populate:Uo};DF$.configDotenv=L6.configDotenv;DF$._configVault=L6._configVault;DF$._parseVault=L6._parseVault;DF$.config=L6.config;DF$.decrypt=L6.decrypt;DF$.parse=L6.parse;DF$.populate=L6.populate;$2.exports=L6});var Zf=J$((EF$,Yf)=>{var K8={};if(process.env.DOTENV_CONFIG_ENCODING!=null)K8.encoding=process.env.DOTENV_CONFIG_ENCODING;if(process.env.DOTENV_CONFIG_PATH!=null)K8.path=process.env.DOTENV_CONFIG_PATH;if(process.env.DOTENV_CONFIG_QUIET!=null)K8.quiet=process.env.DOTENV_CONFIG_QUIET;if(process.env.DOTENV_CONFIG_DEBUG!=null)K8.debug=process.env.DOTENV_CONFIG_DEBUG;if(process.env.DOTENV_CONFIG_OVERRIDE!=null)K8.override=process.env.DOTENV_CONFIG_OVERRIDE;if(process.env.DOTENV_CONFIG_DOTENV_KEY!=null)K8.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY;Yf.exports=K8});var Nf=J$((PF$,Kf)=>{var Ko=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;Kf.exports=function(J){let U=J.reduce(function(Q,_){let G=_.match(Ko);if(G)Q[G[1]]=G[2];return Q},{});if(!("quiet"in U))U.quiet="true";return U}});var Ff=J$(()=>{(function(){Xf().config(Object.assign({},Zf(),Nf()(process.argv)))})()});function Mf($){return String($??"").trim()||void 0}async function OB(){let J=globalThis.process?.env??{},[{homedir:U},Q]=await Promise.all([import("node:os"),import("node:path")]),_=Mf(J.GOATCHAIN_HOME);if(_)return Q.resolve(_,"goatchain");let G=Mf(J.XDG_CONFIG_HOME);if(G)return Q.resolve(G,".goatchain","goatchain");return Q.resolve(U(),".goatchain","goatchain")}async function jB(){let $=await OB(),[{readFile:J},U]=await Promise.all([import("node:fs/promises"),import("node:path")]),Q=U.join($,"cache.json");try{let _=await J(Q,"utf8"),G=JSON.parse(_);if(G&&typeof G==="object"&&G.version===1)return{dir:$,filePath:Q,cache:G}}catch{}return{dir:$,filePath:Q,cache:{version:1,updatedAt:0}}}async function Lf($,J){let[{mkdir:U,writeFile:Q,rename:_,chmod:G},V]=await Promise.all([import("node:fs/promises"),import("node:path")]),X=V.dirname($);await U(X,{recursive:!0});let Z=`${$}.tmp`,Y=`${JSON.stringify(J,null,2)}
|
|
30
|
-
`;await Q(Z,Y,{encoding:"utf8",mode:384}),await _(Z,$);try{await G($,384)}catch{}}async function DB(){let{cache:$}=await jB();return $.settings??{}}var e9=".goatchain",$J="goatchain",yG="state";var fB={};F1(fB,{toPlainJson:()=>Co,saveGoatChainUserCache:()=>wB,normalizeStr:()=>Z6,normalizeNum:()=>F8,loadGoatChainUserCache:()=>AB,getGoatChainUserDir:()=>cG});function Z6($){return String($??"").trim()||void 0}function F8($){if(typeof $==="number"&&Number.isFinite($))return $;let J=String($??"").trim();if(!J)return;let U=Number(J);return Number.isFinite(U)?U:void 0}function Co($){return JSON.parse(JSON.stringify($))}async function cG($){let[{homedir:J},U]=await Promise.all([import("node:os"),import("node:path")]),Q=Z6($.GOATCHAIN_HOME);if(Q)return U.resolve(Q,$J);let _=Z6($.XDG_CONFIG_HOME);if(_)return U.resolve(_,e9,$J);return U.resolve(J(),e9,$J)}async function AB($){let J=await cG($),[{readFile:U},Q]=await Promise.all([import("node:fs/promises"),import("node:path")]),_=Q.join(J,"cache.json");try{let G=await U(_,"utf8"),V=JSON.parse(G);if(V&&typeof V==="object"&&V.version===1)return{dir:J,filePath:_,cache:V}}catch{}return{dir:J,filePath:_,cache:{version:1,updatedAt:0}}}async function wB($,J){let[{mkdir:U,writeFile:Q,rename:_,chmod:G},V]=await Promise.all([import("node:fs/promises"),import("node:path")]),X=V.dirname($);await U(X,{recursive:!0});let Z=globalThis.process?.pid??"p",Y=`${Date.now()}-${Math.random().toString(16).slice(2)}`,K=`${$}.${Z}.${Y}.tmp`,F=`${JSON.stringify(J,null,2)}
|
|
31
|
-
`;await Q(K,F,{encoding:"utf8",mode:384}),await _(K,$);try{await G($,384)}catch{}}var U2=()=>{};var Y_=J$((UD$,gI)=>{var oe=Number.MAX_SAFE_INTEGER||9007199254740991,te=["major","premajor","minor","preminor","patch","prepatch","prerelease"];gI.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:oe,RELEASE_TYPES:te,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Z_=J$((_D$,xI)=>{var se=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...$)=>console.error("SEMVER",...$):()=>{};xI.exports=se});var zU=J$((f1,hI)=>{var{MAX_SAFE_COMPONENT_LENGTH:IO,MAX_SAFE_BUILD_LENGTH:ee,MAX_LENGTH:$$$}=Y_(),J$$=Z_();f1=hI.exports={};var U$$=f1.re=[],_$$=f1.safeRe=[],I$=f1.src=[],Q$$=f1.safeSrc=[],S$=f1.t={},G$$=0,SO="[a-zA-Z0-9-]",V$$=[["\\s",1],["\\d",$$$],[SO,ee]],X$$=($)=>{for(let[J,U]of V$$)$=$.split(`${J}*`).join(`${J}{0,${U}}`).split(`${J}+`).join(`${J}{1,${U}}`);return $},K4=($,J,U)=>{let Q=X$$(J),_=G$$++;J$$($,_,J),S$[$]=_,I$[_]=J,Q$$[_]=Q,U$$[_]=new RegExp(J,U?"g":void 0),_$$[_]=new RegExp(Q,U?"g":void 0)};K4("NUMERICIDENTIFIER","0|[1-9]\\d*");K4("NUMERICIDENTIFIERLOOSE","\\d+");K4("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${SO}*`);K4("MAINVERSION",`(${I$[S$.NUMERICIDENTIFIER]})\\.(${I$[S$.NUMERICIDENTIFIER]})\\.(${I$[S$.NUMERICIDENTIFIER]})`);K4("MAINVERSIONLOOSE",`(${I$[S$.NUMERICIDENTIFIERLOOSE]})\\.(${I$[S$.NUMERICIDENTIFIERLOOSE]})\\.(${I$[S$.NUMERICIDENTIFIERLOOSE]})`);K4("PRERELEASEIDENTIFIER",`(?:${I$[S$.NONNUMERICIDENTIFIER]}|${I$[S$.NUMERICIDENTIFIER]})`);K4("PRERELEASEIDENTIFIERLOOSE",`(?:${I$[S$.NONNUMERICIDENTIFIER]}|${I$[S$.NUMERICIDENTIFIERLOOSE]})`);K4("PRERELEASE",`(?:-(${I$[S$.PRERELEASEIDENTIFIER]}(?:\\.${I$[S$.PRERELEASEIDENTIFIER]})*))`);K4("PRERELEASELOOSE",`(?:-?(${I$[S$.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${I$[S$.PRERELEASEIDENTIFIERLOOSE]})*))`);K4("BUILDIDENTIFIER",`${SO}+`);K4("BUILD",`(?:\\+(${I$[S$.BUILDIDENTIFIER]}(?:\\.${I$[S$.BUILDIDENTIFIER]})*))`);K4("FULLPLAIN",`v?${I$[S$.MAINVERSION]}${I$[S$.PRERELEASE]}?${I$[S$.BUILD]}?`);K4("FULL",`^${I$[S$.FULLPLAIN]}$`);K4("LOOSEPLAIN",`[v=\\s]*${I$[S$.MAINVERSIONLOOSE]}${I$[S$.PRERELEASELOOSE]}?${I$[S$.BUILD]}?`);K4("LOOSE",`^${I$[S$.LOOSEPLAIN]}$`);K4("GTLT","((?:<|>)?=?)");K4("XRANGEIDENTIFIERLOOSE",`${I$[S$.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);K4("XRANGEIDENTIFIER",`${I$[S$.NUMERICIDENTIFIER]}|x|X|\\*`);K4("XRANGEPLAIN",`[v=\\s]*(${I$[S$.XRANGEIDENTIFIER]})(?:\\.(${I$[S$.XRANGEIDENTIFIER]})(?:\\.(${I$[S$.XRANGEIDENTIFIER]})(?:${I$[S$.PRERELEASE]})?${I$[S$.BUILD]}?)?)?`);K4("XRANGEPLAINLOOSE",`[v=\\s]*(${I$[S$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${I$[S$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${I$[S$.XRANGEIDENTIFIERLOOSE]})(?:${I$[S$.PRERELEASELOOSE]})?${I$[S$.BUILD]}?)?)?`);K4("XRANGE",`^${I$[S$.GTLT]}\\s*${I$[S$.XRANGEPLAIN]}$`);K4("XRANGELOOSE",`^${I$[S$.GTLT]}\\s*${I$[S$.XRANGEPLAINLOOSE]}$`);K4("COERCEPLAIN",`(^|[^\\d])(\\d{1,${IO}})(?:\\.(\\d{1,${IO}}))?(?:\\.(\\d{1,${IO}}))?`);K4("COERCE",`${I$[S$.COERCEPLAIN]}(?:$|[^\\d])`);K4("COERCEFULL",I$[S$.COERCEPLAIN]+`(?:${I$[S$.PRERELEASE]})?(?:${I$[S$.BUILD]})?(?:$|[^\\d])`);K4("COERCERTL",I$[S$.COERCE],!0);K4("COERCERTLFULL",I$[S$.COERCEFULL],!0);K4("LONETILDE","(?:~>?)");K4("TILDETRIM",`(\\s*)${I$[S$.LONETILDE]}\\s+`,!0);f1.tildeTrimReplace="$1~";K4("TILDE",`^${I$[S$.LONETILDE]}${I$[S$.XRANGEPLAIN]}$`);K4("TILDELOOSE",`^${I$[S$.LONETILDE]}${I$[S$.XRANGEPLAINLOOSE]}$`);K4("LONECARET","(?:\\^)");K4("CARETTRIM",`(\\s*)${I$[S$.LONECARET]}\\s+`,!0);f1.caretTrimReplace="$1^";K4("CARET",`^${I$[S$.LONECARET]}${I$[S$.XRANGEPLAIN]}$`);K4("CARETLOOSE",`^${I$[S$.LONECARET]}${I$[S$.XRANGEPLAINLOOSE]}$`);K4("COMPARATORLOOSE",`^${I$[S$.GTLT]}\\s*(${I$[S$.LOOSEPLAIN]})$|^$`);K4("COMPARATOR",`^${I$[S$.GTLT]}\\s*(${I$[S$.FULLPLAIN]})$|^$`);K4("COMPARATORTRIM",`(\\s*)${I$[S$.GTLT]}\\s*(${I$[S$.LOOSEPLAIN]}|${I$[S$.XRANGEPLAIN]})`,!0);f1.comparatorTrimReplace="$1$2$3";K4("HYPHENRANGE",`^\\s*(${I$[S$.XRANGEPLAIN]})\\s+-\\s+(${I$[S$.XRANGEPLAIN]})\\s*$`);K4("HYPHENRANGELOOSE",`^\\s*(${I$[S$.XRANGEPLAINLOOSE]})\\s+-\\s+(${I$[S$.XRANGEPLAINLOOSE]})\\s*$`);K4("STAR","(<|>)?=?\\s*\\*");K4("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");K4("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var RV=J$((QD$,uI)=>{var Y$$=Object.freeze({loose:!0}),Z$$=Object.freeze({}),K$$=($)=>{if(!$)return Z$$;if(typeof $!=="object")return Y$$;return $};uI.exports=K$$});var TO=J$((GD$,dI)=>{var mI=/^[0-9]+$/,cI=($,J)=>{if(typeof $==="number"&&typeof J==="number")return $===J?0:$<J?-1:1;let U=mI.test($),Q=mI.test(J);if(U&&Q)$=+$,J=+J;return $===J?0:U&&!Q?-1:Q&&!U?1:$<J?-1:1},N$$=($,J)=>cI(J,$);dI.exports={compareIdentifiers:cI,rcompareIdentifiers:N$$}});var u6=J$((VD$,iI)=>{var AV=Z_(),{MAX_LENGTH:lI,MAX_SAFE_INTEGER:wV}=Y_(),{safeRe:fV,t:kV}=zU(),F$$=RV(),{compareIdentifiers:vO}=TO();class Q1{constructor($,J){if(J=F$$(J),$ instanceof Q1)if($.loose===!!J.loose&&$.includePrerelease===!!J.includePrerelease)return $;else $=$.version;else if(typeof $!=="string")throw TypeError(`Invalid version. Must be a string. Got type "${typeof $}".`);if($.length>lI)throw TypeError(`version is longer than ${lI} characters`);AV("SemVer",$,J),this.options=J,this.loose=!!J.loose,this.includePrerelease=!!J.includePrerelease;let U=$.trim().match(J.loose?fV[kV.LOOSE]:fV[kV.FULL]);if(!U)throw TypeError(`Invalid Version: ${$}`);if(this.raw=$,this.major=+U[1],this.minor=+U[2],this.patch=+U[3],this.major>wV||this.major<0)throw TypeError("Invalid major version");if(this.minor>wV||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>wV||this.patch<0)throw TypeError("Invalid patch version");if(!U[4])this.prerelease=[];else this.prerelease=U[4].split(".").map((Q)=>{if(/^[0-9]+$/.test(Q)){let _=+Q;if(_>=0&&_<wV)return _}return Q});this.build=U[5]?U[5].split("."):[],this.format()}format(){if(this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length)this.version+=`-${this.prerelease.join(".")}`;return this.version}toString(){return this.version}compare($){if(AV("SemVer.compare",this.version,this.options,$),!($ instanceof Q1)){if(typeof $==="string"&&$===this.version)return 0;$=new Q1($,this.options)}if($.version===this.version)return 0;return this.compareMain($)||this.comparePre($)}compareMain($){if(!($ instanceof Q1))$=new Q1($,this.options);if(this.major<$.major)return-1;if(this.major>$.major)return 1;if(this.minor<$.minor)return-1;if(this.minor>$.minor)return 1;if(this.patch<$.patch)return-1;if(this.patch>$.patch)return 1;return 0}comparePre($){if(!($ instanceof Q1))$=new Q1($,this.options);if(this.prerelease.length&&!$.prerelease.length)return-1;else if(!this.prerelease.length&&$.prerelease.length)return 1;else if(!this.prerelease.length&&!$.prerelease.length)return 0;let J=0;do{let U=this.prerelease[J],Q=$.prerelease[J];if(AV("prerelease compare",J,U,Q),U===void 0&&Q===void 0)return 0;else if(Q===void 0)return 1;else if(U===void 0)return-1;else if(U===Q)continue;else return vO(U,Q)}while(++J)}compareBuild($){if(!($ instanceof Q1))$=new Q1($,this.options);let J=0;do{let U=this.build[J],Q=$.build[J];if(AV("build compare",J,U,Q),U===void 0&&Q===void 0)return 0;else if(Q===void 0)return 1;else if(U===void 0)return-1;else if(U===Q)continue;else return vO(U,Q)}while(++J)}inc($,J,U){if($.startsWith("pre")){if(!J&&U===!1)throw Error("invalid increment argument: identifier is empty");if(J){let Q=`-${J}`.match(this.options.loose?fV[kV.PRERELEASELOOSE]:fV[kV.PRERELEASE]);if(!Q||Q[1]!==J)throw Error(`invalid identifier: ${J}`)}}switch($){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",J,U);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",J,U);break;case"prepatch":this.prerelease.length=0,this.inc("patch",J,U),this.inc("pre",J,U);break;case"prerelease":if(this.prerelease.length===0)this.inc("patch",J,U);this.inc("pre",J,U);break;case"release":if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0)this.major++;this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0)this.minor++;this.patch=0,this.prerelease=[];break;case"patch":if(this.prerelease.length===0)this.patch++;this.prerelease=[];break;case"pre":{let Q=Number(U)?1:0;if(this.prerelease.length===0)this.prerelease=[Q];else{let _=this.prerelease.length;while(--_>=0)if(typeof this.prerelease[_]==="number")this.prerelease[_]++,_=-2;if(_===-1){if(J===this.prerelease.join(".")&&U===!1)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(Q)}}if(J){let _=[J,Q];if(U===!1)_=[J];if(vO(this.prerelease[0],J)===0){if(isNaN(this.prerelease[1]))this.prerelease=_}else this.prerelease=_}break}default:throw Error(`invalid increment argument: ${$}`)}if(this.raw=this.format(),this.build.length)this.raw+=`+${this.build.join(".")}`;return this}}iI.exports=Q1});var D8=J$((XD$,nI)=>{var rI=u6(),W$$=($,J,U=!1)=>{if($ instanceof rI)return $;try{return new rI($,J)}catch(Q){if(!U)return null;throw Q}};nI.exports=W$$});var aI=J$((YD$,pI)=>{var q$$=D8(),H$$=($,J)=>{let U=q$$($,J);return U?U.version:null};pI.exports=H$$});var tI=J$((ZD$,oI)=>{var B$$=D8(),O$$=($,J)=>{let U=B$$($.trim().replace(/^[=v]+/,""),J);return U?U.version:null};oI.exports=O$$});var $S=J$((KD$,eI)=>{var sI=u6(),j$$=($,J,U,Q,_)=>{if(typeof U==="string")_=Q,Q=U,U=void 0;try{return new sI($ instanceof sI?$.version:$,U).inc(J,Q,_).version}catch(G){return null}};eI.exports=j$$});var _S=J$((ND$,US)=>{var JS=D8(),D$$=($,J)=>{let U=JS($,null,!0),Q=JS(J,null,!0),_=U.compare(Q);if(_===0)return null;let G=_>0,V=G?U:Q,X=G?Q:U,Z=!!V.prerelease.length;if(!!X.prerelease.length&&!Z){if(!X.patch&&!X.minor)return"major";if(X.compareMain(V)===0){if(X.minor&&!X.patch)return"minor";return"patch"}}let K=Z?"pre":"";if(U.major!==Q.major)return K+"major";if(U.minor!==Q.minor)return K+"minor";if(U.patch!==Q.patch)return K+"patch";return"prerelease"};US.exports=D$$});var GS=J$((FD$,QS)=>{var E$$=u6(),P$$=($,J)=>new E$$($,J).major;QS.exports=P$$});var XS=J$((WD$,VS)=>{var M$$=u6(),L$$=($,J)=>new M$$($,J).minor;VS.exports=L$$});var ZS=J$((qD$,YS)=>{var z$$=u6(),R$$=($,J)=>new z$$($,J).patch;YS.exports=R$$});var NS=J$((HD$,KS)=>{var A$$=D8(),w$$=($,J)=>{let U=A$$($,J);return U&&U.prerelease.length?U.prerelease:null};KS.exports=w$$});var m0=J$((BD$,WS)=>{var FS=u6(),f$$=($,J,U)=>new FS($,U).compare(new FS(J,U));WS.exports=f$$});var HS=J$((OD$,qS)=>{var k$$=m0(),I$$=($,J,U)=>k$$(J,$,U);qS.exports=I$$});var OS=J$((jD$,BS)=>{var S$$=m0(),T$$=($,J)=>S$$($,J,!0);BS.exports=T$$});var IV=J$((DD$,DS)=>{var jS=u6(),v$$=($,J,U)=>{let Q=new jS($,U),_=new jS(J,U);return Q.compare(_)||Q.compareBuild(_)};DS.exports=v$$});var PS=J$((ED$,ES)=>{var C$$=IV(),b$$=($,J)=>$.sort((U,Q)=>C$$(U,Q,J));ES.exports=b$$});var LS=J$((PD$,MS)=>{var y$$=IV(),g$$=($,J)=>$.sort((U,Q)=>y$$(Q,U,J));MS.exports=g$$});var K_=J$((MD$,zS)=>{var x$$=m0(),h$$=($,J,U)=>x$$($,J,U)>0;zS.exports=h$$});var SV=J$((LD$,RS)=>{var u$$=m0(),m$$=($,J,U)=>u$$($,J,U)<0;RS.exports=m$$});var CO=J$((zD$,AS)=>{var c$$=m0(),d$$=($,J,U)=>c$$($,J,U)===0;AS.exports=d$$});var bO=J$((RD$,wS)=>{var l$$=m0(),i$$=($,J,U)=>l$$($,J,U)!==0;wS.exports=i$$});var TV=J$((AD$,fS)=>{var r$$=m0(),n$$=($,J,U)=>r$$($,J,U)>=0;fS.exports=n$$});var vV=J$((wD$,kS)=>{var p$$=m0(),a$$=($,J,U)=>p$$($,J,U)<=0;kS.exports=a$$});var yO=J$((fD$,IS)=>{var o$$=CO(),t$$=bO(),s$$=K_(),e$$=TV(),$4$=SV(),J4$=vV(),U4$=($,J,U,Q)=>{switch(J){case"===":if(typeof $==="object")$=$.version;if(typeof U==="object")U=U.version;return $===U;case"!==":if(typeof $==="object")$=$.version;if(typeof U==="object")U=U.version;return $!==U;case"":case"=":case"==":return o$$($,U,Q);case"!=":return t$$($,U,Q);case">":return s$$($,U,Q);case">=":return e$$($,U,Q);case"<":return $4$($,U,Q);case"<=":return J4$($,U,Q);default:throw TypeError(`Invalid operator: ${J}`)}};IS.exports=U4$});var TS=J$((kD$,SS)=>{var _4$=u6(),Q4$=D8(),{safeRe:CV,t:bV}=zU(),G4$=($,J)=>{if($ instanceof _4$)return $;if(typeof $==="number")$=String($);if(typeof $!=="string")return null;J=J||{};let U=null;if(!J.rtl)U=$.match(J.includePrerelease?CV[bV.COERCEFULL]:CV[bV.COERCE]);else{let Z=J.includePrerelease?CV[bV.COERCERTLFULL]:CV[bV.COERCERTL],Y;while((Y=Z.exec($))&&(!U||U.index+U[0].length!==$.length)){if(!U||Y.index+Y[0].length!==U.index+U[0].length)U=Y;Z.lastIndex=Y.index+Y[1].length+Y[2].length}Z.lastIndex=-1}if(U===null)return null;let Q=U[2],_=U[3]||"0",G=U[4]||"0",V=J.includePrerelease&&U[5]?`-${U[5]}`:"",X=J.includePrerelease&&U[6]?`+${U[6]}`:"";return Q4$(`${Q}.${_}.${G}${V}${X}`,J)};SS.exports=G4$});var bS=J$((ID$,CS)=>{class vS{constructor(){this.max=1000,this.map=new Map}get($){let J=this.map.get($);if(J===void 0)return;else return this.map.delete($),this.map.set($,J),J}delete($){return this.map.delete($)}set($,J){if(!this.delete($)&&J!==void 0){if(this.map.size>=this.max){let Q=this.map.keys().next().value;this.delete(Q)}this.map.set($,J)}return this}}CS.exports=vS});var c0=J$((SD$,hS)=>{var V4$=/\s+/g;class N_{constructor($,J){if(J=Y4$(J),$ instanceof N_)if($.loose===!!J.loose&&$.includePrerelease===!!J.includePrerelease)return $;else return new N_($.raw,J);if($ instanceof gO)return this.raw=$.value,this.set=[[$]],this.formatted=void 0,this;if(this.options=J,this.loose=!!J.loose,this.includePrerelease=!!J.includePrerelease,this.raw=$.trim().replace(V4$," "),this.set=this.raw.split("||").map((U)=>this.parseRange(U.trim())).filter((U)=>U.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let U=this.set[0];if(this.set=this.set.filter((Q)=>!gS(Q[0])),this.set.length===0)this.set=[U];else if(this.set.length>1){for(let Q of this.set)if(Q.length===1&&H4$(Q[0])){this.set=[Q];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let $=0;$<this.set.length;$++){if($>0)this.formatted+="||";let J=this.set[$];for(let U=0;U<J.length;U++){if(U>0)this.formatted+=" ";this.formatted+=J[U].toString().trim()}}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange($){let U=((this.options.includePrerelease&&W4$)|(this.options.loose&&q4$))+":"+$,Q=yS.get(U);if(Q)return Q;let _=this.options.loose,G=_?s6[m6.HYPHENRANGELOOSE]:s6[m6.HYPHENRANGE];$=$.replace(G,R4$(this.options.includePrerelease)),i4("hyphen replace",$),$=$.replace(s6[m6.COMPARATORTRIM],K4$),i4("comparator trim",$),$=$.replace(s6[m6.TILDETRIM],N4$),i4("tilde trim",$),$=$.replace(s6[m6.CARETTRIM],F4$),i4("caret trim",$);let V=$.split(" ").map((K)=>B4$(K,this.options)).join(" ").split(/\s+/).map((K)=>z4$(K,this.options));if(_)V=V.filter((K)=>{return i4("loose invalid filter",K,this.options),!!K.match(s6[m6.COMPARATORLOOSE])});i4("range list",V);let X=new Map,Z=V.map((K)=>new gO(K,this.options));for(let K of Z){if(gS(K))return[K];X.set(K.value,K)}if(X.size>1&&X.has(""))X.delete("");let Y=[...X.values()];return yS.set(U,Y),Y}intersects($,J){if(!($ instanceof N_))throw TypeError("a Range is required");return this.set.some((U)=>{return xS(U,J)&&$.set.some((Q)=>{return xS(Q,J)&&U.every((_)=>{return Q.every((G)=>{return _.intersects(G,J)})})})})}test($){if(!$)return!1;if(typeof $==="string")try{$=new Z4$($,this.options)}catch(J){return!1}for(let J=0;J<this.set.length;J++)if(A4$(this.set[J],$,this.options))return!0;return!1}}hS.exports=N_;var X4$=bS(),yS=new X4$,Y4$=RV(),gO=F_(),i4=Z_(),Z4$=u6(),{safeRe:s6,t:m6,comparatorTrimReplace:K4$,tildeTrimReplace:N4$,caretTrimReplace:F4$}=zU(),{FLAG_INCLUDE_PRERELEASE:W4$,FLAG_LOOSE:q4$}=Y_(),gS=($)=>$.value==="<0.0.0-0",H4$=($)=>$.value==="",xS=($,J)=>{let U=!0,Q=$.slice(),_=Q.pop();while(U&&Q.length)U=Q.every((G)=>{return _.intersects(G,J)}),_=Q.pop();return U},B4$=($,J)=>{return $=$.replace(s6[m6.BUILD],""),i4("comp",$,J),$=D4$($,J),i4("caret",$),$=O4$($,J),i4("tildes",$),$=P4$($,J),i4("xrange",$),$=L4$($,J),i4("stars",$),$},e6=($)=>!$||$.toLowerCase()==="x"||$==="*",O4$=($,J)=>{return $.trim().split(/\s+/).map((U)=>j4$(U,J)).join(" ")},j4$=($,J)=>{let U=J.loose?s6[m6.TILDELOOSE]:s6[m6.TILDE];return $.replace(U,(Q,_,G,V,X)=>{i4("tilde",$,Q,_,G,V,X);let Z;if(e6(_))Z="";else if(e6(G))Z=`>=${_}.0.0 <${+_+1}.0.0-0`;else if(e6(V))Z=`>=${_}.${G}.0 <${_}.${+G+1}.0-0`;else if(X)i4("replaceTilde pr",X),Z=`>=${_}.${G}.${V}-${X} <${_}.${+G+1}.0-0`;else Z=`>=${_}.${G}.${V} <${_}.${+G+1}.0-0`;return i4("tilde return",Z),Z})},D4$=($,J)=>{return $.trim().split(/\s+/).map((U)=>E4$(U,J)).join(" ")},E4$=($,J)=>{i4("caret",$,J);let U=J.loose?s6[m6.CARETLOOSE]:s6[m6.CARET],Q=J.includePrerelease?"-0":"";return $.replace(U,(_,G,V,X,Z)=>{i4("caret",$,_,G,V,X,Z);let Y;if(e6(G))Y="";else if(e6(V))Y=`>=${G}.0.0${Q} <${+G+1}.0.0-0`;else if(e6(X))if(G==="0")Y=`>=${G}.${V}.0${Q} <${G}.${+V+1}.0-0`;else Y=`>=${G}.${V}.0${Q} <${+G+1}.0.0-0`;else if(Z)if(i4("replaceCaret pr",Z),G==="0")if(V==="0")Y=`>=${G}.${V}.${X}-${Z} <${G}.${V}.${+X+1}-0`;else Y=`>=${G}.${V}.${X}-${Z} <${G}.${+V+1}.0-0`;else Y=`>=${G}.${V}.${X}-${Z} <${+G+1}.0.0-0`;else if(i4("no pr"),G==="0")if(V==="0")Y=`>=${G}.${V}.${X}${Q} <${G}.${V}.${+X+1}-0`;else Y=`>=${G}.${V}.${X}${Q} <${G}.${+V+1}.0-0`;else Y=`>=${G}.${V}.${X} <${+G+1}.0.0-0`;return i4("caret return",Y),Y})},P4$=($,J)=>{return i4("replaceXRanges",$,J),$.split(/\s+/).map((U)=>M4$(U,J)).join(" ")},M4$=($,J)=>{$=$.trim();let U=J.loose?s6[m6.XRANGELOOSE]:s6[m6.XRANGE];return $.replace(U,(Q,_,G,V,X,Z)=>{i4("xRange",$,Q,_,G,V,X,Z);let Y=e6(G),K=Y||e6(V),F=K||e6(X),N=F;if(_==="="&&N)_="";if(Z=J.includePrerelease?"-0":"",Y)if(_===">"||_==="<")Q="<0.0.0-0";else Q="*";else if(_&&N){if(K)V=0;if(X=0,_===">")if(_=">=",K)G=+G+1,V=0,X=0;else V=+V+1,X=0;else if(_==="<=")if(_="<",K)G=+G+1;else V=+V+1;if(_==="<")Z="-0";Q=`${_+G}.${V}.${X}${Z}`}else if(K)Q=`>=${G}.0.0${Z} <${+G+1}.0.0-0`;else if(F)Q=`>=${G}.${V}.0${Z} <${G}.${+V+1}.0-0`;return i4("xRange return",Q),Q})},L4$=($,J)=>{return i4("replaceStars",$,J),$.trim().replace(s6[m6.STAR],"")},z4$=($,J)=>{return i4("replaceGTE0",$,J),$.trim().replace(s6[J.includePrerelease?m6.GTE0PRE:m6.GTE0],"")},R4$=($)=>(J,U,Q,_,G,V,X,Z,Y,K,F,N)=>{if(e6(Q))U="";else if(e6(_))U=`>=${Q}.0.0${$?"-0":""}`;else if(e6(G))U=`>=${Q}.${_}.0${$?"-0":""}`;else if(V)U=`>=${U}`;else U=`>=${U}${$?"-0":""}`;if(e6(Y))Z="";else if(e6(K))Z=`<${+Y+1}.0.0-0`;else if(e6(F))Z=`<${Y}.${+K+1}.0-0`;else if(N)Z=`<=${Y}.${K}.${F}-${N}`;else if($)Z=`<${Y}.${K}.${+F+1}-0`;else Z=`<=${Z}`;return`${U} ${Z}`.trim()},A4$=($,J,U)=>{for(let Q=0;Q<$.length;Q++)if(!$[Q].test(J))return!1;if(J.prerelease.length&&!U.includePrerelease){for(let Q=0;Q<$.length;Q++){if(i4($[Q].semver),$[Q].semver===gO.ANY)continue;if($[Q].semver.prerelease.length>0){let _=$[Q].semver;if(_.major===J.major&&_.minor===J.minor&&_.patch===J.patch)return!0}}return!1}return!0}});var F_=J$((TD$,iS)=>{var W_=Symbol("SemVer ANY");class yV{static get ANY(){return W_}constructor($,J){if(J=uS(J),$ instanceof yV)if($.loose===!!J.loose)return $;else $=$.value;if($=$.trim().split(/\s+/).join(" "),hO("comparator",$,J),this.options=J,this.loose=!!J.loose,this.parse($),this.semver===W_)this.value="";else this.value=this.operator+this.semver.version;hO("comp",this)}parse($){let J=this.options.loose?mS[cS.COMPARATORLOOSE]:mS[cS.COMPARATOR],U=$.match(J);if(!U)throw TypeError(`Invalid comparator: ${$}`);if(this.operator=U[1]!==void 0?U[1]:"",this.operator==="=")this.operator="";if(!U[2])this.semver=W_;else this.semver=new dS(U[2],this.options.loose)}toString(){return this.value}test($){if(hO("Comparator.test",$,this.options.loose),this.semver===W_||$===W_)return!0;if(typeof $==="string")try{$=new dS($,this.options)}catch(J){return!1}return xO($,this.operator,this.semver,this.options)}intersects($,J){if(!($ instanceof yV))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new lS($.value,J).test(this.value)}else if($.operator===""){if($.value==="")return!0;return new lS(this.value,J).test($.semver)}if(J=uS(J),J.includePrerelease&&(this.value==="<0.0.0-0"||$.value==="<0.0.0-0"))return!1;if(!J.includePrerelease&&(this.value.startsWith("<0.0.0")||$.value.startsWith("<0.0.0")))return!1;if(this.operator.startsWith(">")&&$.operator.startsWith(">"))return!0;if(this.operator.startsWith("<")&&$.operator.startsWith("<"))return!0;if(this.semver.version===$.semver.version&&this.operator.includes("=")&&$.operator.includes("="))return!0;if(xO(this.semver,"<",$.semver,J)&&this.operator.startsWith(">")&&$.operator.startsWith("<"))return!0;if(xO(this.semver,">",$.semver,J)&&this.operator.startsWith("<")&&$.operator.startsWith(">"))return!0;return!1}}iS.exports=yV;var uS=RV(),{safeRe:mS,t:cS}=zU(),xO=yO(),hO=Z_(),dS=u6(),lS=c0()});var q_=J$((vD$,rS)=>{var w4$=c0(),f4$=($,J,U)=>{try{J=new w4$(J,U)}catch(Q){return!1}return J.test($)};rS.exports=f4$});var pS=J$((CD$,nS)=>{var k4$=c0(),I4$=($,J)=>new k4$($,J).set.map((U)=>U.map((Q)=>Q.value).join(" ").trim().split(" "));nS.exports=I4$});var oS=J$((bD$,aS)=>{var S4$=u6(),T4$=c0(),v4$=($,J,U)=>{let Q=null,_=null,G=null;try{G=new T4$(J,U)}catch(V){return null}return $.forEach((V)=>{if(G.test(V)){if(!Q||_.compare(V)===-1)Q=V,_=new S4$(Q,U)}}),Q};aS.exports=v4$});var sS=J$((yD$,tS)=>{var C4$=u6(),b4$=c0(),y4$=($,J,U)=>{let Q=null,_=null,G=null;try{G=new b4$(J,U)}catch(V){return null}return $.forEach((V)=>{if(G.test(V)){if(!Q||_.compare(V)===1)Q=V,_=new C4$(Q,U)}}),Q};tS.exports=y4$});var JT=J$((gD$,$T)=>{var uO=u6(),g4$=c0(),eS=K_(),x4$=($,J)=>{$=new g4$($,J);let U=new uO("0.0.0");if($.test(U))return U;if(U=new uO("0.0.0-0"),$.test(U))return U;U=null;for(let Q=0;Q<$.set.length;++Q){let _=$.set[Q],G=null;if(_.forEach((V)=>{let X=new uO(V.semver.version);switch(V.operator){case">":if(X.prerelease.length===0)X.patch++;else X.prerelease.push(0);X.raw=X.format();case"":case">=":if(!G||eS(X,G))G=X;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${V.operator}`)}}),G&&(!U||eS(U,G)))U=G}if(U&&$.test(U))return U;return null};$T.exports=x4$});var _T=J$((xD$,UT)=>{var h4$=c0(),u4$=($,J)=>{try{return new h4$($,J).range||"*"}catch(U){return null}};UT.exports=u4$});var gV=J$((hD$,XT)=>{var m4$=u6(),VT=F_(),{ANY:c4$}=VT,d4$=c0(),l4$=q_(),QT=K_(),GT=SV(),i4$=vV(),r4$=TV(),n4$=($,J,U,Q)=>{$=new m4$($,Q),J=new d4$(J,Q);let _,G,V,X,Z;switch(U){case">":_=QT,G=i4$,V=GT,X=">",Z=">=";break;case"<":_=GT,G=r4$,V=QT,X="<",Z="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(l4$($,J,Q))return!1;for(let Y=0;Y<J.set.length;++Y){let K=J.set[Y],F=null,N=null;if(K.forEach((q)=>{if(q.semver===c4$)q=new VT(">=0.0.0");if(F=F||q,N=N||q,_(q.semver,F.semver,Q))F=q;else if(V(q.semver,N.semver,Q))N=q}),F.operator===X||F.operator===Z)return!1;if((!N.operator||N.operator===X)&&G($,N.semver))return!1;else if(N.operator===Z&&V($,N.semver))return!1}return!0};XT.exports=n4$});var ZT=J$((uD$,YT)=>{var p4$=gV(),a4$=($,J,U)=>p4$($,J,">",U);YT.exports=a4$});var NT=J$((mD$,KT)=>{var o4$=gV(),t4$=($,J,U)=>o4$($,J,"<",U);KT.exports=t4$});var qT=J$((cD$,WT)=>{var FT=c0(),s4$=($,J,U)=>{return $=new FT($,U),J=new FT(J,U),$.intersects(J,U)};WT.exports=s4$});var BT=J$((dD$,HT)=>{var e4$=q_(),$6$=m0();HT.exports=($,J,U)=>{let Q=[],_=null,G=null,V=$.sort((K,F)=>$6$(K,F,U));for(let K of V)if(e4$(K,J,U)){if(G=K,!_)_=K}else{if(G)Q.push([_,G]);G=null,_=null}if(_)Q.push([_,null]);let X=[];for(let[K,F]of Q)if(K===F)X.push(K);else if(!F&&K===V[0])X.push("*");else if(!F)X.push(`>=${K}`);else if(K===V[0])X.push(`<=${F}`);else X.push(`${K} - ${F}`);let Z=X.join(" || "),Y=typeof J.raw==="string"?J.raw:String(J);return Z.length<Y.length?Z:J}});var MT=J$((lD$,PT)=>{var OT=c0(),cO=F_(),{ANY:mO}=cO,H_=q_(),dO=m0(),J6$=($,J,U={})=>{if($===J)return!0;$=new OT($,U),J=new OT(J,U);let Q=!1;$:for(let _ of $.set){for(let G of J.set){let V=_6$(_,G,U);if(Q=Q||V!==null,V)continue $}if(Q)return!1}return!0},U6$=[new cO(">=0.0.0-0")],jT=[new cO(">=0.0.0")],_6$=($,J,U)=>{if($===J)return!0;if($.length===1&&$[0].semver===mO)if(J.length===1&&J[0].semver===mO)return!0;else if(U.includePrerelease)$=U6$;else $=jT;if(J.length===1&&J[0].semver===mO)if(U.includePrerelease)return!0;else J=jT;let Q=new Set,_,G;for(let q of $)if(q.operator===">"||q.operator===">=")_=DT(_,q,U);else if(q.operator==="<"||q.operator==="<=")G=ET(G,q,U);else Q.add(q.semver);if(Q.size>1)return null;let V;if(_&&G){if(V=dO(_.semver,G.semver,U),V>0)return null;else if(V===0&&(_.operator!==">="||G.operator!=="<="))return null}for(let q of Q){if(_&&!H_(q,String(_),U))return null;if(G&&!H_(q,String(G),U))return null;for(let H of J)if(!H_(q,String(H),U))return!1;return!0}let X,Z,Y,K,F=G&&!U.includePrerelease&&G.semver.prerelease.length?G.semver:!1,N=_&&!U.includePrerelease&&_.semver.prerelease.length?_.semver:!1;if(F&&F.prerelease.length===1&&G.operator==="<"&&F.prerelease[0]===0)F=!1;for(let q of J){if(K=K||q.operator===">"||q.operator===">=",Y=Y||q.operator==="<"||q.operator==="<=",_){if(N){if(q.semver.prerelease&&q.semver.prerelease.length&&q.semver.major===N.major&&q.semver.minor===N.minor&&q.semver.patch===N.patch)N=!1}if(q.operator===">"||q.operator===">="){if(X=DT(_,q,U),X===q&&X!==_)return!1}else if(_.operator===">="&&!H_(_.semver,String(q),U))return!1}if(G){if(F){if(q.semver.prerelease&&q.semver.prerelease.length&&q.semver.major===F.major&&q.semver.minor===F.minor&&q.semver.patch===F.patch)F=!1}if(q.operator==="<"||q.operator==="<="){if(Z=ET(G,q,U),Z===q&&Z!==G)return!1}else if(G.operator==="<="&&!H_(G.semver,String(q),U))return!1}if(!q.operator&&(G||_)&&V!==0)return!1}if(_&&Y&&!G&&V!==0)return!1;if(G&&K&&!_&&V!==0)return!1;if(N||F)return!1;return!0},DT=($,J,U)=>{if(!$)return J;let Q=dO($.semver,J.semver,U);return Q>0?$:Q<0?J:J.operator===">"&&$.operator===">="?J:$},ET=($,J,U)=>{if(!$)return J;let Q=dO($.semver,J.semver,U);return Q<0?$:Q>0?J:J.operator==="<"&&$.operator==="<="?J:$};PT.exports=J6$});var AT=J$((iD$,RT)=>{var lO=zU(),LT=Y_(),Q6$=u6(),zT=TO(),G6$=D8(),V6$=aI(),X6$=tI(),Y6$=$S(),Z6$=_S(),K6$=GS(),N6$=XS(),F6$=ZS(),W6$=NS(),q6$=m0(),H6$=HS(),B6$=OS(),O6$=IV(),j6$=PS(),D6$=LS(),E6$=K_(),P6$=SV(),M6$=CO(),L6$=bO(),z6$=TV(),R6$=vV(),A6$=yO(),w6$=TS(),f6$=F_(),k6$=c0(),I6$=q_(),S6$=pS(),T6$=oS(),v6$=sS(),C6$=JT(),b6$=_T(),y6$=gV(),g6$=ZT(),x6$=NT(),h6$=qT(),u6$=BT(),m6$=MT();RT.exports={parse:G6$,valid:V6$,clean:X6$,inc:Y6$,diff:Z6$,major:K6$,minor:N6$,patch:F6$,prerelease:W6$,compare:q6$,rcompare:H6$,compareLoose:B6$,compareBuild:O6$,sort:j6$,rsort:D6$,gt:E6$,lt:P6$,eq:M6$,neq:L6$,gte:z6$,lte:R6$,cmp:A6$,coerce:w6$,Comparator:f6$,Range:k6$,satisfies:I6$,toComparators:S6$,maxSatisfying:T6$,minSatisfying:v6$,minVersion:C6$,validRange:b6$,outside:y6$,gtr:g6$,ltr:x6$,intersects:h6$,simplifyRange:u6$,subset:m6$,SemVer:Q6$,re:lO.re,src:lO.src,tokens:lO.t,SEMVER_SPEC_VERSION:LT.SEMVER_SPEC_VERSION,RELEASE_TYPES:LT.RELEASE_TYPES,compareIdentifiers:zT.compareIdentifiers,rcompareIdentifiers:zT.rcompareIdentifiers}});import{appendFileSync as f2$,writeFileSync as k2$}from"node:fs";function bX($){return $.includes("-h")||$.includes("--help")}function yX(){return"Usage: vue-terminal run [--app goatchain|basic] [--route name] [--approvals auto|all] [--auto-approve|-y] [--cols N --rows N] [--record file] [--replay file] [--snapshot file] [--no-mouse] [--no-alt-screen] [--debug] (default: --app goatchain --route home)"}function Cj($,J){let U=J?.stdout,Q=Number.isFinite(U?.columns)?Number(U?.columns):80,_=Number.isFinite(U?.rows)?Number(U?.rows):24,G=Q,V=_,X=!1,Z=!1,Y="goatchain",K="home",F=null,N=null,q=null,H=!0,E=!0,D=null,B=!1;for(let j=0;j<$.length;j++){let f=$[j];if(f==="--cols")G=Number.parseInt($[++j]??"",10),X=!0;else if(f==="--rows")V=Number.parseInt($[++j]??"",10),Z=!0;else if(f==="--app"||f==="--example")Y=String($[++j]??Y);else if(f==="--route"||f==="--initial-route")K=String($[++j]??K);else if(f==="--approvals"||f==="--approval"){let R=String($[++j]??"").trim().toLowerCase();if(R==="auto")D="auto";else if(R==="all"||R==="on"||R==="yes"||R==="true"||R==="1")D="all"}else if(f==="--auto-approve"||f==="--yes"||f==="-y")D="all";else if(f==="--record")F=$[++j]??null;else if(f==="--replay")N=$[++j]??null;else if(f==="--snapshot")q=$[++j]??null;else if(f==="--no-mouse")H=!1;else if(f==="--no-alt-screen")E=!1;else if(f==="--debug")B=!0}return G=Math.max(10,Math.floor(G||Q)),V=Math.max(5,Math.floor(V||_)),{cols:G,rows:V,sizeLocked:X||Z,app:Y,initialRoute:K,recordPath:F,replayPath:N,snapshotPath:q,enableMouse:H,altScreen:E,approvals:D,debug:B}}import*as Vk from"node:path";function bj($){let U=["# GoatChain error","","```text",$ instanceof Error?$.stack||$.message:String($),"```"].join(`
|
|
32
|
-
`);return{async*receiveMessage(Q){yield{role:"assistant",content:U,metadata:{done:!0,error:!0,stopReason:"error",originalEventType:"done"}}}}}import{randomUUID as fo}from"node:crypto";import{encoding_for_model as Yb,get_encoding as Zb}from"tiktoken";var Kb="gpt-4o";function x1($,J){if(!$)return 0;let U=null;try{return U=Yb(J??Kb),U.encode($).length}catch(Q){console.error("Error encoding text:",Q);try{return U=Zb("cl100k_base"),U.encode($).length}catch{return Math.ceil($.length/4)}}finally{U?.free()}}function yj($,J){if(typeof $==="string")return x1($,J);if(Array.isArray($))return $.reduce((U,Q)=>{if(typeof Q==="object"&&Q!==null&&"text"in Q)return U+x1(String(Q.text),J);return U},0);return 0}function gj($,J){try{let U=JSON.stringify($);return x1(U,J)}catch{return Nb($,J)}}function Nb($,J){let Q=4;if(Q+=yj($.content,J),$.role==="assistant"&&$.tool_calls)for(let _ of $.tool_calls){Q+=x1(_.function.name,J);let G=typeof _.function.arguments==="string"?_.function.arguments:JSON.stringify(_.function.arguments);Q+=x1(G,J),Q+=10}if($.role==="tool"&&$.name)Q+=x1($.name,J);if($.role==="assistant"&&$.reasoning_content)Q+=x1($.reasoning_content,J);return Q}function y8($,J){if(!$||$.length===0)return 0;try{let U=JSON.stringify($);return x1(U,J)}catch{return $.reduce((Q,_)=>Q+gj(_,J),3)}}var I6={CHECKPOINT:"checkpoint",COMPRESSION:"compression",SESSION:"session",COMPRESSION_SNAPSHOT:"compression-snapshot"};function h1($,J,U="[Previous conversation context]"){let Q=[...$],_=Q.findIndex((N)=>N.role==="system");if(_===-1)return Q;let G=Q[_],V=G.content;if(!J||J.trim().length===0)return Q;let Z={type:"text",text:`${U}
|
|
33
|
-
|
|
34
|
-
${J}`},K=[...Fb(V,U),Z],F={...G,content:K};return Q[_]=F,Q}function Fb($,J){let U=(Q)=>{let _=Q.indexOf(J);if(_>=0)return Q.slice(0,_).trimEnd();return Q};if(typeof $==="string"){let Q=U($);return Q.trim().length>0?[{type:"text",text:Q}]:[]}if(Array.isArray($)){let Q=[];for(let _ of $){if(typeof _==="string"){let G=U(_);if(G.trim().length>0)Q.push({type:"text",text:G});continue}if(_&&typeof _==="object"&&"type"in _){let G=_;if(G.type==="text"){let V=typeof G.text==="string"?G.text:"",X=U(V);if(X.trim().length>0)Q.push({...G,text:X});continue}Q.push(G)}}return Q}if($&&typeof $==="object"&&"type"in $){let Q=$;if(Q.type==="text"){let _=typeof Q.text==="string"?Q.text:"",G=U(_);return G.trim().length>0?[{...Q,text:G}]:[]}return[Q]}return[]}function gX($,J){let U=[...$],Q=-1;for(let Y=U.length-1;Y>=0;Y--)if(U[Y].role==="user"){Q=Y;break}if(Q===-1){let Y={role:"user",content:J};return[...U,Y]}let _=U[Q],G=_.content,V,X={type:"text",text:J};if(typeof G==="string")V=[{type:"text",text:G},X];else if(Array.isArray(G))V=[...G,X];else V=[G,X];let Z={..._,content:V};return U[Q]=Z,U}var xj="[Old tool result content cleared]",Wb=`
|
|
35
|
-
Summarize the conversation context for future continuation.
|
|
36
|
-
|
|
37
|
-
Rules:
|
|
38
|
-
- Be concise and factual
|
|
39
|
-
- Use bullet points (6-12 bullets)
|
|
40
|
-
- Include: user goals, key decisions, files/paths touched, unresolved issues, next steps
|
|
41
|
-
- Keep under 1200 characters
|
|
42
|
-
- If existing summary provided, merge old + new into one consolidated summary
|
|
43
|
-
- Remove redundancy and repeated facts
|
|
44
|
-
|
|
45
|
-
Existing summary (if any):
|
|
46
|
-
{{existingSummary}}
|
|
47
|
-
|
|
48
|
-
Content to summarize:
|
|
49
|
-
{{content}}
|
|
50
|
-
`;function zJ($){let{maxTokens:J,protectedTurns:U=0,model:Q,stateStore:_,toolCompressionTarget:G=0.45,minKeepToolResults:V=5}=$,X=Math.floor(J*0.5),Z=Math.floor(J*0.8),Y=async(K,F)=>{let N=await _.load(K.sessionId,I6.COMPRESSION),q=K.messages;if(N?.summary)q=h1(q,N.summary);let H=y8(q),E=0,D=0,B=N?.summary,j=!1;if(H>Z){let S=Db(q),O=Eb(q,U),M=await Hb(q,Q,N?.summary,S,O);if(M.summaryApplied)q=M.compressedMessages,B=M.newSummary,D=M.removedCount,j=!0,q=h1(q,B)}if((j?y8(q):H)>X){let S=Math.floor(J*G),O=qb(q,S,V);q=O.compressedMessages,E=O.clearedCount}let R=j||E>0,I=R?y8(q):H,w=R?Date.now():0;if(j){let S={tokensBefore:H,tokensAfter:I,clearedToolOutputs:E,removedMessages:D,summaryGenerated:!0,timestamp:w},O={lastStats:S,history:[...N?.history??[],S],summary:B,updatedAt:w};await _.save(K.sessionId,I6.COMPRESSION,O)}let z={...K,messages:q,metadata:R?{...K.metadata,lastCompression:{tokensBefore:H,tokensAfter:I,clearedToolOutputs:E,removedMessages:D,summaryGenerated:j,timestamp:w}}:K.metadata};return F(z)};return Y.__middlewareName="context-compression",Y}function qb($,J,U){let Q=[];if($.forEach((Z,Y)=>{if(Z.role==="tool")Q.push(Y)}),Q.length===0)return{compressedMessages:$,clearedCount:0};let _=Math.min(U,Q.length),G=Q.slice(0,Q.length-_),V=$,X=0;for(let Z of G){let Y=V[Z];if(typeof Y.content==="string"&&Y.content===xj)continue;if(V=V.map((F,N)=>{if(N===Z)return{...Y,content:xj};return F}),X++,y8(V)<=J)break}return{compressedMessages:V,clearedCount:X}}async function Hb($,J,U,Q,_){let G=$.slice(Q,_);if(G.length===0)return{compressedMessages:$,newSummary:U??"",removedCount:0,summaryApplied:!1};let V=Bb(G),X=await Ob(V,J,U);if(!X)return{compressedMessages:$,newSummary:U??"",removedCount:0,summaryApplied:!1};return{compressedMessages:[...$.slice(0,Q),...$.slice(_)],newSummary:X,removedCount:G.length,summaryApplied:!0}}function Bb($){let J=[];for(let U of $)if(U.role==="user"){let Q=typeof U.content==="string"?U.content:JSON.stringify(U.content);J.push(`## User
|
|
51
|
-
${Q}`)}else if(U.role==="assistant"){let Q=typeof U.content==="string"?U.content:JSON.stringify(U.content);J.push(`## Assistant
|
|
52
|
-
${Q}`)}else if(U.role==="tool"){let Q=U,_=typeof Q.content==="string"?Q.content:JSON.stringify(Q.content),G=_.length>5000?`${_.slice(0,5000)}...[truncated]`:_;J.push(`## Tool: ${Q.name||"unknown"}
|
|
53
|
-
${G}`)}return J.join(`
|
|
54
|
-
|
|
55
|
-
---
|
|
56
|
-
|
|
57
|
-
`)}async function Ob($,J,U,Q){let _=jb(Q??Wb,U,$),G=[{role:"system",content:"You are a helpful assistant that creates concise rolling summaries."},{role:"user",content:_}],V="";for await(let X of J.stream({messages:G,maxOutputTokens:500}))if(X.type==="delta"&&X.chunk.kind==="text")V+=X.chunk.text;else if(X.type==="response_end")break;return V.trim()}function jb($,J,U){let Q=$.includes("{{existingSummary}}"),_=$.includes("{{content}}"),G=$;if(Q)G=G.replace("{{existingSummary}}",J??"(none)");if(_)G=G.replace("{{content}}",U);if(Q&&_)return G;let V=[];if(!Q)V.push(`Existing summary (if any):
|
|
58
|
-
${J??"(none)"}`);if(!_)V.push(`Content to summarize:
|
|
59
|
-
${U}`);return`${G.trim()}
|
|
60
|
-
|
|
61
|
-
${V.join(`
|
|
62
|
-
|
|
63
|
-
`)}
|
|
64
|
-
`}function Db($){let J=-1;for(let Q=0;Q<$.length;Q++)if($[Q].role==="user"){J=Q;break}if(J===-1)return 0;let U=-1;for(let Q=J+1;Q<$.length;Q++)if($[Q].role==="assistant"){U=Q;break}if(U===-1)return J+1;for(let Q=U+1;Q<$.length;Q++)if($[Q].role==="user")return Q;return $.length}function Eb($,J){if(J<=0)return $.length;let U=0,Q=[];for(let G=$.length-1;G>=0;G--)if($[G].role==="user"){if(U++,Q.unshift(G),U>=J)return G}let _=6;return Math.max(0,$.length-_)}var Pb=["planMode","planModeMiddleware","parallelMode","parallelSubagentMiddleware","blockedTools","commitProcessed","_pendingUserInput"];function xX($){let J={};for(let[U,Q]of Object.entries($))if(!Pb.includes(U))J[U]=Q;return J}var Mb=1;function C_($,J){let U=J?.phase;if(!U)if(!$.shouldContinue)U="completed";else if($.pendingToolCalls.length>0)U="tool_execution";else U="llm_call";let Q=J?.status;if(!Q)if(U==="completed")Q=`Completed: ${$.stopReason??"unknown"}`;else if(U==="tool_execution")Q=`Executing tools: ${$.pendingToolCalls.map((V)=>V.toolCall.function.name).join(", ")}`;else if(U==="approval_pending")Q="Waiting for user approval";else Q=`Iteration ${$.iteration}: Calling LLM`;let _=J?.messages??$.messages;return{schemaVersion:Mb,sessionId:$.sessionId,agentName:J?.agentName,iteration:$.iteration,phase:U,status:Q,modelConfig:J?.modelConfig,requestParams:J?.requestParams,messages:[..._],pendingToolCalls:$.pendingToolCalls.map((G)=>({toolCall:{...G.toolCall},result:G.result,isError:G.isError})),currentResponse:$.currentResponse,currentThinking:$.currentThinking,shouldContinue:$.shouldContinue,stopReason:$.stopReason,lastModelStopReason:$.lastModelStopReason,usage:{...$.usage},metadata:xX($.metadata),savedAt:Date.now()}}function uU($){let J=$.schemaVersion??1;if(J!==1)throw Error(`Unsupported checkpoint schemaVersion: ${J}. Please migrate checkpoints or upgrade GoatChain.`);return{sessionId:$.sessionId,iteration:$.iteration,messages:[...$.messages],pendingToolCalls:$.pendingToolCalls.map((U)=>({toolCall:{...U.toolCall},result:U.result,isError:U.isError})),currentResponse:$.currentResponse,currentThinking:$.currentThinking,shouldContinue:$.shouldContinue,stopReason:$.stopReason,lastModelStopReason:$.lastModelStopReason,usage:{...$.usage},metadata:{...$.metadata}}}class hX{stateStore;constructor($){this.stateStore=$}hasStore(){return Boolean(this.stateStore)}async saveCheckpoint($){if(!this.stateStore)return;await this.stateStore.saveCheckpoint($)}async loadCheckpoint($){return this.stateStore?.loadCheckpoint($)}async clearCheckpoint($){if(!this.stateStore)return;await this.stateStore.deleteCheckpoint($)}}import{EventEmitter as py}from"node:events";class W2 extends Error{constructor($="Agent execution aborted"){super($);this.name="AgentAbortError"}}class RJ extends Error{constructor($="Agent execution paused"){super($);this.name="AgentPauseError"}}function u1($,J){if(!$?.aborted)return;let U=$?.reason;if(U instanceof Error)throw U;throw new W2(typeof U==="string"?U:J?`${J} aborted`:"Agent execution aborted")}function b_($){return(J,U)=>{let Q=-1,_=async(G,V)=>{if(G<=Q)throw Error("next() called multiple times");if(Q=G,G===$.length)return U?await U(V):V;let X=$[G];return X(V,(Z)=>_(G+1,Z))};return _(0,J)}}function y_($,J){let U=[{role:"system",content:J},...$.messages??[],{role:"user",content:$.input}];return{sessionId:$.sessionId??"",messages:U,iteration:0,pendingToolCalls:[],currentResponse:"",shouldContinue:!0,usage:{promptTokens:0,completionTokens:0,totalTokens:0},metadata:{}}}class r4 extends Error{code;retryable;status;constructor($,J){super($);this.name="ModelError",this.code=J.code,this.retryable=J.retryable??!1,this.status=J.status}}class AJ{static isRetryableStatus($){return $===408||$===409||$===429||$>=500&&$<=599}static async sleep($,J){if($<=0)return Promise.resolve();return new Promise((U,Q)=>{let _=setTimeout(()=>{G(),U()},$);function G(){if(clearTimeout(_),J)J.removeEventListener("abort",V)}function V(){G(),Q(Error("Aborted"))}if(J){if(J.aborted)return V();J.addEventListener("abort",V)}})}}function mU($="req"){let J=Math.random().toString(16).slice(2),U=Date.now().toString(16);return`${$}_${U}_${J}`}class wJ{maxAttempts;baseDelayMs;maxDelayMs;strategy;jitter;multiplier;_previousDelay;constructor($={}){this.maxAttempts=$.maxAttempts??3,this.baseDelayMs=$.baseDelayMs??500,this.maxDelayMs=$.maxDelayMs??30000,this.strategy=$.strategy??"exponential",this.jitter=$.jitter??"equal",this.multiplier=$.multiplier??2,this._previousDelay=this.baseDelayMs}getDelay($){let J;switch(this.strategy){case"exponential":J=this.baseDelayMs*this.multiplier**($-1);break;case"linear":J=this.baseDelayMs*$;break;case"fixed":J=this.baseDelayMs;break}return J=Math.min(J,this.maxDelayMs),J=this.applyJitter(J),this._previousDelay=J,Math.floor(J)}applyJitter($){switch(this.jitter){case"full":return Math.random()*$;case"equal":return $/2+Math.random()*$/2;case"decorrelated":return Math.min(this.maxDelayMs,Math.random()*(this._previousDelay*3-this.baseDelayMs)+this.baseDelayMs);case"none":default:return $}}canRetry($){return $<this.maxAttempts}reset(){this._previousDelay=this.baseDelayMs}toString(){return`RetryPolicy(${this.strategy}, max=${this.maxAttempts}, base=${this.baseDelayMs}ms, cap=${this.maxDelayMs}ms, jitter=${this.jitter})`}static default=new wJ;static aggressive=new wJ({maxAttempts:5,baseDelayMs:1000,maxDelayMs:60000});static gentle=new wJ({maxAttempts:3,baseDelayMs:2000,maxDelayMs:30000,jitter:"full"})}function g8($){let J=$.adapter;if(!J)throw new r4("Missing adapter. Provide `adapter` option.",{code:"missing_adapter",retryable:!1});if(!J.defaultModelId)throw new r4("Adapter must have a defaultModelId.",{code:"missing_model_id",retryable:!1});let U={provider:J.provider,modelId:J.defaultModelId},Q=new wJ({maxAttempts:$.retry?.maxAttempts??3,baseDelayMs:$.retry?.baseDelayMs??500,maxDelayMs:$.retry?.maxDelayMs??30000,strategy:$.retry?.strategy??"exponential",jitter:$.retry?.jitter??"equal"}),_=$.timeoutMs??60000;async function*G(X){let Z=X.requestId||mU("req"),{model:Y,...K}=X,F=X.model??U,N=X.timeoutMs??_,q=!1,H=0,E=new AbortController,D=X.signal,B=setTimeout(()=>E.abort(),N),j=()=>E.abort();if(D)if(D.aborted)E.abort();else D.addEventListener("abort",j);let f={...K,requestId:Z,model:F,stream:X.stream??!0,signal:E.signal,timeoutMs:N};try{for(let R=1;R<=Q.maxAttempts;R++){H=R;try{for await(let I of J.stream({request:f})){if(I.type==="delta")q=!0;yield I}return}catch(I){let w=hj(I),T=w.retryable;if(q||!T||!Q.canRetry(R))throw w;let z=Q.getDelay(R);$.retry?.onRetry?.({attempt:R,maxAttempts:Q.maxAttempts,delayMs:z,error:{code:w.code,message:w.message,retryable:w.retryable},model:F,request:f}),await AJ.sleep(z,E.signal)}}}catch(R){let I=hj(R);throw yield{type:"error",requestId:Z,terminal:!0,model:F,attempt:H||1,source:"client",error:{code:I.code,message:I.message,retryable:I.retryable}},I}finally{if(clearTimeout(B),D)D.removeEventListener("abort",j)}throw new r4("Max retry attempts exceeded",{code:"max_retries_exceeded",retryable:!1})}async function V(X){let Z="",Y="",K="error",F,N,q=X.requestId||"",H=!1;for await(let E of G({...X,stream:!0}))if(E.type==="response_start")H=!0,q=E.requestId,N=E.model,Z="";else if(E.type==="delta"&&E.chunk.kind==="text")Z+=E.chunk.text;else if(E.type==="response_end")Y=Z,K=E.stopReason,F=E.usage;else if(E.type==="error")K="error";if(!N)throw new r4("Missing response_start from adapter",{code:"protocol_error",retryable:!1});return{requestId:q,model:N,text:H?Y:Z,stopReason:K,usage:F}}return{get modelId(){return U.modelId},get modelRef(){return U},setModelId(X){U={provider:U.provider,modelId:X}},stream:G,run:V}}function hj($){if($ instanceof r4)return $;if($&&typeof $==="object"){let J=typeof $.status==="number"?$.status:void 0,U=typeof $.code==="string"?$.code:J?`http_${J}`:"unknown_error",Q=typeof $.message==="string"?$.message:"Unknown error",_=J?AJ.isRetryableStatus(J):!1;return new r4(Q,{code:U,retryable:_,status:J})}return new r4(String($||"Unknown error"),{code:"unknown_error",retryable:!1})}function m$($,J,U,Q,_){if(Q==="m")throw TypeError("Private method is not writable");if(Q==="a"&&!_)throw TypeError("Private accessor was defined without a setter");if(typeof J==="function"?$!==J||!_:!J.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Q==="a"?_.call($,U):_?_.value=U:J.set($,U),U}function d($,J,U,Q){if(U==="a"&&!Q)throw TypeError("Private accessor was defined without a getter");if(typeof J==="function"?$!==J||!Q:!J.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return U==="m"?Q:U==="a"?Q.call($):Q?Q.value:J.get($)}var uX=function(){let{crypto:$}=globalThis;if($?.randomUUID)return uX=$.randomUUID.bind($),$.randomUUID();let J=new Uint8Array(1),U=$?()=>$.getRandomValues(J)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Q)=>(+Q^U()&15>>+Q/4).toString(16))};function cU($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var dU=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let J=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)J.stack=$.stack;if($.cause&&!J.cause)J.cause=$.cause;if($.name)J.name=$.name;return J}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class w$ extends Error{}class q6 extends w${constructor($,J,U,Q){super(`${q6.makeMessage($,J,U)}`);this.status=$,this.headers=Q,this.requestID=Q?.get("x-request-id"),this.error=J;let _=J;this.code=_?.code,this.param=_?.param,this.type=_?.type}static makeMessage($,J,U){let Q=J?.message?typeof J.message==="string"?J.message:JSON.stringify(J.message):J?JSON.stringify(J):U;if($&&Q)return`${$} ${Q}`;if($)return`${$} status code (no body)`;if(Q)return Q;return"(no status code or body)"}static generate($,J,U,Q){if(!$||!Q)return new fJ({message:U,cause:dU(J)});let _=J?.error;if($===400)return new lU($,_,U,Q);if($===401)return new iU($,_,U,Q);if($===403)return new rU($,_,U,Q);if($===404)return new nU($,_,U,Q);if($===409)return new pU($,_,U,Q);if($===422)return new aU($,_,U,Q);if($===429)return new oU($,_,U,Q);if($>=500)return new tU($,_,U,Q);return new q6($,_,U,Q)}}class D6 extends q6{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class fJ extends q6{constructor({message:$,cause:J}){super(void 0,void 0,$||"Connection error.",void 0);if(J)this.cause=J}}class kJ extends fJ{constructor({message:$}={}){super({message:$??"Request timed out."})}}class lU extends q6{}class iU extends q6{}class rU extends q6{}class nU extends q6{}class pU extends q6{}class aU extends q6{}class oU extends q6{}class tU extends q6{}class sU extends w${constructor(){super("Could not parse response content as the length limit was reached")}}class eU extends w${constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class m1 extends Error{constructor($){super($)}}var Rb=/^[a-z][a-z0-9+.-]*:/i,uj=($)=>{return Rb.test($)},g6=($)=>(g6=Array.isArray,g6($)),mX=g6;function cX($){if(typeof $!=="object")return{};return $??{}}function mj($){if(!$)return!0;for(let J in $)return!1;return!0}function cj($,J){return Object.prototype.hasOwnProperty.call($,J)}function $5($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var dj=($,J)=>{if(typeof J!=="number"||!Number.isInteger(J))throw new w$(`${$} must be an integer`);if(J<0)throw new w$(`${$} must be a positive integer`);return J};var lj=($)=>{try{return JSON.parse($)}catch(J){return}};var W1=($)=>new Promise((J)=>setTimeout(J,$));var q2="6.16.0";var pj=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function Ab(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var wb=()=>{let $=Ab();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":q2,"X-Stainless-OS":rj(Deno.build.os),"X-Stainless-Arch":ij(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":q2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":q2,"X-Stainless-OS":rj(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ij(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let J=fb();if(J)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":q2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${J.browser}`,"X-Stainless-Runtime-Version":J.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":q2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function fb(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:J,pattern:U}of $){let Q=U.exec(navigator.userAgent);if(Q){let _=Q[1]||0,G=Q[2]||0,V=Q[3]||0;return{browser:J,version:`${_}.${G}.${V}`}}}return null}var ij=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},rj=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},nj,aj=()=>{return nj??(nj=wb())};function oj(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function dX(...$){let J=globalThis.ReadableStream;if(typeof J>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new J(...$)}function g_($){let J=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return dX({start(){},async pull(U){let{done:Q,value:_}=await J.next();if(Q)U.close();else U.enqueue(_)},async cancel(){await J.return?.()}})}function lX($){if($[Symbol.asyncIterator])return $;let J=$.getReader();return{async next(){try{let U=await J.read();if(U?.done)J.releaseLock();return U}catch(U){throw J.releaseLock(),U}},async return(){let U=J.cancel();return J.releaseLock(),await U,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function tj($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let J=$.getReader(),U=J.cancel();J.releaseLock(),await U}var sj=({headers:$,body:J})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(J)}};var x_="RFC3986",iX=($)=>String($),h_={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:iX},rX="RFC1738";var u_=($,J)=>(u_=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),u_($,J)),q1=(()=>{let $=[];for(let J=0;J<256;++J)$.push("%"+((J<16?"0":"")+J.toString(16)).toUpperCase());return $})();var nX=1024,ej=($,J,U,Q,_)=>{if($.length===0)return $;let G=$;if(typeof $==="symbol")G=Symbol.prototype.toString.call($);else if(typeof $!=="string")G=String($);if(U==="iso-8859-1")return escape(G).replace(/%u[0-9a-f]{4}/gi,function(X){return"%26%23"+parseInt(X.slice(2),16)+"%3B"});let V="";for(let X=0;X<G.length;X+=nX){let Z=G.length>=nX?G.slice(X,X+nX):G,Y=[];for(let K=0;K<Z.length;++K){let F=Z.charCodeAt(K);if(F===45||F===46||F===95||F===126||F>=48&&F<=57||F>=65&&F<=90||F>=97&&F<=122||_===rX&&(F===40||F===41)){Y[Y.length]=Z.charAt(K);continue}if(F<128){Y[Y.length]=q1[F];continue}if(F<2048){Y[Y.length]=q1[192|F>>6]+q1[128|F&63];continue}if(F<55296||F>=57344){Y[Y.length]=q1[224|F>>12]+q1[128|F>>6&63]+q1[128|F&63];continue}K+=1,F=65536+((F&1023)<<10|Z.charCodeAt(K)&1023),Y[Y.length]=q1[240|F>>18]+q1[128|F>>12&63]+q1[128|F>>6&63]+q1[128|F&63]}V+=Y.join("")}return V};function $D($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function pX($,J){if(g6($)){let U=[];for(let Q=0;Q<$.length;Q+=1)U.push(J($[Q]));return U}return J($)}var UD={brackets($){return String($)+"[]"},comma:"comma",indices($,J){return String($)+"["+J+"]"},repeat($){return String($)}},_D=function($,J){Array.prototype.push.apply($,g6(J)?J:[J])},JD,E6={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ej,encodeValuesOnly:!1,format:x_,formatter:iX,indices:!1,serializeDate($){return(JD??(JD=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function Sb($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var aX={};function QD($,J,U,Q,_,G,V,X,Z,Y,K,F,N,q,H,E,D,B){let j=$,f=B,R=0,I=!1;while((f=f.get(aX))!==void 0&&!I){let O=f.get($);if(R+=1,typeof O<"u")if(O===R)throw RangeError("Cyclic object value");else I=!0;if(typeof f.get(aX)>"u")R=0}if(typeof Y==="function")j=Y(J,j);else if(j instanceof Date)j=N?.(j);else if(U==="comma"&&g6(j))j=pX(j,function(O){if(O instanceof Date)return N?.(O);return O});if(j===null){if(G)return Z&&!E?Z(J,E6.encoder,D,"key",q):J;j=""}if(Sb(j)||$D(j)){if(Z){let O=E?J:Z(J,E6.encoder,D,"key",q);return[H?.(O)+"="+H?.(Z(j,E6.encoder,D,"value",q))]}return[H?.(J)+"="+H?.(String(j))]}let w=[];if(typeof j>"u")return w;let T;if(U==="comma"&&g6(j)){if(E&&Z)j=pX(j,Z);T=[{value:j.length>0?j.join(",")||null:void 0}]}else if(g6(Y))T=Y;else{let O=Object.keys(j);T=K?O.sort(K):O}let z=X?String(J).replace(/\./g,"%2E"):String(J),S=Q&&g6(j)&&j.length===1?z+"[]":z;if(_&&g6(j)&&j.length===0)return S+"[]";for(let O=0;O<T.length;++O){let M=T[O],P=typeof M==="object"&&typeof M.value<"u"?M.value:j[M];if(V&&P===null)continue;let A=F&&X?M.replace(/\./g,"%2E"):M,k=g6(j)?typeof U==="function"?U(S,A):S:S+(F?"."+A:"["+A+"]");B.set($,R);let L=new WeakMap;L.set(aX,B),_D(w,QD(P,k,U,Q,_,G,V,X,U==="comma"&&E&&g6(j)?null:Z,Y,K,F,N,q,H,E,D,L))}return w}function Tb($=E6){if(typeof $.allowEmptyArrays<"u"&&typeof $.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys<"u"&&typeof $.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder<"u"&&typeof $.encoder!=="function")throw TypeError("Encoder has to be a function.");let J=$.charset||E6.charset;if(typeof $.charset<"u"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let U=x_;if(typeof $.format<"u"){if(!u_(h_,$.format))throw TypeError("Unknown format option provided.");U=$.format}let Q=h_[U],_=E6.filter;if(typeof $.filter==="function"||g6($.filter))_=$.filter;let G;if($.arrayFormat&&$.arrayFormat in UD)G=$.arrayFormat;else if("indices"in $)G=$.indices?"indices":"repeat";else G=E6.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let V=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:E6.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:E6.addQueryPrefix,allowDots:V,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:E6.allowEmptyArrays,arrayFormat:G,charset:J,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:E6.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?E6.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:E6.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:E6.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:E6.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:E6.encodeValuesOnly,filter:_,format:U,formatter:Q,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:E6.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:E6.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:E6.strictNullHandling}}function oX($,J={}){let U=$,Q=Tb(J),_,G;if(typeof Q.filter==="function")G=Q.filter,U=G("",U);else if(g6(Q.filter))G=Q.filter,_=G;let V=[];if(typeof U!=="object"||U===null)return"";let X=UD[Q.arrayFormat],Z=X==="comma"&&Q.commaRoundTrip;if(!_)_=Object.keys(U);if(Q.sort)_.sort(Q.sort);let Y=new WeakMap;for(let N=0;N<_.length;++N){let q=_[N];if(Q.skipNulls&&U[q]===null)continue;_D(V,QD(U[q],q,X,Z,Q.allowEmptyArrays,Q.strictNullHandling,Q.skipNulls,Q.encodeDotInKeys,Q.encode?Q.encoder:null,Q.filter,Q.sort,Q.allowDots,Q.serializeDate,Q.format,Q.formatter,Q.encodeValuesOnly,Q.charset,Y))}let K=V.join(Q.delimiter),F=Q.addQueryPrefix===!0?"?":"";if(Q.charsetSentinel)if(Q.charset==="iso-8859-1")F+="utf8=%26%2310003%3B&";else F+="utf8=%E2%9C%93&";return K.length>0?F+K:""}function XD($){let J=0;for(let _ of $)J+=_.length;let U=new Uint8Array(J),Q=0;for(let _ of $)U.set(_,Q),Q+=_.length;return U}var GD;function x8($){let J;return(GD??(J=new globalThis.TextEncoder,GD=J.encode.bind(J)))($)}var VD;function tX($){let J;return(VD??(J=new globalThis.TextDecoder,VD=J.decode.bind(J)))($)}var O0,j0;class h8{constructor(){O0.set(this,void 0),j0.set(this,void 0),m$(this,O0,new Uint8Array,"f"),m$(this,j0,null,"f")}decode($){if($==null)return[];let J=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?x8($):$;m$(this,O0,XD([d(this,O0,"f"),J]),"f");let U=[],Q;while((Q=Cb(d(this,O0,"f"),d(this,j0,"f")))!=null){if(Q.carriage&&d(this,j0,"f")==null){m$(this,j0,Q.index,"f");continue}if(d(this,j0,"f")!=null&&(Q.index!==d(this,j0,"f")+1||Q.carriage)){U.push(tX(d(this,O0,"f").subarray(0,d(this,j0,"f")-1))),m$(this,O0,d(this,O0,"f").subarray(d(this,j0,"f")),"f"),m$(this,j0,null,"f");continue}let _=d(this,j0,"f")!==null?Q.preceding-1:Q.preceding,G=tX(d(this,O0,"f").subarray(0,_));U.push(G),m$(this,O0,d(this,O0,"f").subarray(Q.index),"f"),m$(this,j0,null,"f")}return U}flush(){if(!d(this,O0,"f").length)return[];return this.decode(`
|
|
65
|
-
`)}}O0=new WeakMap,j0=new WeakMap;h8.NEWLINE_CHARS=new Set([`
|
|
66
|
-
`,"\r"]);h8.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Cb($,J){for(let _=J??0;_<$.length;_++){if($[_]===10)return{preceding:_,index:_+1,carriage:!1};if($[_]===13)return{preceding:_,index:_+1,carriage:!0}}return null}function YD($){for(let Q=0;Q<$.length-1;Q++){if($[Q]===10&&$[Q+1]===10)return Q+2;if($[Q]===13&&$[Q+1]===13)return Q+2;if($[Q]===13&&$[Q+1]===10&&Q+3<$.length&&$[Q+2]===13&&$[Q+3]===10)return Q+4}return-1}var c_={off:0,error:200,warn:300,info:400,debug:500},sX=($,J,U)=>{if(!$)return;if(cj(c_,$))return $;G6(U).warn(`${J} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(c_))}`);return};function J5(){}function m_($,J,U){if(!J||c_[$]>c_[U])return J5;else return J[$].bind(J)}var bb={error:J5,warn:J5,info:J5,debug:J5},ZD=new WeakMap;function G6($){let J=$.logger,U=$.logLevel??"off";if(!J)return bb;let Q=ZD.get(J);if(Q&&Q[0]===U)return Q[1];let _={error:m_("error",J,U),warn:m_("warn",J,U),info:m_("info",J,U),debug:m_("debug",J,U)};return ZD.set(J,[U,_]),_}var c1=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([J,U])=>[J,J.toLowerCase()==="authorization"||J.toLowerCase()==="cookie"||J.toLowerCase()==="set-cookie"?"***":U]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var U5;class D0{constructor($,J,U){this.iterator=$,U5.set(this,void 0),this.controller=J,m$(this,U5,U,"f")}static fromSSEResponse($,J,U){let Q=!1,_=U?G6(U):console;async function*G(){if(Q)throw new w$("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let V=!1;try{for await(let X of yb($,J)){if(V)continue;if(X.data.startsWith("[DONE]")){V=!0;continue}if(X.event===null||!X.event.startsWith("thread.")){let Z;try{Z=JSON.parse(X.data)}catch(Y){throw _.error("Could not parse message into JSON:",X.data),_.error("From chunk:",X.raw),Y}if(Z&&Z.error)throw new q6(void 0,Z.error,void 0,$.headers);yield Z}else{let Z;try{Z=JSON.parse(X.data)}catch(Y){throw console.error("Could not parse message into JSON:",X.data),console.error("From chunk:",X.raw),Y}if(X.event=="error")throw new q6(void 0,Z.error,Z.message,void 0);yield{event:X.event,data:Z}}}V=!0}catch(X){if(cU(X))return;throw X}finally{if(!V)J.abort()}}return new D0(G,J,U)}static fromReadableStream($,J,U){let Q=!1;async function*_(){let V=new h8,X=lX($);for await(let Z of X)for(let Y of V.decode(Z))yield Y;for(let Z of V.flush())yield Z}async function*G(){if(Q)throw new w$("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let V=!1;try{for await(let X of _()){if(V)continue;if(X)yield JSON.parse(X)}V=!0}catch(X){if(cU(X))return;throw X}finally{if(!V)J.abort()}}return new D0(G,J,U)}[(U5=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],J=[],U=this.iterator(),Q=(_)=>{return{next:()=>{if(_.length===0){let G=U.next();$.push(G),J.push(G)}return _.shift()}}};return[new D0(()=>Q($),this.controller,d(this,U5,"f")),new D0(()=>Q(J),this.controller,d(this,U5,"f"))]}toReadableStream(){let $=this,J;return dX({async start(){J=$[Symbol.asyncIterator]()},async pull(U){try{let{value:Q,done:_}=await J.next();if(_)return U.close();let G=x8(JSON.stringify(Q)+`
|
|
67
|
-
`);U.enqueue(G)}catch(Q){U.error(Q)}},async cancel(){await J.return?.()}})}}async function*yb($,J){if(!$.body){if(J.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new w$("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new w$("Attempted to iterate over a response with no body")}let U=new KD,Q=new h8,_=lX($.body);for await(let G of gb(_))for(let V of Q.decode(G)){let X=U.decode(V);if(X)yield X}for(let G of Q.flush()){let V=U.decode(G);if(V)yield V}}async function*gb($){let J=new Uint8Array;for await(let U of $){if(U==null)continue;let Q=U instanceof ArrayBuffer?new Uint8Array(U):typeof U==="string"?x8(U):U,_=new Uint8Array(J.length+Q.length);_.set(J),_.set(Q,J.length),J=_;let G;while((G=YD(J))!==-1)yield J.slice(0,G),J=J.slice(G)}if(J.length>0)yield J}class KD{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let _={event:this.event,data:this.data.join(`
|
|
68
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],_}if(this.chunks.push($),$.startsWith(":"))return null;let[J,U,Q]=xb($,":");if(Q.startsWith(" "))Q=Q.substring(1);if(J==="event")this.event=Q;else if(J==="data")this.data.push(Q);return null}}function xb($,J){let U=$.indexOf(J);if(U!==-1)return[$.substring(0,U),J,$.substring(U+J.length)];return[$,"",""]}async function d_($,J){let{response:U,requestLogID:Q,retryOfRequestLogID:_,startTime:G}=J,V=await(async()=>{if(J.options.stream){if(G6($).debug("response",U.status,U.url,U.headers,U.body),J.options.__streamClass)return J.options.__streamClass.fromSSEResponse(U,J.controller,$);return D0.fromSSEResponse(U,J.controller,$)}if(U.status===204)return null;if(J.options.__binaryResponse)return U;let Z=U.headers.get("content-type")?.split(";")[0]?.trim();if(Z?.includes("application/json")||Z?.endsWith("+json")){let F=await U.json();return eX(F,U)}return await U.text()})();return G6($).debug(`[${Q}] response parsed`,c1({retryOfRequestLogID:_,url:U.url,status:U.status,body:V,durationMs:Date.now()-G})),V}function eX($,J){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:J.headers.get("x-request-id"),enumerable:!1})}var _5;class IJ extends Promise{constructor($,J,U=d_){super((Q)=>{Q(null)});this.responsePromise=J,this.parseResponse=U,_5.set(this,void 0),m$(this,_5,$,"f")}_thenUnwrap($){return new IJ(d(this,_5,"f"),this.responsePromise,async(J,U)=>eX($(await this.parseResponse(J,U),U),U.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,J]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:J,request_id:J.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(d(this,_5,"f"),$));return this.parsedPromise}then($,J){return this.parse().then($,J)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}_5=new WeakMap;var l_;class i_{constructor($,J,U,Q){l_.set(this,void 0),m$(this,l_,$,"f"),this.options=Q,this.response=J,this.body=U}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new w$("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await d(this,l_,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(l_=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let J of $.getPaginatedItems())yield J}}class r_ extends IJ{constructor($,J,U){super($,J,async(Q,_)=>new U(Q,_.response,await d_(Q,_),_.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let J of $)yield J}}class d1 extends i_{constructor($,J,U,Q){super($,J,U,Q);this.data=U.data||[],this.object=U.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class H4 extends i_{constructor($,J,U,Q){super($,J,U,Q);this.data=U.data||[],this.has_more=U.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.getPaginatedItems(),J=$[$.length-1]?.id;if(!J)return null;return{...this.options,query:{...cX(this.options.query),after:J}}}}class H2 extends i_{constructor($,J,U,Q){super($,J,U,Q);this.data=U.data||[],this.has_more=U.has_more||!1,this.last_id=U.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.last_id;if(!$)return null;return{...this.options,query:{...cX(this.options.query),after:$}}}}var UY=()=>{if(typeof File>"u"){let{process:$}=globalThis,J=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(J?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function u8($,J,U){return UY(),new File($,J??"unknown_file",U)}function Q5($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var n_=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",_Y=async($,J)=>{if(!$Y($.body))return $;return{...$,body:await FD($.body,J)}},E0=async($,J)=>{return{...$,body:await FD($.body,J)}},ND=new WeakMap;function ub($){let J=typeof $==="function"?$:$.fetch,U=ND.get(J);if(U)return U;let Q=(async()=>{try{let _="Response"in J?J.Response:(await J("data:,")).constructor,G=new FormData;if(G.toString()===await new _(G).text())return!1;return!0}catch{return!0}})();return ND.set(J,Q),Q}var FD=async($,J)=>{if(!await ub(J))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let U=new FormData;return await Promise.all(Object.entries($||{}).map(([Q,_])=>JY(U,Q,_))),U},WD=($)=>$ instanceof Blob&&("name"in $),mb=($)=>typeof $==="object"&&$!==null&&($ instanceof Response||n_($)||WD($)),$Y=($)=>{if(mb($))return!0;if(Array.isArray($))return $.some($Y);if($&&typeof $==="object"){for(let J in $)if($Y($[J]))return!0}return!1},JY=async($,J,U)=>{if(U===void 0)return;if(U==null)throw TypeError(`Received null for "${J}"; to pass null in FormData, you must use the string 'null'`);if(typeof U==="string"||typeof U==="number"||typeof U==="boolean")$.append(J,String(U));else if(U instanceof Response)$.append(J,u8([await U.blob()],Q5(U)));else if(n_(U))$.append(J,u8([await new Response(g_(U)).blob()],Q5(U)));else if(WD(U))$.append(J,U,Q5(U));else if(Array.isArray(U))await Promise.all(U.map((Q)=>JY($,J+"[]",Q)));else if(typeof U==="object")await Promise.all(Object.entries(U).map(([Q,_])=>JY($,`${J}[${Q}]`,_)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${U} instead`)};var qD=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",cb=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&qD($),db=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function p_($,J,U){if(UY(),$=await $,cb($)){if($ instanceof File)return $;return u8([await $.arrayBuffer()],$.name)}if(db($)){let _=await $.blob();return J||(J=new URL($.url).pathname.split(/[\\/]/).pop()),u8(await QY(_),J,U)}let Q=await QY($);if(J||(J=Q5($)),!U?.type){let _=Q.find((G)=>typeof G==="object"&&("type"in G)&&G.type);if(typeof _==="string")U={...U,type:_}}return u8(Q,J,U)}async function QY($){let J=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)J.push($);else if(qD($))J.push($ instanceof Blob?$:await $.arrayBuffer());else if(n_($))for await(let U of $)J.push(...await QY(U));else{let U=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${U?`; constructor: ${U}`:""}${lb($)}`)}return J}function lb($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((U)=>`"${U}"`).join(", ")}]`}class X${constructor($){this._client=$}}function BD($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var HD=Object.freeze(Object.create(null)),rb=($=BD)=>function(U,...Q){if(U.length===1)return U[0];let _=!1,G=[],V=U.reduce((K,F,N)=>{if(/[?#]/.test(F))_=!0;let q=Q[N],H=(_?encodeURIComponent:$)(""+q);if(N!==Q.length&&(q==null||typeof q==="object"&&q.toString===Object.getPrototypeOf(Object.getPrototypeOf(q.hasOwnProperty??HD)??HD)?.toString))H=q+"",G.push({start:K.length+F.length,length:H.length,error:`Value of type ${Object.prototype.toString.call(q).slice(8,-1)} is not a valid path parameter`});return K+F+(N===Q.length?"":H)},""),X=V.split(/[?#]/,1)[0],Z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,Y;while((Y=Z.exec(X))!==null)G.push({start:Y.index,length:Y[0].length,error:`Value "${Y[0]}" can't be safely passed as a path parameter`});if(G.sort((K,F)=>K.start-F.start),G.length>0){let K=0,F=G.reduce((N,q)=>{let H=" ".repeat(q.start-K),E="^".repeat(q.length);return K=q.start+q.length,N+H+E},"");throw new w$(`Path parameters result in path with invalid segments:
|
|
69
|
-
${G.map((N)=>N.error).join(`
|
|
70
|
-
`)}
|
|
71
|
-
${V}
|
|
72
|
-
${F}`)}return V},U$=rb(BD);class m8 extends X${list($,J={},U){return this._client.getAPIList(U$`/chat/completions/${$}/messages`,H4,{query:J,...U})}}function G5($){return $!==void 0&&"function"in $&&$.function!==void 0}function V5($){return $?.$brand==="auto-parseable-response-format"}function SJ($){return $?.$brand==="auto-parseable-tool"}function OD($,J){if(!J||!GY(J))return{...$,choices:$.choices.map((U)=>{return DD(U.message.tool_calls),{...U,message:{...U.message,parsed:null,...U.message.tool_calls?{tool_calls:U.message.tool_calls}:void 0}}})};return X5($,J)}function X5($,J){let U=$.choices.map((Q)=>{if(Q.finish_reason==="length")throw new sU;if(Q.finish_reason==="content_filter")throw new eU;return DD(Q.message.tool_calls),{...Q,message:{...Q.message,...Q.message.tool_calls?{tool_calls:Q.message.tool_calls?.map((_)=>ob(J,_))??void 0}:void 0,parsed:Q.message.content&&!Q.message.refusal?ab(J,Q.message.content):null}}});return{...$,choices:U}}function ab($,J){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(J);return JSON.parse(J)}return null}function ob($,J){let U=$.tools?.find((Q)=>G5(Q)&&Q.function?.name===J.function.name);return{...J,function:{...J.function,parsed_arguments:SJ(U)?U.$parseRaw(J.function.arguments):U?.function.strict?JSON.parse(J.function.arguments):null}}}function jD($,J){if(!$||!("tools"in $)||!$.tools)return!1;let U=$.tools?.find((Q)=>G5(Q)&&Q.function?.name===J.function.name);return G5(U)&&(SJ(U)||U?.function.strict||!1)}function GY($){if(V5($.response_format))return!0;return $.tools?.some((J)=>SJ(J)||J.type==="function"&&J.function.strict===!0)??!1}function DD($){for(let J of $||[])if(J.type!=="function")throw new w$(`Currently only \`function\` tool calls are supported; Received \`${J.type}\``)}function ED($){for(let J of $??[]){if(J.type!=="function")throw new w$(`Currently only \`function\` tool types support auto-parsing; Received \`${J.type}\``);if(J.function.strict!==!0)throw new w$(`The \`${J.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var c8=($)=>{return $?.role==="assistant"},VY=($)=>{return $?.role==="tool"};var XY,a_,o_,Y5,Z5,t_,K5,l1,N5,s_,e_,d8,PD;class TJ{constructor(){XY.add(this),this.controller=new AbortController,a_.set(this,void 0),o_.set(this,()=>{}),Y5.set(this,()=>{}),Z5.set(this,void 0),t_.set(this,()=>{}),K5.set(this,()=>{}),l1.set(this,{}),N5.set(this,!1),s_.set(this,!1),e_.set(this,!1),d8.set(this,!1),m$(this,a_,new Promise(($,J)=>{m$(this,o_,$,"f"),m$(this,Y5,J,"f")}),"f"),m$(this,Z5,new Promise(($,J)=>{m$(this,t_,$,"f"),m$(this,K5,J,"f")}),"f"),d(this,a_,"f").catch(()=>{}),d(this,Z5,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},d(this,XY,"m",PD).bind(this))},0)}_connected(){if(this.ended)return;d(this,o_,"f").call(this),this._emit("connect")}get ended(){return d(this,N5,"f")}get errored(){return d(this,s_,"f")}get aborted(){return d(this,e_,"f")}abort(){this.controller.abort()}on($,J){return(d(this,l1,"f")[$]||(d(this,l1,"f")[$]=[])).push({listener:J}),this}off($,J){let U=d(this,l1,"f")[$];if(!U)return this;let Q=U.findIndex((_)=>_.listener===J);if(Q>=0)U.splice(Q,1);return this}once($,J){return(d(this,l1,"f")[$]||(d(this,l1,"f")[$]=[])).push({listener:J,once:!0}),this}emitted($){return new Promise((J,U)=>{if(m$(this,d8,!0,"f"),$!=="error")this.once("error",U);this.once($,J)})}async done(){m$(this,d8,!0,"f"),await d(this,Z5,"f")}_emit($,...J){if(d(this,N5,"f"))return;if($==="end")m$(this,N5,!0,"f"),d(this,t_,"f").call(this);let U=d(this,l1,"f")[$];if(U)d(this,l1,"f")[$]=U.filter((Q)=>!Q.once),U.forEach(({listener:Q})=>Q(...J));if($==="abort"){let Q=J[0];if(!d(this,d8,"f")&&!U?.length)Promise.reject(Q);d(this,Y5,"f").call(this,Q),d(this,K5,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=J[0];if(!d(this,d8,"f")&&!U?.length)Promise.reject(Q);d(this,Y5,"f").call(this,Q),d(this,K5,"f").call(this,Q),this._emit("end")}}_emitFinal(){}}a_=new WeakMap,o_=new WeakMap,Y5=new WeakMap,Z5=new WeakMap,t_=new WeakMap,K5=new WeakMap,l1=new WeakMap,N5=new WeakMap,s_=new WeakMap,e_=new WeakMap,d8=new WeakMap,XY=new WeakSet,PD=function(J){if(m$(this,s_,!0,"f"),J instanceof Error&&J.name==="AbortError")J=new D6;if(J instanceof D6)return m$(this,e_,!0,"f"),this._emit("abort",J);if(J instanceof w$)return this._emit("error",J);if(J instanceof Error){let U=new w$(J.message);return U.cause=J,this._emit("error",U)}return this._emit("error",new w$(String(J)))};function MD($){return typeof $.parse==="function"}var c6,YY,$Q,ZY,KY,NY,LD,zD,tb=10;class F5 extends TJ{constructor(){super(...arguments);c6.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let J=$.choices[0]?.message;if(J)this._addMessage(J);return $}_addMessage($,J=!0){if(!("content"in $))$.content=null;if(this.messages.push($),J){if(this._emit("message",$),VY($)&&$.content)this._emit("functionToolCallResult",$.content);else if(c8($)&&$.tool_calls){for(let U of $.tool_calls)if(U.type==="function")this._emit("functionToolCall",U.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new w$("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),d(this,c6,"m",YY).call(this)}async finalMessage(){return await this.done(),d(this,c6,"m",$Q).call(this)}async finalFunctionToolCall(){return await this.done(),d(this,c6,"m",ZY).call(this)}async finalFunctionToolCallResult(){return await this.done(),d(this,c6,"m",KY).call(this)}async totalUsage(){return await this.done(),d(this,c6,"m",NY).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let J=d(this,c6,"m",$Q).call(this);if(J)this._emit("finalMessage",J);let U=d(this,c6,"m",YY).call(this);if(U)this._emit("finalContent",U);let Q=d(this,c6,"m",ZY).call(this);if(Q)this._emit("finalFunctionToolCall",Q);let _=d(this,c6,"m",KY).call(this);if(_!=null)this._emit("finalFunctionToolCallResult",_);if(this._chatCompletions.some((G)=>G.usage))this._emit("totalUsage",d(this,c6,"m",NY).call(this))}async _createChatCompletion($,J,U){let Q=U?.signal;if(Q){if(Q.aborted)this.controller.abort();Q.addEventListener("abort",()=>this.controller.abort())}d(this,c6,"m",LD).call(this,J);let _=await $.chat.completions.create({...J,stream:!1},{...U,signal:this.controller.signal});return this._connected(),this._addChatCompletion(X5(_,J))}async _runChatCompletion($,J,U){for(let Q of J.messages)this._addMessage(Q,!1);return await this._createChatCompletion($,J,U)}async _runTools($,J,U){let{tool_choice:_="auto",stream:G,...V}=J,X=typeof _!=="string"&&_.type==="function"&&_?.function?.name,{maxChatCompletions:Z=tb}=U||{},Y=J.tools.map((N)=>{if(SJ(N)){if(!N.$callback)throw new w$("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:N.$callback,name:N.function.name,description:N.function.description||"",parameters:N.function.parameters,parse:N.$parseRaw,strict:!0}}}return N}),K={};for(let N of Y)if(N.type==="function")K[N.function.name||N.function.function.name]=N.function;let F="tools"in J?Y.map((N)=>N.type==="function"?{type:"function",function:{name:N.function.name||N.function.function.name,parameters:N.function.parameters,description:N.function.description,strict:N.function.strict}}:N):void 0;for(let N of J.messages)this._addMessage(N,!1);for(let N=0;N<Z;++N){let H=(await this._createChatCompletion($,{...V,tool_choice:_,tools:F,messages:[...this.messages]},U)).choices[0]?.message;if(!H)throw new w$("missing message in ChatCompletion response");if(!H.tool_calls?.length)return;for(let E of H.tool_calls){if(E.type!=="function")continue;let D=E.id,{name:B,arguments:j}=E.function,f=K[B];if(!f){let T=`Invalid tool_call: ${JSON.stringify(B)}. Available options are: ${Object.keys(K).map((z)=>JSON.stringify(z)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:D,content:T});continue}else if(X&&X!==B){let T=`Invalid tool_call: ${JSON.stringify(B)}. ${JSON.stringify(X)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:D,content:T});continue}let R;try{R=MD(f)?await f.parse(j):j}catch(T){let z=T instanceof Error?T.message:String(T);this._addMessage({role:"tool",tool_call_id:D,content:z});continue}let I=await f.function(R,this),w=d(this,c6,"m",zD).call(this,I);if(this._addMessage({role:"tool",tool_call_id:D,content:w}),X)return}}return}}c6=new WeakSet,YY=function(){return d(this,c6,"m",$Q).call(this).content??null},$Q=function(){let J=this.messages.length;while(J-- >0){let U=this.messages[J];if(c8(U))return{...U,content:U.content??null,refusal:U.refusal??null}}throw new w$("stream ended without producing a ChatCompletionMessage with role=assistant")},ZY=function(){for(let J=this.messages.length-1;J>=0;J--){let U=this.messages[J];if(c8(U)&&U?.tool_calls?.length)return U.tool_calls.filter((Q)=>Q.type==="function").at(-1)?.function}return},KY=function(){for(let J=this.messages.length-1;J>=0;J--){let U=this.messages[J];if(VY(U)&&U.content!=null&&typeof U.content==="string"&&this.messages.some((Q)=>Q.role==="assistant"&&Q.tool_calls?.some((_)=>_.type==="function"&&_.id===U.tool_call_id)))return U.content}return},NY=function(){let J={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:U}of this._chatCompletions)if(U)J.completion_tokens+=U.completion_tokens,J.prompt_tokens+=U.prompt_tokens,J.total_tokens+=U.total_tokens;return J},LD=function(J){if(J.n!=null&&J.n>1)throw new w$("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},zD=function(J){return typeof J==="string"?J:J===void 0?"undefined":JSON.stringify(J)};class W5 extends F5{static runTools($,J,U){let Q=new W5,_={...U,headers:{...U?.headers,"X-Stainless-Helper-Method":"runTools"}};return Q._run(()=>Q._runTools($,J,_)),Q}_addMessage($,J=!0){if(super._addMessage($,J),c8($)&&$.content)this._emit("content",$.content)}}var w6={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class RD extends Error{}class AD extends Error{}function sb($,J=w6.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return eb($.trim(),J)}var eb=($,J)=>{let U=$.length,Q=0,_=(N)=>{throw new RD(`${N} at position ${Q}`)},G=(N)=>{throw new AD(`${N} at position ${Q}`)},V=()=>{if(F(),Q>=U)_("Unexpected end of input");if($[Q]==='"')return X();if($[Q]==="{")return Z();if($[Q]==="[")return Y();if($.substring(Q,Q+4)==="null"||w6.NULL&J&&U-Q<4&&"null".startsWith($.substring(Q)))return Q+=4,null;if($.substring(Q,Q+4)==="true"||w6.BOOL&J&&U-Q<4&&"true".startsWith($.substring(Q)))return Q+=4,!0;if($.substring(Q,Q+5)==="false"||w6.BOOL&J&&U-Q<5&&"false".startsWith($.substring(Q)))return Q+=5,!1;if($.substring(Q,Q+8)==="Infinity"||w6.INFINITY&J&&U-Q<8&&"Infinity".startsWith($.substring(Q)))return Q+=8,1/0;if($.substring(Q,Q+9)==="-Infinity"||w6.MINUS_INFINITY&J&&1<U-Q&&U-Q<9&&"-Infinity".startsWith($.substring(Q)))return Q+=9,-1/0;if($.substring(Q,Q+3)==="NaN"||w6.NAN&J&&U-Q<3&&"NaN".startsWith($.substring(Q)))return Q+=3,NaN;return K()},X=()=>{let N=Q,q=!1;Q++;while(Q<U&&($[Q]!=='"'||q&&$[Q-1]==="\\"))q=$[Q]==="\\"?!q:!1,Q++;if($.charAt(Q)=='"')try{return JSON.parse($.substring(N,++Q-Number(q)))}catch(H){G(String(H))}else if(w6.STR&J)try{return JSON.parse($.substring(N,Q-Number(q))+'"')}catch(H){return JSON.parse($.substring(N,$.lastIndexOf("\\"))+'"')}_("Unterminated string literal")},Z=()=>{Q++,F();let N={};try{while($[Q]!=="}"){if(F(),Q>=U&&w6.OBJ&J)return N;let q=X();F(),Q++;try{let H=V();Object.defineProperty(N,q,{value:H,writable:!0,enumerable:!0,configurable:!0})}catch(H){if(w6.OBJ&J)return N;else throw H}if(F(),$[Q]===",")Q++}}catch(q){if(w6.OBJ&J)return N;else _("Expected '}' at end of object")}return Q++,N},Y=()=>{Q++;let N=[];try{while($[Q]!=="]")if(N.push(V()),F(),$[Q]===",")Q++}catch(q){if(w6.ARR&J)return N;_("Expected ']' at end of array")}return Q++,N},K=()=>{if(Q===0){if($==="-"&&w6.NUM&J)_("Not sure what '-' is");try{return JSON.parse($)}catch(q){if(w6.NUM&J)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(H){}G(String(q))}}let N=Q;if($[Q]==="-")Q++;while($[Q]&&!",]}".includes($[Q]))Q++;if(Q==U&&!(w6.NUM&J))_("Unterminated number literal");try{return JSON.parse($.substring(N,Q))}catch(q){if($.substring(N,Q)==="-"&&w6.NUM&J)_("Not sure what '-' is");try{return JSON.parse($.substring(N,$.lastIndexOf("e")))}catch(H){G(String(H))}}},F=()=>{while(Q<U&&`
|
|
73
|
-
\r `.includes($[Q]))Q++};return V()},FY=($)=>sb($,w6.ALL^w6.NUM);var P6,i1,l8,B2,WY,JQ,qY,HY,BY,UQ,OY,wD;class O2 extends F5{constructor($){super();P6.add(this),i1.set(this,void 0),l8.set(this,void 0),B2.set(this,void 0),m$(this,i1,$,"f"),m$(this,l8,[],"f")}get currentChatCompletionSnapshot(){return d(this,B2,"f")}static fromReadableStream($){let J=new O2(null);return J._run(()=>J._fromReadableStream($)),J}static createChatCompletion($,J,U){let Q=new O2(J);return Q._run(()=>Q._runChatCompletion($,{...J,stream:!0},{...U,headers:{...U?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}async _createChatCompletion($,J,U){super._createChatCompletion;let Q=U?.signal;if(Q){if(Q.aborted)this.controller.abort();Q.addEventListener("abort",()=>this.controller.abort())}d(this,P6,"m",WY).call(this);let _=await $.chat.completions.create({...J,stream:!0},{...U,signal:this.controller.signal});this._connected();for await(let G of _)d(this,P6,"m",qY).call(this,G);if(_.controller.signal?.aborted)throw new D6;return this._addChatCompletion(d(this,P6,"m",UQ).call(this))}async _fromReadableStream($,J){let U=J?.signal;if(U){if(U.aborted)this.controller.abort();U.addEventListener("abort",()=>this.controller.abort())}d(this,P6,"m",WY).call(this),this._connected();let Q=D0.fromReadableStream($,this.controller),_;for await(let G of Q){if(_&&_!==G.id)this._addChatCompletion(d(this,P6,"m",UQ).call(this));d(this,P6,"m",qY).call(this,G),_=G.id}if(Q.controller.signal?.aborted)throw new D6;return this._addChatCompletion(d(this,P6,"m",UQ).call(this))}[(i1=new WeakMap,l8=new WeakMap,B2=new WeakMap,P6=new WeakSet,WY=function(){if(this.ended)return;m$(this,B2,void 0,"f")},JQ=function(J){let U=d(this,l8,"f")[J.index];if(U)return U;return U={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},d(this,l8,"f")[J.index]=U,U},qY=function(J){if(this.ended)return;let U=d(this,P6,"m",wD).call(this,J);this._emit("chunk",J,U);for(let Q of J.choices){let _=U.choices[Q.index];if(Q.delta.content!=null&&_.message?.role==="assistant"&&_.message?.content)this._emit("content",Q.delta.content,_.message.content),this._emit("content.delta",{delta:Q.delta.content,snapshot:_.message.content,parsed:_.message.parsed});if(Q.delta.refusal!=null&&_.message?.role==="assistant"&&_.message?.refusal)this._emit("refusal.delta",{delta:Q.delta.refusal,snapshot:_.message.refusal});if(Q.logprobs?.content!=null&&_.message?.role==="assistant")this._emit("logprobs.content.delta",{content:Q.logprobs?.content,snapshot:_.logprobs?.content??[]});if(Q.logprobs?.refusal!=null&&_.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:Q.logprobs?.refusal,snapshot:_.logprobs?.refusal??[]});let G=d(this,P6,"m",JQ).call(this,_);if(_.finish_reason){if(d(this,P6,"m",BY).call(this,_),G.current_tool_call_index!=null)d(this,P6,"m",HY).call(this,_,G.current_tool_call_index)}for(let V of Q.delta.tool_calls??[]){if(G.current_tool_call_index!==V.index){if(d(this,P6,"m",BY).call(this,_),G.current_tool_call_index!=null)d(this,P6,"m",HY).call(this,_,G.current_tool_call_index)}G.current_tool_call_index=V.index}for(let V of Q.delta.tool_calls??[]){let X=_.message.tool_calls?.[V.index];if(!X?.type)continue;if(X?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:X.function?.name,index:V.index,arguments:X.function.arguments,parsed_arguments:X.function.parsed_arguments,arguments_delta:V.function?.arguments??""});else kD(X?.type)}}},HY=function(J,U){if(d(this,P6,"m",JQ).call(this,J).done_tool_calls.has(U))return;let _=J.message.tool_calls?.[U];if(!_)throw Error("no tool call snapshot");if(!_.type)throw Error("tool call snapshot missing `type`");if(_.type==="function"){let G=d(this,i1,"f")?.tools?.find((V)=>G5(V)&&V.function.name===_.function.name);this._emit("tool_calls.function.arguments.done",{name:_.function.name,index:U,arguments:_.function.arguments,parsed_arguments:SJ(G)?G.$parseRaw(_.function.arguments):G?.function.strict?JSON.parse(_.function.arguments):null})}else kD(_.type)},BY=function(J){let U=d(this,P6,"m",JQ).call(this,J);if(J.message.content&&!U.content_done){U.content_done=!0;let Q=d(this,P6,"m",OY).call(this);this._emit("content.done",{content:J.message.content,parsed:Q?Q.$parseRaw(J.message.content):null})}if(J.message.refusal&&!U.refusal_done)U.refusal_done=!0,this._emit("refusal.done",{refusal:J.message.refusal});if(J.logprobs?.content&&!U.logprobs_content_done)U.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:J.logprobs.content});if(J.logprobs?.refusal&&!U.logprobs_refusal_done)U.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:J.logprobs.refusal})},UQ=function(){if(this.ended)throw new w$("stream has ended, this shouldn't happen");let J=d(this,B2,"f");if(!J)throw new w$("request ended without sending any chunks");return m$(this,B2,void 0,"f"),m$(this,l8,[],"f"),$y(J,d(this,i1,"f"))},OY=function(){let J=d(this,i1,"f")?.response_format;if(V5(J))return J;return null},wD=function(J){var U,Q,_,G;let V=d(this,B2,"f"),{choices:X,...Z}=J;if(!V)V=m$(this,B2,{...Z,choices:[]},"f");else Object.assign(V,Z);for(let{delta:Y,finish_reason:K,index:F,logprobs:N=null,...q}of J.choices){let H=V.choices[F];if(!H)H=V.choices[F]={finish_reason:K,index:F,message:{},logprobs:N,...q};if(N)if(!H.logprobs)H.logprobs=Object.assign({},N);else{let{content:I,refusal:w,...T}=N;if(fD(T),Object.assign(H.logprobs,T),I)(U=H.logprobs).content??(U.content=[]),H.logprobs.content.push(...I);if(w)(Q=H.logprobs).refusal??(Q.refusal=[]),H.logprobs.refusal.push(...w)}if(K){if(H.finish_reason=K,d(this,i1,"f")&&GY(d(this,i1,"f"))){if(K==="length")throw new sU;if(K==="content_filter")throw new eU}}if(Object.assign(H,q),!Y)continue;let{content:E,refusal:D,function_call:B,role:j,tool_calls:f,...R}=Y;if(fD(R),Object.assign(H.message,R),D)H.message.refusal=(H.message.refusal||"")+D;if(j)H.message.role=j;if(B)if(!H.message.function_call)H.message.function_call=B;else{if(B.name)H.message.function_call.name=B.name;if(B.arguments)(_=H.message.function_call).arguments??(_.arguments=""),H.message.function_call.arguments+=B.arguments}if(E){if(H.message.content=(H.message.content||"")+E,!H.message.refusal&&d(this,P6,"m",OY).call(this))H.message.parsed=FY(H.message.content)}if(f){if(!H.message.tool_calls)H.message.tool_calls=[];for(let{index:I,id:w,type:T,function:z,...S}of f){let O=(G=H.message.tool_calls)[I]??(G[I]={});if(Object.assign(O,S),w)O.id=w;if(T)O.type=T;if(z)O.function??(O.function={name:z.name??"",arguments:""});if(z?.name)O.function.name=z.name;if(z?.arguments){if(O.function.arguments+=z.arguments,jD(d(this,i1,"f"),O))O.function.parsed_arguments=FY(O.function.arguments)}}}}return V},Symbol.asyncIterator)](){let $=[],J=[],U=!1;return this.on("chunk",(Q)=>{let _=J.shift();if(_)_.resolve(Q);else $.push(Q)}),this.on("end",()=>{U=!0;for(let Q of J)Q.resolve(void 0);J.length=0}),this.on("abort",(Q)=>{U=!0;for(let _ of J)_.reject(Q);J.length=0}),this.on("error",(Q)=>{U=!0;for(let _ of J)_.reject(Q);J.length=0}),{next:async()=>{if(!$.length){if(U)return{value:void 0,done:!0};return new Promise((_,G)=>J.push({resolve:_,reject:G})).then((_)=>_?{value:_,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new D0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function $y($,J){let{id:U,choices:Q,created:_,model:G,system_fingerprint:V,...X}=$,Z={...X,id:U,choices:Q.map(({message:Y,finish_reason:K,index:F,logprobs:N,...q})=>{if(!K)throw new w$(`missing finish_reason for choice ${F}`);let{content:H=null,function_call:E,tool_calls:D,...B}=Y,j=Y.role;if(!j)throw new w$(`missing role for choice ${F}`);if(E){let{arguments:f,name:R}=E;if(f==null)throw new w$(`missing function_call.arguments for choice ${F}`);if(!R)throw new w$(`missing function_call.name for choice ${F}`);return{...q,message:{content:H,function_call:{arguments:f,name:R},role:j,refusal:Y.refusal??null},finish_reason:K,index:F,logprobs:N}}if(D)return{...q,index:F,finish_reason:K,logprobs:N,message:{...B,role:j,content:H,refusal:Y.refusal??null,tool_calls:D.map((f,R)=>{let{function:I,type:w,id:T,...z}=f,{arguments:S,name:O,...M}=I||{};if(T==null)throw new w$(`missing choices[${F}].tool_calls[${R}].id
|
|
74
|
-
${_Q($)}`);if(w==null)throw new w$(`missing choices[${F}].tool_calls[${R}].type
|
|
75
|
-
${_Q($)}`);if(O==null)throw new w$(`missing choices[${F}].tool_calls[${R}].function.name
|
|
76
|
-
${_Q($)}`);if(S==null)throw new w$(`missing choices[${F}].tool_calls[${R}].function.arguments
|
|
77
|
-
${_Q($)}`);return{...z,id:T,type:w,function:{...M,name:O,arguments:S}}})}};return{...q,message:{...B,content:H,role:j,refusal:Y.refusal??null},finish_reason:K,index:F,logprobs:N}}),created:_,model:G,object:"chat.completion",...V?{system_fingerprint:V}:{}};return OD(Z,J)}function _Q($){return JSON.stringify($)}function fD($){return}function kD($){}class i8 extends O2{static fromReadableStream($){let J=new i8(null);return J._run(()=>J._fromReadableStream($)),J}static runTools($,J,U){let Q=new i8(J),_={...U,headers:{...U?.headers,"X-Stainless-Helper-Method":"runTools"}};return Q._run(()=>Q._runTools($,J,_)),Q}}class j2 extends X${constructor(){super(...arguments);this.messages=new m8(this._client)}create($,J){return this._client.post("/chat/completions",{body:$,...J,stream:$.stream??!1})}retrieve($,J){return this._client.get(U$`/chat/completions/${$}`,J)}update($,J,U){return this._client.post(U$`/chat/completions/${$}`,{body:J,...U})}list($={},J){return this._client.getAPIList("/chat/completions",H4,{query:$,...J})}delete($,J){return this._client.delete(U$`/chat/completions/${$}`,J)}parse($,J){return ED($.tools),this._client.chat.completions.create($,{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((U)=>X5(U,$))}runTools($,J){if($.stream)return i8.runTools(this._client,$,J);return W5.runTools(this._client,$,J)}stream($,J){return O2.createChatCompletion(this._client,$,J)}}j2.Messages=m8;class vJ extends X${constructor(){super(...arguments);this.completions=new j2(this._client)}}vJ.Completions=j2;var ID=Symbol("brand.privateNullableHeaders");function*Uy($){if(!$)return;if(ID in $){let{values:Q,nulls:_}=$;yield*Q.entries();for(let G of _)yield[G,null];return}let J=!1,U;if($ instanceof Headers)U=$.entries();else if(mX($))U=$;else J=!0,U=Object.entries($??{});for(let Q of U){let _=Q[0];if(typeof _!=="string")throw TypeError("expected header name to be a string");let G=mX(Q[1])?Q[1]:[Q[1]],V=!1;for(let X of G){if(X===void 0)continue;if(J&&!V)V=!0,yield[_,null];yield[_,X]}}}var j$=($)=>{let J=new Headers,U=new Set;for(let Q of $){let _=new Set;for(let[G,V]of Uy(Q)){let X=G.toLowerCase();if(!_.has(X))J.delete(G),_.add(X);if(V===null)J.delete(G),U.add(X);else J.append(G,V),U.delete(X)}}return{[ID]:!0,values:J,nulls:U}};class q5 extends X${create($,J){return this._client.post("/audio/speech",{body:$,...J,headers:j$([{Accept:"application/octet-stream"},J?.headers]),__binaryResponse:!0})}}class H5 extends X${create($,J){return this._client.post("/audio/transcriptions",E0({body:$,...J,stream:$.stream??!1,__metadata:{model:$.model}},this._client))}}class B5 extends X${create($,J){return this._client.post("/audio/translations",E0({body:$,...J,__metadata:{model:$.model}},this._client))}}class r1 extends X${constructor(){super(...arguments);this.transcriptions=new H5(this._client),this.translations=new B5(this._client),this.speech=new q5(this._client)}}r1.Transcriptions=H5;r1.Translations=B5;r1.Speech=q5;class r8 extends X${create($,J){return this._client.post("/batches",{body:$,...J})}retrieve($,J){return this._client.get(U$`/batches/${$}`,J)}list($={},J){return this._client.getAPIList("/batches",H4,{query:$,...J})}cancel($,J){return this._client.post(U$`/batches/${$}/cancel`,J)}}class O5 extends X${create($,J){return this._client.post("/assistants",{body:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}retrieve($,J){return this._client.get(U$`/assistants/${$}`,{...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}update($,J,U){return this._client.post(U$`/assistants/${$}`,{body:J,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}list($={},J){return this._client.getAPIList("/assistants",H4,{query:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}delete($,J){return this._client.delete(U$`/assistants/${$}`,{...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}}class j5 extends X${create($,J){return this._client.post("/realtime/sessions",{body:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}}class D5 extends X${create($,J){return this._client.post("/realtime/transcription_sessions",{body:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}}class CJ extends X${constructor(){super(...arguments);this.sessions=new j5(this._client),this.transcriptionSessions=new D5(this._client)}}CJ.Sessions=j5;CJ.TranscriptionSessions=D5;class E5 extends X${create($,J){return this._client.post("/chatkit/sessions",{body:$,...J,headers:j$([{"OpenAI-Beta":"chatkit_beta=v1"},J?.headers])})}cancel($,J){return this._client.post(U$`/chatkit/sessions/${$}/cancel`,{...J,headers:j$([{"OpenAI-Beta":"chatkit_beta=v1"},J?.headers])})}}class P5 extends X${retrieve($,J){return this._client.get(U$`/chatkit/threads/${$}`,{...J,headers:j$([{"OpenAI-Beta":"chatkit_beta=v1"},J?.headers])})}list($={},J){return this._client.getAPIList("/chatkit/threads",H2,{query:$,...J,headers:j$([{"OpenAI-Beta":"chatkit_beta=v1"},J?.headers])})}delete($,J){return this._client.delete(U$`/chatkit/threads/${$}`,{...J,headers:j$([{"OpenAI-Beta":"chatkit_beta=v1"},J?.headers])})}listItems($,J={},U){return this._client.getAPIList(U$`/chatkit/threads/${$}/items`,H2,{query:J,...U,headers:j$([{"OpenAI-Beta":"chatkit_beta=v1"},U?.headers])})}}class bJ extends X${constructor(){super(...arguments);this.sessions=new E5(this._client),this.threads=new P5(this._client)}}bJ.Sessions=E5;bJ.Threads=P5;class M5 extends X${create($,J,U){return this._client.post(U$`/threads/${$}/messages`,{body:J,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}retrieve($,J,U){let{thread_id:Q}=J;return this._client.get(U$`/threads/${Q}/messages/${$}`,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}update($,J,U){let{thread_id:Q,..._}=J;return this._client.post(U$`/threads/${Q}/messages/${$}`,{body:_,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}list($,J={},U){return this._client.getAPIList(U$`/threads/${$}/messages`,H4,{query:J,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}delete($,J,U){let{thread_id:Q}=J;return this._client.delete(U$`/threads/${Q}/messages/${$}`,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}}class L5 extends X${retrieve($,J,U){let{thread_id:Q,run_id:_,...G}=J;return this._client.get(U$`/threads/${Q}/runs/${_}/steps/${$}`,{query:G,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}list($,J,U){let{thread_id:Q,..._}=J;return this._client.getAPIList(U$`/threads/${Q}/runs/${$}/steps`,H4,{query:_,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}}var SD=($)=>{if(typeof Buffer<"u"){let J=Buffer.from($,"base64");return Array.from(new Float32Array(J.buffer,J.byteOffset,J.length/Float32Array.BYTES_PER_ELEMENT))}else{let J=atob($),U=J.length,Q=new Uint8Array(U);for(let _=0;_<U;_++)Q[_]=J.charCodeAt(_);return Array.from(new Float32Array(Q.buffer))}};var D2=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var S6,gJ,jY,H1,QQ,p0,xJ,n8,yJ,XQ,P0,GQ,VQ,A5,z5,R5,TD,vD,CD,bD,yD,gD,xD;class E2 extends TJ{constructor(){super(...arguments);S6.add(this),jY.set(this,[]),H1.set(this,{}),QQ.set(this,{}),p0.set(this,void 0),xJ.set(this,void 0),n8.set(this,void 0),yJ.set(this,void 0),XQ.set(this,void 0),P0.set(this,void 0),GQ.set(this,void 0),VQ.set(this,void 0),A5.set(this,void 0)}[(jY=new WeakMap,H1=new WeakMap,QQ=new WeakMap,p0=new WeakMap,xJ=new WeakMap,n8=new WeakMap,yJ=new WeakMap,XQ=new WeakMap,P0=new WeakMap,GQ=new WeakMap,VQ=new WeakMap,A5=new WeakMap,S6=new WeakSet,Symbol.asyncIterator)](){let $=[],J=[],U=!1;return this.on("event",(Q)=>{let _=J.shift();if(_)_.resolve(Q);else $.push(Q)}),this.on("end",()=>{U=!0;for(let Q of J)Q.resolve(void 0);J.length=0}),this.on("abort",(Q)=>{U=!0;for(let _ of J)_.reject(Q);J.length=0}),this.on("error",(Q)=>{U=!0;for(let _ of J)_.reject(Q);J.length=0}),{next:async()=>{if(!$.length){if(U)return{value:void 0,done:!0};return new Promise((_,G)=>J.push({resolve:_,reject:G})).then((_)=>_?{value:_,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let J=new gJ;return J._run(()=>J._fromReadableStream($)),J}async _fromReadableStream($,J){let U=J?.signal;if(U){if(U.aborted)this.controller.abort();U.addEventListener("abort",()=>this.controller.abort())}this._connected();let Q=D0.fromReadableStream($,this.controller);for await(let _ of Q)d(this,S6,"m",z5).call(this,_);if(Q.controller.signal?.aborted)throw new D6;return this._addRun(d(this,S6,"m",R5).call(this))}toReadableStream(){return new D0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,J,U,Q){let _=new gJ;return _._run(()=>_._runToolAssistantStream($,J,U,{...Q,headers:{...Q?.headers,"X-Stainless-Helper-Method":"stream"}})),_}async _createToolAssistantStream($,J,U,Q){let _=Q?.signal;if(_){if(_.aborted)this.controller.abort();_.addEventListener("abort",()=>this.controller.abort())}let G={...U,stream:!0},V=await $.submitToolOutputs(J,G,{...Q,signal:this.controller.signal});this._connected();for await(let X of V)d(this,S6,"m",z5).call(this,X);if(V.controller.signal?.aborted)throw new D6;return this._addRun(d(this,S6,"m",R5).call(this))}static createThreadAssistantStream($,J,U){let Q=new gJ;return Q._run(()=>Q._threadAssistantStream($,J,{...U,headers:{...U?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}static createAssistantStream($,J,U,Q){let _=new gJ;return _._run(()=>_._runAssistantStream($,J,U,{...Q,headers:{...Q?.headers,"X-Stainless-Helper-Method":"stream"}})),_}currentEvent(){return d(this,GQ,"f")}currentRun(){return d(this,VQ,"f")}currentMessageSnapshot(){return d(this,p0,"f")}currentRunStepSnapshot(){return d(this,A5,"f")}async finalRunSteps(){return await this.done(),Object.values(d(this,H1,"f"))}async finalMessages(){return await this.done(),Object.values(d(this,QQ,"f"))}async finalRun(){if(await this.done(),!d(this,xJ,"f"))throw Error("Final run was not received.");return d(this,xJ,"f")}async _createThreadAssistantStream($,J,U){let Q=U?.signal;if(Q){if(Q.aborted)this.controller.abort();Q.addEventListener("abort",()=>this.controller.abort())}let _={...J,stream:!0},G=await $.createAndRun(_,{...U,signal:this.controller.signal});this._connected();for await(let V of G)d(this,S6,"m",z5).call(this,V);if(G.controller.signal?.aborted)throw new D6;return this._addRun(d(this,S6,"m",R5).call(this))}async _createAssistantStream($,J,U,Q){let _=Q?.signal;if(_){if(_.aborted)this.controller.abort();_.addEventListener("abort",()=>this.controller.abort())}let G={...U,stream:!0},V=await $.create(J,G,{...Q,signal:this.controller.signal});this._connected();for await(let X of V)d(this,S6,"m",z5).call(this,X);if(V.controller.signal?.aborted)throw new D6;return this._addRun(d(this,S6,"m",R5).call(this))}static accumulateDelta($,J){for(let[U,Q]of Object.entries(J)){if(!$.hasOwnProperty(U)){$[U]=Q;continue}let _=$[U];if(_===null||_===void 0){$[U]=Q;continue}if(U==="index"||U==="type"){$[U]=Q;continue}if(typeof _==="string"&&typeof Q==="string")_+=Q;else if(typeof _==="number"&&typeof Q==="number")_+=Q;else if($5(_)&&$5(Q))_=this.accumulateDelta(_,Q);else if(Array.isArray(_)&&Array.isArray(Q)){if(_.every((G)=>typeof G==="string"||typeof G==="number")){_.push(...Q);continue}for(let G of Q){if(!$5(G))throw Error(`Expected array delta entry to be an object but got: ${G}`);let V=G.index;if(V==null)throw console.error(G),Error("Expected array delta entry to have an `index` property");if(typeof V!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${V}`);let X=_[V];if(X==null)_.push(G);else _[V]=this.accumulateDelta(X,G)}continue}else throw Error(`Unhandled record type: ${U}, deltaValue: ${Q}, accValue: ${_}`);$[U]=_}return $}_addRun($){return $}async _threadAssistantStream($,J,U){return await this._createThreadAssistantStream(J,$,U)}async _runAssistantStream($,J,U,Q){return await this._createAssistantStream(J,$,U,Q)}async _runToolAssistantStream($,J,U,Q){return await this._createToolAssistantStream(J,$,U,Q)}}gJ=E2,z5=function(J){if(this.ended)return;switch(m$(this,GQ,J,"f"),d(this,S6,"m",CD).call(this,J),J.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":d(this,S6,"m",xD).call(this,J);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":d(this,S6,"m",vD).call(this,J);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":d(this,S6,"m",TD).call(this,J);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:Hy(J)}},R5=function(){if(this.ended)throw new w$("stream has ended, this shouldn't happen");if(!d(this,xJ,"f"))throw Error("Final run has not been received");return d(this,xJ,"f")},TD=function(J){let[U,Q]=d(this,S6,"m",yD).call(this,J,d(this,p0,"f"));m$(this,p0,U,"f"),d(this,QQ,"f")[U.id]=U;for(let _ of Q){let G=U.content[_.index];if(G?.type=="text")this._emit("textCreated",G.text)}switch(J.event){case"thread.message.created":this._emit("messageCreated",J.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",J.data.delta,U),J.data.delta.content)for(let _ of J.data.delta.content){if(_.type=="text"&&_.text){let G=_.text,V=U.content[_.index];if(V&&V.type=="text")this._emit("textDelta",G,V.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(_.index!=d(this,n8,"f")){if(d(this,yJ,"f"))switch(d(this,yJ,"f").type){case"text":this._emit("textDone",d(this,yJ,"f").text,d(this,p0,"f"));break;case"image_file":this._emit("imageFileDone",d(this,yJ,"f").image_file,d(this,p0,"f"));break}m$(this,n8,_.index,"f")}m$(this,yJ,U.content[_.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(d(this,n8,"f")!==void 0){let _=J.data.content[d(this,n8,"f")];if(_)switch(_.type){case"image_file":this._emit("imageFileDone",_.image_file,d(this,p0,"f"));break;case"text":this._emit("textDone",_.text,d(this,p0,"f"));break}}if(d(this,p0,"f"))this._emit("messageDone",J.data);m$(this,p0,void 0,"f")}},vD=function(J){let U=d(this,S6,"m",bD).call(this,J);switch(m$(this,A5,U,"f"),J.event){case"thread.run.step.created":this._emit("runStepCreated",J.data);break;case"thread.run.step.delta":let Q=J.data.delta;if(Q.step_details&&Q.step_details.type=="tool_calls"&&Q.step_details.tool_calls&&U.step_details.type=="tool_calls")for(let G of Q.step_details.tool_calls)if(G.index==d(this,XQ,"f"))this._emit("toolCallDelta",G,U.step_details.tool_calls[G.index]);else{if(d(this,P0,"f"))this._emit("toolCallDone",d(this,P0,"f"));if(m$(this,XQ,G.index,"f"),m$(this,P0,U.step_details.tool_calls[G.index],"f"),d(this,P0,"f"))this._emit("toolCallCreated",d(this,P0,"f"))}this._emit("runStepDelta",J.data.delta,U);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(m$(this,A5,void 0,"f"),J.data.step_details.type=="tool_calls"){if(d(this,P0,"f"))this._emit("toolCallDone",d(this,P0,"f")),m$(this,P0,void 0,"f")}this._emit("runStepDone",J.data,U);break;case"thread.run.step.in_progress":break}},CD=function(J){d(this,jY,"f").push(J),this._emit("event",J)},bD=function(J){switch(J.event){case"thread.run.step.created":return d(this,H1,"f")[J.data.id]=J.data,J.data;case"thread.run.step.delta":let U=d(this,H1,"f")[J.data.id];if(!U)throw Error("Received a RunStepDelta before creation of a snapshot");let Q=J.data;if(Q.delta){let _=gJ.accumulateDelta(U,Q.delta);d(this,H1,"f")[J.data.id]=_}return d(this,H1,"f")[J.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":d(this,H1,"f")[J.data.id]=J.data;break}if(d(this,H1,"f")[J.data.id])return d(this,H1,"f")[J.data.id];throw Error("No snapshot available")},yD=function(J,U){let Q=[];switch(J.event){case"thread.message.created":return[J.data,Q];case"thread.message.delta":if(!U)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let _=J.data;if(_.delta.content)for(let G of _.delta.content)if(G.index in U.content){let V=U.content[G.index];U.content[G.index]=d(this,S6,"m",gD).call(this,G,V)}else U.content[G.index]=G,Q.push(G);return[U,Q];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(U)return[U,Q];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},gD=function(J,U){return gJ.accumulateDelta(U,J)},xD=function(J){switch(m$(this,VQ,J.data,"f"),J.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(m$(this,xJ,J.data,"f"),d(this,P0,"f"))this._emit("toolCallDone",d(this,P0,"f")),m$(this,P0,void 0,"f");break;case"thread.run.cancelling":break}};function Hy($){}class p8 extends X${constructor(){super(...arguments);this.steps=new L5(this._client)}create($,J,U){let{include:Q,..._}=J;return this._client.post(U$`/threads/${$}/runs`,{query:{include:Q},body:_,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers]),stream:J.stream??!1})}retrieve($,J,U){let{thread_id:Q}=J;return this._client.get(U$`/threads/${Q}/runs/${$}`,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}update($,J,U){let{thread_id:Q,..._}=J;return this._client.post(U$`/threads/${Q}/runs/${$}`,{body:_,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}list($,J={},U){return this._client.getAPIList(U$`/threads/${$}/runs`,H4,{query:J,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}cancel($,J,U){let{thread_id:Q}=J;return this._client.post(U$`/threads/${Q}/runs/${$}/cancel`,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}async createAndPoll($,J,U){let Q=await this.create($,J,U);return await this.poll(Q.id,{thread_id:$},U)}createAndStream($,J,U){return E2.createAssistantStream($,this._client.beta.threads.runs,J,U)}async poll($,J,U){let Q=j$([U?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":U?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:_,response:G}=await this.retrieve($,J,{...U,headers:{...U?.headers,...Q}}).withResponse();switch(_.status){case"queued":case"in_progress":case"cancelling":let V=5000;if(U?.pollIntervalMs)V=U.pollIntervalMs;else{let X=G.headers.get("openai-poll-after-ms");if(X){let Z=parseInt(X);if(!isNaN(Z))V=Z}}await W1(V);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return _}}}stream($,J,U){return E2.createAssistantStream($,this._client.beta.threads.runs,J,U)}submitToolOutputs($,J,U){let{thread_id:Q,..._}=J;return this._client.post(U$`/threads/${Q}/runs/${$}/submit_tool_outputs`,{body:_,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers]),stream:J.stream??!1})}async submitToolOutputsAndPoll($,J,U){let Q=await this.submitToolOutputs($,J,U);return await this.poll(Q.id,J,U)}submitToolOutputsStream($,J,U){return E2.createToolAssistantStream($,this._client.beta.threads.runs,J,U)}}p8.Steps=L5;class hJ extends X${constructor(){super(...arguments);this.runs=new p8(this._client),this.messages=new M5(this._client)}create($={},J){return this._client.post("/threads",{body:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}retrieve($,J){return this._client.get(U$`/threads/${$}`,{...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}update($,J,U){return this._client.post(U$`/threads/${$}`,{body:J,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}delete($,J){return this._client.delete(U$`/threads/${$}`,{...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}createAndRun($,J){return this._client.post("/threads/runs",{body:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers]),stream:$.stream??!1})}async createAndRunPoll($,J){let U=await this.createAndRun($,J);return await this.runs.poll(U.id,{thread_id:U.thread_id},J)}createAndRunStream($,J){return E2.createThreadAssistantStream($,this._client.beta.threads,J)}}hJ.Runs=p8;hJ.Messages=M5;class B1 extends X${constructor(){super(...arguments);this.realtime=new CJ(this._client),this.chatkit=new bJ(this._client),this.assistants=new O5(this._client),this.threads=new hJ(this._client)}}B1.Realtime=CJ;B1.ChatKit=bJ;B1.Assistants=O5;B1.Threads=hJ;class a8 extends X${create($,J){return this._client.post("/completions",{body:$,...J,stream:$.stream??!1})}}class w5 extends X${retrieve($,J,U){let{container_id:Q}=J;return this._client.get(U$`/containers/${Q}/files/${$}/content`,{...U,headers:j$([{Accept:"application/binary"},U?.headers]),__binaryResponse:!0})}}class o8 extends X${constructor(){super(...arguments);this.content=new w5(this._client)}create($,J,U){return this._client.post(U$`/containers/${$}/files`,E0({body:J,...U},this._client))}retrieve($,J,U){let{container_id:Q}=J;return this._client.get(U$`/containers/${Q}/files/${$}`,U)}list($,J={},U){return this._client.getAPIList(U$`/containers/${$}/files`,H4,{query:J,...U})}delete($,J,U){let{container_id:Q}=J;return this._client.delete(U$`/containers/${Q}/files/${$}`,{...U,headers:j$([{Accept:"*/*"},U?.headers])})}}o8.Content=w5;class uJ extends X${constructor(){super(...arguments);this.files=new o8(this._client)}create($,J){return this._client.post("/containers",{body:$,...J})}retrieve($,J){return this._client.get(U$`/containers/${$}`,J)}list($={},J){return this._client.getAPIList("/containers",H4,{query:$,...J})}delete($,J){return this._client.delete(U$`/containers/${$}`,{...J,headers:j$([{Accept:"*/*"},J?.headers])})}}uJ.Files=o8;class f5 extends X${create($,J,U){let{include:Q,..._}=J;return this._client.post(U$`/conversations/${$}/items`,{query:{include:Q},body:_,...U})}retrieve($,J,U){let{conversation_id:Q,..._}=J;return this._client.get(U$`/conversations/${Q}/items/${$}`,{query:_,...U})}list($,J={},U){return this._client.getAPIList(U$`/conversations/${$}/items`,H2,{query:J,...U})}delete($,J,U){let{conversation_id:Q}=J;return this._client.delete(U$`/conversations/${Q}/items/${$}`,U)}}class mJ extends X${constructor(){super(...arguments);this.items=new f5(this._client)}create($={},J){return this._client.post("/conversations",{body:$,...J})}retrieve($,J){return this._client.get(U$`/conversations/${$}`,J)}update($,J,U){return this._client.post(U$`/conversations/${$}`,{body:J,...U})}delete($,J){return this._client.delete(U$`/conversations/${$}`,J)}}mJ.Items=f5;class t8 extends X${create($,J){let U=!!$.encoding_format,Q=U?$.encoding_format:"base64";if(U)G6(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let _=this._client.post("/embeddings",{body:{...$,encoding_format:Q},...J});if(U)return _;return G6(this._client).debug("embeddings/decoding base64 embeddings from base64"),_._thenUnwrap((G)=>{if(G&&G.data)G.data.forEach((V)=>{let X=V.embedding;V.embedding=SD(X)});return G})}}class k5 extends X${retrieve($,J,U){let{eval_id:Q,run_id:_}=J;return this._client.get(U$`/evals/${Q}/runs/${_}/output_items/${$}`,U)}list($,J,U){let{eval_id:Q,..._}=J;return this._client.getAPIList(U$`/evals/${Q}/runs/${$}/output_items`,H4,{query:_,...U})}}class s8 extends X${constructor(){super(...arguments);this.outputItems=new k5(this._client)}create($,J,U){return this._client.post(U$`/evals/${$}/runs`,{body:J,...U})}retrieve($,J,U){let{eval_id:Q}=J;return this._client.get(U$`/evals/${Q}/runs/${$}`,U)}list($,J={},U){return this._client.getAPIList(U$`/evals/${$}/runs`,H4,{query:J,...U})}delete($,J,U){let{eval_id:Q}=J;return this._client.delete(U$`/evals/${Q}/runs/${$}`,U)}cancel($,J,U){let{eval_id:Q}=J;return this._client.post(U$`/evals/${Q}/runs/${$}`,U)}}s8.OutputItems=k5;class cJ extends X${constructor(){super(...arguments);this.runs=new s8(this._client)}create($,J){return this._client.post("/evals",{body:$,...J})}retrieve($,J){return this._client.get(U$`/evals/${$}`,J)}update($,J,U){return this._client.post(U$`/evals/${$}`,{body:J,...U})}list($={},J){return this._client.getAPIList("/evals",H4,{query:$,...J})}delete($,J){return this._client.delete(U$`/evals/${$}`,J)}}cJ.Runs=s8;class e8 extends X${create($,J){return this._client.post("/files",E0({body:$,...J},this._client))}retrieve($,J){return this._client.get(U$`/files/${$}`,J)}list($={},J){return this._client.getAPIList("/files",H4,{query:$,...J})}delete($,J){return this._client.delete(U$`/files/${$}`,J)}content($,J){return this._client.get(U$`/files/${$}/content`,{...J,headers:j$([{Accept:"application/binary"},J?.headers]),__binaryResponse:!0})}async waitForProcessing($,{pollInterval:J=5000,maxWait:U=1800000}={}){let Q=new Set(["processed","error","deleted"]),_=Date.now(),G=await this.retrieve($);while(!G.status||!Q.has(G.status))if(await W1(J),G=await this.retrieve($),Date.now()-_>U)throw new kJ({message:`Giving up on waiting for file ${$} to finish processing after ${U} milliseconds.`});return G}}class I5 extends X${}class S5 extends X${run($,J){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...J})}validate($,J){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...J})}}class $9 extends X${constructor(){super(...arguments);this.graders=new S5(this._client)}}$9.Graders=S5;class T5 extends X${create($,J,U){return this._client.getAPIList(U$`/fine_tuning/checkpoints/${$}/permissions`,d1,{body:J,method:"post",...U})}retrieve($,J={},U){return this._client.get(U$`/fine_tuning/checkpoints/${$}/permissions`,{query:J,...U})}delete($,J,U){let{fine_tuned_model_checkpoint:Q}=J;return this._client.delete(U$`/fine_tuning/checkpoints/${Q}/permissions/${$}`,U)}}class J9 extends X${constructor(){super(...arguments);this.permissions=new T5(this._client)}}J9.Permissions=T5;class v5 extends X${list($,J={},U){return this._client.getAPIList(U$`/fine_tuning/jobs/${$}/checkpoints`,H4,{query:J,...U})}}class U9 extends X${constructor(){super(...arguments);this.checkpoints=new v5(this._client)}create($,J){return this._client.post("/fine_tuning/jobs",{body:$,...J})}retrieve($,J){return this._client.get(U$`/fine_tuning/jobs/${$}`,J)}list($={},J){return this._client.getAPIList("/fine_tuning/jobs",H4,{query:$,...J})}cancel($,J){return this._client.post(U$`/fine_tuning/jobs/${$}/cancel`,J)}listEvents($,J={},U){return this._client.getAPIList(U$`/fine_tuning/jobs/${$}/events`,H4,{query:J,...U})}pause($,J){return this._client.post(U$`/fine_tuning/jobs/${$}/pause`,J)}resume($,J){return this._client.post(U$`/fine_tuning/jobs/${$}/resume`,J)}}U9.Checkpoints=v5;class O1 extends X${constructor(){super(...arguments);this.methods=new I5(this._client),this.jobs=new U9(this._client),this.checkpoints=new J9(this._client),this.alpha=new $9(this._client)}}O1.Methods=I5;O1.Jobs=U9;O1.Checkpoints=J9;O1.Alpha=$9;class C5 extends X${}class dJ extends X${constructor(){super(...arguments);this.graderModels=new C5(this._client)}}dJ.GraderModels=C5;class _9 extends X${createVariation($,J){return this._client.post("/images/variations",E0({body:$,...J},this._client))}edit($,J){return this._client.post("/images/edits",E0({body:$,...J,stream:$.stream??!1},this._client))}generate($,J){return this._client.post("/images/generations",{body:$,...J,stream:$.stream??!1})}}class Q9 extends X${retrieve($,J){return this._client.get(U$`/models/${$}`,J)}list($){return this._client.getAPIList("/models",d1,$)}delete($,J){return this._client.delete(U$`/models/${$}`,J)}}class G9 extends X${create($,J){return this._client.post("/moderations",{body:$,...J})}}class b5 extends X${accept($,J,U){return this._client.post(U$`/realtime/calls/${$}/accept`,{body:J,...U,headers:j$([{Accept:"*/*"},U?.headers])})}hangup($,J){return this._client.post(U$`/realtime/calls/${$}/hangup`,{...J,headers:j$([{Accept:"*/*"},J?.headers])})}refer($,J,U){return this._client.post(U$`/realtime/calls/${$}/refer`,{body:J,...U,headers:j$([{Accept:"*/*"},U?.headers])})}reject($,J={},U){return this._client.post(U$`/realtime/calls/${$}/reject`,{body:J,...U,headers:j$([{Accept:"*/*"},U?.headers])})}}class y5 extends X${create($,J){return this._client.post("/realtime/client_secrets",{body:$,...J})}}class P2 extends X${constructor(){super(...arguments);this.clientSecrets=new y5(this._client),this.calls=new b5(this._client)}}P2.ClientSecrets=y5;P2.Calls=b5;function hD($,J){if(!J||!Cy(J))return{...$,output_parsed:null,output:$.output.map((U)=>{if(U.type==="function_call")return{...U,parsed_arguments:null};if(U.type==="message")return{...U,content:U.content.map((Q)=>({...Q,parsed:null}))};else return U})};return DY($,J)}function DY($,J){let U=$.output.map((_)=>{if(_.type==="function_call")return{..._,parsed_arguments:gy(J,_)};if(_.type==="message"){let G=_.content.map((V)=>{if(V.type==="output_text")return{...V,parsed:vy(J,V.text)};return V});return{..._,content:G}}return _}),Q=Object.assign({},$,{output:U});if(!Object.getOwnPropertyDescriptor($,"output_text"))YQ(Q);return Object.defineProperty(Q,"output_parsed",{enumerable:!0,get(){for(let _ of Q.output){if(_.type!=="message")continue;for(let G of _.content)if(G.type==="output_text"&&G.parsed!==null)return G.parsed}return null}}),Q}function vy($,J){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(J);return JSON.parse(J)}function Cy($){if(V5($.text?.format))return!0;return!1}function by($){return $?.$brand==="auto-parseable-tool"}function yy($,J){return $.find((U)=>U.type==="function"&&U.name===J)}function gy($,J){let U=yy($.tools??[],J.name);return{...J,...J,parsed_arguments:by(U)?U.$parseRaw(J.arguments):U?.strict?JSON.parse(J.arguments):null}}function YQ($){let J=[];for(let U of $.output){if(U.type!=="message")continue;for(let Q of U.content)if(Q.type==="output_text")J.push(Q.text)}$.output_text=J.join("")}var V9,ZQ,M2,KQ,uD,mD,cD,dD;class NQ extends TJ{constructor($){super();V9.add(this),ZQ.set(this,void 0),M2.set(this,void 0),KQ.set(this,void 0),m$(this,ZQ,$,"f")}static createResponse($,J,U){let Q=new NQ(J);return Q._run(()=>Q._createOrRetrieveResponse($,J,{...U,headers:{...U?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}async _createOrRetrieveResponse($,J,U){let Q=U?.signal;if(Q){if(Q.aborted)this.controller.abort();Q.addEventListener("abort",()=>this.controller.abort())}d(this,V9,"m",uD).call(this);let _,G=null;if("response_id"in J)_=await $.responses.retrieve(J.response_id,{stream:!0},{...U,signal:this.controller.signal,stream:!0}),G=J.starting_after??null;else _=await $.responses.create({...J,stream:!0},{...U,signal:this.controller.signal});this._connected();for await(let V of _)d(this,V9,"m",mD).call(this,V,G);if(_.controller.signal?.aborted)throw new D6;return d(this,V9,"m",cD).call(this)}[(ZQ=new WeakMap,M2=new WeakMap,KQ=new WeakMap,V9=new WeakSet,uD=function(){if(this.ended)return;m$(this,M2,void 0,"f")},mD=function(J,U){if(this.ended)return;let Q=(G,V)=>{if(U==null||V.sequence_number>U)this._emit(G,V)},_=d(this,V9,"m",dD).call(this,J);switch(Q("event",J),J.type){case"response.output_text.delta":{let G=_.output[J.output_index];if(!G)throw new w$(`missing output at index ${J.output_index}`);if(G.type==="message"){let V=G.content[J.content_index];if(!V)throw new w$(`missing content at index ${J.content_index}`);if(V.type!=="output_text")throw new w$(`expected content to be 'output_text', got ${V.type}`);Q("response.output_text.delta",{...J,snapshot:V.text})}break}case"response.function_call_arguments.delta":{let G=_.output[J.output_index];if(!G)throw new w$(`missing output at index ${J.output_index}`);if(G.type==="function_call")Q("response.function_call_arguments.delta",{...J,snapshot:G.arguments});break}default:Q(J.type,J);break}},cD=function(){if(this.ended)throw new w$("stream has ended, this shouldn't happen");let J=d(this,M2,"f");if(!J)throw new w$("request ended without sending any events");m$(this,M2,void 0,"f");let U=xy(J,d(this,ZQ,"f"));return m$(this,KQ,U,"f"),U},dD=function(J){let U=d(this,M2,"f");if(!U){if(J.type!=="response.created")throw new w$(`When snapshot hasn't been set yet, expected 'response.created' event, got ${J.type}`);return U=m$(this,M2,J.response,"f"),U}switch(J.type){case"response.output_item.added":{U.output.push(J.item);break}case"response.content_part.added":{let Q=U.output[J.output_index];if(!Q)throw new w$(`missing output at index ${J.output_index}`);let _=Q.type,G=J.part;if(_==="message"&&G.type!=="reasoning_text")Q.content.push(G);else if(_==="reasoning"&&G.type==="reasoning_text"){if(!Q.content)Q.content=[];Q.content.push(G)}break}case"response.output_text.delta":{let Q=U.output[J.output_index];if(!Q)throw new w$(`missing output at index ${J.output_index}`);if(Q.type==="message"){let _=Q.content[J.content_index];if(!_)throw new w$(`missing content at index ${J.content_index}`);if(_.type!=="output_text")throw new w$(`expected content to be 'output_text', got ${_.type}`);_.text+=J.delta}break}case"response.function_call_arguments.delta":{let Q=U.output[J.output_index];if(!Q)throw new w$(`missing output at index ${J.output_index}`);if(Q.type==="function_call")Q.arguments+=J.delta;break}case"response.reasoning_text.delta":{let Q=U.output[J.output_index];if(!Q)throw new w$(`missing output at index ${J.output_index}`);if(Q.type==="reasoning"){let _=Q.content?.[J.content_index];if(!_)throw new w$(`missing content at index ${J.content_index}`);if(_.type!=="reasoning_text")throw new w$(`expected content to be 'reasoning_text', got ${_.type}`);_.text+=J.delta}break}case"response.completed":{m$(this,M2,J.response,"f");break}}return U},Symbol.asyncIterator)](){let $=[],J=[],U=!1;return this.on("event",(Q)=>{let _=J.shift();if(_)_.resolve(Q);else $.push(Q)}),this.on("end",()=>{U=!0;for(let Q of J)Q.resolve(void 0);J.length=0}),this.on("abort",(Q)=>{U=!0;for(let _ of J)_.reject(Q);J.length=0}),this.on("error",(Q)=>{U=!0;for(let _ of J)_.reject(Q);J.length=0}),{next:async()=>{if(!$.length){if(U)return{value:void 0,done:!0};return new Promise((_,G)=>J.push({resolve:_,reject:G})).then((_)=>_?{value:_,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=d(this,KQ,"f");if(!$)throw new w$("stream ended without producing a ChatCompletion");return $}}function xy($,J){return hD($,J)}class g5 extends X${list($,J={},U){return this._client.getAPIList(U$`/responses/${$}/input_items`,H4,{query:J,...U})}}class x5 extends X${count($={},J){return this._client.post("/responses/input_tokens",{body:$,...J})}}class L2 extends X${constructor(){super(...arguments);this.inputItems=new g5(this._client),this.inputTokens=new x5(this._client)}create($,J){return this._client.post("/responses",{body:$,...J,stream:$.stream??!1})._thenUnwrap((U)=>{if("object"in U&&U.object==="response")YQ(U);return U})}retrieve($,J={},U){return this._client.get(U$`/responses/${$}`,{query:J,...U,stream:J?.stream??!1})._thenUnwrap((Q)=>{if("object"in Q&&Q.object==="response")YQ(Q);return Q})}delete($,J){return this._client.delete(U$`/responses/${$}`,{...J,headers:j$([{Accept:"*/*"},J?.headers])})}parse($,J){return this._client.responses.create($,J)._thenUnwrap((U)=>DY(U,$))}stream($,J){return NQ.createResponse(this._client,$,J)}cancel($,J){return this._client.post(U$`/responses/${$}/cancel`,J)}compact($,J){return this._client.post("/responses/compact",{body:$,...J})}}L2.InputItems=g5;L2.InputTokens=x5;class h5 extends X${create($,J,U){return this._client.post(U$`/uploads/${$}/parts`,E0({body:J,...U},this._client))}}class lJ extends X${constructor(){super(...arguments);this.parts=new h5(this._client)}create($,J){return this._client.post("/uploads",{body:$,...J})}cancel($,J){return this._client.post(U$`/uploads/${$}/cancel`,J)}complete($,J,U){return this._client.post(U$`/uploads/${$}/complete`,{body:J,...U})}}lJ.Parts=h5;var lD=async($)=>{let J=await Promise.allSettled($),U=J.filter((_)=>_.status==="rejected");if(U.length){for(let _ of U)console.error(_.reason);throw Error(`${U.length} promise(s) failed - see the above errors`)}let Q=[];for(let _ of J)if(_.status==="fulfilled")Q.push(_.value);return Q};class u5 extends X${create($,J,U){return this._client.post(U$`/vector_stores/${$}/file_batches`,{body:J,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}retrieve($,J,U){let{vector_store_id:Q}=J;return this._client.get(U$`/vector_stores/${Q}/file_batches/${$}`,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}cancel($,J,U){let{vector_store_id:Q}=J;return this._client.post(U$`/vector_stores/${Q}/file_batches/${$}/cancel`,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}async createAndPoll($,J,U){let Q=await this.create($,J);return await this.poll($,Q.id,U)}listFiles($,J,U){let{vector_store_id:Q,..._}=J;return this._client.getAPIList(U$`/vector_stores/${Q}/file_batches/${$}/files`,H4,{query:_,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}async poll($,J,U){let Q=j$([U?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":U?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:_,response:G}=await this.retrieve(J,{vector_store_id:$},{...U,headers:Q}).withResponse();switch(_.status){case"in_progress":let V=5000;if(U?.pollIntervalMs)V=U.pollIntervalMs;else{let X=G.headers.get("openai-poll-after-ms");if(X){let Z=parseInt(X);if(!isNaN(Z))V=Z}}await W1(V);break;case"failed":case"cancelled":case"completed":return _}}}async uploadAndPoll($,{files:J,fileIds:U=[]},Q){if(J==null||J.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let _=Q?.maxConcurrency??5,G=Math.min(_,J.length),V=this._client,X=J.values(),Z=[...U];async function Y(F){for(let N of F){let q=await V.files.create({file:N,purpose:"assistants"},Q);Z.push(q.id)}}let K=Array(G).fill(X).map(Y);return await lD(K),await this.createAndPoll($,{file_ids:Z})}}class m5 extends X${create($,J,U){return this._client.post(U$`/vector_stores/${$}/files`,{body:J,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}retrieve($,J,U){let{vector_store_id:Q}=J;return this._client.get(U$`/vector_stores/${Q}/files/${$}`,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}update($,J,U){let{vector_store_id:Q,..._}=J;return this._client.post(U$`/vector_stores/${Q}/files/${$}`,{body:_,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}list($,J={},U){return this._client.getAPIList(U$`/vector_stores/${$}/files`,H4,{query:J,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}delete($,J,U){let{vector_store_id:Q}=J;return this._client.delete(U$`/vector_stores/${Q}/files/${$}`,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}async createAndPoll($,J,U){let Q=await this.create($,J,U);return await this.poll($,Q.id,U)}async poll($,J,U){let Q=j$([U?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":U?.pollIntervalMs?.toString()??void 0}]);while(!0){let _=await this.retrieve(J,{vector_store_id:$},{...U,headers:Q}).withResponse(),G=_.data;switch(G.status){case"in_progress":let V=5000;if(U?.pollIntervalMs)V=U.pollIntervalMs;else{let X=_.response.headers.get("openai-poll-after-ms");if(X){let Z=parseInt(X);if(!isNaN(Z))V=Z}}await W1(V);break;case"failed":case"completed":return G}}}async upload($,J,U){let Q=await this._client.files.create({file:J,purpose:"assistants"},U);return this.create($,{file_id:Q.id},U)}async uploadAndPoll($,J,U){let Q=await this.upload($,J,U);return await this.poll($,Q.id,U)}content($,J,U){let{vector_store_id:Q}=J;return this._client.getAPIList(U$`/vector_stores/${Q}/files/${$}/content`,d1,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}}class z2 extends X${constructor(){super(...arguments);this.files=new m5(this._client),this.fileBatches=new u5(this._client)}create($,J){return this._client.post("/vector_stores",{body:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}retrieve($,J){return this._client.get(U$`/vector_stores/${$}`,{...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}update($,J,U){return this._client.post(U$`/vector_stores/${$}`,{body:J,...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}list($={},J){return this._client.getAPIList("/vector_stores",H4,{query:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}delete($,J){return this._client.delete(U$`/vector_stores/${$}`,{...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}search($,J,U){return this._client.getAPIList(U$`/vector_stores/${$}/search`,d1,{body:J,method:"post",...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}}z2.Files=m5;z2.FileBatches=u5;class X9 extends X${create($,J){return this._client.post("/videos",_Y({body:$,...J},this._client))}retrieve($,J){return this._client.get(U$`/videos/${$}`,J)}list($={},J){return this._client.getAPIList("/videos",H2,{query:$,...J})}delete($,J){return this._client.delete(U$`/videos/${$}`,J)}downloadContent($,J={},U){return this._client.get(U$`/videos/${$}/content`,{query:J,...U,headers:j$([{Accept:"application/binary"},U?.headers]),__binaryResponse:!0})}remix($,J,U){return this._client.post(U$`/videos/${$}/remix`,_Y({body:J,...U},this._client))}}var Y9,iD,FQ;class Z9 extends X${constructor(){super(...arguments);Y9.add(this)}async unwrap($,J,U=this._client.webhookSecret,Q=300){return await this.verifySignature($,J,U,Q),JSON.parse($)}async verifySignature($,J,U=this._client.webhookSecret,Q=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");d(this,Y9,"m",iD).call(this,U);let _=j$([J]).values,G=d(this,Y9,"m",FQ).call(this,_,"webhook-signature"),V=d(this,Y9,"m",FQ).call(this,_,"webhook-timestamp"),X=d(this,Y9,"m",FQ).call(this,_,"webhook-id"),Z=parseInt(V,10);if(isNaN(Z))throw new m1("Invalid webhook timestamp format");let Y=Math.floor(Date.now()/1000);if(Y-Z>Q)throw new m1("Webhook timestamp is too old");if(Z>Y+Q)throw new m1("Webhook timestamp is too new");let K=G.split(" ").map((H)=>H.startsWith("v1,")?H.substring(3):H),F=U.startsWith("whsec_")?Buffer.from(U.replace("whsec_",""),"base64"):Buffer.from(U,"utf-8"),N=X?`${X}.${V}.${$}`:`${V}.${$}`,q=await crypto.subtle.importKey("raw",F,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let H of K)try{let E=Buffer.from(H,"base64");if(await crypto.subtle.verify("HMAC",q,E,new TextEncoder().encode(N)))return}catch{continue}throw new m1("The given webhook signature does not match the expected signature")}}Y9=new WeakSet,iD=function(J){if(typeof J!=="string"||J.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},FQ=function(J,U){if(!J)throw Error("Headers are required");let Q=J.get(U);if(Q===null||Q===void 0)throw Error(`Missing required header: ${U}`);return Q};var EY,PY,WQ,rD;class s${constructor({baseURL:$=D2("OPENAI_BASE_URL"),apiKey:J=D2("OPENAI_API_KEY"),organization:U=D2("OPENAI_ORG_ID")??null,project:Q=D2("OPENAI_PROJECT_ID")??null,webhookSecret:_=D2("OPENAI_WEBHOOK_SECRET")??null,...G}={}){if(EY.add(this),WQ.set(this,void 0),this.completions=new a8(this),this.chat=new vJ(this),this.embeddings=new t8(this),this.files=new e8(this),this.images=new _9(this),this.audio=new r1(this),this.moderations=new G9(this),this.models=new Q9(this),this.fineTuning=new O1(this),this.graders=new dJ(this),this.vectorStores=new z2(this),this.webhooks=new Z9(this),this.beta=new B1(this),this.batches=new r8(this),this.uploads=new lJ(this),this.responses=new L2(this),this.realtime=new P2(this),this.conversations=new mJ(this),this.evals=new cJ(this),this.containers=new uJ(this),this.videos=new X9(this),J===void 0)throw new w$("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let V={apiKey:J,organization:U,project:Q,webhookSecret:_,...G,baseURL:$||"https://api.openai.com/v1"};if(!V.dangerouslyAllowBrowser&&pj())throw new w$(`It looks like you're running in a browser-like environment.
|
|
78
|
-
|
|
79
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
80
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
81
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
82
|
-
|
|
83
|
-
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
84
|
-
|
|
85
|
-
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
86
|
-
`);this.baseURL=V.baseURL,this.timeout=V.timeout??PY.DEFAULT_TIMEOUT,this.logger=V.logger??console;let X="warn";this.logLevel=X,this.logLevel=sX(V.logLevel,"ClientOptions.logLevel",this)??sX(D2("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??X,this.fetchOptions=V.fetchOptions,this.maxRetries=V.maxRetries??2,this.fetch=V.fetch??oj(),m$(this,WQ,sj,"f"),this._options=V,this.apiKey=typeof J==="string"?J:"Missing Key",this.organization=U,this.project=Q,this.webhookSecret=_}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:J}){return}async authHeaders($){return j$([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery($){return oX($,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${q2}`}defaultIdempotencyKey(){return`stainless-node-retry-${uX()}`}makeStatusError($,J,U,Q){return q6.generate($,J,U,Q)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let J;try{J=await $()}catch(U){if(U instanceof w$)throw U;throw new w$(`Failed to get token from 'apiKey' function: ${U.message}`,{cause:U})}if(typeof J!=="string"||!J)throw new w$(`Expected 'apiKey' function argument to return a string but it returned ${J}`);return this.apiKey=J,!0}buildURL($,J,U){let Q=!d(this,EY,"m",rD).call(this)&&U||this.baseURL,_=uj($)?new URL($):new URL(Q+(Q.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),G=this.defaultQuery();if(!mj(G))J={...G,...J};if(typeof J==="object"&&J&&!Array.isArray(J))_.search=this.stringifyQuery(J);return _.toString()}async prepareOptions($){await this._callApiKey()}async prepareRequest($,{url:J,options:U}){}get($,J){return this.methodRequest("get",$,J)}post($,J){return this.methodRequest("post",$,J)}patch($,J){return this.methodRequest("patch",$,J)}put($,J){return this.methodRequest("put",$,J)}delete($,J){return this.methodRequest("delete",$,J)}methodRequest($,J,U){return this.request(Promise.resolve(U).then((Q)=>{return{method:$,path:J,...Q}}))}request($,J=null){return new IJ(this,this.makeRequest($,J,void 0))}async makeRequest($,J,U){let Q=await $,_=Q.maxRetries??this.maxRetries;if(J==null)J=_;await this.prepareOptions(Q);let{req:G,url:V,timeout:X}=await this.buildRequest(Q,{retryCount:_-J});await this.prepareRequest(G,{url:V,options:Q});let Z="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),Y=U===void 0?"":`, retryOf: ${U}`,K=Date.now();if(G6(this).debug(`[${Z}] sending request`,c1({retryOfRequestLogID:U,method:Q.method,url:V,options:Q,headers:G.headers})),Q.signal?.aborted)throw new D6;let F=new AbortController,N=await this.fetchWithTimeout(V,G,X,F).catch(dU),q=Date.now();if(N instanceof globalThis.Error){let D=`retrying, ${J} attempts remaining`;if(Q.signal?.aborted)throw new D6;let B=cU(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(J)return G6(this).info(`[${Z}] connection ${B?"timed out":"failed"} - ${D}`),G6(this).debug(`[${Z}] connection ${B?"timed out":"failed"} (${D})`,c1({retryOfRequestLogID:U,url:V,durationMs:q-K,message:N.message})),this.retryRequest(Q,J,U??Z);if(G6(this).info(`[${Z}] connection ${B?"timed out":"failed"} - error; no more retries left`),G6(this).debug(`[${Z}] connection ${B?"timed out":"failed"} (error; no more retries left)`,c1({retryOfRequestLogID:U,url:V,durationMs:q-K,message:N.message})),B)throw new kJ;throw new fJ({cause:N})}let H=[...N.headers.entries()].filter(([D])=>D==="x-request-id").map(([D,B])=>", "+D+": "+JSON.stringify(B)).join(""),E=`[${Z}${Y}${H}] ${G.method} ${V} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${q-K}ms`;if(!N.ok){let D=await this.shouldRetry(N);if(J&&D){let w=`retrying, ${J} attempts remaining`;return await tj(N.body),G6(this).info(`${E} - ${w}`),G6(this).debug(`[${Z}] response error (${w})`,c1({retryOfRequestLogID:U,url:N.url,status:N.status,headers:N.headers,durationMs:q-K})),this.retryRequest(Q,J,U??Z,N.headers)}let B=D?"error; no more retries left":"error; not retryable";G6(this).info(`${E} - ${B}`);let j=await N.text().catch((w)=>dU(w).message),f=lj(j),R=f?void 0:j;throw G6(this).debug(`[${Z}] response error (${B})`,c1({retryOfRequestLogID:U,url:N.url,status:N.status,headers:N.headers,message:R,durationMs:Date.now()-K})),this.makeStatusError(N.status,f,R,N.headers)}return G6(this).info(E),G6(this).debug(`[${Z}] response start`,c1({retryOfRequestLogID:U,url:N.url,status:N.status,headers:N.headers,durationMs:q-K})),{response:N,options:Q,controller:F,requestLogID:Z,retryOfRequestLogID:U,startTime:K}}getAPIList($,J,U){return this.requestAPIList(J,{method:"get",path:$,...U})}requestAPIList($,J){let U=this.makeRequest(J,null,void 0);return new r_(this,U,$)}async fetchWithTimeout($,J,U,Q){let{signal:_,method:G,...V}=J||{};if(_)_.addEventListener("abort",()=>Q.abort());let X=setTimeout(()=>Q.abort(),U),Z=globalThis.ReadableStream&&V.body instanceof globalThis.ReadableStream||typeof V.body==="object"&&V.body!==null&&Symbol.asyncIterator in V.body,Y={signal:Q.signal,...Z?{duplex:"half"}:{},method:"GET",...V};if(G)Y.method=G.toUpperCase();try{return await this.fetch.call(void 0,$,Y)}finally{clearTimeout(X)}}async shouldRetry($){let J=$.headers.get("x-should-retry");if(J==="true")return!0;if(J==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,J,U,Q){let _,G=Q?.get("retry-after-ms");if(G){let X=parseFloat(G);if(!Number.isNaN(X))_=X}let V=Q?.get("retry-after");if(V&&!_){let X=parseFloat(V);if(!Number.isNaN(X))_=X*1000;else _=Date.parse(V)-Date.now()}if(!(_&&0<=_&&_<60000)){let X=$.maxRetries??this.maxRetries;_=this.calculateDefaultRetryTimeoutMillis(J,X)}return await W1(_),this.makeRequest($,J-1,U)}calculateDefaultRetryTimeoutMillis($,J){let _=J-$,G=Math.min(0.5*Math.pow(2,_),8),V=1-Math.random()*0.25;return G*V*1000}async buildRequest($,{retryCount:J=0}={}){let U={...$},{method:Q,path:_,query:G,defaultBaseURL:V}=U,X=this.buildURL(_,G,V);if("timeout"in U)dj("timeout",U.timeout);U.timeout=U.timeout??this.timeout;let{bodyHeaders:Z,body:Y}=this.buildBody({options:U}),K=await this.buildHeaders({options:$,method:Q,bodyHeaders:Z,retryCount:J});return{req:{method:Q,headers:K,...U.signal&&{signal:U.signal},...globalThis.ReadableStream&&Y instanceof globalThis.ReadableStream&&{duplex:"half"},...Y&&{body:Y},...this.fetchOptions??{},...U.fetchOptions??{}},url:X,timeout:U.timeout}}async buildHeaders({options:$,method:J,bodyHeaders:U,retryCount:Q}){let _={};if(this.idempotencyHeader&&J!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();_[this.idempotencyHeader]=$.idempotencyKey}let G=j$([_,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Q),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...aj(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($),this._options.defaultHeaders,U,$.headers]);return this.validateHeaders(G),G.values}buildBody({options:{body:$,headers:J}}){if(!$)return{bodyHeaders:void 0,body:void 0};let U=j$([J]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&U.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:g_($)};else return d(this,WQ,"f").call(this,{body:$,headers:U})}}PY=s$,WQ=new WeakMap,EY=new WeakSet,rD=function(){return this.baseURL!=="https://api.openai.com/v1"};s$.OpenAI=PY;s$.DEFAULT_TIMEOUT=600000;s$.OpenAIError=w$;s$.APIError=q6;s$.APIConnectionError=fJ;s$.APIConnectionTimeoutError=kJ;s$.APIUserAbortError=D6;s$.NotFoundError=nU;s$.ConflictError=pU;s$.RateLimitError=oU;s$.BadRequestError=lU;s$.AuthenticationError=iU;s$.InternalServerError=tU;s$.PermissionDeniedError=rU;s$.UnprocessableEntityError=aU;s$.InvalidWebhookSignatureError=m1;s$.toFile=p_;s$.Completions=a8;s$.Chat=vJ;s$.Embeddings=t8;s$.Files=e8;s$.Images=_9;s$.Audio=r1;s$.Moderations=G9;s$.Models=Q9;s$.FineTuning=O1;s$.Graders=dJ;s$.VectorStores=z2;s$.Webhooks=Z9;s$.Beta=B1;s$.Batches=r8;s$.Uploads=lJ;s$.Responses=L2;s$.Realtime=P2;s$.Conversations=mJ;s$.Evals=cJ;s$.Containers=uJ;s$.Videos=X9;function iy($){function J(U,Q){if(typeof U!=="string")return"";let _=U.trim();if(!_)return"";if(/^data:/i.test(_)||/^https?:\/\//i.test(_))return _;if(typeof Q==="string"&&Q.trim())return`data:${Q.trim()};base64,${_}`;return _}if(typeof $==="string")return $.trim().length===0?"":$;if($===null||$===void 0)return"";if(typeof $==="object"&&"type"in $){let U=$;if(U.type==="text"&&U.text)return U.text;if(U.type==="image"){let Q=J(U.data??U.source?.data,U.mimeType??U.source?.media_type??U.source?.mimeType);if(!Q)return"";return[{type:"image_url",image_url:{url:Q}}]}}if(Array.isArray($)){let U=[];for(let Q of $)if(typeof Q==="string")U.push({type:"text",text:Q});else if(Q&&typeof Q==="object"&&"type"in Q){let _=Q;if(_.type==="text"&&_.text)U.push({type:"text",text:_.text});else if(_.type==="image"){let G=J(_.data??_.source?.data,_.mimeType??_.source?.media_type??_.source?.mimeType);if(G)U.push({type:"image_url",image_url:{url:G}})}}return U.length>0?U:""}return String($)}function ry($){return{...$,content:iy($.content)}}function ny($,J){if(typeof J==="string"&&/deepseek/i.test(J))return!0;return/^deepseek-/i.test($)}function K9($={}){let J=$.baseUrl;function U(){if(typeof $.apiKey==="function"){let Y=$.apiKey();if(typeof Y==="string"){let K=Y.trim();if(!K)throw new r4("Missing apiKey",{code:"missing_api_key",retryable:!1});return K}if(Y!=null)throw new r4("Invalid apiKey provider",{code:"invalid_api_key",retryable:!1})}if(typeof $.apiKey==="string"){let Y=$.apiKey.trim();if(!Y)throw new r4("Missing apiKey",{code:"missing_api_key",retryable:!1});return Y}let Z=typeof process<"u"?process.env?.OPENAI_API_KEY:void 0;if(typeof Z!=="string"||!Z.trim())throw new r4("Missing OPENAI_API_KEY",{code:"missing_api_key",retryable:!1});return Z.trim()}function Q(){if(!(typeof globalThis.window<"u"))return!1;let Y=typeof process<"u"&&!!process?.versions?.node,K=typeof globalThis.Bun<"u"||typeof process<"u"&&!!process?.versions?.bun;return Y||K}function _(){let Z=U(),Y=Q();if(typeof J==="string"&&/\/chat\/completions\/?$/.test(J))return new s$({apiKey:Z,dangerouslyAllowBrowser:Y,organization:$.organization,project:$.project,baseURL:"https://api.openai.com/v1",fetch:(F,N)=>{return fetch(J,N)}});return new s$({apiKey:Z,dangerouslyAllowBrowser:Y,organization:$.organization,project:$.project,baseURL:J||void 0})}function G(Z){return{provider:"openai",modelId:Z.model.modelId}}function V(Z){if(Z instanceof r4)return Z;let Y=typeof Z?.status==="number"?Z.status:void 0,K=typeof Z?.message==="string"?Z.message:"OpenAI error",F=typeof Z?.code==="string"?Z.code:Y?`openai_http_${Y}`:"openai_error",N=Y?AJ.isRetryableStatus(Y):!1;return new r4(K,{code:F,retryable:N,status:Y})}async function*X(Z){let{request:Y}=Z,K=Y.requestId||mU("req"),F=_(),N=Y.model.modelId,q=$.compat?.interleavedThinking,H=typeof q==="boolean"?q:ny(N,J),E=Y.stream!==!1,D=[];if(Y.messages&&Array.isArray(Y.messages)){let f=-1;for(let R=Y.messages.length-1;R>=0;R--)if(Y.messages[R].role==="user"){f=R;break}for(let R=0;R<Y.messages.length;R++){let I=Y.messages[R],w=ry(I),T=R<f;if(w&&typeof w==="object"&&w.role==="assistant"){if(T){if("reasoning_content"in w)delete w.reasoning_content}else if(!H){if("reasoning_content"in w)delete w.reasoning_content}else if(Array.isArray(w?.tool_calls)&&w.tool_calls.length>0){let z=w.reasoning_content;if(typeof z!=="string"||z.length===0)w.reasoning_content="."}}D.push(w)}}else{if(typeof Y.instructions==="string"&&Y.instructions.length>0)D.push({role:"system",content:Y.instructions});D.push({role:"user",content:Y.input})}let B=(()=>{let f=Y.reasoning?.effort;if(typeof f!=="string")return;if(f==="none"||f==="minimal"||f==="low"||f==="medium"||f==="high"||f==="xhigh")return f;return})(),j={model:N,messages:D,stream:E,stream_options:E?{include_usage:!0}:void 0,metadata:Y.metadata??void 0,reasoning_effort:B,max_completion_tokens:Y.maxOutputTokens??void 0,stop:Y.stop??void 0,temperature:Y.temperature??void 0,top_p:Y.topP??void 0};if(Y.tools&&Array.isArray(Y.tools)&&Y.tools.length>0)j.tools=Y.tools;try{let f=G(Y);if(yield{type:"response_start",requestId:K,model:f},!E){let O=await F.chat.completions.create({...j,stream:!1},{signal:Y.signal,timeout:Y.timeoutMs}),M=Array.isArray(O?.choices)?O.choices[0]:void 0,P=M?.message,A=typeof P?.reasoning_content==="string"?P.reasoning_content:"";if(A.length>0)yield{type:"delta",requestId:K,chunk:{kind:"thinking_start"}},yield{type:"delta",requestId:K,chunk:{kind:"thinking_delta",text:A}},yield{type:"delta",requestId:K,chunk:{kind:"thinking_end",text:A}};let k=typeof P?.content==="string"?P.content:"";if(k.length>0)yield{type:"delta",requestId:K,chunk:{kind:"text",text:k}};let L=Array.isArray(P?.tool_calls)?P.tool_calls:[];for(let C=0;C<L.length;C++){let b=L[C],y=typeof b?.id==="string"?b.id:`call_${C}`,x=typeof b?.function?.name==="string"?b.function.name:void 0,c=typeof b?.function?.arguments==="string"?b.function.arguments:void 0;if(c||x)yield{type:"delta",requestId:K,chunk:{kind:"tool_call_delta",callId:y,toolId:x,argsTextDelta:c}}}let v=nD(M?.finish_reason);yield{type:"response_end",requestId:K,stopReason:v,usage:O?.usage};return}let R=await F.chat.completions.create({...j,stream:!0},{signal:Y.signal,timeout:Y.timeoutMs}),I=null,w,T=new Map,z=!1,S="";for await(let O of R){if(O?.usage!=null)w=O.usage;let M=Array.isArray(O?.choices)?O.choices:[];for(let P of M){if(P?.finish_reason!=null)I=P.finish_reason;let A=P?.delta,k=A?.reasoning_content;if(typeof k==="string"&&k.length>0){if(!z)z=!0,yield{type:"delta",requestId:K,chunk:{kind:"thinking_start"}};S+=k,yield{type:"delta",requestId:K,chunk:{kind:"thinking_delta",text:k}}}let L=A?.content;if(typeof L==="string"&&L.length>0){if(z)z=!1,yield{type:"delta",requestId:K,chunk:{kind:"thinking_end",text:S||void 0}};yield{type:"delta",requestId:K,chunk:{kind:"text",text:L}}}let v=Array.isArray(A?.tool_calls)?A.tool_calls:[];for(let C of v){let b=typeof C?.index==="number"?C.index:0,x=T.get(b)||(typeof C?.id==="string"?C.id:`call_${b}`);T.set(b,x);let c=typeof C?.function?.name==="string"?C.function.name:void 0,s=typeof C?.function?.arguments==="string"?C.function.arguments:void 0;if(c||s)yield{type:"delta",requestId:K,chunk:{kind:"tool_call_delta",callId:x,toolId:c,argsTextDelta:s}}}}}if(z)yield{type:"delta",requestId:K,chunk:{kind:"thinking_end",text:S||void 0}};yield{type:"response_end",requestId:K,stopReason:nD(I),usage:w}}catch(f){if(f?.name==="AbortError")throw new r4("Aborted",{code:"aborted",retryable:!1});throw V(f)}}return{provider:"openai",defaultModelId:$.defaultModelId,stream:X}}function nD($){if($==="tool_calls"||$==="function_call")return"tool_call";if($==="length")return"length";if($==="content_filter")return"error";if($==="stop"||$==null)return"final";return"final"}class qQ{queue=[];waiters=[];enqueue($){let J=this.waiters.shift();if(J){J($);return}this.queue.push($)}isEmpty(){return this.queue.length===0}async dequeueOrWait($){if(this.queue.length>0)return this.queue.shift();return new Promise((J)=>{let U=setTimeout(()=>{let Q=this.waiters.indexOf(J);if(Q>=0)this.waiters.splice(Q,1);J(void 0)},$);this.waiters.push((Q)=>{clearTimeout(U),J(Q)})})}}class MY{tools;options;eventQueue=new qQ;constructor($,J){this.tools=$;this.options=J}async*executeTasksInParallel($,J,U){this.eventQueue=new qQ;let Q=!1,_=$.map(async(X)=>{let Z=X.toolCall.function.name,Y=this.tools?.get(Z);if(!Y)return{tc:X,result:`Tool "${Z}" not found`,isError:!0};try{let K=typeof X.toolCall.function.arguments==="string"?JSON.parse(X.toolCall.function.arguments):X.toolCall.function.arguments,F=`${J.sessionId}:subagent:${crypto.randomUUID()}`,N={...U,sessionId:F,emitEvent:(H)=>{this.eventQueue.enqueue({...H,sessionId:J.sessionId})}},q=await Y.execute(K,N);return{tc:X,result:q,isError:!1}}catch(K){return{tc:X,result:`Task execution failed: ${K instanceof Error?K.message:String(K)}`,isError:!0}}}),G=Promise.allSettled(_).then((X)=>{return Q=!0,X});while(!Q||!this.eventQueue.isEmpty()){let X=await this.eventQueue.dequeueOrWait(5);if(X)yield X}let V=await G;for(let[X,Z]of V.entries()){let Y=$[X];if(Z.status==="fulfilled"){let{result:K,isError:F}=Z.value;Y.result=K,Y.isError=F}else Y.result=`Task execution rejected: ${Z.reason}`,Y.isError=!0;if(!this.options.hasAssistantToolCallMessage(J,Y.toolCall.id))this.options.addAssistantMessageWithToolCalls(J);yield{type:"tool_result",tool_call_id:Y.toolCall.id,result:Y.result,isError:Y.isError,sessionId:J.sessionId},this.options.addToolResultToHistory(J,Y)}}}class iJ{hooks;constructor($){this.hooks=$??{}}async executePreToolUse($){let J=this.hooks.preToolUse;if(!J)return{allow:!0};return await J($)}async executePostToolUse($,J){let U=this.hooks.postToolUse;if(!U)return;await U($,J)}async executePostToolUseFailure($,J){let U=this.hooks.postToolUseFailure;if(!U)return;await U($,J)}}class LY{options;toolEventQueue=[];constructor($){this.options=$}_log(...$){if(this.options.log)this.options.log(...$)}createToolExecutionContext($,J,U,Q){return{sessionId:$.sessionId,toolCallId:U,toolName:Q,signal:J,usage:$.usage,emitEvent:(_)=>{this.toolEventQueue.push({..._,sessionId:$.sessionId})}}}async executeToolCall($,J,U,Q,_){u1(U,`Tool execution: ${$.toolCall.function.name}`);let G=Q?new iJ(Q):void 0,V=$.toolCall.id,X=$.toolCall,Z=X,Y=(q)=>({sessionId:J.sessionId,toolCall:q,toolContext:J});if(_){if(!_.allow)return $.result="Tool execution blocked by PreToolUse hook",$.isError=!0,{type:"tool_result",tool_call_id:V,result:$.result,isError:!0,sessionId:J.sessionId};if(_.modifiedToolCall)Z={..._.modifiedToolCall,id:V,type:X.type}}else if(G){let q=await G.executePreToolUse(Y(Z));if(!q.allow)return $.result="Tool execution blocked by PreToolUse hook",$.isError=!0,{type:"tool_result",tool_call_id:V,result:$.result,isError:!0,sessionId:J.sessionId};if(q.modifiedToolCall)Z={...q.modifiedToolCall,id:V,type:X.type}}let K=this.options.tools?.get(Z.function.name);if(!K)return this._log(`Tool NOT FOUND: ${Z.function.name}`),$.result=`Tool not found: ${Z.function.name}`,$.isError=!0,{type:"tool_result",tool_call_id:V,result:$.result,isError:!0,sessionId:J.sessionId};let F;try{F=typeof Z.function.arguments==="string"?Z.function.arguments.trim()===""?{}:JSON.parse(Z.function.arguments):Z.function.arguments??{}}catch(q){this._log(`Warning: Failed to parse tool arguments for ${Z.function.name}, using empty object`),F={}}let N={...J,toolCallId:V,toolName:Z.function.name};try{if($.result=await K.execute(F,N),$.isError=!1,G)await G.executePostToolUse(Y(Z),$.result);return{type:"tool_result",tool_call_id:V,result:$.result,sessionId:J.sessionId}}catch(q){let H=q instanceof Error?q:Error(String(q));if(this._log(`Tool execution threw ERROR: ${Z.function.name} - ${H.message}`),$.result=H.message,$.isError=!0,G)await G.executePostToolUseFailure(Y(Z),H);return{type:"tool_result",tool_call_id:V,result:$.result,isError:!0,sessionId:J.sessionId}}}async*handleToolCalls($,J,U){let Q=$.pendingToolCalls.length,_=U?.signal,G=U?.toolContextInput,V=G?.approval,X=V?.decisions??{},Z=(B)=>{return this.options.approvalHandler.shouldRequireApproval(V,B)},Y=(B)=>{return $.messages.some((j)=>{if(!j||typeof j!=="object"||j.role!=="assistant")return!1;let f=j.tool_calls;return Array.isArray(f)&&f.some((R)=>R?.id===B)})},K=(B)=>{if(!Y(B))this.options.addAssistantMessageWithToolCalls($)},F=(B)=>{return $.messages.some((j)=>j&&typeof j==="object"&&j.role==="tool"&&j.tool_call_id===B)},N=new Set,q=(B)=>{try{return typeof B.function.arguments==="string"?JSON.parse(B.function.arguments):B.function.arguments}catch(j){let f=j instanceof Error?j.message:String(j);return{_raw:B.function.arguments,_parseError:f}}},H=(B)=>{let j=[];for(let f=B;f<$.pendingToolCalls.length;f++){let R=$.pendingToolCalls[f];if(F(R.toolCall.id))continue;if(N.has(R.toolCall.id))continue;if(X[R.toolCall.id])continue;let I=this.options.tools?.get(R.toolCall.function.name),w=I?.riskLevel??"safe";if(I&&this.options.isToolDisabled(R.toolCall.function.name))continue;if(I&&this.options.isToolBlocked($,R.toolCall.function.name))continue;if(!I||!Z(w))continue;N.add(R.toolCall.id),j.push({type:"tool_approval_requested",tool_call_id:R.toolCall.id,toolName:R.toolCall.function.name,riskLevel:w,args:q(R.toolCall),sessionId:$.sessionId})}return j};if($.metadata?.parallelMode===!0){let B=$.pendingToolCalls.filter((j)=>{let f=j.toolCall.function.name;return f==="Task"||f.endsWith("_Task")});if(B.length>1)yield*this.options.parallelTaskExecutor.executeTasksInParallel(B,$,J),$.pendingToolCalls=$.pendingToolCalls.filter((j)=>!B.includes(j))}let D=this.options.checkpointManager.hasStore();for(let B=0;B<$.pendingToolCalls.length;B++){let j=$.pendingToolCalls[B];if(F(j.toolCall.id)){$.pendingToolCalls.splice(B,1),B--;continue}let f=j.toolCall.function.name,R;if(U?.hooks?.preToolUse){let O=new iJ(U.hooks),M=(P)=>({sessionId:$.sessionId,toolCall:P,toolContext:J});if(R=await O.executePreToolUse(M(j.toolCall)),!R.allow){this._log(`Tool BLOCKED by preToolUse hook: ${f}`),j.result="Tool execution blocked by PreToolUse hook",j.isError=!0,K(j.toolCall.id),yield{type:"tool_result",tool_call_id:j.toolCall.id,result:j.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,j),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:`Tool blocked by preToolUse hook: ${f}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}}if(R?.modifiedToolCall)j.toolCall={...R.modifiedToolCall,id:j.toolCall.id,type:j.toolCall.type};let I=j.toolCall.function.name,w=this.options.tools?.get(I),T=w?.riskLevel??"safe";if(w&&this.options.isToolBlocked($,I)){let O=`Tool "${I}" is blocked by middleware`;this._log(`Tool BLOCKED: ${I} - ${O}`),j.result=`Tool execution skipped: ${O}`,j.isError=!0,K(j.toolCall.id),yield{type:"tool_skipped",tool_call_id:j.toolCall.id,toolName:I,reason:O,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:j.toolCall.id,result:j.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,j),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:`Tool blocked: ${I}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}if(w&&this.options.isToolDisabled(I)){let O=`Tool "${I}" is disabled for this session`;this._log(`Tool DISABLED: ${I}`),j.result=`Tool execution skipped: ${O}`,j.isError=!0,K(j.toolCall.id),yield{type:"tool_skipped",tool_call_id:j.toolCall.id,toolName:I,reason:O,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:j.toolCall.id,result:j.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,j),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:`Tool disabled: ${I}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}if(w&&Z(T)){let O=X[j.toolCall.id];if(!O){this._log(`Tool approval required: ${I} (risk: ${T})`),$.stopReason="approval_required";for(let P of H(B)){if(P.type==="tool_approval_requested")this._log(` - Requesting approval for: ${P.toolName}`);yield P}let M=await this.options.saveCheckpoint($,{phase:"approval_pending",status:`Waiting for approval: ${I}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});throw yield{type:"requires_action",kind:"tool_approval",checkpoint:D?void 0:M,checkpointRef:D?{sessionId:M.sessionId}:void 0,sessionId:$.sessionId},await this.options.persistSessionState($),yield{type:"done",finalResponse:$.currentResponse,stopReason:"approval_required",modelStopReason:$.lastModelStopReason,usage:{...$.usage},sessionId:$.sessionId},new RJ}if(!O.approved){let M=O.reason??"User denied approval";this._log(`Tool approval REJECTED: ${I} - ${M}`),j.result=`Tool execution skipped: ${M}`,j.isError=!0,K(j.toolCall.id),yield{type:"tool_skipped",tool_call_id:j.toolCall.id,toolName:j.toolCall.function.name,reason:M,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:j.toolCall.id,result:j.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,j),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:`Tool approval rejected: ${I}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}this._log(`Tool approval APPROVED: ${I}`)}K(j.toolCall.id),this._log(`Executing tool: ${I}`),this.toolEventQueue=[];let z=await this.executeToolCall(j,J,_,U?.hooks,R);for(let O of this.toolEventQueue)yield O;if(this.toolEventQueue=[],z.type==="tool_result")if(z.isError||z.result&&typeof z.result==="object"&&z.result.isError===!0){let M=typeof z.result==="string"?z.result:JSON.stringify(z.result);this._log(`Tool execution ERROR: ${I} - ${M.slice(0,100)}`)}else{let M=typeof z.result==="string"?z.result.slice(0,100):JSON.stringify(z.result).slice(0,100);this._log(`Tool execution SUCCESS: ${I} - ${M}${M.length>=100?"...":""}`)}let S=z.type==="tool_result"&&(z.isError||z.result&&typeof z.result==="object"&&z.result.isError===!0);if(w&&w.name==="AskUserQuestion"&&S){let O=G?.askUser?.rejected?.[j.toolCall.id];if(O!==void 0){let P=O||"User cancelled the question";this._log(`AskUser CANCELLED: ${P}`),j.result=`User cancelled the question: ${P}`,j.isError=!0,K(j.toolCall.id),yield{type:"tool_skipped",tool_call_id:j.toolCall.id,toolName:w.name,reason:P,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:j.toolCall.id,result:j.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,j),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:`AskUser cancelled: ${w.name}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}let M=G?.askUser?.answers?.[j.toolCall.id];if(!M){let A=(typeof j.toolCall.function.arguments==="string"?JSON.parse(j.toolCall.function.arguments):j.toolCall.function.arguments)?.questions||[];this._log(`AskUser waiting for answers (${A.length} questions)`),yield z,$.stopReason="approval_required";let k=await this.options.saveCheckpoint($,{phase:"approval_pending",status:`Waiting for user answers: ${w.name}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});throw await this.options.persistSessionState($),yield{type:"requires_action",kind:"ask_user",toolCallId:j.toolCall.id,questions:A,checkpoint:D?void 0:k,checkpointRef:D?{sessionId:k.sessionId}:void 0,sessionId:$.sessionId},yield{type:"done",finalResponse:$.currentResponse,stopReason:"approval_required",modelStopReason:$.lastModelStopReason,usage:{...$.usage},sessionId:$.sessionId},new RJ}else{let A={...typeof j.toolCall.function.arguments==="string"?JSON.parse(j.toolCall.function.arguments):j.toolCall.function.arguments,answers:M};j.toolCall.function.arguments=JSON.stringify(A),this.toolEventQueue=[];let k=await this.executeToolCall(j,J,_,U?.hooks,R);for(let L of this.toolEventQueue)yield L;this.toolEventQueue=[],yield k,this.options.addToolResultToHistory($,j),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:j.isError?`AskUser error: ${w.name}`:`AskUser completed: ${w.name}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}}yield z,this.options.addToolResultToHistory($,j),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:j.isError?`Tool error: ${I}`:`Tool completed: ${I}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams})}$.pendingToolCalls=[],$.iteration++,yield{type:"iteration_end",iteration:$.iteration-1,willContinue:!0,toolCallCount:Q,usage:{...$.usage},sessionId:$.sessionId}}}class HQ{static APPROVAL_REQUIRED_LEVELS=new Set(["high","critical"]);requiresApproval($){return HQ.APPROVAL_REQUIRED_LEVELS.has($)}shouldRequireApproval($,J){if($?.autoApprove===!0)return!1;if(($?.strategy??"high_risk")==="all")return!0;return this.requiresApproval(J)}}class zY{saveHandler;onError;constructor($,J){this.saveHandler=$;this.onError=J}async trigger(){try{await this.saveHandler()}catch($){let J=$ instanceof Error?$:Error(String($));console.warn("[Session] Auto-save failed:",J.message),this.onError?.(J)}}}var ay=1000;function oy($){if(!$)return;if($ instanceof r4)return{code:$.code,message:$.message,status:$.status,retryable:$.retryable};if($ instanceof Error){let J=$,U=typeof J.code==="string"?J.code:void 0,Q=typeof J.status==="number"?J.status:void 0,_=typeof J.retryable==="boolean"?J.retryable:void 0;return{code:U,message:$.message,status:Q,retryable:_}}return{message:String($)}}function aD($){let J=$?.function?.arguments;if(typeof J==="string")try{return JSON.parse(J),$}catch(U){let Q=U instanceof Error?U.message:String(U);return{...$,function:{...$.function,arguments:JSON.stringify({_raw:J,_parseError:Q})}}}if(J&&typeof J==="object")return{...$,function:{...$.function,arguments:JSON.stringify(J)}};return{...$,function:{...$.function,arguments:JSON.stringify(J??null)}}}function pD($){let J=!1,U=$.map((Q)=>{if(!Q||typeof Q!=="object"||Q.role!=="assistant")return Q;let _=Q.tool_calls;if(!Array.isArray(_)||_.length===0)return Q;let G=!1,V=_.map((X)=>{let Z=aD(X);if(Z!==X)G=!0;return Z});if(!G)return Q;return J=!0,{...Q,tool_calls:V}});return J?U:$}class M0 extends py{id;createdAt;status;title;updatedAt;lastActiveAt;errorMessage;configOverride;metadata;messages;toolCallCount;usage;responseCount;avgResponseTime;_stateStore;_checkpointManager;_approvalHandler;_parallelTaskExecutor;_toolExecutor;_autoSave;_autoSaveManager;_modelClient;_tools;_middlewares;_systemPrompt;_agentName;_onUsage;_pendingInput=null;_isReceiving=!1;_hooks;_modelOverride;_maxIterations;_requestParams;_emitSessionCreatedEvent;_sessionCreatedEventEmitted=!1;_abortController=null;_enableLogging;_checkpointOriginalMessages;_checkpointNewMessages=[];_checkpointSkipSnapshot;getDisabledToolNames(){let $=this.configOverride?.disabledTools;if(!$||$.length===0)return new Set;return new Set($)}isToolDisabled($){return this.getDisabledToolNames().has($)}collectBlockedTools($){let J=new Set;for(let U of this._middlewares)if(typeof U.__getBlockedTools==="function"){let Q=U.__getBlockedTools($);(Array.isArray(Q)?Q:Array.from(Q)).forEach((G)=>J.add(G))}return J}isToolBlocked($,J){let U=$.metadata?.blockedTools;if(!U)return!1;if(U instanceof Set)return U.has(J);if(Array.isArray(U))return U.includes(J);return!1}getToolsForModel($){let J=this._tools?.toOpenAIFormat();if(!J||J.length===0)return;let U=this.getDisabledToolNames(),Q=U.size===0?J:J.filter((G)=>!U.has(G.function.name)),_=$.metadata?.blockedTools;if(_&&_.size>0)Q=Q.filter((G)=>!_.has(G.function.name));return Q.length>0?Q:void 0}getEffectiveSystemPrompt(){let $=this.configOverride?.systemPromptOverride;if(typeof $==="string")return $;return this._systemPrompt}_log(...$){if(this._enableLogging){let J=this._agentName?`[GoatChain:Session:${this._agentName}:${this.id.slice(0,8)}]`:`[GoatChain:Session:${this.id.slice(0,8)}]`;console.warn(J,...$)}}constructor($,J,U,Q){super();if(this._stateStore=$,this._checkpointManager=new hX($),this._approvalHandler=new HQ,this.id=J,U)this.createdAt=U.createdAt,this.restoreFromSnapshot(U);else{let _=Date.now();this.createdAt=_,this.status="active",this.updatedAt=_,this.lastActiveAt=_,this.messages=[],this.toolCallCount=0,this.metadata=void 0,this.usage={promptTokens:0,completionTokens:0,totalTokens:0},this.responseCount=0}this._autoSave=!0,this._autoSaveManager=new zY(()=>this.save(),(_)=>{this.emit("auto-save-failed",{error:_})}),this._modelClient=Q?.modelClient,this._tools=Q?.tools,this._middlewares=Q?.middlewares??[],this._systemPrompt=Q?.systemPrompt,this._agentName=Q?.agentName,this._onUsage=Q?.onUsage,this._hooks=Q?.hooks,this._modelOverride=Q?.model,this._maxIterations=Q?.maxIterations,this._requestParams=Q?.requestParams,this._emitSessionCreatedEvent=Q?.emitSessionCreatedEvent===!0,this._enableLogging=Q?.enableLogging??!1,this._parallelTaskExecutor=new MY(this._tools,{hasAssistantToolCallMessage:(_,G)=>this.hasAssistantToolCallMessage(_,G),addAssistantMessageWithToolCalls:(_)=>this.addAssistantMessageWithToolCalls(_),addToolResultToHistory:(_,G)=>this.addToolResultToHistory(_,G)}),this._toolExecutor=new LY({tools:this._tools,approvalHandler:this._approvalHandler,checkpointManager:this._checkpointManager,saveCheckpoint:(_,G)=>this.saveCheckpointForState(_,G),parallelTaskExecutor:this._parallelTaskExecutor,isToolDisabled:(_)=>this.isToolDisabled(_),isToolBlocked:(_,G)=>this.isToolBlocked(_,G),addAssistantMessageWithToolCalls:(_)=>this.addAssistantMessageWithToolCalls(_),addToolResultToHistory:(_,G)=>this.addToolResultToHistory(_,G),persistSessionState:(_)=>this.persistSessionState(_),log:(..._)=>this._log(..._)})}async hasCheckpoint(){try{return await this._checkpointManager.loadCheckpoint(this.id)!=null}catch{return!1}}send($,J){if(this._ensureRuntimeConfigured(!0),this._isReceiving)throw Error("Cannot send while receiving messages");if(this._pendingInput)throw Error("Pending input already exists; call receive() to consume it before sending another message");let U=typeof $==="string"?$:JSON.stringify($);this._log("send() called with input:",U.slice(0,100)+(U.length>100?"...":"")),this._pendingInput={input:$,options:J}}cancel(){if(this._abortController)this._abortController.abort("Session cancelled by user")}async*receive($){if(this._isReceiving)throw Error("Cannot receive concurrently");let J=await this._checkpointManager.loadCheckpoint(this.id).catch(()=>null),U=J!=null;if(!U&&!this._pendingInput)throw Error("Nothing to receive; call send() first (or resume from a session that has a checkpoint)");this._log(`receive() started, hasCheckpoint: ${U}, hasPendingInput: ${!!this._pendingInput}`),this._abortController=new AbortController;let Q=this._abortController.signal;this._isReceiving=!0;try{if(this._emitSessionCreatedEvent&&!this._sessionCreatedEventEmitted)this._sessionCreatedEventEmitted=!0,yield{type:"session_created",sessionId:this.id};if(U&&this._pendingInput){this._log("Resuming from checkpoint with new user message");let{input:_,options:G}=this._pendingInput;this._pendingInput=null;let V=uU(J);if(V.sessionId!==this.id)V.sessionId=this.id;V.shouldContinue=!0,V.stopReason=void 0,V.metadata={...V.metadata,_pendingUserInput:_};let X=this._requestParams??J.requestParams,Z=G??$,Y=this.buildAutoRejectToolContext(V,Z?.toolContext);if(!(yield*this._streamWithPauseDetection(V,{maxIterations:this._maxIterations,signal:Q,model:this.getRuntimeModelOverride(),toolContext:Y,hooks:this._hooks,requestParams:X})))await this._finalizeRun(V,Date.now());return}if(U){this._log("Resuming from checkpoint without new message");let _=uU(J);if(_.sessionId!==this.id)_.sessionId=this.id;let G=this._requestParams??J.requestParams,V=this.buildAutoRejectToolContext(_,$?.toolContext);if(!(yield*this._streamWithPauseDetection(_,{maxIterations:this._maxIterations,signal:Q,model:this.getRuntimeModelOverride(),toolContext:V,hooks:this._hooks,requestParams:G})))await this._finalizeRun(_,Date.now());return}if(this._pendingInput){this._log("Starting new message flow");let{input:_,options:G}=this._pendingInput;this._pendingInput=null,yield*this._stream(_,G)}}catch(_){if(_ instanceof W2){yield{type:"done",finalResponse:"",stopReason:"cancelled",usage:{promptTokens:0,completionTokens:0,totalTokens:0},sessionId:this.id};return}throw _}finally{this._isReceiving=!1,this._abortController=null}}async*receiveWithApprovals($,J){let U=J?.toolContext,Q={...U??{},approval:{...U?.approval??{},decisions:{...U?.approval?.decisions??{},...$}}};yield*this.receive({...J,toolContext:Q})}async*_stream($,J){this._ensureRuntimeConfigured(!0);let U=Date.now(),Q=this.getRuntimeModelOverride(),_=this._abortController?.signal;if(!this.title&&this.messages.length===0){let Z=this.extractTextFromContent($);if(Z)this.title=this.createTitle(Z)}let G=this.messages.filter((Z)=>Z.role!=="system");this._log(`Starting agent loop with ${G.length} existing messages`);let V=y_({sessionId:this.id,input:$,messages:G},this.getEffectiveSystemPrompt()??"");if(!(yield*this._streamWithPauseDetection(V,{maxIterations:this._maxIterations,signal:_,model:Q,toolContext:J?.toolContext,hooks:this._hooks,requestParams:this._requestParams})))await this._finalizeRun(V,U)}async*_streamWithPauseDetection($,J){try{return yield*this._streamWithState($,J),!1}catch(U){if(U instanceof RJ)return this.messages=$.messages.filter((Q)=>Q.role!=="system"),!0;throw U}}resolveModelRef($){if($.provider)return{provider:$.provider,modelId:$.modelId};let J=this._modelClient?.modelRef?.provider;if(J)return{provider:J,modelId:$.modelId};return}buildAutoRejectToolContext($,J){if($.pendingToolCalls.length===0)return J??{};let U={},Q={};for(let _ of $.pendingToolCalls){let G=_.toolCall.id,V=_.toolCall.function.name;if(!J?.approval?.decisions?.[G])U[G]={approved:!1,reason:"Auto-rejected: session resumed without tool context"};if(V==="AskUserQuestion"&&!J?.askUser?.answers?.[G])Q[G]="Auto-rejected: session resumed without user answers"}if(Object.keys(U).length===0&&Object.keys(Q).length===0)return J??{};return{...J,approval:{...J?.approval,decisions:{...J?.approval?.decisions,...U}},askUser:{answers:J?.askUser?.answers??{},rejected:{...J?.askUser?.rejected,...Q}}}}getRuntimeModelOverride(){if(this.configOverride?.model){let $=this.resolveModelRef(this.configOverride.model);if($)return $}return this._modelOverride}_ensureRuntimeConfigured($){if(!this._modelClient)throw Error("Session is not configured with a model client");if($&&this.getEffectiveSystemPrompt()===void 0)throw Error("Session is not configured with a system prompt")}extractTextFromContent($){if(typeof $==="string")return $;if(Array.isArray($))return $.filter((J)=>J.type==="text").map((J)=>J.text).join(" ");if($&&typeof $==="object"&&$.type==="text")return $.text||"";return""}createTitle($,J=50){let U=$.trim();if(U.length<=J)return U;return`${U.substring(0,J).trim()}...`}_recordUsage($){if(this._onUsage)this._onUsage($)}async executeModelStream($,J,U,Q,_){if(!this._modelClient)throw Error("Session is not configured with a model client");let G=[],V=$.sessionId,X=new Map,Z=!1,Y=!1,K=(j)=>{let f=X.get(j);if(f)return f;let R={argsText:"",started:!1};return X.set(j,R),R},F=(j,f)=>{let R=K(j);if(f&&!R.toolName)R.toolName=f;if(!R.started)R.started=!0,this._log(`Stream: tool_call_start - ${R.toolName} (${j.slice(0,8)})`),G.push({type:"tool_call_start",callId:j,toolName:R.toolName,sessionId:V})},N=(j,f,R)=>{let I=K(j);if(f&&!I.toolName)I.toolName=f;if(typeof R==="string"&&R.length>0)I.argsText+=R;F(j,I.toolName),G.push({type:"tool_call_delta",callId:j,toolName:I.toolName,argsTextDelta:R,sessionId:V})},q=()=>{if(Z)return;Z=!0,this._log("Stream: text_start"),G.push({type:"text_start",sessionId:V})},H=()=>{if(!Z||Y)return;Y=!0;let j=$.currentResponse.slice(0,50)+($.currentResponse.length>50?"...":"");this._log(`Stream: text_end - "${j}"`),G.push({type:"text_end",content:$.currentResponse,sessionId:V})},E=()=>{for(let[j,f]of X){if(!f.toolName)continue;let R={id:j,type:"function",function:{name:f.toolName,arguments:f.argsText}};if(this._tools){$.pendingToolCalls.push({toolCall:R});let I=f.argsText.slice(0,100)+(f.argsText.length>100?"...":"");this._log(`Stream: tool_call_end - ${f.toolName} with args: ${I}`)}G.push({type:"tool_call_end",toolCall:R,sessionId:V})}X.clear()},D=(()=>{if(!_)return;let j={..._};if(typeof j.maxOutputTokens!=="number"&&typeof _.maxTokens==="number")j.maxOutputTokens=_.maxTokens;return delete j.maxTokens,j})(),B=Q?{model:Q,messages:pD($.messages),tools:U,signal:J,...D??{}}:{messages:pD($.messages),tools:U,signal:J,...D??{}};try{for await(let j of this._modelClient.stream(B))if(u1(J,"Session streaming"),j.type==="delta"){if(j.chunk.kind==="text")q(),$.currentResponse+=j.chunk.text,G.push({type:"text_delta",delta:j.chunk.text,sessionId:V});else if(j.chunk.kind==="thinking_start")this._log("Stream: thinking_start"),G.push({type:"thinking_start",sessionId:V});else if(j.chunk.kind==="thinking_delta")$.currentThinking=($.currentThinking??"")+j.chunk.text,G.push({type:"thinking_delta",delta:j.chunk.text,sessionId:V});else if(j.chunk.kind==="thinking_end"){let f=typeof j.chunk.text==="string"?j.chunk.text:"";if(f&&typeof $.currentThinking!=="string")$.currentThinking=f;let R=typeof $.currentThinking==="string"?$.currentThinking:f,I=R?R.slice(0,50)+(R.length>50?"...":""):"";this._log(`Stream: thinking_end - "${I}"`),G.push({type:"thinking_end",sessionId:V,...R?{content:R}:{}})}else if(j.chunk.kind==="tool_call_delta")N(j.chunk.callId,j.chunk.toolId,j.chunk.argsTextDelta)}else if(j.type==="response_end"){this._log(`Stream: response_end - stopReason: ${j.stopReason}`),H(),E(),$.lastModelStopReason=j.stopReason;let f=j.usage;if(f&&typeof f==="object"){let R=f;if(R.prompt_tokens||R.completion_tokens||R.total_tokens){let I={promptTokens:R.prompt_tokens??0,completionTokens:R.completion_tokens??0,totalTokens:R.total_tokens??0};$.usage.promptTokens=I.promptTokens,$.usage.completionTokens=I.completionTokens,$.usage.totalTokens+=I.totalTokens,this._recordUsage(I)}}}else if(j.type==="error"){if(j.terminal!==!1){let f=j.error?.code??"model_error",R=j.error?.message??"Model error",I=new r4(R,{code:f,retryable:j.error?.retryable});$.error=I,$.shouldContinue=!1,$.stopReason="error"}}}catch(j){if(j instanceof W2)throw j;if(J?.aborted)throw new W2(typeof J?.reason==="string"?J.reason:"Agent execution aborted");$.error=j instanceof Error?j:Error(String(j)),$.shouldContinue=!1,$.stopReason="error"}finally{if(H(),X.size>0)E()}return G}mergeStateResults($,J){if($.currentResponse=J.currentResponse,$.currentThinking=J.currentThinking,$.pendingToolCalls=J.pendingToolCalls,$.usage=J.usage,$.metadata=J.metadata,$.shouldContinue=J.shouldContinue,$.stopReason=J.stopReason,$.lastModelStopReason=J.lastModelStopReason,$.error=J.error,this._checkpointSkipSnapshot=J._skipMessageSnapshot,this._checkpointOriginalMessages&&!this._checkpointSkipSnapshot){let U=this._checkpointOriginalMessages;$.messages=[...U,...this._checkpointNewMessages]}else $.messages=J.messages}appendMessage($,J){if($.messages.push(J),this._checkpointOriginalMessages&&!this._checkpointSkipSnapshot)this._checkpointNewMessages.push(J)}getCheckpointMessages($){if(this._checkpointSkipSnapshot||!this._checkpointOriginalMessages)return $.messages;return[...this._checkpointOriginalMessages,...this._checkpointNewMessages]}async saveCheckpointForState($,J){let U=C_($,{agentName:this._agentName,phase:J?.phase,status:J?.status,modelConfig:J?.modelConfig,requestParams:J?.requestParams,messages:this.getCheckpointMessages($)});return await this._checkpointManager.saveCheckpoint(U),U}addToolResultToHistory($,J){let U=J.result,Q,_=J.isError;if(typeof U==="string")Q=U;else if(U&&typeof U==="object"&&"content"in U){let G=U;if(Q=JSON.stringify(G.content),G.isError===!0)_=!0}else Q=JSON.stringify(U);this.appendMessage($,{role:"tool",tool_call_id:J.toolCall.id,content:Q,..._?{isError:!0}:{}})}addAssistantMessageWithToolCalls($){let J=typeof $.currentThinking==="string"?$.currentThinking:void 0;this.appendMessage($,{role:"assistant",content:$.currentResponse||"",tool_calls:$.pendingToolCalls.map((U)=>aD(U.toolCall)),...J&&J.length>0?{reasoning_content:J}:{}})}addFinalAssistantMessage($){if($.currentResponse){let J=typeof $.currentThinking==="string"?$.currentThinking:void 0;this.appendMessage($,{role:"assistant",content:$.currentResponse,...J&&J.length>0?{reasoning_content:J}:{}})}}async persistSessionState($){this.messages=$.messages.filter((J)=>J.role!=="system"),await this.save()}async*_streamWithState($,J){let U=J.maxIterations??ay,Q=J.signal,_=b_(this._middlewares),G=this._toolExecutor.createToolExecutionContext($,Q),V=this._stateStore,X=V?.deleteOnComplete??!0,Z=J.model?{modelId:J.model.modelId,provider:J.model.provider}:this._modelClient?{modelId:this._modelClient.modelId}:void 0,Y=async(K)=>{if(!V)return;await this.saveCheckpointForState($,{phase:K?.phase,status:K?.status,modelConfig:Z,requestParams:J.requestParams})};while($.shouldContinue){if(u1(Q,`Session iteration ${$.iteration}`),$.iteration>=U){this._log(`Max iterations (${U}) reached`),$.shouldContinue=!1,$.stopReason="max_iterations",yield{type:"done",finalResponse:$.currentResponse,stopReason:"max_iterations",modelStopReason:$.lastModelStopReason,usage:{...$.usage},sessionId:$.sessionId};break}if(this._log(`Iteration ${$.iteration} started, pending tool calls: ${$.pendingToolCalls.length}`),yield{type:"iteration_start",iteration:$.iteration,sessionId:$.sessionId},this._checkpointOriginalMessages=structuredClone($.messages),this._checkpointNewMessages=[],this._checkpointSkipSnapshot=$._skipMessageSnapshot,$.pendingToolCalls.length>0){if(this._log(`Executing ${$.pendingToolCalls.length} tool calls`),yield*this._toolExecutor.handleToolCalls($,G,{signal:Q,toolContextInput:J.toolContext,hooks:J.hooks,checkpointModelConfig:Z,requestParams:J.requestParams}),$.metadata?._pendingUserInput){let N=$.metadata._pendingUserInput;delete $.metadata._pendingUserInput,this.appendMessage($,{role:"user",content:N})}continue}if($.metadata?._pendingUserInput){let N=$.metadata._pendingUserInput;delete $.metadata._pendingUserInput,this.appendMessage($,{role:"user",content:N})}$.currentResponse="",$.currentThinking=void 0,$.pendingToolCalls=[],$.lastModelStopReason=void 0,await Y();let K=[],F=await _({...$,messages:structuredClone($.messages)},async(N)=>{u1(Q,"Session model call");let q=this.collectBlockedTools(N);N.metadata.blockedTools=q;let H=this.getToolsForModel(N),E=H?.length??0;return this._log(`Calling model with ${N.messages.length} messages and ${E} tools`),K=await this.executeModelStream(N,Q,H,J.model,J.requestParams),this._log(`Model response: ${N.currentResponse.slice(0,100)}${N.currentResponse.length>100?"...":""}, tool calls: ${N.pendingToolCalls.length}`),N});this.mergeStateResults($,F);for(let N of K)yield N;if(u1(Q,`Session iteration ${$.iteration}`),$.stopReason==="error"){yield{type:"iteration_end",iteration:$.iteration,willContinue:!1,toolCallCount:$.pendingToolCalls.length,usage:{...$.usage},sessionId:$.sessionId},yield{type:"done",finalResponse:$.currentResponse,stopReason:"error",modelStopReason:$.lastModelStopReason,error:oy($.error),usage:{...$.usage},sessionId:$.sessionId};break}if($.pendingToolCalls.length>0)yield*this._toolExecutor.handleToolCalls($,G,{signal:Q,toolContextInput:J.toolContext,hooks:J.hooks,checkpointModelConfig:Z,requestParams:J.requestParams});else yield*this.handleFinalResponse($);if(await Y(),!$.shouldContinue){if(this._log(`Agent loop finished. Stop reason: ${$.stopReason}`),V&&X)await V.deleteCheckpoint($.sessionId);break}}}hasAssistantToolCallMessage($,J){return $.messages.some((U)=>{if(!U||typeof U!=="object"||U.role!=="assistant")return!1;let Q=U.tool_calls;return Array.isArray(Q)&&Q.some((_)=>_?.id===J)})}async*handleFinalResponse($){$.shouldContinue=!1,$.stopReason="final_response",this.addFinalAssistantMessage($),yield{type:"iteration_end",iteration:$.iteration,willContinue:!1,toolCallCount:0,usage:{...$.usage},sessionId:$.sessionId},yield{type:"done",finalResponse:$.currentResponse,stopReason:"final_response",modelStopReason:$.lastModelStopReason,usage:{...$.usage},sessionId:$.sessionId}}async _finalizeRun($,J){if(this.messages=$.messages.filter((Q)=>Q.role!=="system"),$.usage.totalTokens>0)this.addUsage($.usage);let U=Date.now()-J;this.recordResponse(U),await this.save()}getLastMessagePreview($=100){if(this.messages.length===0)return;let J=this.messages[this.messages.length-1],U=typeof J.content==="string"?J.content:JSON.stringify(J.content);return U.length>$?`${U.substring(0,$)}...`:U}toSnapshot(){let $={status:this.status,updatedAt:this.updatedAt,lastActiveAt:this.lastActiveAt,title:this.title,errorMessage:this.errorMessage},J={messages:[...this.messages],messageCount:this.messages.length,lastMessagePreview:this.getLastMessagePreview(),toolCallCount:this.toolCallCount},U={usage:{...this.usage},responseCount:this.responseCount,avgResponseTime:this.avgResponseTime};return{id:this.id,createdAt:this.createdAt,state:$,configOverride:this.configOverride?{...this.configOverride}:void 0,context:J,stats:U,metadata:this.metadata?{...this.metadata}:void 0}}restoreFromSnapshot($){this.status=$.state.status,this.updatedAt=$.state.updatedAt,this.lastActiveAt=$.state.lastActiveAt,this.title=$.state.title,this.errorMessage=$.state.errorMessage,this.configOverride=$.configOverride?{...$.configOverride}:void 0,this.metadata=$.metadata&&typeof $.metadata==="object"?{...$.metadata}:void 0,this.messages=[...$.context.messages],this.toolCallCount=$.context.toolCallCount,this.usage={...$.stats.usage},this.responseCount=$.stats.responseCount,this.avgResponseTime=$.stats.avgResponseTime}async save(){let $=this.toSnapshot();await this._stateStore.save(this.id,I6.SESSION,$)}async load(){let $=await this._stateStore.load(this.id,I6.SESSION);if($)return this.restoreFromSnapshot($),!0;return!1}triggerAutoSave(){this._autoSaveManager.trigger()}setStatus($,J){if(this.status=$,this.errorMessage=J,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}markActive(){if(this.lastActiveAt=Date.now(),this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}addMessage($){if(this.messages.push($),this.markActive(),this._autoSave)this.triggerAutoSave()}addUsage($){if(this.usage.promptTokens=$.promptTokens,this.usage.completionTokens=$.completionTokens,this.usage.totalTokens+=$.totalTokens,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}recordResponse($){let J=(this.avgResponseTime??0)*this.responseCount;if(this.responseCount++,this.avgResponseTime=(J+$)/this.responseCount,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}incrementToolCallCount(){if(this.toolCallCount++,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}setModelOverride($){if(!this.configOverride)this.configOverride={};if(this.configOverride.model=$,this.updatedAt=Date.now(),this._modelOverride=this.resolveModelRef($)??this._modelOverride,this._autoSave)this.triggerAutoSave()}clearModelOverride(){if(this.configOverride)delete this.configOverride.model,this.updatedAt=Date.now();if(this._modelOverride=void 0,this._autoSave)this.triggerAutoSave()}setSystemPromptOverride($){if(!this.configOverride)this.configOverride={};if(this.configOverride.systemPromptOverride=$,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}clearSystemPromptOverride(){if(this.configOverride)delete this.configOverride.systemPromptOverride,this.updatedAt=Date.now();if(this._autoSave)this.triggerAutoSave()}disableTools($){if(!this.configOverride)this.configOverride={};if(this.configOverride.disabledTools=[...this.configOverride.disabledTools??[],...$],this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}enableAllTools(){if(this.configOverride)delete this.configOverride.disabledTools,this.updatedAt=Date.now();if(this._autoSave)this.triggerAutoSave()}setAutoSave($){this._autoSave=$}}class c5{}import{randomUUID as ty}from"node:crypto";class BQ extends c5{_stateStore;constructor($){super();this._stateStore=$}async create($){let J=$??ty(),U=Date.now(),Q=(()=>{try{let V=globalThis?.process;return typeof V?.cwd==="function"?String(V.cwd()):void 0}catch{return}})(),_={id:J,createdAt:U,state:{status:"active",updatedAt:U,lastActiveAt:U},context:{messages:[],messageCount:0,toolCallCount:0},stats:{usage:{promptTokens:0,completionTokens:0,totalTokens:0},responseCount:0},metadata:Q?{cwd:Q}:void 0},G=new M0(this._stateStore,J,_);return await G.save(),G}async get($){let J=await this._stateStore.load($,I6.SESSION);if(!J)return;return new M0(this._stateStore,$,J)}async list(){let $=await this._stateStore.listSessions(),J=[];for(let U of $){let Q=await this._stateStore.load(U,I6.SESSION);if(Q){let _=new M0(this._stateStore,U,Q);J.push(_)}}return J}async destroy($){await this._stateStore.deleteSession($)}}import{existsSync as R2,mkdirSync as oD,readdirSync as RY,readFileSync as sy,rmSync as AY,writeFileSync as ey}from"node:fs";import nJ from"node:path";class rJ{deleteOnComplete;constructor($){this.deleteOnComplete=$?.deleteOnComplete??!0}assertValidStorageSegment($,J){if(!J)throw Error(`${$} must be a non-empty string`);if(J==="."||J==="..")throw Error(`${$} must not be "." or ".."`);if(J.includes("/")||J.includes("\\"))throw Error(`${$} must not contain path separators`);if(J.includes("\x00"))throw Error(`${$} must not contain NUL bytes`)}async save($,J,U){let Q=this.buildPath($,J),_=JSON.stringify(U,null,2);await this._write(Q,_)}async load($,J){let U=this.buildPath($,J),Q=await this._read(U);if(Q===void 0)return;try{return JSON.parse(Q)}catch{return}}async delete($,J){let U=this.buildPath($,J);await this._delete(U)}async deleteSession($){let J=this.buildPrefix($),U=await this._list(J);await Promise.all(U.map((Q)=>this._delete(Q)))}async listKeys($){let J=this.buildPrefix($);return(await this._list(J)).map((Q)=>this.extractKey($,Q))}async exists($,J){let U=this.buildPath($,J);return this._exists(U)}async saveCheckpoint($){let J={_meta:{description:"GoatChain Agent Loop Checkpoint - DO NOT EDIT MANUALLY",savedAt:new Date().toISOString(),agentName:$.agentName,sessionId:$.sessionId,iteration:$.iteration,phase:$.phase,status:$.status,messageCount:$.messages.length,toolCallsPending:$.pendingToolCalls?.length??0},checkpoint:$};await this.save($.sessionId,I6.CHECKPOINT,J)}async loadCheckpoint($){return(await this.load($,I6.CHECKPOINT))?.checkpoint}async deleteCheckpoint($){await this.delete($,I6.CHECKPOINT)}async listCheckpoints(){let $=await this.listSessions(),J=[];for(let U of $){let Q=await this.loadCheckpoint(U);if(Q)J.push(Q)}return J}async listSessions(){let $=await this._list(""),J=new Set;for(let U of $){let Q=this.extractSessionId(U);if(Q)J.add(Q)}return Array.from(J)}buildPath($,J){return this.assertValidStorageSegment("sessionId",$),this.assertValidStorageSegment("key",J),`${$}/${J}`}buildPrefix($){return this.assertValidStorageSegment("sessionId",$),`${$}/`}extractKey($,J){let U=this.buildPrefix($);return J.startsWith(U)?J.slice(U.length):J}extractSessionId($){let J=$.split("/");return J.length>0?J[0]:void 0}}class A2 extends rJ{baseDir;constructor($){super($);this.baseDir=nJ.resolve($.dir),this.ensureDir(this.baseDir)}async _write($,J){let U=this.toFilePath($);this.ensureDir(nJ.dirname(U)),ey(U,J,"utf-8")}async _read($){let J=this.toFilePath($);try{if(!R2(J))return;return sy(J,"utf-8")}catch{return}}async _delete($){let J=this.toFilePath($);if(R2(J))AY(J);let U=nJ.dirname(J);if(R2(U))try{if(RY(U).length===0)AY(U,{recursive:!0})}catch{}}async _exists($){let J=this.toFilePath($);return R2(J)}async _list($){let J=[];if(!R2(this.baseDir))return J;let U=RY(this.baseDir,{withFileTypes:!0}).filter((Q)=>Q.isDirectory()).map((Q)=>Q.name);for(let Q of U){if($&&!Q.startsWith($.split("/")[0]))continue;let _=nJ.join(this.baseDir,Q),G=this.listJsonFiles(_);for(let V of G){let X=nJ.basename(V,".json"),Z=`${Q}/${X}`;if(!$||Z.startsWith($))J.push(Z)}}return J}toFilePath($){return nJ.join(this.baseDir,`${$}.json`)}ensureDir($){if(!R2($))oD($,{recursive:!0})}listJsonFiles($){if(!R2($))return[];return RY($).filter((J)=>J.endsWith(".json")).map((J)=>nJ.join($,J))}getBaseDir(){return this.baseDir}clear(){if(R2(this.baseDir))AY(this.baseDir,{recursive:!0}),oD(this.baseDir,{recursive:!0})}}class w2 extends rJ{store=new Map;constructor($){super($)}async _write($,J){this.store.set($,J)}async _read($){return this.store.get($)}async _delete($){this.store.delete($)}async _exists($){return this.store.has($)}async _list($){let J=[];for(let U of this.store.keys())if($===""||U.startsWith($))J.push(U);return J}clear(){this.store.clear()}stats(){let $=new Set;for(let J of this.store.keys()){let U=this.extractSessionId(J);if(U)$.add(U)}return{entryCount:this.store.size,sessionCount:$.size}}}class j1{id;name;systemPrompt;createdAt;_model;_modelOverride;_tools;_stateStore;_sessionManager;_middlewares=[];_middlewareCounter=0;_middlewareTools=new Map;_enableLogging;_initializationPromise=null;_initialized=!1;constructor($){this.id=$.id??crypto.randomUUID(),this.name=$.name,this.systemPrompt=$.systemPrompt,this.createdAt=Date.now(),this._model=$.model,this._tools=$.tools,this._stateStore=$.stateStore??new w2,this._enableLogging=$.enableLogging??!1,this._sessionManager=new BQ(this._stateStore),this._log(`Agent created: ${this.name} (id: ${this.id})`);let J=$.middleware??[];if(J.length>0)this._initializationPromise=this._initializeMiddleware(J)}async _initializeMiddleware($){for(let J of $)await this.use(J);this._initialized=!0}async _ensureInitialized(){if(this._initializationPromise&&!this._initialized)await this._initializationPromise}_log(...$){if(this._enableLogging)console.warn(`[GoatChain:Agent:${this.name}]`,...$)}get model(){return this._model}get modelId(){return this.modelRef?.modelId??this._model.modelId}get modelRef(){return this._modelOverride??this._model.modelRef}get tools(){return this._tools}get stateStore(){return this._stateStore}get sessionManager(){return this._sessionManager}async createSession($){if(await this._ensureInitialized(),!this._sessionManager)throw Error("SessionManager is not configured");let J=await this._sessionManager.create($?.sessionId);if(!this._stateStore)throw Error("StateStore is required to create sessions");this._log(`Creating new session: ${J.id}`);let U=J.toSnapshot();return new M0(this._stateStore,J.id,U,{...$,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map((Q)=>Q.fn),emitSessionCreatedEvent:!0,enableLogging:this._enableLogging})}async resumeSession($,J){if(!this._sessionManager)throw Error("SessionManager is not configured");let U=await this._sessionManager.get($);if(!U)throw Error(`Session not found: ${$}`);if(!this._stateStore)throw Error("StateStore is required to resume sessions");this._log(`Resuming session: ${$}`);let Q=U.toSnapshot();return new M0(this._stateStore,U.id,Q,{...J,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map((_)=>_.fn),emitSessionCreatedEvent:!1,enableLogging:this._enableLogging})}async use($,J){let U=J??$.__middlewareName??`middleware_${this._middlewareCounter++}`;if(this._middlewares.some((_)=>_.name===U))throw Error(`Middleware with name "${U}" already exists`);let Q={name:U,fn:$};if(this._middlewares.push(Q),this._log(`Middleware registered: ${U}`),$.__createTools&&typeof $.__createTools==="function")await this._registerMiddlewareTools(U,$.__createTools);return()=>{this.removeMiddleware(U)}}removeMiddleware($){let J=-1,U;if(typeof $==="string")J=this._middlewares.findIndex((Q)=>Q.name===$),U=$;else if(J=this._middlewares.findIndex((Q)=>Q.fn===$),J>-1)U=this._middlewares[J].name;if(J>-1&&U)return this._unregisterMiddlewareTools(U),this._middlewares.splice(J,1),!0;return!1}clearMiddlewares(){for(let $ of this._middlewareTools.keys())this._unregisterMiddlewareTools($);this._middlewares=[]}get middlewares(){return[...this._middlewares]}get middlewareNames(){return this._middlewares.map(($)=>$.name)}setModel($){if(((U)=>{return Boolean(U&&typeof U==="object"&&typeof U.provider==="string"&&typeof U.modelId==="string"&&typeof U.stream!=="function")})($))this._modelOverride=$;else this._model=$,this._modelOverride=void 0}_getNamespacedToolName($,J){return`${$}_${J}`}async _registerMiddlewareTools($,J){if(!this._tools)return;let U=await J(),Q=[];for(let _ of U){let G=this._getNamespacedToolName($,_.name),V=Object.create(Object.getPrototypeOf(_));Object.assign(V,_),Object.defineProperty(V,"name",{value:G,writable:!1,configurable:!0});try{this._tools.register(V),Q.push(G)}catch(X){console.warn(`Failed to register tool ${G}:`,X)}}if(Q.length>0)this._middlewareTools.set($,Q)}_unregisterMiddlewareTools($){if(!this._tools)return;let J=this._middlewareTools.get($);if(!J)return;for(let U of J)this._tools.unregister(U);this._middlewareTools.delete($)}}import{readFile as _g}from"node:fs/promises";import Qg from"node:path";import Gg from"node:process";var Vg=["AGENTS.md","CLAUDE.md"],Xg="[Project Agent Rules]";async function Yg($,J){let U=[];for(let Q of J)try{let _=Qg.resolve($,Q),G=await _g(_,"utf-8");if(G.trim())U.push(G.trim())}catch{continue}return U.length>0?U.join(`
|
|
87
|
-
|
|
88
|
-
---
|
|
89
|
-
|
|
90
|
-
`):""}function OQ($){let{cwd:J,ruleFiles:U=Vg,marker:Q=Xg}=$??{},_=async(G,V)=>{let X=typeof J==="function"?J():J??Gg.cwd(),Z=await Yg(X,U),Y=G.messages;if(Z)Y=h1(Y,Z,Q);let K={...G,messages:Y};return V(K)};return _.__middlewareName="agent-rules",_}import{execSync as H6}from"node:child_process";import{unlinkSync as Zg,writeFileSync as Kg}from"node:fs";import{tmpdir as Ng}from"node:os";import{join as Fg}from"node:path";function wY($){try{return H6("git rev-parse --git-dir",{cwd:$,stdio:"pipe"}),!0}catch{return!1}}function tD($){try{return H6("git add --all",{cwd:$,encoding:"utf-8"}),H6("git diff --staged --name-only",{cwd:$,encoding:"utf-8"}).trim().split(`
|
|
91
|
-
`).filter(Boolean)}catch(J){throw Error(`Failed to stage files: ${J instanceof Error?J.message:String(J)}`)}}function sD($){try{return H6("git diff --staged",{cwd:$,encoding:"utf-8"})}catch(J){throw Error(`Failed to get diff: ${J instanceof Error?J.message:String(J)}`)}}function fY($){try{return H6("git diff --staged --name-only",{cwd:$,encoding:"utf-8"}).trim().length>0}catch{return!1}}function eD($){try{let J=H6("git diff --staged --name-status",{cwd:$,encoding:"utf-8"});if(!J.trim())return[];return J.trim().split(`
|
|
92
|
-
`).filter(Boolean).map((U)=>{let Q=U.split("\t"),_=Q[0].charAt(0);if(_==="R"||_==="C")return{file:Q[2],status:_,oldFile:Q[1]};return{file:Q[1],status:_}})}catch{return[]}}function kY($){try{if(H6("git diff --name-only",{cwd:$,encoding:"utf-8"}).trim().length>0)return!0;return H6("git ls-files --others --exclude-standard",{cwd:$,encoding:"utf-8"}).trim().length>0}catch{return!1}}function $E($,J){try{let U=Fg(Ng(),`goatchain-commit-${Date.now()}.txt`);Kg(U,$,"utf-8");try{return H6(`git commit -F "${U}"`,{cwd:J,stdio:"pipe"}),H6("git rev-parse HEAD",{cwd:J,encoding:"utf-8"}).trim()}finally{try{Zg(U)}catch{}}}catch(U){throw Error(`Failed to create commit: ${U instanceof Error?U.message:String(U)}`)}}function IY($){try{let J=H6("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8"}).trim();return J==="HEAD"?null:J}catch{return null}}function Wg($,J="origin"){try{return H6("git remote",{cwd:$,encoding:"utf-8"}).split(`
|
|
93
|
-
`).map((Q)=>Q.trim()).includes(J)}catch{return!1}}function qg($){try{return H6("git rev-parse --abbrev-ref --symbolic-full-name @{u}",{cwd:$,encoding:"utf-8"}).trim()||null}catch{return null}}function JE($,J="origin"){try{return H6(`git fetch ${J}`,{cwd:$,stdio:"pipe"}),!0}catch{return!1}}function Hg($){try{let J=H6("git rev-list --left-right --count @{u}...HEAD",{cwd:$,encoding:"utf-8"}).trim(),[U,Q]=J.split(/\s+/).map((_)=>Number.parseInt(_,10));return{ahead:Q||0,behind:U||0,hasUpstream:!0}}catch{return{ahead:0,behind:0,hasUpstream:!1}}}function Bg($){try{let J=H6("git status --porcelain",{cwd:$,encoding:"utf-8"});return/^(?:UU|AA|DD|AU|UA|DU|UD)\s/m.test(J)}catch{return!1}}function Og($){try{let J=H6("git status --porcelain",{cwd:$,encoding:"utf-8"}),U=[],Q=J.split(`
|
|
94
|
-
`);for(let _ of Q){let G=_.match(/^(?:UU|AA|DD|AU|UA|DU|UD)\s+(\S.*)$/);if(G)U.push(G[1].trim())}return U}catch{return[]}}function jg($){try{try{return H6("git rev-parse --verify MERGE_HEAD",{cwd:$,stdio:"pipe"}),{inMerge:!0,type:"merge"}}catch{}try{return H6("test -d .git/rebase-merge -o -d .git/rebase-apply",{cwd:$,stdio:"pipe"}),{inMerge:!0,type:"rebase"}}catch{}try{return H6("git rev-parse --verify CHERRY_PICK_HEAD",{cwd:$,stdio:"pipe"}),{inMerge:!0,type:"cherry-pick"}}catch{}return{inMerge:!1,type:null}}catch{return{inMerge:!1,type:null}}}function SY($){let J={canCommit:!0,isGitRepo:!1,hasChanges:!1,hasConflicts:!1,conflictFiles:[],inMergeState:!1,mergeStateType:null,hasRemote:!1,hasUpstream:!1,ahead:0,behind:0,isDiverged:!1,currentBranch:null,warnings:[],errors:[]};if(J.isGitRepo=wY($),!J.isGitRepo)return J.canCommit=!1,J.errors.push("Not a git repository"),J;if(J.currentBranch=IY($),!J.currentBranch)J.warnings.push("Detached HEAD state - no branch checked out");let U=jg($);if(J.inMergeState=U.inMerge,J.mergeStateType=U.type,J.inMergeState)J.warnings.push(`Currently in ${J.mergeStateType} state`);if(J.hasConflicts=Bg($),J.hasConflicts)J.conflictFiles=Og($),J.canCommit=!1,J.errors.push(`Unresolved conflicts in ${J.conflictFiles.length} file(s): ${J.conflictFiles.join(", ")}`);if(J.hasChanges=kY($)||fY($),!J.hasChanges&&!J.inMergeState)J.canCommit=!1,J.errors.push("No changes to commit");if(J.hasRemote=Wg($),J.hasRemote){let Q=qg($);if(J.hasUpstream=!!Q,J.hasUpstream){let _=Hg($);if(J.ahead=_.ahead,J.behind=_.behind,J.isDiverged=J.ahead>0&&J.behind>0,J.behind>0)J.warnings.push(`Local branch is ${J.behind} commit(s) behind remote`);if(J.isDiverged)J.warnings.push(`Branch has diverged: ${J.ahead} ahead, ${J.behind} behind`)}else J.warnings.push("No upstream branch configured")}return J}var Dg="You are a commit message generator. You print plain text without code blocks and don't talk.";function Eg($,J,U){if(U)return U.replace("[DIFF_CONTENT]",$).replace("[LANGUAGE]",J);return`Analyze the following staged diffs and craft a conventional commit message in ${J}.
|
|
95
|
-
|
|
96
|
-
Staged Diffs:
|
|
97
|
-
\`\`\`diff
|
|
98
|
-
${$}
|
|
99
|
-
\`\`\`
|
|
100
|
-
|
|
101
|
-
Requirements:
|
|
102
|
-
- Title: Under 50 characters with appropriate type (feat/fix/docs/style/refactor/test/chore)
|
|
103
|
-
- Body: List changes in categories (Added/Changed/Fixed/Removed/etc.) with lines under 70 chars
|
|
104
|
-
- Format exactly as:
|
|
105
|
-
|
|
106
|
-
<type>[optional scope]: <title>
|
|
107
|
-
|
|
108
|
-
Added (if applicable):
|
|
109
|
-
- [New features/modules]
|
|
110
|
-
|
|
111
|
-
Changed (if applicable):
|
|
112
|
-
- [Modifications to existing functionality]
|
|
113
|
-
|
|
114
|
-
Fixed (if applicable):
|
|
115
|
-
- [Bug fixes]
|
|
116
|
-
|
|
117
|
-
Security (if applicable):
|
|
118
|
-
- [Security improvements]`}function TY($){let J=[];if($.errors.length>0)J.push("❌ 错误 (Errors):"),$.errors.forEach((U)=>J.push(` • ${U}`));if($.warnings.length>0)J.push("⚠️ 警告 (Warnings):"),$.warnings.forEach((U)=>J.push(` • ${U}`));if($.conflictFiles.length>0)J.push(""),J.push("\uD83D\uDD00 冲突文件 (Conflict files):"),$.conflictFiles.forEach((U)=>J.push(` • ${U}`));if($.inMergeState)J.push(""),J.push(`\uD83D\uDCCC 当前状态: 正在进行 ${$.mergeStateType}`);if($.hasUpstream&&($.ahead>0||$.behind>0)){if(J.push(""),J.push("\uD83D\uDCCA 分支状态:"),$.ahead>0)J.push(` • 领先远程 ${$.ahead} 个提交`);if($.behind>0)J.push(` • 落后远程 ${$.behind} 个提交`)}return J.join(`
|
|
119
|
-
`)}function UE($){switch($){case"A":return"新增 (new file)";case"M":return"修改 (modified)";case"D":return"删除 (deleted)";case"R":return"重命名 (renamed)";case"C":return"复制 (copied)";case"T":return"类型变更 (typechange)";case"U":return"未合并 (unmerged)";default:return $}}function Pg($){if($.length===0)return"";let J=["\uD83D\uDCCB Changes to be committed (待提交的更改):",""],U={};for(let _ of $){let G=_.status;if(!U[G])U[G]=[];U[G].push(_)}let Q=["A","M","D","R","C","T","U"];for(let _ of Q){let G=U[_];if(!G||G.length===0)continue;J.push(` ${UE(_)}:`);for(let V of G)if(V.oldFile)J.push(` • ${V.oldFile} → ${V.file}`);else J.push(` • ${V.file}`);J.push("")}for(let[_,G]of Object.entries(U)){if(Q.includes(_))continue;J.push(` ${UE(_)}:`);for(let V of G)J.push(` • ${V.file}`);J.push("")}return J.push(` 共 ${$.length} 个文件 (Total: ${$.length} files)`),J.join(`
|
|
120
|
-
`)}function vY($){let J=$.name??"commit-mode",U=$.model,Q=$.defaultLanguage??"English",_=$.defaultAutoStage??!0,G=$.fetchBeforeCommit??!1,V=$.allowBehindRemote??!1,X=$.cwd??process.cwd(),Z=$.customPrompt,Y=async(K,F)=>{if(K.metadata?.commitProcessed)return F(K);try{let N=SY(X);if(!N.isGitRepo){let O={role:"assistant",content:`✗ 错误:当前目录不是 git 仓库。
|
|
121
|
-
|
|
122
|
-
Error: Not in a git repository. Please run this from within a git repository.`};return{...K,messages:[...K.messages,O],currentResponse:O.content,shouldContinue:!1,stopReason:"final_response",metadata:{...K.metadata,commitProcessed:!0,preCommitCheck:N}}}let q={fetched:!1,message:""};if(G&&N.hasRemote)if(JE(X)){q={fetched:!0,message:"已从远程获取最新更新"};let M=SY(X);Object.assign(N,{ahead:M.ahead,behind:M.behind,isDiverged:M.isDiverged})}else q={fetched:!1,message:"无法从远程获取更新(网络问题或无权限)"};if(N.hasConflicts){let O={role:"assistant",content:`✗ 存在未解决的冲突,无法提交。
|
|
123
|
-
|
|
124
|
-
❌ Cannot commit: Unresolved conflicts detected.
|
|
125
|
-
|
|
126
|
-
${TY(N)}
|
|
127
|
-
|
|
128
|
-
请先解决以上冲突文件,然后再次尝试提交。
|
|
129
|
-
Please resolve the conflicts above before committing.`};return{...K,messages:[...K.messages,O],currentResponse:O.content,shouldContinue:!1,stopReason:"final_response",metadata:{...K.metadata,commitProcessed:!0,preCommitCheck:N,hasConflicts:!0}}}if(N.inMergeState&&!N.hasChanges){let O={role:"assistant",content:`✗ 当前正在进行 ${N.mergeStateType},但没有暂存的更改。
|
|
130
|
-
|
|
131
|
-
❌ Currently in ${N.mergeStateType} state but no staged changes.
|
|
132
|
-
|
|
133
|
-
${TY(N)}
|
|
134
|
-
|
|
135
|
-
请先完成或取消当前的 ${N.mergeStateType} 操作。
|
|
136
|
-
Please complete or abort the current ${N.mergeStateType} operation.`};return{...K,messages:[...K.messages,O],currentResponse:O.content,shouldContinue:!1,stopReason:"final_response",metadata:{...K.metadata,commitProcessed:!0,preCommitCheck:N}}}if(!V&&N.behind>0){let O={role:"assistant",content:`⚠️ 本地分支落后于远程 ${N.behind} 个提交。
|
|
137
|
-
|
|
138
|
-
⚠️ Local branch is ${N.behind} commit(s) behind remote.
|
|
139
|
-
|
|
140
|
-
${TY(N)}
|
|
141
|
-
|
|
142
|
-
建议先执行 git pull 拉取最新更改,解决可能的冲突后再提交。
|
|
143
|
-
Recommend running 'git pull' first to get latest changes and resolve any conflicts before committing.
|
|
144
|
-
|
|
145
|
-
如需强制提交,请使用 allowBehindRemote: true 选项。`};return{...K,messages:[...K.messages,O],currentResponse:O.content,shouldContinue:!1,stopReason:"final_response",metadata:{...K.metadata,commitProcessed:!0,preCommitCheck:N,isBehindRemote:!0}}}if(_){if(kY(X))tD(X);else if(!fY(X)&&!N.inMergeState){let O={role:"assistant",content:`✗ 没有需要提交的更改。
|
|
146
|
-
|
|
147
|
-
No changes to commit. Working directory is clean.`};return{...K,messages:[...K.messages,O],currentResponse:O.content,shouldContinue:!1,stopReason:"final_response",metadata:{...K.metadata,commitProcessed:!0,preCommitCheck:N}}}}let H=eD(X),E=sD(X);if(!E||E.trim().length===0){let O={role:"assistant",content:`✗ 没有暂存的更改。
|
|
148
|
-
|
|
149
|
-
No staged changes to commit. Please stage files first or enable auto_stage.`};return{...K,messages:[...K.messages,O],currentResponse:O.content,shouldContinue:!1,stopReason:"final_response",metadata:{...K.metadata,commitProcessed:!0,preCommitCheck:N}}}if(!U.run)throw Error("Model does not support run() method");let D=Eg(E,Q,Z),B=[{role:"system",content:Dg},{role:"user",content:D}],f=(await U.run({messages:B})).text.trim();if(!f)throw Error("LLM returned empty commit message");let R=$E(f,X),I=Pg(H),w=q.fetched?`
|
|
150
|
-
|
|
151
|
-
\uD83D\uDCE1 ${q.message}`:"",T=N.warnings.length>0?`
|
|
152
|
-
|
|
153
|
-
⚠️ 注意事项:
|
|
154
|
-
${N.warnings.map((O)=>` • ${O}`).join(`
|
|
155
|
-
`)}`:"",z=N.currentBranch?`
|
|
156
|
-
分支: ${N.currentBranch}`:"",S={role:"assistant",content:`✓ 成功创建 commit
|
|
157
|
-
|
|
158
|
-
Commit Hash: ${R}${z}${w}${T}
|
|
159
|
-
|
|
160
|
-
${I}
|
|
161
|
-
|
|
162
|
-
Commit Message:
|
|
163
|
-
${f}`};return{...K,messages:[...K.messages,S],currentResponse:S.content,shouldContinue:!1,stopReason:"final_response",metadata:{...K.metadata,commitProcessed:!0,commitHash:R,commitMessage:f,preCommitCheck:N}}}catch(N){let q={role:"assistant",content:`✗ 创建 commit 失败
|
|
164
|
-
|
|
165
|
-
Error: ${N instanceof Error?N.message:String(N)}`};return{...K,messages:[...K.messages,q],currentResponse:q.content,shouldContinue:!1,stopReason:"error",metadata:{...K.metadata,commitProcessed:!0}}}};return Y.__middlewareName=J,Y}import{readdir as _E,readFile as Mg}from"node:fs/promises";import n1 from"node:path";import QE from"node:process";var Lg="[Environment Information]";async function zg($){try{let J=n1.join($,".gitignore"),U=await Mg(J,"utf-8"),Q=new Set;for(let _ of U.split(`
|
|
166
|
-
`)){let G=_.trim();if(G&&!G.startsWith("#"))Q.add(G)}return Q}catch{return new Set}}function GE($,J,U){if(J===".git")return!0;for(let Q of U)if(Q.endsWith("/")){let _=Q.slice(0,-1);if(J===_||$.startsWith(`${_}/`))return!0}else if(J===Q||$===Q)return!0;else if(Q.includes("*")){if(new RegExp(`^${Q.replace(/\*/g,".*")}$`).test(J))return!0}return!1}function VE($){return n1.extname($)||$}async function XE($,J,U,Q,_){try{let G=await _E($,{withFileTypes:!0}),V=n1.relative(Q.cwd,$),X=[],Z={},Y=0,K=G.sort((N,q)=>{if(N.isDirectory()&&!q.isDirectory())return-1;if(!N.isDirectory()&&q.isDirectory())return 1;return N.name.localeCompare(q.name)}),F=0;for(let N of K){if(F>=Q.maxEntriesPerDir)break;let q=n1.join($,N.name),H=n1.relative(Q.cwd,q);if(Q.respectGitignore&&GE(H,N.name,_))continue;if(N.isDirectory())if(U<Q.maxDepth){let E=await XE(q,J,U+1,Q,_);if(E){X.push(E),Y+=E.totalFiles;for(let[D,B]of Object.entries(E.fileStats))Z[D]=(Z[D]||0)+B}}else{let E=await YE(q,_,Q);X.push({name:N.name,path:H,children:[],fileStats:E.stats,totalFiles:E.total}),Y+=E.total;for(let[D,B]of Object.entries(E.stats))Z[D]=(Z[D]||0)+B}else{X.push({name:N.name,path:H});let E=VE(N.name);Z[E]=(Z[E]||0)+1,Y+=1}F++}return{name:n1.basename($),path:V||".",children:X,fileStats:Z,totalFiles:Y}}catch{return null}}async function YE($,J,U){let Q={},_=0;try{let G=await _E($,{withFileTypes:!0});for(let V of G){let X=n1.join($,V.name),Z=n1.relative(U.cwd,X);if(U.respectGitignore&&GE(Z,V.name,J))continue;if(V.isDirectory()){let Y=await YE(X,J,U);_+=Y.total;for(let[K,F]of Object.entries(Y.stats))Q[K]=(Q[K]||0)+F}else{let Y=VE(V.name);Q[Y]=(Q[Y]||0)+1,_+=1}}}catch{}return{total:_,stats:Q}}function Rg($,J){if(J===0)return"";let Q=Object.entries($).sort((_,G)=>G[1]-_[1]).slice(0,5).map(([_,G])=>`${G} ${_}`);return`[${J} files in subtree: ${Q.join(", ")}]`}function ZE($,J="",U=!0){let Q=[];if(U)Q.push(`${$.name}/`);for(let _=0;_<$.children.length;_++){let G=$.children[_];if("children"in G){let V=G;if(Q.push(`${J}${V.name}/`),V.totalFiles>0&&V.children.length===0){let X=Rg(V.fileStats,V.totalFiles);if(X)Q.push(`${J} ${X}`)}else if(V.children.length>0){let X=ZE(V,`${J} `,!1);Q.push(X)}}else{let V=G;Q.push(`${J}${V.name}`)}}return Q.join(`
|
|
167
|
-
`)}async function Ag($){try{let J=$.respectGitignore?await zg($.cwd):new Set,U=await XE($.cwd,$.cwd,0,$,J);if(!U)return"Unable to read directory structure";return ZE(U)}catch(J){return`Error generating file tree: ${J instanceof Error?J.message:String(J)}`}}function wg($){let J=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],U=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Q=J[$.getDay()],_=U[$.getMonth()],G=$.getDate().toString().padStart(2,"0"),V=$.getFullYear();return`${Q} ${_} ${G} ${V}`}async function fg($,J,U){let Q=[],_=[];_.push(`Working directory: ${$}`);let G=wY($);if(G){let V=IY($);if(V)_.push(`Is directory a git repo: yes, branch: ${V}`);else _.push("Is directory a git repo: yes")}else _.push("Is directory a git repo: no");if(_.push(`Platform: ${QE.platform}`),_.push(`Today's date: ${wg(new Date)}`),Q.push(`<env>
|
|
168
|
-
${_.join(`
|
|
169
|
-
`)}
|
|
170
|
-
</env>`),J&&G&&U){let V=await Ag(U);Q.push(`<files>
|
|
171
|
-
${V}
|
|
172
|
-
</files>`)}return Q.join(`
|
|
173
|
-
|
|
174
|
-
`)}function jQ($){let{cwd:J,marker:U=Lg,includeFileTree:Q=!0,maxDepth:_=3,maxEntriesPerDir:G=50,respectGitignore:V=!0}=$??{},X=async(Z,Y)=>{let K=typeof J==="function"?J():J??QE.cwd(),N=await fg(K,Q,{cwd:K,maxDepth:_,maxEntriesPerDir:G,respectGitignore:V}),q=Z.messages;if(N)q=h1(q,N,U);let H={...Z,messages:q};return Y(H)};return X.__middlewareName="env-info",X}function S4($){return{content:[{type:"text",text:$}],isError:!0}}class P4{riskLevel="safe"}class f2 extends P4{name="AskUserQuestion";riskLevel="safe";description=`Use this tool when you need to ask the user questions during execution. This allows you to:
|
|
175
|
-
1. Gather user preferences or requirements
|
|
176
|
-
2. Clarify ambiguous instructions
|
|
177
|
-
3. Get decisions on implementation choices as you work
|
|
178
|
-
4. Offer choices to the user about what direction to take
|
|
179
|
-
|
|
180
|
-
Usage notes:
|
|
181
|
-
- Users will always be able to select "Other" to provide custom text input
|
|
182
|
-
- Use multiSelect: true to allow multiple answers to be selected for a question
|
|
183
|
-
- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label`;parameters={type:"object",properties:{questions:{type:"array",items:{type:"object",properties:{question:{type:"string",description:'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'},header:{type:"string",maxLength:12,description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'},options:{type:"array",items:{type:"object",properties:{label:{type:"string",description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."},description:{type:"string",description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}},required:["label","description"]},minItems:2,maxItems:4,description:"The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no 'Other' option, that will be provided automatically."},multiSelect:{type:"boolean",description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."}},required:["question","header","options","multiSelect"]},minItems:1,maxItems:4,description:"Questions to ask the user (1-4 questions)"},answers:{type:"object",additionalProperties:{oneOf:[{type:"string"},{type:"array",items:{type:"string"}}]},description:"User answers collected by the permission component"}},required:["questions"]};async execute($,J){let{questions:U,answers:Q}=this.validateArgs($);if(!Q||Object.keys(Q).length===0)throw Error("AskUserTool.execute() was called without answers. This indicates a bug: Session should have intercepted this tool call and emitted a requires_action event. The tool should only be executed after the user provides answers via toolContext.");let _=this.formatAnswersMessage(U,Q);return{content:[{type:"text",text:_}],structuredContent:{success:!0,answers:Q,message:_}}}validateArgs($){let J=$.questions;if(!Array.isArray(J))throw TypeError("questions is required and must be an array");if(J.length<1||J.length>4)throw Error("questions must contain 1-4 items");let U=[];for(let _=0;_<J.length;_++){let G=J[_];if(typeof G!=="object"||G===null)throw TypeError(`questions[${_}] must be an object`);let{question:V,header:X,options:Z,multiSelect:Y}=G;if(typeof V!=="string"||!V.trim())throw Error(`questions[${_}].question is required and must be a non-empty string`);if(typeof X!=="string"||!X.trim())throw Error(`questions[${_}].header is required and must be a non-empty string`);if(X.length>12)throw Error(`questions[${_}].header must be at most 12 characters`);if(!Array.isArray(Z))throw TypeError(`questions[${_}].options must be an array`);if(Z.length<2||Z.length>4)throw Error(`questions[${_}].options must contain 2-4 items`);if(typeof Y!=="boolean")throw TypeError(`questions[${_}].multiSelect is required and must be a boolean`);let K=[];for(let F=0;F<Z.length;F++){let N=Z[F];if(typeof N!=="object"||N===null)throw TypeError(`questions[${_}].options[${F}] must be an object`);let{label:q,description:H}=N;if(typeof q!=="string"||!q.trim())throw Error(`questions[${_}].options[${F}].label is required and must be a non-empty string`);if(typeof H!=="string"||!H.trim())throw Error(`questions[${_}].options[${F}].description is required and must be a non-empty string`);K.push({label:q.trim(),description:H.trim()})}U.push({question:V.trim(),header:X.trim(),options:K,multiSelect:Boolean(Y)})}let Q;if($.answers&&typeof $.answers==="object"&&$.answers!==null){Q={};for(let[_,G]of Object.entries($.answers))if(typeof G==="string")Q[_]=G;else if(Array.isArray(G))Q[_]=G.map((V)=>String(V));else Q[_]=String(G)}return{questions:U,answers:Q}}formatAnswersMessage($,J){let U=[];for(let Q=0;Q<$.length;Q++){let _=$[Q],G=J[String(Q)];if(G===void 0)continue;U.push(`Question ${Q+1} (${_.header}): ${_.question}`);let V=this.formatAnswerText(G);if(V.inline!==void 0)U.push(`Answer: ${V.inline}`);else if(V.lines){U.push("Answer:");for(let X of V.lines)U.push(` ${X}`)}U.push("")}if(U.length===0)return"No answers received";if(U[U.length-1]==="")U.pop();return`User responses:
|
|
184
|
-
|
|
185
|
-
${U.join(`
|
|
186
|
-
`)}`}formatAnswerText($){if(Array.isArray($)){if($.length===0)return{inline:"(no response)"};if($.length===1){let U=String($[0]);if(U.includes(`
|
|
187
|
-
`))return{lines:U.split(`
|
|
188
|
-
`)};return{inline:U}}return{lines:this.formatArrayAnswer($.map((U)=>String(U)))}}let J=String($);if(J.includes(`
|
|
189
|
-
`))return{lines:J.split(`
|
|
190
|
-
`)};return{inline:J}}formatArrayAnswer($){let J=[];for(let U of $){let Q=U.split(`
|
|
191
|
-
`);J.push(`- ${Q[0]??""}`);for(let _=1;_<Q.length;_++)J.push(` ${Q[_]}`)}return J}}import og from"node:process";import{spawn as WE}from"node:child_process";import{chmodSync as kg,existsSync as a0,mkdirSync as Ig,statSync as Sg,unlinkSync as Tg}from"node:fs";import{writeFile as vg}from"node:fs/promises";import{createRequire as CY}from"node:module";import{homedir as KE}from"node:os";import L0 from"node:path";import B6 from"node:process";var Cg="ast-grep/ast-grep",qE="0.40.0",k2=["bash","c","cpp","csharp","css","elixir","go","haskell","html","java","javascript","json","kotlin","lua","nix","php","python","ruby","rust","scala","solidity","swift","typescript","tsx","yaml"],bg=300000,d5=1048576,NE=500,yg={"darwin-arm64":{arch:"aarch64",os:"apple-darwin"},"darwin-x64":{arch:"x86_64",os:"apple-darwin"},"linux-arm64":{arch:"aarch64",os:"unknown-linux-gnu"},"linux-x64":{arch:"x86_64",os:"unknown-linux-gnu"},"win32-x64":{arch:"x86_64",os:"pc-windows-msvc"},"win32-arm64":{arch:"aarch64",os:"pc-windows-msvc"},"win32-ia32":{arch:"i686",os:"pc-windows-msvc"}};function l5($){try{return Sg($).size>1e4}catch{return!1}}function gg(){return{"darwin-arm64":"@ast-grep/cli-darwin-arm64","darwin-x64":"@ast-grep/cli-darwin-x64","linux-arm64":"@ast-grep/cli-linux-arm64-gnu","linux-x64":"@ast-grep/cli-linux-x64-gnu","win32-x64":"@ast-grep/cli-win32-x64-msvc","win32-arm64":"@ast-grep/cli-win32-arm64-msvc","win32-ia32":"@ast-grep/cli-win32-ia32-msvc"}[`${B6.platform}-${B6.arch}`]??null}function xg(){try{return CY(import.meta.url)("@ast-grep/cli/package.json").version}catch{return qE}}function i5(){if(B6.platform==="win32"){let Q=B6.env.LOCALAPPDATA||B6.env.APPDATA||L0.join(KE(),"AppData","Local");return L0.join(Q,"goat-chain","bin")}let J=B6.env.XDG_CACHE_HOME||L0.join(KE(),".cache");return L0.join(J,"goat-chain","bin")}function bY(){return B6.platform==="win32"?"ast-grep.exe":"ast-grep"}function hg(){return B6.platform==="win32"?"sg.exe":"sg"}function ug(){let $=[bY(),hg()];return Array.from(new Set($))}function HE(){let $=i5();for(let J of ug()){let U=L0.join($,J);if(a0(U)&&l5(U))return U}return null}async function mg($,J){let U=B6.platform==="win32",Q=U?"powershell":"unzip",_=U?["-command",`Expand-Archive -Path '${$}' -DestinationPath '${J}' -Force`]:["-o",$,"-d",J],{exitCode:G,stderr:V}=await ig(Q,_);if(G!==0)throw Error(`zip extraction failed (exit ${G}): ${V}
|
|
192
|
-
|
|
193
|
-
${U?"Ensure PowerShell is available on your system.":"Please install 'unzip' (e.g., apt install unzip, brew install unzip)."}`)}async function cg($=qE){let J=`${B6.platform}-${B6.arch}`,U=yg[J];if(!U)return console.error(`[goat-chain] Unsupported platform for ast-grep: ${J}`),null;let Q=i5(),_=bY(),G=L0.join(Q,_);if(a0(G))return G;let{arch:V,os:X}=U,Z=`app-${V}-${X}.zip`,Y=`https://github.com/${Cg}/releases/download/${$}/${Z}`;console.log("[goat-chain] Downloading ast-grep binary...");try{if(!a0(Q))Ig(Q,{recursive:!0});let K=await fetch(Y,{redirect:"follow"});if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let F=L0.join(Q,Z),N=await K.arrayBuffer();if(await vg(F,Buffer.from(N)),await mg(F,Q),a0(F))Tg(F);if(B6.platform!=="win32"&&a0(G))kg(G,493);return console.log("[goat-chain] ast-grep binary ready."),G}catch(K){return console.error(`[goat-chain] Failed to download ast-grep: ${K instanceof Error?K.message:K}`),null}}async function BE(){let $=xg(),J=await cg($);if(J)p1=J,jE(J);return J}async function FE(){let $=HE();if($)return $;if(D1)return D1;return D1=(async()=>{try{return await BE()}finally{D1=null}})(),D1}function OE(){let $=bY(),J=HE();if(J&&l5(J))return J;try{let _=CY(import.meta.url).resolve("@ast-grep/cli/package.json"),G=L0.dirname(_),V=L0.join(G,$);if(a0(V)&&l5(V))return V}catch{}let U=gg();if(U)try{let _=CY(import.meta.url).resolve(`${U}/package.json`),G=L0.dirname(_),V=B6.platform==="win32"?"ast-grep.exe":"ast-grep",X=L0.join(G,V);if(a0(X)&&l5(X))return X}catch{}if(B6.platform==="darwin"){let Q=["/opt/homebrew/bin/ast-grep","/usr/local/bin/ast-grep","/opt/homebrew/bin/sg","/usr/local/bin/sg"];for(let _ of Q)if(a0(_)&&l5(_))return _}return null}var p1=null,D1=null;function dg(){if(p1!==null)return p1;let $=OE();if($)return p1=$,$;return"sg"}function jE($){p1=$}async function lg(){if(p1!==null&&a0(p1))return p1;if(D1)return D1;return D1=(async()=>{try{let $=OE();if($&&a0($))return p1=$,jE($),$;return await BE()}finally{D1=null}})(),D1}function ig($,J){return new Promise((U,Q)=>{let _=WE($,J,{stdio:["ignore","pipe","pipe"]}),G="",V="";_.stdout?.on("data",(X)=>{G+=X.toString()}),_.stderr?.on("data",(X)=>{V+=X.toString()}),_.on("error",(X)=>{Q(X)}),_.on("close",(X)=>{U({exitCode:X,stdout:G,stderr:V})})})}function rg($,J,U,Q){return new Promise((_,G)=>{let V=!1,X=!1,Z=[],Y=0,K=[],F=0;console.log("[goat-chain] Spawning process:",$,J,Q??B6.cwd());let N=WE($,J,{cwd:Q,stdio:["ignore","pipe","pipe"]}),q=setTimeout(()=>{V=!0,N.kill()},U);N.stdout?.on("data",(H)=>{if(Y>=d5){X=!0;return}let E=d5-Y;if(H.length>E)Z.push(H.subarray(0,E)),Y+=E,X=!0;else Z.push(H),Y+=H.length}),N.stderr?.on("data",(H)=>{if(F>=d5)return;let E=d5-F;if(H.length>E)K.push(H.subarray(0,E)),F+=E;else K.push(H),F+=H.length}),N.on("error",(H)=>{clearTimeout(q),G(H)}),N.on("close",(H)=>{clearTimeout(q),_({stdout:Buffer.concat(Z).toString(),stderr:Buffer.concat(K).toString(),exitCode:H,timedOut:V,outputTruncated:X})})})}function ng($){return $.code==="ENOENT"||$.message?.includes("ENOENT")||$.message?.includes("not found")||$.message?.includes("cannot execute")||$.message?.includes("Exec format error")||$.code==="EACCES"}function pg($,J){try{let U=JSON.parse($);return Array.isArray(U)?U:[]}catch{if(!J)return[]}try{let U=$.lastIndexOf("}");if(U>0){let Q=$.lastIndexOf("},",U);if(Q>0){let _=`${$.substring(0,Q+1)}]`,G=JSON.parse(_);return Array.isArray(G)?G:[]}}}catch{return null}return null}async function pJ($){console.log("[goat-chain] Running ast-grep command...",$);let J=$.jsonOutput!==!1,U=["run","-p",$.pattern,"--lang",$.lang];if(J)U.push("--json=compact");if($.rewrite){if(U.push("-r",$.rewrite),$.updateAll)U.push("--update-all")}if($.context&&$.context>0)U.push("-C",String($.context));if($.globs)for(let q of $.globs)U.push("--globs",q);let Q=$.paths&&$.paths.length>0?$.paths:["."];U.push(...Q);let _=bg,G=Boolean($.binaryPath),V=$.binaryPath??dg();if(!G&&!a0(V)&&V!=="sg"){let q=await lg();if(q)V=q}let X;try{X=await rg(V,U,_,$.cwd)}catch(q){let H=q;if(!G&&ng(H)){if(await FE())return pJ($);return{matches:[],totalMatches:0,truncated:!1,error:`ast-grep CLI binary not found or invalid.
|
|
194
|
-
|
|
195
|
-
Auto-download failed. Manual install options:
|
|
196
|
-
pnpm install --force # Re-run postinstall scripts
|
|
197
|
-
bun add -D @ast-grep/cli
|
|
198
|
-
cargo install ast-grep --locked
|
|
199
|
-
brew install ast-grep
|
|
200
|
-
|
|
201
|
-
See docs/TROUBLESHOOTING.md for more information.`}}return{matches:[],totalMatches:0,truncated:!1,error:`Failed to spawn ast-grep: ${H.message}`}}if(X.timedOut)return{matches:[],totalMatches:0,truncated:!0,truncatedReason:"timeout",error:`Search timeout after ${_}ms`,exitCode:X.exitCode,stderr:X.stderr};if(!J){let q=X.stdout.trim(),H=X.stderr.trim();if(X.exitCode!==0){let E=H||q||`ast-grep exited with code ${X.exitCode}`;return{matches:[],totalMatches:0,truncated:X.outputTruncated,truncatedReason:X.outputTruncated?"max_output_bytes":void 0,error:E,exitCode:X.exitCode,stderr:X.stderr}}return{matches:[],totalMatches:0,truncated:X.outputTruncated,truncatedReason:X.outputTruncated?"max_output_bytes":void 0,exitCode:X.exitCode,stderr:X.stderr}}if(X.exitCode!==0&&X.stdout.trim()===""){if(X.stderr.includes("No files found"))return{matches:[],totalMatches:0,truncated:!1,exitCode:X.exitCode,stderr:X.stderr};let q=X.stderr.toLowerCase();if(!G&&(q.includes("command not found")||q.includes("cannot execute")||q.includes("exec format error")||q.includes("permission denied"))){if(await FE())return pJ($)}if(X.stderr.trim())return{matches:[],totalMatches:0,truncated:!1,error:X.stderr.trim(),exitCode:X.exitCode,stderr:X.stderr};return{matches:[],totalMatches:0,truncated:!1,exitCode:X.exitCode,stderr:X.stderr}}if(!X.stdout.trim())return{matches:[],totalMatches:0,truncated:!1,exitCode:X.exitCode,stderr:X.stderr};let Z=X.outputTruncated||Buffer.byteLength(X.stdout)>=d5,Y=pg(X.stdout,Z);if(Y===null)return{matches:[],totalMatches:0,truncated:!0,truncatedReason:"max_output_bytes",error:"Output too large and could not be parsed",exitCode:X.exitCode,stderr:X.stderr};let K=Y.length,F=K>NE;return{matches:F?Y.slice(0,NE):Y,totalMatches:K,truncated:Z||F,truncatedReason:Z?"max_output_bytes":F?"max_matches":void 0,exitCode:X.exitCode,stderr:X.stderr}}import DE from"node:path";function EE($,J){if(!$||!J)return $;let U=DE.relative(J,$);if(U&&!U.startsWith("..")&&!DE.isAbsolute(U))return U;return $}function PE($){if($.truncatedReason==="max_matches")return`showing first ${$.matches.length} of ${$.totalMatches}`;if($.truncatedReason==="max_output_bytes")return"output exceeded 1MB limit";if($.truncatedReason==="timeout")return"search timed out";return"output truncated"}function ag($){let J=($.lines??$.text??"").trim();return J?` ${J}`:""}function ME($,J){if($.error)return`Error: ${$.error}`;if($.matches.length===0)return"No matches found";let U=[];if($.truncated)U.push(`Results truncated (${PE($)})
|
|
202
|
-
`);U.push(`Found ${$.matches.length} match(es)${$.truncated?` (truncated from ${$.totalMatches})`:""}:
|
|
203
|
-
`);for(let Q of $.matches){let _=(Q.range?.start?.line??0)+1,G=(Q.range?.start?.column??0)+1,V=`${EE(Q.file,J)}:${_}:${G}`;U.push(V);let X=ag(Q);if(X)U.push(X);U.push("")}return U.join(`
|
|
204
|
-
`)}function yY($,J,U){if($.error)return`Error: ${$.error}`;if($.matches.length===0)return"No matches found to replace";let Q=J?"[DRY RUN] ":"",_=[];if($.truncated)_.push(`Results truncated (${PE($)})
|
|
205
|
-
`);_.push(`${Q}${$.matches.length} replacement(s):
|
|
206
|
-
`);for(let G of $.matches){let V=(G.range?.start?.line??0)+1,X=(G.range?.start?.column??0)+1,Z=`${EE(G.file,U)}:${V}:${X}`;_.push(Z);let Y=G.text?.trim();if(Y)_.push(` ${Y}`);_.push("")}if(J)_.push("Use dryRun=false to apply changes");return _.join(`
|
|
207
|
-
`)}function LE($,J){let U=$.trim();if(J==="python"){if(U.startsWith("class ")&&U.endsWith(":"))return`Hint: Remove trailing colon. Try: "${U.slice(0,-1)}"`;if((U.startsWith("def ")||U.startsWith("async def "))&&U.endsWith(":"))return`Hint: Remove trailing colon. Try: "${U.slice(0,-1)}"`}if(["javascript","typescript","tsx"].includes(J)){if(/^(?:export\s+)?(?:async\s+)?function\s+\$[A-Z_]+\s*$/i.test(U))return'Hint: Function patterns need params and body. Try "function $NAME($$$) { $$$ }"'}return null}class I2 extends P4{name="ast_grep_replace";riskLevel="high";description=`Replace code patterns across filesystem with AST-aware rewriting. Dry-run by default.
|
|
208
|
-
|
|
209
|
-
Usage notes:
|
|
210
|
-
- Use meta-variables in rewrite to preserve matched content
|
|
211
|
-
- Example: pattern='console.log($MSG)' rewrite='logger.info($MSG)'
|
|
212
|
-
- Set dryRun=false to apply changes`;parameters={type:"object",properties:{pattern:{type:"string",description:"AST pattern to match."},rewrite:{type:"string",description:"Replacement pattern (can use $VAR from pattern)."},lang:{type:"string",enum:[...k2],description:"Target language (ast-grep language identifier)."},paths:{type:"array",items:{type:"string"},description:'Paths to search (default: ["."]).'},globs:{type:"array",items:{type:"string"},description:"Include/exclude globs (prefix ! to exclude)."},dryRun:{type:"boolean",description:"Preview changes without applying (default: true)."}},required:["pattern","rewrite","lang"]};cwd;astGrepPath;constructor($){super();this.cwd=$?.cwd??og.cwd(),this.astGrepPath=$?.astGrepPath}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($,J){let U=this.validateArgs($),Q=U.dryRun!==!1,_=await pJ({pattern:U.pattern,rewrite:U.rewrite,lang:U.lang,paths:U.paths,globs:U.globs,updateAll:!1,cwd:this.cwd,binaryPath:this.astGrepPath});if(!Q&&!_.error&&_.matches.length>0){let X=await pJ({pattern:U.pattern,rewrite:U.rewrite,lang:U.lang,paths:U.paths,globs:U.globs,updateAll:!0,jsonOutput:!1,cwd:this.cwd,binaryPath:this.astGrepPath});if(Boolean(X.error)||X.exitCode!==null&&X.exitCode!==0){let N=`Error: ${X.error||X.stderr?.trim()||`ast-grep replace failed${X.exitCode!==null?` (exit ${X.exitCode})`:""}`}`,q={exitCode:X.exitCode??_.exitCode??null,output:N,matches:_.matches,matchCount:_.totalMatches,stderr:X.stderr?.trim()||_.stderr?.trim()||void 0,truncated:_.truncated,truncatedReason:_.truncatedReason,timedOut:_.truncatedReason==="timeout"};return{content:[{type:"text",text:N}],structuredContent:q,isError:!0}}let Y=yY(_,Q,this.cwd),K={exitCode:X.exitCode??_.exitCode??null,output:Y,matches:_.matches,matchCount:_.totalMatches,stderr:X.stderr?.trim()||_.stderr?.trim()||void 0,truncated:_.truncated,truncatedReason:_.truncatedReason,timedOut:_.truncatedReason==="timeout"};return{content:[{type:"text",text:Y}],structuredContent:K,isError:!1}}let G=yY(_,Q,this.cwd),V={exitCode:_.exitCode??null,output:G,matches:_.matches,matchCount:_.totalMatches,stderr:_.stderr?.trim()||void 0,truncated:_.truncated,truncatedReason:_.truncatedReason,timedOut:_.truncatedReason==="timeout"};return{content:[{type:"text",text:G}],structuredContent:V,isError:Boolean(_.error)}}validateArgs($){let{pattern:J,rewrite:U,lang:Q}=$;if(typeof J!=="string"||!J.trim())throw Error("pattern is required and must be a non-empty string");if(typeof U!=="string"||!U.trim())throw Error("rewrite is required and must be a non-empty string");if(typeof Q!=="string"||!Q.trim())throw Error("lang is required and must be a non-empty string");if(!k2.includes(Q))throw Error(`lang must be one of: ${k2.join(", ")}`);let _={pattern:J.trim(),rewrite:U.trim(),lang:Q.trim()};if($.paths!==void 0&&$.paths!==null){if(!Array.isArray($.paths)||$.paths.some((G)=>typeof G!=="string"))throw TypeError("paths must be an array of strings");_.paths=$.paths.map((G)=>G.trim()).filter(Boolean)}if($.globs!==void 0&&$.globs!==null){if(!Array.isArray($.globs)||$.globs.some((G)=>typeof G!=="string"))throw TypeError("globs must be an array of strings");_.globs=$.globs.map((G)=>G.trim()).filter(Boolean)}if($.dryRun!==void 0&&$.dryRun!==null)_.dryRun=Boolean($.dryRun);return _}}import tg from"node:process";var zE=5000;class S2 extends P4{name="ast_grep_search";description=`Search code patterns across filesystem using AST-aware matching. Supports 25 languages.
|
|
213
|
-
|
|
214
|
-
Usage notes:
|
|
215
|
-
- Use meta-variables: $VAR (single node), $$$ (multiple nodes)
|
|
216
|
-
- Patterns must be complete AST nodes (valid code)
|
|
217
|
-
- For functions, include params and body: 'export async function $NAME($$$) { $$$ }' not 'export async function $NAME'
|
|
218
|
-
- Examples: 'console.log($MSG)', 'def $FUNC($$$):', 'async function $NAME($$$)'`;parameters={type:"object",properties:{pattern:{type:"string",description:"AST pattern with meta-variables ($VAR, $$$). Must be complete AST node."},lang:{type:"string",enum:[...k2],description:"Target language (ast-grep language identifier)."},paths:{type:"array",items:{type:"string"},description:'Paths to search (default: ["."]).'},globs:{type:"array",items:{type:"string"},description:"Include/exclude globs (prefix ! to exclude)."},context:{type:"number",description:"Context lines around match."}},required:["pattern","lang"]};cwd;astGrepPath;constructor($){super();this.cwd=$?.cwd??tg.cwd(),this.astGrepPath=$?.astGrepPath}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($,J){let U=this.validateArgs($),Q=await pJ({pattern:U.pattern,lang:U.lang,paths:U.paths,globs:U.globs,context:U.context,cwd:this.cwd,binaryPath:this.astGrepPath}),_=ME(Q,this.cwd);if(Q.matches.length===0&&!Q.error){let Z=LE(U.pattern,U.lang);if(Z)_+=`
|
|
219
|
-
|
|
220
|
-
${Z}`}let{truncated:G,truncatedReason:V}=Q;if(_.length>zE){if(_=_.slice(0,zE)+`
|
|
221
|
-
|
|
222
|
-
... [output truncated due to length limit]`,G=!0,!V)V="max_output_bytes"}let X={exitCode:Q.exitCode??null,output:_,matches:Q.matches,matchCount:Q.totalMatches,stderr:Q.stderr?.trim()||void 0,truncated:G,truncatedReason:V,timedOut:Q.truncatedReason==="timeout"};return{content:[{type:"text",text:_}],structuredContent:X,isError:Boolean(Q.error)}}validateArgs($){let{pattern:J,lang:U}=$;if(typeof J!=="string"||!J.trim())throw Error("pattern is required and must be a non-empty string");if(typeof U!=="string"||!U.trim())throw Error("lang is required and must be a non-empty string");if(!k2.includes(U))throw Error(`lang must be one of: ${k2.join(", ")}`);let Q={pattern:J.trim(),lang:U.trim()};if($.paths!==void 0&&$.paths!==null){if(!Array.isArray($.paths)||$.paths.some((_)=>typeof _!=="string"))throw TypeError("paths must be an array of strings");Q.paths=$.paths.map((_)=>_.trim()).filter(Boolean)}if($.globs!==void 0&&$.globs!==null){if(!Array.isArray($.globs)||$.globs.some((_)=>typeof _!=="string"))throw TypeError("globs must be an array of strings");Q.globs=$.globs.map((_)=>_.trim()).filter(Boolean)}if($.context!==void 0&&$.context!==null){if(typeof $.context!=="number"||!Number.isFinite($.context)||$.context<0)throw TypeError("context must be a non-negative number");Q.context=Math.floor($.context)}return Q}}import{spawn as RE}from"node:child_process";import Q0 from"node:process";var DQ=30000,AE=120000,sg=600000,E1=new Map;async function N9($){try{if(Q0.platform==="win32"){let{execSync:J}=await import("node:child_process");try{return J(`taskkill /PID ${$} /T /F`,{stdio:"ignore"}),!0}catch{return!1}}else try{Q0.kill(-$,"SIGTERM"),await new Promise((J)=>setTimeout(J,100));try{Q0.kill(-$,"SIGKILL")}catch{}return!0}catch(J){try{Q0.kill($,"SIGTERM"),await new Promise((U)=>setTimeout(U,100));try{Q0.kill($,"SIGKILL")}catch{}return!0}catch{return!1}}}catch{return!1}}function r5($){try{return Q0.kill($,0),!0}catch{return!1}}function gY(){for(let[$]of E1)if(!r5($))E1.delete($);return Array.from(E1.values())}async function xY($){let J=[];for(let[U,Q]of E1)if(Q.category===$&&r5(U)){if(await N9(U))J.push(U),E1.delete(U)}return J}async function hY(){let $=[];for(let[J]of E1){if(r5(J)){if(await N9(J))$.push(J)}E1.delete(J)}return $}function wE($){let J=$.toLowerCase().trim();if(/^(npm|yarn|pnpm|bun)\s+(run\s+)?(dev|start|serve)/.test(J))return"dev-server";if(/^(npm|yarn|pnpm|bun)\s+run\s+watch/.test(J))return"watch";if(/^node\s+.*server/.test(J))return"node-server";if(/^(vite|webpack-dev-server|parcel|rollup)/.test(J))return"bundler-server";if(/^(next|nuxt)\s+dev/.test(J))return"framework-server";if(/^(redis-server|mongod|postgres|mysql)/.test(J))return"database";if(/^(python|python3)\s+-m\s+(http\.server|SimpleHTTPServer)/.test(J))return"python-server";return}class T2 extends P4{name="Bash";riskLevel="critical";description=`Executes a given bash command in a persistent shell session with optional timeout.
|
|
223
|
-
|
|
224
|
-
Usage notes:
|
|
225
|
-
- The command argument is required.
|
|
226
|
-
- Use 'run_in_background: true' for long-running processes such as:
|
|
227
|
-
* Development servers: npm run dev, yarn dev, pnpm dev, npm start
|
|
228
|
-
* Server processes: node server.js, python -m http.server
|
|
229
|
-
* Watch modes: npm run watch, yarn watch
|
|
230
|
-
* Database/service daemons: redis-server, mongod
|
|
231
|
-
* Any command that runs indefinitely until manually stopped
|
|
232
|
-
- If not specified, commands will timeout after 120000ms (2 minutes).
|
|
233
|
-
- Standard timeout is suitable for short-lived commands like builds, tests, and file operations.
|
|
234
|
-
- If the output exceeds 30000 characters, it will be truncated.
|
|
235
|
-
|
|
236
|
-
Examples:
|
|
237
|
-
- Background: { command: "npm run dev", run_in_background: true, description: "Start dev server" }
|
|
238
|
-
- Foreground: { command: "npm test", timeout: 60000, description: "Run tests" }
|
|
239
|
-
- Foreground: { command: "npm run build", description: "Build project" }`;parameters={type:"object",properties:{command:{type:"string",description:"The command to execute"},timeout:{type:"number",description:"Optional timeout in milliseconds (max 600000)"},description:{type:"string",description:"Clear, concise description of what this command does in 5-10 words"},run_in_background:{type:"boolean",description:"Set to true to run this command in the background. REQUIRED for long-running processes like dev servers (npm run dev, npm start), watch modes, or any command that runs indefinitely. The command will start immediately and return its PID without waiting for completion."},workdir:{type:"string",description:"Working directory to run the command in. Use this instead of cd commands."}},required:["command"]};cwd;shell;constructor($){super();this.cwd=$?.cwd??Q0.cwd(),this.shell=$?.shell??(Q0.platform==="win32"?"cmd.exe":"/bin/bash")}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($,J){let{command:U,timeout:Q=AE,run_in_background:_,workdir:G}=this.validateArgs($),V=G||this.cwd,X=this.shouldRunInBackground(U),Z,Y=[];if(X&&!_)Z=`⚠️ WARNING: This command appears to be a long-running process (dev server, watch mode, or daemon). It will timeout after ${Q}ms. Consider using 'run_in_background: true' to run it properly in the background.`;if(_){let q=wE(U);if(q)Y=await xY(q)}let K=_?await this.executeBackground(U,V,J):await this.executeSync(U,Q,V,J);if(Z)K.warning=Z;if(Y.length>0)K.killedPids=Y;let F=[];if(Y.length>0)F.push(`[Killed ${Y.length} existing process(es) of same type: PID ${Y.join(", ")}]`),F.push("");if(K.warning)F.push(K.warning),F.push("");if(K.stdout)F.push(K.stdout);if(K.stderr)F.push(`[stderr]:
|
|
240
|
-
${K.stderr}`);if(K.timedOut){if(F.push(`[Command timed out after ${Q}ms]`),X)F.push("[Hint: This looks like a long-running process. Retry with 'run_in_background: true']")}if(K.background)F.push(`[Running in background with PID ${K.pid}]`);return{content:[{type:"text",text:F.join(`
|
|
241
|
-
`)||"[No output]"}],structuredContent:K,isError:K.exitCode!==0&&K.exitCode!==null&&!K.background}}shouldRunInBackground($){let J=$.toLowerCase().trim();return[/^(npm|yarn|pnpm|bun)\s+(run\s+)?(dev|start|serve)/,/^(npm|yarn|pnpm|bun)\s+run\s+watch/,/^node\s+.*server/,/^(python|python3)\s+-m\s+(http\.server|SimpleHTTPServer)/,/^(ruby)\s+-run\s+-e\s+httpd/,/^(vite|webpack-dev-server|parcel|rollup)\s+/,/^(redis-server|mongod|postgres|mysql)/,/^(next|nuxt)\s+dev/].some((Q)=>Q.test(J))}validateArgs($){let J=$.command;if(typeof J!=="string"||!J.trim())throw Error("Command is required and must be a non-empty string");let U=AE;if($.timeout!==void 0){if(typeof $.timeout!=="number")throw TypeError("Timeout must be a number");U=Math.min(Math.max(0,$.timeout),sg)}return{command:J.trim(),timeout:U,description:typeof $.description==="string"?$.description:void 0,run_in_background:$.run_in_background===!0,workdir:typeof $.workdir==="string"?$.workdir:void 0}}executeSync($,J,U,Q){return new Promise((_)=>{let G="",V="",X=!1,Z=!1,Y=!1,K=!1,F=!1,N=Q0.platform==="win32"?["/c",$]:["-c",$],q=RE(this.shell,N,{cwd:U,env:Q0.env,stdio:["ignore","pipe","pipe"],detached:Q0.platform!=="win32"}),H=q.pid,E=()=>{if(!F&&Q?.emitEvent&&Q.toolCallId)F=!0,Q.emitEvent({type:"tool_output_start",tool_call_id:Q.toolCallId,toolName:Q.toolName||"Bash"})},D=(w,T)=>{if(Q?.emitEvent&&Q.toolCallId)E(),Q.emitEvent({type:"tool_output_delta",tool_call_id:Q.toolCallId,delta:w,isStderr:T})},B=async()=>{if(H&&!K)await N9(H)},j=()=>{Y=!0,B()},f=Q?.signal;if(f)if(f.aborted)Y=!0,B();else f.addEventListener("abort",j,{once:!0});let R=setTimeout(()=>{X=!0,B()},J),I=()=>{if(clearTimeout(R),f)f.removeEventListener("abort",j)};q.stdout?.on("data",(w)=>{let T=w.toString();if(G.length+T.length>DQ)G+=T.slice(0,DQ-G.length),Z=!0;else G+=T;D(T,!1)}),q.stderr?.on("data",(w)=>{let T=w.toString();if(V.length+T.length>DQ)V+=T.slice(0,DQ-V.length),Z=!0;else V+=T;D(T,!0)}),q.on("close",(w)=>{K=!0,I();let T=Z?`${G}
|
|
242
|
-
... [output truncated]`:G,z=V,S=[];if(X)S.push(`Command terminated after exceeding timeout ${J}ms`);if(Y)S.push("Command was aborted by user");if(S.length>0)z+=(z?`
|
|
243
|
-
|
|
244
|
-
`:"")+`<bash_metadata>
|
|
245
|
-
`+S.join(`
|
|
246
|
-
`)+`
|
|
247
|
-
</bash_metadata>`;_({exitCode:w,stdout:T,stderr:z,truncated:Z,timedOut:X,background:!1})}),q.on("error",(w)=>{K=!0,I(),_({exitCode:1,stdout:"",stderr:`Failed to execute command: ${w.message}`,truncated:!1,timedOut:!1,background:!1})})})}executeBackground($,J,U){return new Promise((Q)=>{let _=Q0.platform==="win32"?["/c",$]:["-c",$],G=RE(this.shell,_,{cwd:J,env:Q0.env,stdio:["ignore","pipe","pipe"],detached:Q0.platform!=="win32"}),V=G.pid,X=!1,Z=()=>{if(!X&&U?.emitEvent&&U.toolCallId)X=!0,U.emitEvent({type:"tool_output_start",tool_call_id:U.toolCallId,toolName:U.toolName||"Bash"})},Y=(q,H)=>{if(U?.emitEvent&&U.toolCallId)Z(),U.emitEvent({type:"tool_output_delta",tool_call_id:U.toolCallId,delta:q,isStderr:H})},K="",F="",N=2000;if(G.stdout?.on("data",(q)=>{let H=q.toString();if(K.length<1000)K+=H;Y(H,!1)}),G.stderr?.on("data",(q)=>{let H=q.toString();if(F.length<1000)F+=H;Y(H,!0)}),V){let q=wE($);E1.set(V,{pid:V,command:$,startedAt:Date.now(),process:G,category:q}),G.on("exit",()=>{E1.delete(V)})}setTimeout(()=>{G.unref();let q=[];if(q.push(`Command started in background with PID ${V}`),K.trim())q.push(`
|
|
248
|
-
[Initial output]:
|
|
249
|
-
${K.trim()}`);if(F.trim())q.push(`
|
|
250
|
-
[Initial stderr]:
|
|
251
|
-
${F.trim()}`);Q({exitCode:null,stdout:q.join(""),stderr:"",truncated:!1,timedOut:!1,background:!0,pid:V})},N)})}async killProcess($){let J=await N9($);if(J)E1.delete($);return J}getRunningProcesses(){return gY()}async killAllProcesses(){return hY()}}import{readFile as eg,stat as $x,writeFile as Jx}from"node:fs/promises";import uY from"node:path";import Ux from"node:process";var fE=0,_x=0.3;function kE($,J){if($===""||J==="")return Math.max($.length,J.length);let U=Array.from({length:$.length+1},(Q,_)=>Array.from({length:J.length+1},(G,V)=>_===0?V:V===0?_:0));for(let Q=1;Q<=$.length;Q++)for(let _=1;_<=J.length;_++){let G=$[Q-1]===J[_-1]?0:1;U[Q][_]=Math.min(U[Q-1][_]+1,U[Q][_-1]+1,U[Q-1][_-1]+G)}return U[$.length][J.length]}var Qx=function*($,J){yield J},Gx=function*($,J){let U=$.split(`
|
|
252
|
-
`),Q=J.split(`
|
|
253
|
-
`);if(Q[Q.length-1]==="")Q.pop();for(let _=0;_<=U.length-Q.length;_++){let G=!0;for(let V=0;V<Q.length;V++){let X=U[_+V].trim(),Z=Q[V].trim();if(X!==Z){G=!1;break}}if(G){let V=0;for(let Z=0;Z<_;Z++)V+=U[Z].length+1;let X=V;for(let Z=0;Z<Q.length;Z++)if(X+=U[_+Z].length,Z<Q.length-1)X+=1;yield $.substring(V,X)}}},Vx=function*($,J){let U=$.split(`
|
|
254
|
-
`),Q=J.split(`
|
|
255
|
-
`);if(Q.length<3)return;if(Q[Q.length-1]==="")Q.pop();let _=Q[0].trim(),G=Q[Q.length-1].trim(),V=Q.length,X=[];for(let K=0;K<U.length;K++){if(U[K].trim()!==_)continue;for(let F=K+2;F<U.length;F++)if(U[F].trim()===G){X.push({startLine:K,endLine:F});break}}if(X.length===0)return;if(X.length===1){let{startLine:K,endLine:F}=X[0],N=F-K+1,q=0,H=Math.min(V-2,N-2);if(H>0)for(let E=1;E<V-1&&E<N-1;E++){let D=U[K+E].trim(),B=Q[E].trim(),j=Math.max(D.length,B.length);if(j===0)continue;let f=kE(D,B);if(q+=(1-f/j)/H,q>=fE)break}else q=1;if(q>=fE){let E=0;for(let B=0;B<K;B++)E+=U[B].length+1;let D=E;for(let B=K;B<=F;B++)if(D+=U[B].length,B<F)D+=1;yield $.substring(E,D)}return}let Z=null,Y=-1;for(let K of X){let{startLine:F,endLine:N}=K,q=N-F+1,H=0,E=Math.min(V-2,q-2);if(E>0){for(let D=1;D<V-1&&D<q-1;D++){let B=U[F+D].trim(),j=Q[D].trim(),f=Math.max(B.length,j.length);if(f===0)continue;let R=kE(B,j);H+=1-R/f}H/=E}else H=1;if(H>Y)Y=H,Z=K}if(Y>=_x&&Z){let{startLine:K,endLine:F}=Z,N=0;for(let H=0;H<K;H++)N+=U[H].length+1;let q=N;for(let H=K;H<=F;H++)if(q+=U[H].length,H<F)q+=1;yield $.substring(N,q)}},Xx=function*($,J){let U=(V)=>V.replace(/\s+/g," ").trim(),Q=U(J),_=$.split(`
|
|
256
|
-
`);for(let V=0;V<_.length;V++){let X=_[V];if(U(X)===Q)yield X;else if(U(X).includes(Q)){let Y=J.trim().split(/\s+/);if(Y.length>0){let K=Y.map((F)=>F.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s+");try{let F=new RegExp(K),N=X.match(F);if(N)yield N[0]}catch{}}}}let G=J.split(`
|
|
257
|
-
`);if(G.length>1)for(let V=0;V<=_.length-G.length;V++){let X=_.slice(V,V+G.length);if(U(X.join(`
|
|
258
|
-
`))===Q)yield X.join(`
|
|
259
|
-
`)}},Yx=function*($,J){let U=(V)=>{let X=V.split(`
|
|
260
|
-
`),Z=X.filter((K)=>K.trim().length>0);if(Z.length===0)return V;let Y=Math.min(...Z.map((K)=>{let F=K.match(/^(\s*)/);return F?F[1].length:0}));return X.map((K)=>K.trim().length===0?K:K.slice(Y)).join(`
|
|
261
|
-
`)},Q=U(J),_=$.split(`
|
|
262
|
-
`),G=J.split(`
|
|
263
|
-
`);for(let V=0;V<=_.length-G.length;V++){let X=_.slice(V,V+G.length).join(`
|
|
264
|
-
`);if(U(X)===Q)yield X}},Zx=function*($,J){let U=(V)=>{return V.replace(/\\([ntr'"`\\\n$])/g,(X,Z)=>{switch(Z){case"n":return`
|
|
265
|
-
`;case"t":return"\t";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case`
|
|
266
|
-
`:return`
|
|
267
|
-
`;case"$":return"$";default:return X}})},Q=U(J);if($.includes(Q))yield Q;let _=$.split(`
|
|
268
|
-
`),G=Q.split(`
|
|
269
|
-
`);for(let V=0;V<=_.length-G.length;V++){let X=_.slice(V,V+G.length).join(`
|
|
270
|
-
`);if(U(X)===Q)yield X}},Kx=function*($,J){let U=J.trim();if(U===J)return;if($.includes(U))yield U;let Q=$.split(`
|
|
271
|
-
`),_=J.split(`
|
|
272
|
-
`);for(let G=0;G<=Q.length-_.length;G++){let V=Q.slice(G,G+_.length).join(`
|
|
273
|
-
`);if(V.trim()===U)yield V}},Nx=function*($,J){let U=J.split(`
|
|
274
|
-
`);if(U.length<3)return;if(U[U.length-1]==="")U.pop();let Q=$.split(`
|
|
275
|
-
`),_=U[0].trim(),G=U[U.length-1].trim();for(let V=0;V<Q.length;V++){if(Q[V].trim()!==_)continue;for(let X=V+2;X<Q.length;X++)if(Q[X].trim()===G){let Z=Q.slice(V,X+1),Y=Z.join(`
|
|
276
|
-
`);if(Z.length===U.length){let K=0,F=0;for(let N=1;N<Z.length-1;N++){let q=Z[N].trim(),H=U[N].trim();if(q.length>0||H.length>0){if(F++,q===H)K++}}if(F===0||K/F>=0.5){yield Y;break}}break}}};class v2 extends P4{name="Edit";riskLevel="high";description=`Performs exact string replacements in files.
|
|
277
|
-
|
|
278
|
-
Usage notes:
|
|
279
|
-
- When editing, preserve the exact indentation (tabs/spaces) from the original file
|
|
280
|
-
- The edit will FAIL if old_string is not unique in the file unless replace_all is true
|
|
281
|
-
- Use replace_all for replacing/renaming strings across the entire file
|
|
282
|
-
- old_string and new_string must be different
|
|
283
|
-
- If exact matching fails, the tool tries normalized variants (trimmed lines, whitespace, indentation, escapes)
|
|
284
|
-
- ALWAYS prefer editing existing files over creating new ones`;parameters={type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with (must be different from old_string)"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)"}},required:["file_path","old_string","new_string"]};cwd;constructor($){super();this.cwd=$?.cwd??Ux.cwd()}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($,J){let{file_path:U,old_string:Q,new_string:_,replace_all:G}=this.validateArgs($),V=uY.isAbsolute(U)?U:uY.resolve(this.cwd,U);try{if((await $x(V)).isDirectory())return S4(`Path is a directory, not a file: ${V}`)}catch(N){if(N.code==="ENOENT")return S4(`File not found: ${V}`);throw N}let X=await eg(V,"utf-8"),Z=this.replaceWithFallback(X,Q,_,G??!1);if(Z.kind==="not_found")return S4(`old_string not found in file: ${V}
|
|
285
|
-
|
|
286
|
-
Searched for (including normalized variants):
|
|
287
|
-
${this.truncateForError(Q)}`);if(Z.kind==="not_unique")return S4("old_string matched multiple places in the file. Provide more context to make it unique, or set replace_all: true to replace all occurrences.");let{content:Y,replacements:K}=Z;await Jx(V,Y,"utf-8");let F={success:!0,replacements:K,filePath:V,message:`Successfully replaced ${K} occurrence${K>1?"s":""} in ${uY.basename(V)}`};return{content:[{type:"text",text:F.message}],structuredContent:F}}validateArgs($){let{file_path:J,old_string:U,new_string:Q}=$;if(typeof J!=="string"||!J.trim())throw Error("file_path is required and must be a non-empty string");if(typeof U!=="string")throw TypeError("old_string is required and must be a string");if(U==="")throw Error("old_string cannot be empty");if(typeof Q!=="string")throw TypeError("new_string is required and must be a string");if(U===Q)throw Error("new_string must be different from old_string");return{file_path:J.trim(),old_string:U,new_string:Q,replace_all:$.replace_all===!0}}countOccurrences($,J){let U=0,Q=$.indexOf(J);while(Q!==-1)U++,Q=$.indexOf(J,Q+J.length);return U}replaceWithFallback($,J,U,Q){let _=!1,G=[Qx,Gx,Vx,Xx,Yx,Zx,Kx,Nx];for(let V of G)for(let X of V($,J)){if(!X)continue;let Z=this.countOccurrences($,X);if(Z===0)continue;if(Q)return{kind:"ok",content:$.split(X).join(U),replacements:Z};if(Z===1){let Y=$.indexOf(X);return{kind:"ok",content:$.slice(0,Y)+U+$.slice(Y+X.length),replacements:1}}_=!0}return _?{kind:"not_unique"}:{kind:"not_found"}}truncateForError($,J=200){if($.length<=J)return $;return`${$.slice(0,J)}... [truncated, ${$.length} chars total]`}}import{readdir as Fx,stat as IE}from"node:fs/promises";import EQ from"node:path";import Wx from"node:process";var mY=1000,qx=20;function Hx($){let J="",U=0;while(U<$.length){let Q=$[U];if(Q==="*")if($[U+1]==="*")if($[U+2]==="/")J+="(?:.*\\/)?",U+=3;else J+=".*",U+=2;else J+="[^/]*",U++;else if(Q==="?")J+="[^/]",U++;else if(Q==="{"){let _=$.indexOf("}",U);if(_!==-1){let G=$.slice(U+1,_).split(",");J+=`(?:${G.map((V)=>Bx(V)).join("|")})`,U=_+1}else J+="\\{",U++}else if(Q==="["){let _=$.indexOf("]",U);if(_!==-1)J+=$.slice(U,_+1),U=_+1;else J+="\\[",U++}else if(Q===".")J+="\\.",U++;else if(Q==="/")J+="\\/",U++;else if("()[]{}^$+|\\".includes(Q))J+=`\\${Q}`,U++;else J+=Q,U++}return new RegExp(`^${J}$`)}function Bx($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}class C2 extends P4{name="Glob";description=`Fast file pattern matching tool that works with any codebase size.
|
|
288
|
-
|
|
289
|
-
Usage notes:
|
|
290
|
-
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
|
|
291
|
-
- Returns matching file paths sorted by modification time (newest first)
|
|
292
|
-
- Use this tool when you need to find files by name patterns
|
|
293
|
-
- You can call multiple tools in a single response for parallel searches
|
|
294
|
-
|
|
295
|
-
Supported patterns:
|
|
296
|
-
- \`*\` matches any sequence of characters except path separator
|
|
297
|
-
- \`**\` matches any sequence of characters including path separator
|
|
298
|
-
- \`?\` matches any single character
|
|
299
|
-
- \`{a,b}\` matches either a or b
|
|
300
|
-
- \`[abc]\` matches any character in brackets`;parameters={type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files against"},path:{type:"string",description:'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior.'}},required:["pattern"]};cwd;constructor($){super();this.cwd=$?.cwd??Wx.cwd()}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($,J){let{pattern:U,path:Q}=this.validateArgs($),_=Q?EQ.isAbsolute(Q)?Q:EQ.resolve(this.cwd,Q):this.cwd;try{if(!(await IE(_)).isDirectory())return S4(`Path is not a directory: ${_}`)}catch(N){if(N.code==="ENOENT")return S4(`Directory not found: ${_}`);throw N}let G=U;if(!U.startsWith("**/")&&!U.startsWith("/")&&!U.startsWith("./"))G=`**/${U}`;let V=Hx(G),X=[];await this.walkDirectory(_,"",V,X,0),X.sort((N,q)=>q.mtime-N.mtime);let Z=X.length>mY,Y=X.slice(0,mY).map((N)=>N.path),K={files:Y,totalMatches:X.length,truncated:Z};return{content:[{type:"text",text:Y.length>0?`Found ${X.length} file${X.length!==1?"s":""}${Z?` (showing first ${mY})`:""}:
|
|
301
|
-
${Y.join(`
|
|
302
|
-
`)}`:`No files found matching pattern: ${U}`}],structuredContent:K}}validateArgs($){let J=$.pattern;if(typeof J!=="string"||!J.trim())throw Error("Pattern is required and must be a non-empty string");let U;if($.path!==void 0&&$.path!==null&&$.path!=="undefined"&&$.path!=="null"){if(typeof $.path!=="string")throw TypeError("Path must be a string");U=$.path.trim()||void 0}return{pattern:J.trim(),path:U}}async walkDirectory($,J,U,Q,_){if(_>qx)return;let G=J?EQ.join($,J):$,V;try{V=await Fx(G,{withFileTypes:!0})}catch{return}for(let X of V){if(X.name.startsWith(".")||X.name==="node_modules")continue;let Z=J?`${J}/${X.name}`:X.name;if(X.isDirectory())await this.walkDirectory($,Z,U,Q,_+1);else if(X.isFile()){if(U.test(Z))try{let Y=EQ.join(G,X.name),K=await IE(Y);Q.push({path:Z,mtime:K.mtimeMs})}catch{}}}}}var mZ=U4(GR(),1),kR=U4(wR(),1);import{Buffer as xl}from"node:buffer";import{spawn as uZ}from"node:child_process";import{chmodSync as hl,existsSync as U7,mkdirSync as ul,statSync as ml}from"node:fs";import{copyFile as cl,mkdtemp as dl,readdir as ll,readFile as il,rm as fR,stat as rl,writeFile as nl}from"node:fs/promises";import V0 from"node:path";import g2 from"node:process";var y2=5000,hZ=60000,pl="BurntSushi/ripgrep",IR="latest",al={"darwin-arm64":{arch:"aarch64",os:"apple-darwin"},"darwin-x64":{arch:"x86_64",os:"apple-darwin"},"linux-arm64":{arch:"aarch64",os:"unknown-linux-musl"},"linux-x64":{arch:"x86_64",os:"unknown-linux-musl"},"win32-x64":{arch:"x86_64",os:"pc-windows-msvc"},"win32-arm64":{arch:"aarch64",os:"pc-windows-msvc"}};function cZ($){try{return ml($).size>1e4}catch{return!1}}function SR(){return g2.platform==="win32"?"rg.exe":"rg"}function dZ(){let $=V0.join(i5(),SR());return U7($)&&cZ($)?$:null}function ol($){return $.code==="ENOENT"||$.message?.includes("ENOENT")||$.message?.includes("not found")}function TR($,J){return new Promise((U,Q)=>{let _=uZ($,J,{stdio:["ignore","pipe","pipe"]}),G="",V="";_.stdout?.on("data",(X)=>{G+=X.toString()}),_.stderr?.on("data",(X)=>{V+=X.toString()}),_.on("error",(X)=>{Q(X)}),_.on("close",(X)=>{U({exitCode:X,stdout:G,stderr:V})})})}async function tl($,J){let Q=["-command",`Expand-Archive -Path '${$}' -DestinationPath '${J}' -Force`],{exitCode:_,stderr:G}=await TR("powershell",Q);if(_!==0)throw Error(`zip extraction failed (exit ${_}): ${G}
|
|
303
|
-
|
|
304
|
-
Ensure PowerShell is available on your system.`)}async function sl($,J){let{exitCode:U,stderr:Q}=await TR("tar",["-xzf",$,"-C",J]);if(U!==0)throw Error(`tar extraction failed (exit ${U}): ${Q}
|
|
305
|
-
|
|
306
|
-
Please install 'tar' (e.g., apt install tar, brew install gnu-tar).`)}async function vR($,J){let U=await ll($,{withFileTypes:!0});for(let Q of U){let _=V0.join($,Q.name);if(Q.isFile()&&Q.name===J)return _;if(Q.isDirectory()){let G=await vR(_,J);if(G)return G}}return null}var J7=null,cQ=null,dQ=null;async function el($){if($!=="latest")return $;if(dQ)return dQ;try{let J=new AbortController,U=setTimeout(()=>J.abort(),30000);try{let Q=await fetch("https://api.github.com/repos/BurntSushi/ripgrep/releases/latest",{redirect:"follow",signal:J.signal});if(!Q.ok)throw Error(`HTTP ${Q.status}: ${Q.statusText}`);let G=(await Q.json())?.tag_name;if(!G)throw Error("Missing tag_name in GitHub response.");return dQ=G.startsWith("v")?G.slice(1):G,dQ}finally{clearTimeout(U)}}catch(J){return console.error(`[goat-chain] Failed to resolve latest ripgrep version: ${J instanceof Error?J.message:J}`),null}}async function $i($=IR){let J=`${g2.platform}-${g2.arch}`,U=al[J];if(!U)return console.error(`[goat-chain] Unsupported platform for ripgrep: ${J}`),null;let Q=i5(),_=SR(),G=V0.join(Q,_);if(U7(G)&&cZ(G))return G;let V=await el($);if(!V)return null;let{arch:X,os:Z}=U,Y=g2.platform==="win32"?"zip":"tar.gz",K=`ripgrep-${V}-${X}-${Z}.${Y}`,F=`https://github.com/${pl}/releases/download/${V}/${K}`;console.log("[goat-chain] Downloading ripgrep binary...");let N=null,q=V0.join(Q,K);try{if(!U7(Q))ul(Q,{recursive:!0});let H=new AbortController,E=setTimeout(()=>H.abort(),120000);try{let B=await fetch(F,{redirect:"follow",signal:H.signal});if(!B.ok)throw Error(`HTTP ${B.status}: ${B.statusText}`);let j=await B.arrayBuffer();await nl(q,xl.from(j))}finally{clearTimeout(E)}if(N=await dl(V0.join(Q,"ripgrep-")),Y==="zip")await tl(q,N);else await sl(q,N);let D=await vR(N,_);if(!D)throw Error("ripgrep binary not found in extracted archive.");if(await cl(D,G),g2.platform!=="win32"&&U7(G))hl(G,493);if(!cZ(G))throw Error("Downloaded ripgrep binary failed validation.");return console.log("[goat-chain] ripgrep binary ready."),G}catch(H){return console.error(`[goat-chain] Failed to download ripgrep: ${H instanceof Error?H.message:H}`),null}finally{if(await fR(q,{force:!0}).catch(()=>{}),N)await fR(N,{recursive:!0,force:!0}).catch(()=>{})}}async function Ji($=IR){let J=dZ();if(J)return J;return $i($)}async function Ui(){if(J7!==null&&U7(J7))return J7;if(cQ)return cQ;return cQ=(async()=>{let $=dZ();if($)return J7=$,$;let J=await Ji();if(J)return J7=J,J;return null})(),cQ}class x2 extends P4{name="Grep";description=`A powerful search tool built on ripgrep.
|
|
307
|
-
|
|
308
|
-
Usage notes:
|
|
309
|
-
- Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
|
|
310
|
-
- Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
|
|
311
|
-
- Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
|
|
312
|
-
- Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
|
|
313
|
-
- Multiline matching: By default patterns match within single lines only. For cross-line patterns, use multiline: true
|
|
314
|
-
- If ripgrep is not available, this tool falls back to a JS-based search (slower). You can opt into downloading a ripgrep binary via the GrepTool constructor option \`allowDownload: true\`.`;parameters={type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")'},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:'Output mode: "content" shows matching lines, "files_with_matches" shows file paths (default), "count" shows match counts.'},"-B":{type:"number",description:'Number of lines to show before each match. Requires output_mode: "content".'},"-A":{type:"number",description:'Number of lines to show after each match. Requires output_mode: "content".'},"-C":{type:"number",description:'Number of lines to show before and after each match. Requires output_mode: "content".'},"-n":{type:"boolean",description:'Show line numbers in output. Requires output_mode: "content". Defaults to true.'},"-i":{type:"boolean",description:"Case insensitive search"},type:{type:"string",description:"File type to search (e.g., js, py, rust, go, java). More efficient than glob for standard file types."},head_limit:{type:"number",description:"Limit output to first N lines/entries. Defaults to 0 (unlimited)."},offset:{type:"number",description:"Skip first N lines/entries before applying head_limit. Defaults to 0."},multiline:{type:"boolean",description:"Enable multiline mode where . matches newlines and patterns can span lines. Default: false."}},required:["pattern"]};cwd;rgPath;allowDownload;constructor($){super();this.cwd=$?.cwd??g2.cwd(),this.rgPath=$?.rgPath??"rg",this.allowDownload=$?.allowDownload===!0}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($,J){let U=this.validateArgs($),Q=this.buildRgArgs(U),_=await this.runRipgrep(Q,U),G=_.output||"[No matches found]";if(_.timedOut)G+=`
|
|
315
|
-
[Search timed out]`;if(_.matchCount!==void 0)G=`Found ${_.matchCount} match${_.matchCount!==1?"es":""}
|
|
316
|
-
${G}`;return{content:[{type:"text",text:G}],structuredContent:_,isError:_.exitCode!==null&&_.exitCode!==0&&_.exitCode!==1}}validateArgs($){let J=$.pattern;if(typeof J!=="string"||!J.trim())throw Error("Pattern is required and must be a non-empty string");let U={pattern:J.trim()};if($.path!==void 0&&$.path!==null&&$.path!==""){if(typeof $.path!=="string")throw TypeError("Path must be a string");U.path=$.path.trim()}if($.glob!==void 0&&$.glob!==null&&$.glob!==""){if(typeof $.glob!=="string")throw TypeError("Glob must be a string");U.glob=$.glob.trim()}if($.type!==void 0&&$.type!==null&&$.type!==""){if(typeof $.type!=="string")throw TypeError("Type must be a string");U.type=$.type.trim()}if($.output_mode!==void 0){let G=["content","files_with_matches","count"];if(!G.includes($.output_mode))throw Error(`Invalid output_mode. Must be one of: ${G.join(", ")}`);U.output_mode=$.output_mode}let Q=["-B","-A","-C","head_limit","offset"];for(let G of Q)if($[G]!==void 0&&$[G]!==null){if(typeof $[G]!=="number")throw TypeError(`${G} must be a number`);U[G]=Math.max(0,Math.floor($[G]))}let _=["-n","-i","multiline"];for(let G of _)if($[G]!==void 0&&$[G]!==null)U[G]=Boolean($[G]);return U}buildRgArgs($){let J=[],U=$.output_mode??"files_with_matches";if(U==="files_with_matches")J.push("-l");else if(U==="count")J.push("-c");if(U==="content"){if($["-n"]!==!1)J.push("-n");if($["-B"]!==void 0&&$["-B"]>0)J.push("-B",String($["-B"]));if($["-A"]!==void 0&&$["-A"]>0)J.push("-A",String($["-A"]));if($["-C"]!==void 0&&$["-C"]>0)J.push("-C",String($["-C"]))}if($["-i"])J.push("-i");if($.multiline)J.push("-U","--multiline-dotall");if($.type)J.push("--type",$.type);if($.glob)J.push("--glob",$.glob);if(J.push("--color","never"),J.push("--no-heading"),J.push("--regexp",$.pattern),$.path)J.push("--",$.path);return J}runRipgrep($,J,U=!1){return new Promise((Q)=>{let _="",G=!1,V=!1,X=!1,Z=null,Y=!1;if(this.rgPath==="rg"){let q=dZ();if(q)this.rgPath=q}let K=uZ(this.rgPath,$,{cwd:this.cwd,env:g2.env,stdio:["ignore","pipe","pipe"]}),F=(q)=>{if(X)return;X=!0,Q(q)},N=setTimeout(()=>{G=!0,K.kill("SIGTERM"),setTimeout(()=>{if(!K.killed)K.kill("SIGKILL")},5000)},hZ);K.stdout?.on("data",(q)=>{let H=q.toString();if(_.length+H.length>y2)_+=H.slice(0,y2-_.length),V=!0,clearTimeout(N),K.kill("SIGTERM");else _+=H}),K.stderr?.on("data",(q)=>{let H=q.toString();if(H.includes("error:"))_+=`
|
|
317
|
-
[stderr]: ${H}`}),K.on("close",(q)=>{if(X)return;if(clearTimeout(N),Z||q!==null&&q<0){if(!Y)this.runJsSearch(J).then(F);return}let H=_;if(J.offset||J.head_limit){let D=_.split(`
|
|
318
|
-
`).filter((R)=>R.trim()),B=J.offset??0,j=J.head_limit??D.length;H=D.slice(B,B+j).join(`
|
|
319
|
-
`)}let E;if(J.output_mode==="count")E=H.split(`
|
|
320
|
-
`).filter((D)=>D.trim()).reduce((D,B)=>{let j=B.match(/:(\d+)$/);return D+(j?Number.parseInt(j[1],10):0)},0);F({exitCode:q,output:V?`${H}
|
|
321
|
-
... [output truncated]`:H,truncated:V,timedOut:G,matchCount:E})}),K.on("error",(q)=>{if(X)return;Z=q,Y=!0,clearTimeout(N);let H=q;if(this.allowDownload&&!U&&ol(H)){(async()=>{try{let D=await Ui();if(D){this.rgPath=D;let B=await this.runRipgrep($,J,!0);F(B);return}}catch{}let E=await this.runJsSearch(J);F(E)})();return}this.runJsSearch(J).then(F)})})}async runJsSearch($){let J=!1,U=!1,Q=setTimeout(()=>{J=!0},hZ),_=$.output_mode??"files_with_matches",G=$["-B"]??0,V=$["-A"]??0,X=$["-C"]??0;if(X>0)G=Math.max(G,X),V=Math.max(V,X);let Z=Boolean($["-i"]),Y=Boolean($.multiline),K=`${Z?"i":""}${Y?"sm":""}`,F=null,N=null;try{if(Y)N=new RegExp($.pattern,`${K}g`);else F=new RegExp($.pattern,K)}catch(C){return clearTimeout(Q),{exitCode:2,engine:"js",output:`Invalid regex pattern: ${C.message}`,truncated:!1,timedOut:!1}}let q=$.path??".",H=V0.isAbsolute(q)?q:V0.resolve(this.cwd,q),E=V0.isAbsolute(q),D;try{D=await rl(H)}catch{return clearTimeout(Q),{exitCode:2,engine:"js",output:`Search path not found: ${q}`,truncated:!1,timedOut:!1}}let B=[],j=mZ.default.default??mZ.default;if(typeof j!=="function")return clearTimeout(Q),this.runSystemGrep($);let f=H;if(D.isFile())B=[H],f=V0.dirname(H);else if(D.isDirectory()){f=H;try{B=await j("**/*",{cwd:f,absolute:!0,onlyFiles:!0,dot:!0})}catch{return clearTimeout(Q),this.runSystemGrep($)}}else return clearTimeout(Q),{exitCode:2,engine:"js",output:`Search path not found: ${q}`,truncated:!1,timedOut:!1};B.sort();let R=[],I=!1,w=0,T=(C)=>{let b=C.length+1;if(w+b>y2)return U=!0,!1;return R.push(C),w+=b,!0},z={js:[".js",".cjs",".mjs"],jsx:[".jsx"],ts:[".ts",".tsx",".d.ts"],tsx:[".tsx"],json:[".json"],md:[".md",".markdown"],py:[".py"],go:[".go"],rs:[".rs"],java:[".java"],c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx",".h"]},S=(C)=>{if(!$.type)return!0;let b=$.type.toLowerCase(),y=z[b]??[b.startsWith(".")?b:`.${b}`],x=C.toLowerCase();return y.some((c)=>x.endsWith(c))},O=(C)=>{if(E)return C;return V0.relative(this.cwd,C)||V0.basename(C)},M=$.glob,P=kR.default.isMatch,A=_==="content"?$["-n"]!==!1:!1;for(let C of B){if(J)break;if(w>=y2){U=!0;break}if(!S(C))continue;if(M&&P&&!P(V0.basename(C),M))continue;let b="";try{b=await il(C,"utf-8")}catch{continue}if(!b||b.includes("\x00"))continue;let y=O(C);if(!Y){let u$=b.split(/\r?\n/),_$=new Set;for(let G$=0;G$<u$.length;G$++)if(F.test(u$[G$]))_$.add(G$+1);if(_$.size===0)continue;I=!0;let n=_$.size;if(_==="files_with_matches"){if(!T(y))break;continue}if(_==="count"){if(!T(`${y}:${n}`))break;continue}let a=new Set(_$);if(G>0||V>0){let G$=u$.length;for(let L$ of _$){let P$=Math.max(1,L$-G),f$=Math.min(G$,L$+V);for(let V4=P$;V4<=f$;V4++)a.add(V4)}}let m=!1;for(let G$ of Array.from(a).sort((L$,P$)=>L$-P$)){let L$=u$[G$-1]??"",P$=A?`${y}:${G$}:${L$}`:`${y}:${L$}`;if(!T(P$)){m=!0;break}}if(m)break;continue}let x=b.split(/\r?\n/),c=[0];for(let u$=0;u$<b.length;u$++)if(b[u$]===`
|
|
322
|
-
`)c.push(u$+1);let s=(u$)=>{let _$=0,n=c.length-1;while(_$<=n){let a=Math.floor((_$+n)/2);if(c[a]<=u$)_$=a+1;else n=a-1}return Math.max(n+1,1)};N.lastIndex=0;let F$=new Set;for(let u$ of b.matchAll(N)){let _$=u$.index??0,n=u$[0]?.length??0,a=Math.max(_$,_$+n-1),m=s(_$),G$=s(a);for(let L$=m;L$<=G$;L$++)F$.add(L$)}if(F$.size===0)continue;I=!0;let K$=F$.size;if(_==="files_with_matches"){if(!T(y))break;continue}if(_==="count"){if(!T(`${y}:${K$}`))break;continue}let V$=new Set(F$);if(G>0||V>0){let u$=x.length;for(let _$ of F$){let n=Math.max(1,_$-G),a=Math.min(u$,_$+V);for(let m=n;m<=a;m++)V$.add(m)}}let Y$=!1;for(let u$ of Array.from(V$).sort((_$,n)=>_$-n)){let _$=x[u$-1]??"",n=A?`${y}:${u$}:${_$}`:`${y}:${_$}`;if(!T(n)){Y$=!0;break}}if(Y$)break}clearTimeout(Q);let k=R;if($.offset||$.head_limit){let C=R.filter((x)=>x.trim()),b=$.offset??0,y=$.head_limit??C.length;k=C.slice(b,b+y)}let L=k.join(`
|
|
323
|
-
`);if(L.length>y2)L=L.slice(0,y2),U=!0;let v;if(_==="count")v=L.split(`
|
|
324
|
-
`).filter((C)=>C.trim()).reduce((C,b)=>{let y=b.split(":").pop(),x=y?Number.parseInt(y,10):Number.NaN;return C+(Number.isFinite(x)?x:0)},0);return{exitCode:I?0:1,engine:"js",output:U?`${L}
|
|
325
|
-
... [output truncated]`:L,truncated:U,timedOut:J,matchCount:v}}runSystemGrep($){return new Promise((J)=>{let U="",Q=!1,_=!1,G=[];G.push("-R","-E","-I");let V=$.output_mode??"files_with_matches";if(V==="files_with_matches")G.push("-l");else if(V==="count")G.push("-c");else G.push("-n");if(V==="content"){if($["-B"]!==void 0&&$["-B"]>0)G.push("-B",String($["-B"]));if($["-A"]!==void 0&&$["-A"]>0)G.push("-A",String($["-A"]));if($["-C"]!==void 0&&$["-C"]>0)G.push("-C",String($["-C"]))}if($["-i"])G.push("-i");if(G.push($.pattern),$.path)G.push($.path);else G.push(".");let X=uZ("grep",G,{cwd:this.cwd,env:g2.env,stdio:["ignore","pipe","pipe"]}),Z=setTimeout(()=>{Q=!0,X.kill("SIGTERM"),setTimeout(()=>{if(!X.killed)X.kill("SIGKILL")},5000)},hZ);X.stdout?.on("data",(Y)=>{let K=Y.toString();if(U.length+K.length>y2)U+=K.slice(0,y2-U.length),_=!0,clearTimeout(Z),X.kill("SIGTERM");else U+=K}),X.stderr?.on("data",(Y)=>{let K=Y.toString();if(K.trim())U+=`
|
|
326
|
-
[stderr]: ${K}`}),X.on("close",(Y)=>{clearTimeout(Z);let K=U;if($.offset||$.head_limit){let N=U.split(`
|
|
327
|
-
`).filter((E)=>E.trim()),q=$.offset??0,H=$.head_limit??N.length;K=N.slice(q,q+H).join(`
|
|
328
|
-
`)}let F;if(V==="count")F=K.split(`
|
|
329
|
-
`).filter((N)=>N.trim()).reduce((N,q)=>{let H=q.split(":").pop(),E=H?Number.parseInt(H,10):Number.NaN;return N+(Number.isFinite(E)?E:0)},0);J({exitCode:Y,engine:"grep",output:_?`${K}
|
|
330
|
-
... [output truncated]`:K,truncated:_,timedOut:Q,matchCount:F})}),X.on("error",(Y)=>{clearTimeout(Z),J({exitCode:1,engine:"grep",output:`Failed to execute grep: ${Y.message}.`,truncated:!1,timedOut:!1})})})}}import{readFile as lQ,stat as _i}from"node:fs/promises";import sJ from"node:path";import Qi from"node:process";var CR=2000,lZ=2000,Gi=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".pdf",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".mp3",".mp4",".avi",".mov",".wav",".woff",".woff2",".ttf",".eot"]),Vi={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".pdf":"application/pdf",".json":"application/json",".js":"text/javascript",".ts":"text/typescript",".html":"text/html",".css":"text/css",".md":"text/markdown",".txt":"text/plain"};class h2 extends P4{name="Read";_cwd;_allowedDirectory;constructor($){super();this._cwd=$?.cwd??Qi.cwd(),this._allowedDirectory=$?.allowedDirectory}get description(){let $=`Reads a file from the local filesystem. You can access any file directly by using this tool.
|
|
331
|
-
|
|
332
|
-
Usage notes:
|
|
333
|
-
- Current working directory: ${this._cwd}
|
|
334
|
-
- Supports both absolute paths and relative paths (relative to cwd)
|
|
335
|
-
- IMPORTANT: Do NOT guess file paths. Use Glob to search for files first if unsure.
|
|
336
|
-
- By default, it reads up to ${CR} lines starting from the beginning
|
|
337
|
-
- You can optionally specify a line offset and limit for large files
|
|
338
|
-
- Any lines longer than ${lZ} characters will be truncated
|
|
339
|
-
- Results are returned with line numbers (like cat -n format)
|
|
340
|
-
- Can read images (PNG, JPG, etc.), PDFs, and Jupyter notebooks
|
|
341
|
-
- You can call multiple tools in parallel to read multiple files at once`;if(this._allowedDirectory)return`${$}
|
|
342
|
-
- IMPORTANT: Files can ONLY be read from within: ${this._allowedDirectory}
|
|
343
|
-
- Use paths within ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)`;return $}get parameters(){return{type:"object",properties:{file_path:{type:"string",description:this._allowedDirectory?`The path to the file to read (must be within ${this._allowedDirectory})`:`The path to the file to read (absolute or relative to ${this._cwd})`},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]}}setCwd($){this._cwd=$}getCwd(){return this._cwd}setAllowedDirectory($){this._allowedDirectory=$}getAllowedDirectory(){return this._allowedDirectory}async execute($,J){let{file_path:U,offset:Q,limit:_}=this.validateArgs($),G=sJ.isAbsolute(U)?U:sJ.resolve(this._cwd,U);if(this._allowedDirectory){let F=sJ.resolve(this._allowedDirectory),N=sJ.resolve(G);if(!N.startsWith(F+sJ.sep)&&N!==F)return S4(`Access denied: ${U}
|
|
344
|
-
Files can only be read from within: ${this._allowedDirectory}
|
|
345
|
-
Please use a path like: ${this._allowedDirectory}/<filename>`)}let V;try{V=await _i(G)}catch(F){if(F.code==="ENOENT")return S4(`File not found: ${G}`);throw F}if(V.isDirectory())return S4(`Path is a directory, not a file: ${G}. Use ls command via Bash tool to read directories.`);let X=sJ.extname(G).toLowerCase(),Z=Gi.has(X),Y=Vi[X],K;if(Z){if(K=await this.handleBinaryFile(G,V.size,Y),Y?.startsWith("image/"))return{content:[{type:"image",data:(await lQ(G)).toString("base64"),mimeType:Y}],structuredContent:K}}else if(X===".ipynb")K=await this.handleJupyterNotebook(G,V.size,Q,_);else K=await this.handleTextFile(G,V.size,Q,_);return{content:[{type:"text",text:K.content}],structuredContent:K}}validateArgs($){let J=$.file_path;if(typeof J!=="string"||!J.trim())throw Error("file_path is required and must be a non-empty string");let U={file_path:J.trim()};if($.offset!==void 0&&$.offset!==null){if(typeof $.offset!=="number")throw TypeError("offset must be a number");U.offset=Math.max(1,Math.floor($.offset))}if($.limit!==void 0&&$.limit!==null){if(typeof $.limit!=="number")throw TypeError("limit must be a number");U.limit=Math.max(1,Math.floor($.limit))}return U}async handleBinaryFile($,J,U){let _=(await lQ($)).toString("base64");return{content:`[Binary file: ${sJ.basename($)}]
|
|
346
|
-
Size: ${this.formatSize(J)}
|
|
347
|
-
MIME type: ${U??"unknown"}
|
|
348
|
-
Base64 encoded content:
|
|
349
|
-
${_}`,totalLines:1,linesReturned:1,startLine:1,truncated:!1,fileSize:J,isBinary:!0,mimeType:U}}async handleJupyterNotebook($,J,U,Q){let _=await lQ($,"utf-8"),G;try{G=JSON.parse(_)}catch{throw Error(`Invalid Jupyter notebook format: ${$}`)}let V=G.cells||[],X=[];for(let Z=0;Z<V.length;Z++){let Y=V[Z],K=Z+1,F=Y.cell_type||"unknown";X.push(`--- Cell ${K} (${F}) ---`);let N=Array.isArray(Y.source)?Y.source.join(""):Y.source||"";if(X.push(...N.split(`
|
|
350
|
-
`)),Y.outputs&&Y.outputs.length>0){X.push("--- Output ---");for(let q of Y.outputs)if(q.text){let H=Array.isArray(q.text)?q.text.join(""):q.text;X.push(...H.split(`
|
|
351
|
-
`))}else if(q.data){if(q.data["text/plain"]){let H=Array.isArray(q.data["text/plain"])?q.data["text/plain"].join(""):q.data["text/plain"];X.push(...H.split(`
|
|
352
|
-
`))}}}X.push("")}return this.formatOutput(X,J,U,Q)}async handleTextFile($,J,U,Q){let _=await lQ($,"utf-8");if(_.length===0)return{content:"[File is empty]",totalLines:0,linesReturned:0,startLine:1,truncated:!1,fileSize:J,isBinary:!1};let G=_.split(`
|
|
353
|
-
`);return this.formatOutput(G,J,U,Q)}formatOutput($,J,U,Q){let _=$.length,G=U??1,V=Q??CR,X=G-1,Z=Math.min(X+V,_),Y=$.slice(X,Z),K=!1;return{content:Y.map((N,q)=>{let H=G+q,E=String(H).padStart(6," "),D=N;if(N.length>lZ)D=`${N.slice(0,lZ)}... [truncated]`,K=!0;return`${E}|${D}`}).join(`
|
|
354
|
-
`),totalLines:_,linesReturned:Y.length,startLine:G,truncated:K,fileSize:J,isBinary:!1}}formatSize($){let J=["B","KB","MB","GB"],U=$,Q=0;while(U>=1024&&Q<J.length-1)U/=1024,Q++;return`${U.toFixed(Q===0?0:2)} ${J[Q]}`}}class _7 extends P4{name="Task";description;parameters={type:"object",properties:{description:{type:"string",description:"A short (3-5 word) description of the task"},prompt:{type:"string",description:"The task for the agent to perform"},subagent_type:{type:"string",description:"The type of specialized agent to use for this task"},resume:{type:"string",description:"Optional subagent ID to resume from. If provided, the subagent will continue from the previous execution."},run_in_background:{type:"boolean",description:"Set to true to run this agent in the background. Use TaskOutput to read the output later."}},required:["description","prompt","subagent_type"]};subagents;executor;constructor($){super();if(this.subagents=new Map,this.executor=$?.executor,$?.subagents)for(let J of $.subagents)this.subagents.set(J.name,J);this.description=this.buildDescription()}registerSubagent($){this.subagents.set($.name,$)}unregisterSubagent($){return this.subagents.delete($)}getSubagents(){return Array.from(this.subagents.values())}hasSubagent($){return this.subagents.has($)}setExecutor($){this.executor=$}async execute($,J){let U=this.validateArgs($);if(!this.subagents.has(U.subagent_type)){let Q=Array.from(this.subagents.keys()).join(", ");return S4(`Subagent type "${U.subagent_type}" not found. Available types: ${Q||"none"}`)}if(!this.executor)return S4("Task executor is not configured. Please set an executor using setExecutor().");try{let{subagentId:Q,data:_}=await this.executor(U,J),G={success:!0,subagentId:Q,subagentType:U.subagent_type,description:U.description,background:U.run_in_background??!1,data:_},V=G.background?" (running in background)":"",X=`Task "${U.description}" started with subagent ${Q}${V}`,Z=G.background?null:this.formatTaskData(_);return{content:[{type:"text",text:`Result:${X}
|
|
355
|
-
|
|
356
|
-
${Z}`}],structuredContent:G}}catch(Q){return S4(`Task execution failed: ${Q instanceof Error?Q.message:String(Q)}`)}}validateArgs($){let{description:J,prompt:U,subagent_type:Q}=$;if(typeof J!=="string"||!J.trim())throw Error("description is required and must be a non-empty string");if(typeof U!=="string"||!U.trim())throw Error("prompt is required and must be a non-empty string");if(typeof Q!=="string"||!Q.trim())throw Error("subagent_type is required and must be a non-empty string");let _={description:J.trim(),prompt:U.trim(),subagent_type:Q.trim()};if($.resume!==void 0&&$.resume!==null&&$.resume!==""){if(typeof $.resume!=="string")throw TypeError("resume must be a string");_.resume=$.resume.trim()}if($.run_in_background!==void 0&&$.run_in_background!==null)_.run_in_background=Boolean($.run_in_background);return _}formatTaskData($){if($===void 0||$===null)return null;if(typeof $==="string"){let J=$.trim();return J.length>0?J:null}if(typeof $==="number"||typeof $==="boolean")return String($);try{let J=JSON.stringify($,null,2);return J===void 0?null:J}catch{return String($)}}buildDescription(){return`Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
357
|
-
|
|
358
|
-
<available_agents>
|
|
359
|
-
${this.buildAgentsList()||"No subagent types registered."}
|
|
360
|
-
</available_agents>
|
|
361
|
-
|
|
362
|
-
When to use the Task tool:
|
|
363
|
-
- When you are instructed to execute custom slash commands. Use the Task tool with the slash command invocation as the entire prompt
|
|
364
|
-
- For complex multi-step tasks requiring autonomous exploration across many files
|
|
365
|
-
- When you need to research or analyze code that spans multiple directories
|
|
366
|
-
|
|
367
|
-
When NOT to use the Task tool:
|
|
368
|
-
- If you want to read a specific file path, use the Read or Glob tool instead of the Task tool, to find the match more quickly
|
|
369
|
-
- If you are searching for a specific class definition like "class Foo", use the Glob tool instead, to find the match more quickly
|
|
370
|
-
- If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead of the Task tool, to find the match more quickly
|
|
371
|
-
- For simple tasks that can be completed with 1-2 tool calls
|
|
372
|
-
|
|
373
|
-
Usage notes:
|
|
374
|
-
1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
|
|
375
|
-
2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
|
|
376
|
-
3. Each agent invocation is stateless unless you provide a resume ID. Your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
|
|
377
|
-
4. The agent's outputs should generally be trusted
|
|
378
|
-
5. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
|
|
379
|
-
6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
|
|
380
|
-
7. Use "run_in_background: true" to run agents in background. Use TaskOutput to read the output later.`}buildAgentsList(){if(this.subagents.size===0)return"";return Array.from(this.subagents.values()).map(($)=>{let J=`- ${$.name}: ${$.description}`;if($.tools&&$.tools.length>0)J+=` (Tools: ${$.tools.join(", ")})`;if($.blockedTools&&$.blockedTools.length>0)J+=` (Blocked: ${$.blockedTools.join(", ")})`;return J}).join(`
|
|
381
|
-
`)}}class O9 extends P4{name="TodoPlan";riskLevel="safe";description=`Use this tool to draft a structured task list in plan mode.
|
|
382
|
-
|
|
383
|
-
This tool only generates a plan for review and does NOT update any execution state.
|
|
384
|
-
Use TodoWrite in agent mode when you are actively executing tasks.
|
|
385
|
-
|
|
386
|
-
When to use:
|
|
387
|
-
- Plan mode task breakdowns (3+ steps)
|
|
388
|
-
- Presenting a proposed plan for review
|
|
389
|
-
- After clarifying requirements in plan mode
|
|
390
|
-
|
|
391
|
-
When NOT to use:
|
|
392
|
-
- Active execution tracking (use TodoWrite)
|
|
393
|
-
- Single, straightforward task
|
|
394
|
-
- Purely conversational/informational requests
|
|
395
|
-
|
|
396
|
-
Task States:
|
|
397
|
-
- pending: Task not yet started
|
|
398
|
-
- in_progress: Currently working on (limit to ONE at a time)
|
|
399
|
-
- completed: Task finished successfully
|
|
400
|
-
|
|
401
|
-
Task descriptions have two forms:
|
|
402
|
-
- content: Imperative form (e.g., "Run tests")
|
|
403
|
-
- activeForm: Present continuous form (e.g., "Running tests")`;parameters={type:"object",properties:{todos:{type:"array",items:{type:"object",properties:{content:{type:"string",minLength:1,description:'The task description in imperative form (e.g., "Run tests")'},status:{type:"string",enum:["pending","in_progress","completed"],description:"Current status of the task"},activeForm:{type:"string",minLength:1,description:'The task description in present continuous form (e.g., "Running tests")'}},required:["content","status","activeForm"]},description:"The drafted todo list"}},required:["todos"]};async execute($,J){let{todos:U}=this.validateArgs($),Q=U.filter((Y)=>Y.status==="pending").length,_=U.filter((Y)=>Y.status==="in_progress").length,G=U.filter((Y)=>Y.status==="completed").length,V=[];if(G>0)V.push(`${G} completed`);if(_>0)V.push(`${_} in progress`);if(Q>0)V.push(`${Q} pending`);let X=this.formatTodoList(U,V);return{content:[{type:"text",text:X}],structuredContent:{success:!0,todos:U,pendingCount:Q,inProgressCount:_,completedCount:G,message:X}}}validateArgs($){let J=$.todos;if(!Array.isArray(J))throw TypeError("todos is required and must be an array");let U=[],Q=["pending","in_progress","completed"];for(let G=0;G<J.length;G++){let V=J[G];if(typeof V!=="object"||V===null)throw TypeError(`todos[${G}] must be an object`);let{content:X,status:Z,activeForm:Y}=V;if(typeof X!=="string"||!X.trim())throw Error(`todos[${G}].content is required and must be a non-empty string`);if(typeof Z!=="string"||!Q.includes(Z))throw Error(`todos[${G}].status must be one of: ${Q.join(", ")}`);if(typeof Y!=="string"||!Y.trim())throw Error(`todos[${G}].activeForm is required and must be a non-empty string`);U.push({content:X.trim(),status:Z,activeForm:Y.trim()})}let _=U.filter((G)=>G.status==="in_progress");if(_.length>1)console.warn(`Warning: ${_.length} tasks are in_progress. Ideally only one task should be in_progress at a time.`);return{todos:U}}formatTodoList($,J){if($.length===0)return"Plan todo list is empty";let U=[],Q=J.length>0?J.join(", "):"0 pending";U.push(`Plan todo list drafted: ${Q}`),U.push(""),U.push("Todos:");for(let _=0;_<$.length;_++){let G=$[_];U.push(`${_+1}. [${G.status}] ${G.content}`),U.push(` activeForm: ${G.activeForm}`)}return U.join(`
|
|
404
|
-
`)}}class u2 extends P4{name="TodoWrite";riskLevel="low";description=`Use this tool to create and manage a structured task list for your current coding session.
|
|
405
|
-
|
|
406
|
-
When to use:
|
|
407
|
-
- Complex multi-step tasks (3+ steps)
|
|
408
|
-
- Non-trivial tasks requiring careful planning
|
|
409
|
-
- User explicitly requests todo list
|
|
410
|
-
- User provides multiple tasks
|
|
411
|
-
- After receiving new instructions
|
|
412
|
-
|
|
413
|
-
When NOT to use:
|
|
414
|
-
- Single, straightforward task
|
|
415
|
-
- Trivial tasks (< 3 steps)
|
|
416
|
-
- Purely conversational/informational requests
|
|
417
|
-
|
|
418
|
-
Task States:
|
|
419
|
-
- pending: Task not yet started
|
|
420
|
-
- in_progress: Currently working on (limit to ONE at a time)
|
|
421
|
-
- completed: Task finished successfully
|
|
422
|
-
|
|
423
|
-
Task descriptions have two forms:
|
|
424
|
-
- content: Imperative form (e.g., "Run tests")
|
|
425
|
-
- activeForm: Present continuous form (e.g., "Running tests")`;parameters={type:"object",properties:{todos:{type:"array",items:{type:"object",properties:{content:{type:"string",minLength:1,description:'The task description in imperative form (e.g., "Run tests")'},status:{type:"string",enum:["pending","in_progress","completed"],description:"Current status of the task"},activeForm:{type:"string",minLength:1,description:'The task description in present continuous form (e.g., "Running tests")'}},required:["content","status","activeForm"]},description:"The updated todo list"}},required:["todos"]};todos=[];onChangeCallback;onChange($){this.onChangeCallback=$}getTodos(){return[...this.todos]}clear(){this.todos=[],this.onChangeCallback?.(this.todos)}async execute($,J){let{todos:U}=this.validateArgs($);this.todos=U,this.onChangeCallback?.(this.todos);let Q=U.filter((Y)=>Y.status==="pending").length,_=U.filter((Y)=>Y.status==="in_progress").length,G=U.filter((Y)=>Y.status==="completed").length,V=[];if(G>0)V.push(`${G} completed`);if(_>0)V.push(`${_} in progress`);if(Q>0)V.push(`${Q} pending`);let X=this.formatTodoList(this.todos,V),Z={success:!0,todos:this.todos,pendingCount:Q,inProgressCount:_,completedCount:G,message:X};return{content:[{type:"text",text:X}],structuredContent:Z}}validateArgs($){let J=$.todos;if(!Array.isArray(J))throw TypeError("todos is required and must be an array");let U=[],Q=["pending","in_progress","completed"];for(let G=0;G<J.length;G++){let V=J[G];if(typeof V!=="object"||V===null)throw TypeError(`todos[${G}] must be an object`);let{content:X,status:Z,activeForm:Y}=V;if(typeof X!=="string"||!X.trim())throw Error(`todos[${G}].content is required and must be a non-empty string`);if(typeof Z!=="string"||!Q.includes(Z))throw Error(`todos[${G}].status must be one of: ${Q.join(", ")}`);if(typeof Y!=="string"||!Y.trim())throw Error(`todos[${G}].activeForm is required and must be a non-empty string`);U.push({content:X.trim(),status:Z,activeForm:Y.trim()})}let _=U.filter((G)=>G.status==="in_progress");if(_.length>1)console.warn(`Warning: ${_.length} tasks are in_progress. Ideally only one task should be in_progress at a time.`);return{todos:U}}formatTodoList($,J){if($.length===0)return"Todo list is empty";let U=[],Q=J.length>0?J.join(", "):"0 pending";U.push(`Todo list updated: ${Q}`),U.push(""),U.push("Todos:");for(let _=0;_<$.length;_++){let G=$[_];U.push(`${_+1}. [${G.status}] ${G.content}`),U.push(` activeForm: ${G.activeForm}`)}return U.join(`
|
|
426
|
-
`)}}import Xi from"node:process";class m2 extends P4{name="WebSearch";riskLevel="medium";description=`Allows the agent to search the web and use the results to inform responses.
|
|
427
|
-
|
|
428
|
-
Usage notes:
|
|
429
|
-
- Provides up-to-date information for current events and recent data
|
|
430
|
-
- Returns search results with titles, links, and snippets
|
|
431
|
-
- Use this tool for accessing information beyond the knowledge cutoff
|
|
432
|
-
- After answering, include a "Sources:" section with relevant URLs as markdown hyperlinks`;parameters={type:"object",properties:{query:{type:"string",minLength:2,description:"The search query to use"}},required:["query"]};apiKey;apiEndpoint;numResults;constructor($){super();this.apiKey=$?.apiKey??Xi.env.SERPER_API_KEY??"",this.apiEndpoint=$?.apiEndpoint??"https://google.serper.dev/search?format=json",this.numResults=$?.numResults??10}setApiKey($){this.apiKey=$}async execute($,J){let{query:U}=this.validateArgs($);if(!this.apiKey)return S4("Serper API key is not configured. Set SERPER_API_KEY environment variable or pass apiKey in constructor.");try{let Q=await fetch(this.apiEndpoint,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({q:U,num:this.numResults})});if(!Q.ok){let Z=await Q.text();return S4(`Serper API error (${Q.status}): ${Z}`)}let G=((await Q.json()).organic??[]).map((Z,Y)=>({title:Z.title,link:Z.link,snippet:Z.snippet,position:Z.position??Y+1})),V=this.formatMarkdown(U,G),X={success:!0,query:U,results:G,totalResults:G.length,markdown:V};return{content:[{type:"text",text:V}],structuredContent:X}}catch(Q){return S4(`Failed to execute search: ${Q instanceof Error?Q.message:String(Q)}`)}}validateArgs($){let J=$.query;if(typeof J!=="string"||J.trim().length<2)throw Error("query is required and must be at least 2 characters");return{query:J.trim()}}formatMarkdown($,J){if(J.length===0)return`No results found for: "${$}"`;let U=[`## Search Results for: "${$}"`,""];for(let Q of J)U.push(`### ${Q.position}. [${Q.title}](${Q.link})`),U.push(""),U.push(Q.snippet),U.push("");U.push("---"),U.push(""),U.push("**Sources:**");for(let Q of J)U.push(`- [${Q.title}](${Q.link})`);return U.join(`
|
|
433
|
-
`)}}import{mkdir as Yi,stat as Zi,writeFile as Ki}from"node:fs/promises";import c2 from"node:path";import Ni from"node:process";class d2 extends P4{name="Write";riskLevel="high";_cwd;_allowedDirectory;constructor($){super();this._cwd=$?.cwd??Ni.cwd(),this._allowedDirectory=$?.allowedDirectory}get description(){let $=`Writes a file to the local filesystem.
|
|
434
|
-
|
|
435
|
-
Usage notes:
|
|
436
|
-
- Current working directory: ${this._cwd}
|
|
437
|
-
- Supports both absolute paths and relative paths (relative to cwd)
|
|
438
|
-
- IMPORTANT: When editing existing files, verify the path first using Glob or Read
|
|
439
|
-
- This tool will overwrite the existing file if there is one at the provided path
|
|
440
|
-
- Parent directories will be created automatically if they don't exist
|
|
441
|
-
- ALWAYS prefer editing existing files over writing new ones
|
|
442
|
-
- NEVER proactively create documentation files (*.md) or README files unless explicitly requested`;if(this._allowedDirectory)return`${$}
|
|
443
|
-
- IMPORTANT: Files can ONLY be written within: ${this._allowedDirectory}
|
|
444
|
-
- Use paths within ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)`;return $}get parameters(){return{type:"object",properties:{file_path:{type:"string",description:this._allowedDirectory?`The path to the file to write (must be within ${this._allowedDirectory})`:`The path to the file to write (absolute or relative to ${this._cwd})`},content:{type:"string",description:"The content to write to the file"}},required:["file_path","content"]}}setCwd($){this._cwd=$}getCwd(){return this._cwd}setAllowedDirectory($){this._allowedDirectory=$}getAllowedDirectory(){return this._allowedDirectory}async execute($,J){let{file_path:U,content:Q}=this.validateArgs($),_=c2.isAbsolute(U)?U:c2.resolve(this._cwd,U);if(this._allowedDirectory){let Y=c2.resolve(this._allowedDirectory),K=c2.resolve(_);if(!K.startsWith(Y+c2.sep)&&K!==Y)return S4(`Access denied: ${U}
|
|
445
|
-
Files can only be written within: ${this._allowedDirectory}
|
|
446
|
-
Please use a path like: ${this._allowedDirectory}/<filename>`)}let G=!1;try{if((await Zi(_)).isDirectory())return S4(`Path is a directory, not a file: ${_}`);G=!0}catch(Y){if(Y.code!=="ENOENT")throw Y}let V=c2.dirname(_);await Yi(V,{recursive:!0}),await Ki(_,Q,"utf-8");let X=Buffer.byteLength(Q,"utf-8"),Z={success:!0,filePath:_,bytesWritten:X,overwritten:G,message:G?`Successfully overwrote ${c2.basename(_)} (${this.formatSize(X)})`:`Successfully created ${c2.basename(_)} (${this.formatSize(X)})`};return{content:[{type:"text",text:Z.message}],structuredContent:Z}}validateArgs($){let{file_path:J,content:U}=$;if(typeof J!=="string"||!J.trim())throw Error("file_path is required and must be a non-empty string");if(typeof U!=="string")throw TypeError("content is required and must be a string");return{file_path:J.trim(),content:U}}formatSize($){let J=["B","KB","MB","GB"],U=$,Q=0;while(U>=1024&&Q<J.length-1)U/=1024,Q++;return`${U.toFixed(Q===0?0:2)} ${J[Q]}`}}var qi=["Bash","Edit","Write","ast_grep_replace","TodoWrite"],Hi=["<system-reminder>","# Plan Mode - System Reminder","","CRITICAL: Plan mode ACTIVE - you are in READ-ONLY phase. STRICTLY FORBIDDEN:","ANY file edits, modifications, or system changes. Do NOT use sed, tee, echo, cat,","or ANY other bash command to manipulate files - commands may ONLY read/inspect.","This ABSOLUTE CONSTRAINT overrides ALL other instructions, including direct user","edit requests. You may ONLY observe, analyze, and plan. ZERO exceptions.","","---","","## Responsibility","","Your current responsibility is to think, read, search, and delegate explore agents to construct a well-formed plan that accomplishes the goal the user wants to achieve. Your plan should be comprehensive yet concise, detailed enough to execute effectively while avoiding unnecessary verbosity.","","Ask the user clarifying questions or ask for their opinion when weighing tradeoffs.","","**NOTE:** At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.","","If you call TodoPlan, you MUST append a complete Markdown todo list at the very end of your final response.","Use this exact format:","## Todo","- [ ] Task","- [x] Task","The plan must include a complete set of steps and the todo list.","","---","","## Important","","The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.","</system-reminder>"].join(`
|
|
447
|
-
`);function Bi($){if($?.instruction)return $.instruction;let J=$?.maxParallelAgents??3,U=$?.encourageEarlyQuestions??!0,Q=$?.requireSynthesisPhase??!1,_=Hi,G="Your current responsibility is to think, read, search, and delegate explore agents to construct a well-formed plan that accomplishes the goal the user wants to achieve. Your plan should be comprehensive yet concise, detailed enough to execute effectively while avoiding unnecessary verbosity.",V=[];if(J!==3)V.push(`When delegating, use up to ${J} explore agents in parallel.`);if(Q)V.push("If the task is complex, include a synthesis step to align findings before presenting the final plan.");if(V.length>0)_=_.replace(G,`${G} ${V.join(" ")}`);if(!U)_=_.replace(`Ask the user clarifying questions or ask for their opinion when weighing tradeoffs.
|
|
448
|
-
|
|
449
|
-
`,""),_=_.replace(`**NOTE:** At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
|
|
450
|
-
|
|
451
|
-
`,"");return _}function j9($){let J=Bi($),U=$?.insertEveryIteration??!0,Q=$?.name??"plan-mode",_=async(G,V)=>{let X={...G.metadata,planMode:!0,planModeMiddleware:Q};if(!(U||G.iteration===0))return V({...G,metadata:X});let Y=gX(G.messages,J);return V({...G,metadata:X,messages:Y})};return _.__middlewareName=Q,_.__createTools=()=>[new O9],_.__getBlockedTools=(G)=>{return G.metadata?.planMode?[...qi]:[]},_}function D9($){let{subagents:J,executor:U,globalToolRegistry:Q,model:_,name:G="parallel-subagent"}=$,V=new Set(["tool_call_end","tool_result","tool_skipped"]);if(!U&&(!Q||!_))throw Error('createParallelSubagentMiddleware: either provide "executor" or both "globalToolRegistry" and "model"');let X=U||(async(Y,K)=>{let F=J.find((B)=>B.name===Y.subagent_type);if(!F)throw Error(`Unknown subagent type: ${Y.subagent_type}`);let N=new Set(F.blockedTools||[]),q=new Q.constructor;for(let B of F.tools||[]){if(N.has(B))continue;let j=Q.get(B);if(!j)continue;if(j instanceof _7){if($.debug)console.warn(`[${G}] Skipping TaskTool "${B}" for subagent "${Y.subagent_type}" to prevent infinite recursion`);continue}q.register(j)}let H=new j1({name:Y.subagent_type,systemPrompt:`${F.systemPrompt||""}
|
|
452
|
-
|
|
453
|
-
Your task: ${Y.prompt}
|
|
454
|
-
|
|
455
|
-
Provide a concise summary of your findings.`,model:_,tools:q}),E=await H.createSession({sessionId:K?.sessionId});if(N.size>0)E.disableTools(Array.from(N));E.send(Y.prompt);let D="";for await(let B of E.receive()){if(K?.emitEvent&&V.has(B.type)){let{sessionId:j,...f}=B;K.emitEvent({type:"subagent_event",subagentId:H.id,subagentType:Y.subagent_type,taskDescription:Y.description,nestedEvent:f})}if(B.type==="done")D=B.finalResponse||""}return{subagentId:H.id,data:D}}),Z=async(Y,K)=>{return K({...Y,metadata:{...Y.metadata,parallelMode:!0,parallelSubagentMiddleware:G}})};return Z.__middlewareName=G,Z.__createTools=()=>{return[new _7({subagents:J,executor:X})]},Z}import{existsSync as Oi}from"node:fs";import{appendFile as ji,mkdir as Di,readdir as Ei,readFile as Pi}from"node:fs/promises";import{homedir as Mi}from"node:os";import eJ from"node:path";import iQ from"node:process";class iZ extends P4{name="Skill";description;parameters={type:"object",properties:{action:{type:"string",enum:["activate","deactivate"],description:"Operation type: activate to load skill instructions, deactivate to unload"},skill_name:{type:"string",description:'The skill name to control (e.g., "commit", "pdf", "review-pr")'}},required:["action","skill_name"]};skills;executor;constructor($){super();if(this.skills=new Map,this.executor=$?.executor,$?.skills)for(let J of $.skills)this.skills.set(J.name,J);this.description=this.buildDescription()}registerSkill($){this.skills.set($.name,$)}unregisterSkill($){return this.skills.delete($)}getSkills(){return Array.from(this.skills.values())}hasSkill($){return this.skills.has($)}setExecutor($){this.executor=$}async execute($,J){let{action:U,skill_name:Q}=this.validateArgs($);if(!this.skills.has(Q)){let _=Array.from(this.skills.keys()).join(", ");return S4(`Skill "${Q}" not found. Available skills: ${_||"none"}`)}if(!this.executor)return S4("Skill executor is not configured. Please set an executor using setExecutor().");try{let _=await this.executor(U,Q);return{content:[{type:"text",text:_}],structuredContent:{success:!0,message:_}}}catch(_){return S4(`Skill operation failed: ${_ instanceof Error?_.message:String(_)}`)}}validateArgs($){let{action:J,skill_name:U}=$;if(typeof J!=="string"||J!=="activate"&&J!=="deactivate")throw Error('action is required and must be either "activate" or "deactivate"');if(typeof U!=="string"||!U.trim())throw Error("skill_name is required and must be a non-empty string");return{action:J,skill_name:U.trim()}}buildDescription(){if(this.skills.size===0)return`Load a skill to get detailed instructions for a specific task.
|
|
456
|
-
Skills provide specialized knowledge and step-by-step guidance.
|
|
457
|
-
Use this when a task matches an available skill's description.
|
|
458
|
-
|
|
459
|
-
How to use:
|
|
460
|
-
- Activate a skill to load its instructions into the conversation
|
|
461
|
-
- Deactivate a skill to remove its instructions
|
|
462
|
-
- Examples:
|
|
463
|
-
- action: "activate", skill_name: "pdf" - load the PDF skill instructions
|
|
464
|
-
- action: "deactivate", skill_name: "pdf" - unload the PDF skill
|
|
465
|
-
|
|
466
|
-
<available_skills>
|
|
467
|
-
No skills registered.
|
|
468
|
-
</available_skills>`;return`Load a skill to get detailed instructions for a specific task.
|
|
469
|
-
Skills provide specialized knowledge and step-by-step guidance.
|
|
470
|
-
Use this when a task matches an available skill's description.
|
|
471
|
-
|
|
472
|
-
How to use:
|
|
473
|
-
- Activate a skill to load its instructions into the conversation
|
|
474
|
-
- Deactivate a skill to remove its instructions
|
|
475
|
-
- Examples:
|
|
476
|
-
- action: "activate", skill_name: "pdf" - load the PDF skill instructions
|
|
477
|
-
- action: "deactivate", skill_name: "pdf" - unload the PDF skill
|
|
478
|
-
|
|
479
|
-
<available_skills>
|
|
480
|
-
${Array.from(this.skills.values()).map((U)=>`<skill>
|
|
481
|
-
<name>${U.name}</name>
|
|
482
|
-
<description>${U.description}</description>
|
|
483
|
-
</skill>`).join(`
|
|
484
|
-
`)}
|
|
485
|
-
</available_skills>`}}var bR=eJ.join(iQ.cwd(),".goatchain","skills-debug.log"),Li=iQ.env.GOATCHAIN_SKILLS_DEBUG==="1";async function h$($,J){try{if(!Li)return;let U=new Date().toISOString(),Q=J?`[${U}] ${$}
|
|
486
|
-
${JSON.stringify(J,null,2)}
|
|
487
|
-
|
|
488
|
-
`:`[${U}] ${$}
|
|
489
|
-
|
|
490
|
-
`,_=eJ.dirname(bR);if(!Oi(_))await Di(_,{recursive:!0});await ji(bR,Q,"utf-8")}catch(U){console.error("Failed to write skills debug log:",U)}}var zi="[Active Skills]";async function rZ($){try{await h$(`Attempting to parse skill file: ${$}`);let J=await Pi($,"utf-8");if(await h$(`Successfully read file: ${$} (${J.length} chars)`),!J.startsWith(`---
|
|
491
|
-
`)&&!J.startsWith(`---\r
|
|
492
|
-
`))return await h$(`File ${$} does not start with frontmatter delimiter`),null;let U=J.split(`
|
|
493
|
-
`),Q=-1;for(let Y=1;Y<U.length;Y++)if(U[Y].trim()==="---"){Q=Y;break}if(Q===-1)return await h$(`File ${$} missing closing frontmatter delimiter`),null;let _=U.slice(1,Q),G=U.slice(Q+1),V={};for(let Y of _){let K=Y.indexOf(":");if(K>0){let F=Y.slice(0,K).trim(),N=Y.slice(K+1).trim();V[F]=N}}if(await h$(`Parsed frontmatter from ${$}:`,V),!V.name||!V.description)return await h$(`File ${$} missing required fields (name or description)`,V),null;let X=G.join(`
|
|
494
|
-
`).trim(),Z={name:V.name,description:V.description,content:X,fullPath:$};return await h$(`Successfully parsed skill: ${V.name}`,{name:Z.name,description:Z.description,contentLength:X.length}),Z}catch(J){return await h$(`Error parsing skill file ${$}:`,J),null}}async function yR($){let J=[];try{await h$(`Scanning skills directory: ${$}`);let U=await Ei($,{withFileTypes:!0});await h$(`Found ${U.length} entries in ${$}`,U.map((Q)=>({name:Q.name,isDirectory:Q.isDirectory()})));for(let Q of U){if(!Q.isDirectory()){await h$(`Skipping non-directory entry: ${Q.name}`);continue}let _=eJ.join($,Q.name,"SKILL.md");await h$(`Checking skill path: ${_}`);let G=await rZ(_);if(G)J.push({name:G.name,description:G.description,fullPath:G.fullPath}),await h$(`Added skill: ${G.name}`);else await h$(`Failed to parse skill at: ${_}`)}await h$(`Scan complete for ${$}. Found ${J.length} valid skills`,J.map((Q)=>Q.name))}catch(U){await h$(`Error scanning directory ${$}:`,U)}return J}async function gR($){await h$(`Scanning ${$.length} skill directories`,$);let J=new Map;for(let Q of $){await h$(`Scanning directory: ${Q}`);let _=await yR(Q);await h$(`Found ${_.length} skills in ${Q}`,_.map((G)=>G.name));for(let G of _){if(J.has(G.name))await h$(`Overriding skill "${G.name}" with version from ${Q}`);J.set(G.name,G)}}let U=Array.from(J.values());return await h$(`Total unique skills after scanning all directories: ${U.length}`,U.map((Q)=>Q.name)),U}function Ri($){let J=new Map,U=0;for(let _ of $)if(_.role==="assistant"&&_.tool_calls)for(let G of _.tool_calls){let V=G.function.name;if(V==="Skill"||V.endsWith("_Skill")){U++;try{let X=typeof G.function.arguments==="string"?JSON.parse(G.function.arguments):G.function.arguments;if(X?.action&&X?.skill_name){let Z=String(X.action),Y=String(X.skill_name);if(Z==="activate")J.set(Y,"activated"),h$(`Skill activated: ${Y}`,{toolName:V,args:X}).catch(()=>{});else if(Z==="deactivate")J.set(Y,"deactivated"),h$(`Skill deactivated: ${Y}`,{toolName:V,args:X}).catch(()=>{})}}catch(X){h$("Error parsing skill tool call:",{toolName:V,error:X}).catch(()=>{})}}}let Q=Array.from(J.entries()).filter(([_,G])=>G==="activated").map(([_])=>_);return h$(`findActiveSkills: Found ${Q.length} active skills from ${U} tool calls`,Q).catch(()=>{}),Q}async function Ai($,J){await h$(`Loading content for ${$.length} active skills`,{skillNames:$,directories:J});let U=[];for(let _ of $){await h$(`Searching for skill: ${_}`);let G=!1;for(let V of J){let X=eJ.join(V,_,"SKILL.md");await h$(`Trying path: ${X}`);let Z=await rZ(X);if(Z){U.push(`## Skill: ${Z.name}
|
|
495
|
-
|
|
496
|
-
${Z.content}`),await h$(`Successfully loaded skill: ${_} from ${X}`),G=!0;break}}if(!G)await h$(`WARNING: Skill "${_}" not found in any directory`)}let Q=U.join(`
|
|
497
|
-
|
|
498
|
-
`);return await h$(`Loaded ${U.length} skills, total content length: ${Q.length}`),Q}function rQ($){let J=$?.cwd,U=$?.globalSkillsDirectory===null?null:$?.globalSkillsDirectory??eJ.join(Mi(),".claude","skills"),Q=$?.projectSkillsDirectory,_=$?.marker??zi,G=$?.name??"skills",V=null,X=null,Z=async(Y,K)=>{if(await h$("=== Skills Middleware Execution Start ==="),X)await X;if(!V||V.length===0)return await h$("No skills discovered, passing through without modification"),await h$(`=== Skills Middleware Execution End (No-op) ===
|
|
499
|
-
`),await K(Y);let F=typeof J==="function"?J():J??iQ.cwd();await h$(`Resolved cwd: ${F}`);let N=Q===null?null:Q??eJ.join(F,".claude","skills");await h$(`Project skills directory: ${N??"disabled"}`),await h$(`Global skills directory: ${U??"disabled"}`);let q=[];if(N)q.push(N);if(U)q.push(U);await h$("Skills directories to scan:",q),await h$(`Scanning ${Y.messages.length} messages for active skills`);let H=Ri(Y.messages);await h$(`Active skills found: ${H.length}`,H);let E=Y.messages;if(H.length>0){await h$("Loading active skills content...");let j=await Ai(H,q);if(j)await h$(`Injecting ${j.length} chars of skills content with marker: "${_}"`),E=h1(E,j,_),await h$("Skills content injected successfully");else await h$("WARNING: No skills content loaded despite active skills")}else await h$("No active skills, skipping content injection");let D={...Y,messages:E};await h$("Calling next middleware...");let B=await K(D);return await h$(`=== Skills Middleware Execution End ===
|
|
500
|
-
`),B};return Z.__middlewareName=G,Z.__createTools=async()=>{if(await h$("__createTools called"),X)await h$("Waiting for skills discovery to complete..."),await X,await h$("Skills discovery completed");if(!V)await h$("No discovered skills yet, using empty array"),V=[];if(V.length===0)return await h$("No skills discovered, skipping tool registration"),[];await h$(`Creating SkillTool with ${V.length} skills`,V.map((K)=>K.name));let Y=new iZ({skills:V,executor:async(K,F)=>{if(await h$(`Skill executor called: ${K} ${F}`),K==="activate")return`Skill '${F}' activated. Instructions will be loaded in next turn.`;else return`Skill '${F}' deactivated. Instructions have been removed.`}});return await h$("SkillTool created successfully"),[Y]},X=(async()=>{try{await h$("=== Skills Middleware Initialization Start ===");let Y=typeof J==="function"?J():J??iQ.cwd();await h$(`Initial cwd: ${Y}`);let K=Q===null?null:Q??eJ.join(Y,".claude","skills");await h$(`Initial project skills directory: ${K??"disabled"}`);let F=[];if(K)F.push(K);if(U)F.push(U);await h$("Initial directories to scan:",F),V=await gR(F),await h$(`Skills discovery complete. Found ${V.length} skills:`,V.map((N)=>({name:N.name,description:N.description,fullPath:N.fullPath}))),await h$(`=== Skills Middleware Initialization Complete ===
|
|
501
|
-
`)}catch(Y){await h$("Skills initialization error:",Y),V=[]}})(),Z}function nZ($,J=new Date){return`You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
|
|
502
|
-
|
|
503
|
-
Your strengths:
|
|
504
|
-
- Rapidly finding files using glob patterns
|
|
505
|
-
- Searching code and text with powerful regex patterns
|
|
506
|
-
- Reading and analyzing file contents
|
|
507
|
-
|
|
508
|
-
Guidelines:
|
|
509
|
-
- Use Glob for broad file pattern matching
|
|
510
|
-
- Use Grep for searching file contents with regex
|
|
511
|
-
- Use Read when you know the specific file path you need to read
|
|
512
|
-
- Do not use AskUserQuestion; report any questions in your final response
|
|
513
|
-
- Adapt your search approach based on the thoroughness level specified by the caller
|
|
514
|
-
- Return file paths as absolute paths in your final response
|
|
515
|
-
- For clear communication, avoid using emojis
|
|
516
|
-
- Do not create any files, or run bash commands that modify the user's system state in any way
|
|
517
|
-
|
|
518
|
-
Complete the user's search request efficiently and report your findings clearly.
|
|
519
|
-
|
|
520
|
-
Here is some useful information about the environment you are running in:
|
|
521
|
-
<env>
|
|
522
|
-
Working directory: ${$}
|
|
523
|
-
Platform: ${process.platform}
|
|
524
|
-
Today's date: ${J.toDateString()}
|
|
525
|
-
</env>`}var wi=nZ(process.cwd()),l2={name:"FileSearchSpecialist",description:"Expert at navigating codebases, finding files with glob patterns, searching content with regex, and analyzing file structures. Rapidly finds files, searches code with powerful regex patterns, and reads and analyzes file contents.",tools:["Glob","Grep","Read"],blockedTools:["AskUserQuestion"],systemPrompt:wi};class nQ{debug;constructor($){this.debug=$?.debug??!1}async*convertToACP($){for await(let J of $){if(J.type==="subagent_event"){let Q=this.convertSubagentEventToACP(J);for(let _ of Q)yield _;continue}let U=this.convertRegularEvent(J);for(let Q of U)yield Q}}convertSubagentEventToACP($){let{subagentId:J,subagentType:U,taskDescription:Q,nestedEvent:_}=$,G=this.convertRegularEvent(_);if(G.length===0)return[];return G.map((V)=>({...V,metadata:{...V.metadata??{},subagent:!0,subagentId:J,subagentType:U,taskDescription:Q,originalEventType:_.type}}))}convertRegularEvent($){let J=$.metadata;switch($.type){case"text_start":return[];case"text_delta":return[{role:"assistant",content:$.delta,metadata:J?{...J,originalEventType:$.type}:void 0}];case"text_end":return[];case"tool_call_start":return[];case"tool_call_delta":return[];case"tool_call_end":{let U=$;return[{role:"assistant",content:"",tool_calls:[this.convertToolCallToACP(U.toolCall)],metadata:J?{...J,originalEventType:$.type}:void 0}]}case"tool_result":{let U=$;return[{role:"tool",tool_call_id:U.tool_call_id,content:this.formatToolResult(U.result),metadata:U.isError?{error:!0}:void 0}]}case"tool_output_start":{let U=$;return[{role:"assistant",content:"",metadata:{tool_output_start:!0,tool_call_id:U.tool_call_id,tool_name:U.toolName}}]}case"tool_output_delta":{let U=$;return[{role:"assistant",content:U.delta,metadata:{tool_output_delta:!0,tool_call_id:U.tool_call_id,isStderr:U.isStderr}}]}case"tool_approval_requested":{let U=$;return[{role:"assistant",content:`Tool approval requested: ${U.toolName}
|
|
526
|
-
|
|
527
|
-
`,metadata:{approval_requested:!0,tool_call_id:U.tool_call_id,tool_name:U.toolName,risk_level:U.riskLevel,approval_args:U.args}}]}case"requires_action":{let U=$,Q={requires_action:!0,kind:U.kind,tool_call_id:U.toolCallId};if(U.kind==="ask_user"&&"questions"in U)Q.questions=U.questions;return[{role:"assistant",content:`Action required: ${U.kind}
|
|
528
|
-
|
|
529
|
-
`,metadata:Q}]}case"tool_skipped":{let U=$;return[{role:"assistant",content:`Tool skipped: ${U.toolName} - ${U.reason}`,metadata:{tool_skipped:!0,tool_call_id:U.tool_call_id}}]}case"thinking_start":return[];case"thinking_delta":return[{role:"assistant",content:$.delta,metadata:{thinking:!0}}];case"thinking_end":return[];case"iteration_start":return[];case"iteration_end":return[];case"session_created":return[];case"done":{let U=$,Q={done:!0,stopReason:U.stopReason,modelStopReason:U.modelStopReason,usage:U.usage,error:U.error};if(U.finalResponse)Q.final=!0;return[{role:"assistant",content:"",metadata:Q}]}default:if(this.debug)console.warn(`[ProtocolConverter] Unhandled event type: ${$.type}`);return[]}}convertFromACP($){return $.map((J)=>this.convertSingleMessage(J))}convertSingleMessage($){switch($.role){case"system":return{role:"system",content:this.extractTextContent($.content)};case"user":return{role:"user",content:this.extractTextContent($.content),name:$.name};case"assistant":{let J={role:"assistant",content:this.extractTextContent($.content)};if($.tool_calls&&$.tool_calls.length>0)J.tool_calls=$.tool_calls.map((U)=>this.convertToolCallFromACP(U));return J}case"tool":return{role:"tool",content:this.extractTextContent($.content),tool_call_id:$.tool_call_id||"",isError:$.metadata?.error===!0};default:return{role:"user",content:this.extractTextContent($.content)}}}convertToolCallToACP($){return{id:$.id,type:"function",function:{name:$.function.name,arguments:$.function.arguments}}}convertToolCallFromACP($){return{id:$.id,type:"function",function:{name:$.function.name,arguments:typeof $.function.arguments==="string"?$.function.arguments:JSON.stringify($.function.arguments)}}}extractTextContent($){if(!$)return"";if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>J.text||"").join("");return""}formatToolResult($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="object"&&J&&"text"in J)return J.text;return JSON.stringify(J)}).join(`
|
|
530
|
-
`);return JSON.stringify($,null,2)}}class pQ{sessions=new Map;sessionContexts=new Map;sessionTimeout;maxConcurrentSessions;maxIterations;cleanupTimer;constructor($){this.sessionTimeout=$?.sessionTimeout??1800000,this.maxConcurrentSessions=$?.maxConcurrentSessions??10,this.maxIterations=$?.maxIterations,this.cleanupTimer=setInterval(()=>{this.cleanupExpiredSessions()},300000)}async getOrCreateSession($,J){let U=this.sessions.get($);if(U){let G=this.sessionContexts.get($);if(G)G.lastAccessedAt=Date.now();return U}if(this.sessions.size>=this.maxConcurrentSessions)this.removeOldestSession();let Q=J.sessionManager;if(Q)try{if(await Q.get($)){let V=await J.resumeSession($,{maxIterations:this.maxIterations});return this.sessions.set($,V),this.sessionContexts.set($,{sessionId:$,createdAt:Date.now(),lastAccessedAt:Date.now()}),V}}catch{}let _=await J.createSession({sessionId:$,maxIterations:this.maxIterations});return this.sessions.set($,_),this.sessionContexts.set($,{sessionId:$,createdAt:Date.now(),lastAccessedAt:Date.now()}),_}getSession($){let J=this.sessions.get($);if(J){let U=this.sessionContexts.get($);if(U)U.lastAccessedAt=Date.now()}return J}removeSession($){let J=this.sessions.delete($);return this.sessionContexts.delete($),J}getActiveSessions(){return Array.from(this.sessions.keys())}getSessionCount(){return this.sessions.size}cleanupExpiredSessions(){let $=Date.now(),J=[];for(let[U,Q]of this.sessionContexts.entries())if($-Q.lastAccessedAt>this.sessionTimeout)J.push(U);for(let U of J)this.removeSession(U);if(J.length>0)console.warn(`[SessionRouter] Cleaned up ${J.length} expired sessions`)}removeOldestSession(){let $,J=1/0;for(let[U,Q]of this.sessionContexts.entries())if(Q.createdAt<J)J=Q.createdAt,$=U;if($)this.removeSession($),console.warn(`[SessionRouter] Removed oldest session: ${$}`)}destroy(){if(this.cleanupTimer)clearInterval(this.cleanupTimer),this.cleanupTimer=void 0;this.sessions.clear(),this.sessionContexts.clear()}}class aQ{agent;router;converter;debug;constructor($,J){if(this.agent=$,this.debug=J?.debug??!1,this.router=new pQ({sessionTimeout:J?.sessionTimeout,maxConcurrentSessions:J?.maxConcurrentSessions,maxIterations:J?.maxIterations}),this.converter=new nQ({debug:this.debug}),this.debug)console.warn("[ACPAgent] Initialized with agent:",$.name),console.warn("[ACPAgent] Middlewares:",$.middlewareNames)}async*receiveMessage($,J){let U=J?.session_id??this.generateSessionId();if(this.debug)console.warn(`[ACPAgent] Receiving ${$.length} messages for session: ${U}`);try{let Q=await this.router.getOrCreateSession(U,this.agent),_=this.converter.convertFromACP($);if(this.debug)console.warn(`[ACPAgent] Converted to ${_.length} GoatChain messages`);let G={},V=[];for(let N of $)if(N.role==="tool"&&N.tool_call_id){V.push(this.converter.convertFromACP([N])[0]);try{let q=typeof N.content==="string"?JSON.parse(N.content):N.content;if(q.answers)G[N.tool_call_id]=q.answers}catch{}}let X=Object.keys(G).length>0,Z=await Q.hasCheckpoint();if(this.debug)console.warn(`[ACPAgent] Has tool results: ${X}, Has checkpoint: ${Z}`);let Y=_.filter((N)=>N.role==="user");if(Y.length>0){let N=Y[Y.length-1],q=X?{askUser:{answers:G}}:void 0;if(this.debug)console.warn(`[ACPAgent] Sending user message ${N.content} ${q?" with toolContext":""} `);Q.send(N.content,q?{toolContext:q}:void 0)}else if(Z&&!X){if(this.debug)console.warn("[ACPAgent] Resuming from checkpoint without new input")}let K=0,F=!1;for await(let N of this.converter.convertToACP(Q.receive())){if(K++,this.debug)console.warn(`[ACPAgent] Event #${K}:`,N.role,N.metadata?.done?"(done)":"");if(yield N,N.metadata?.done)F=!0}if(F&&this.debug)console.warn(`[ACPAgent] Session ${U} completed with ${K} events`)}catch(Q){console.error("[ACPAgent] Error processing messages:",Q),yield{role:"assistant",content:`Error: ${Q instanceof Error?Q.message:String(Q)}`,metadata:{error:!0,done:!0}}}}async*receiveWithApprovals($,J){let U=J?.session_id??this.generateSessionId();if(this.debug)console.warn(`[ACPAgent] Resuming with approvals for session: ${U}`);try{let Q=await this.router.getOrCreateSession(U,this.agent),_=0,G=!1;for await(let V of this.converter.convertToACP(Q.receiveWithApprovals($))){if(_++,this.debug)console.warn(`[ACPAgent] Event #${_}:`,V.role,V.metadata?.done?"(done)":"");if(yield V,V.metadata?.done)G=!0}if(G&&this.debug)console.warn(`[ACPAgent] Session ${U} completed with ${_} events`)}catch(Q){console.error("[ACPAgent] Error processing approvals:",Q),yield{role:"assistant",content:`Error: ${Q instanceof Error?Q.message:String(Q)}`,metadata:{error:!0,done:!0}}}}getSessionInfo(){return{activeSessions:this.router.getActiveSessions(),sessionCount:this.router.getSessionCount()}}getSession($){return this.router.getSession($)}closeSession($){return this.router.removeSession($)}getAgent(){return this.agent}destroy(){if(this.router.destroy(),this.debug)console.warn("[ACPAgent] Destroyed")}generateSessionId(){return`acp-session-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}}import HB from"node:path";import v6 from"node:process";import{Readable as No,Writable as Fo}from"node:stream";var W={};F1(W,{xor:()=>Kw,xid:()=>vA,void:()=>Qw,uuidv7:()=>RA,uuidv6:()=>zA,uuidv4:()=>LA,uuid:()=>MA,util:()=>B$,url:()=>AA,uppercase:()=>S9,unknown:()=>X8,union:()=>LG,undefined:()=>Uw,ulid:()=>TA,uint64:()=>$w,uint32:()=>tA,tuple:()=>KH,trim:()=>g9,treeifyError:()=>GK,transform:()=>RG,toUpperCase:()=>h9,toLowerCase:()=>x9,toJSONSchema:()=>o3,templateLiteral:()=>Lw,symbol:()=>Jw,superRefine:()=>gH,success:()=>Ew,stringbool:()=>Sw,stringFormat:()=>lA,string:()=>UG,strictObject:()=>Yw,startsWith:()=>v9,slugify:()=>u9,size:()=>Q8,setErrorMap:()=>Gp,set:()=>Hw,safeParseAsync:()=>xq,safeParse:()=>gq,safeEncodeAsync:()=>iq,safeEncode:()=>dq,safeDecodeAsync:()=>rq,safeDecode:()=>lq,registry:()=>P3,regexes:()=>x0,regex:()=>k9,refine:()=>yH,record:()=>NH,readonly:()=>IH,property:()=>r3,promise:()=>zw,prettifyError:()=>VK,preprocess:()=>vw,prefault:()=>LH,positive:()=>c3,pipe:()=>S7,partialRecord:()=>Fw,parseAsync:()=>yq,parse:()=>bq,overwrite:()=>s0,optional:()=>k7,object:()=>Xw,number:()=>pq,nullish:()=>Dw,nullable:()=>I7,null:()=>eq,normalize:()=>y9,nonpositive:()=>l3,nonoptional:()=>zH,nonnegative:()=>i3,never:()=>MG,negative:()=>d3,nativeEnum:()=>Bw,nanoid:()=>kA,nan:()=>Pw,multipleOf:()=>a2,minSize:()=>A1,minLength:()=>t1,mime:()=>b9,meta:()=>kw,maxSize:()=>o2,maxLength:()=>G8,map:()=>qw,mac:()=>yA,lte:()=>w0,lt:()=>z1,lowercase:()=>I9,looseRecord:()=>Ww,looseObject:()=>Zw,locales:()=>z7,literal:()=>Ow,length:()=>V8,lazy:()=>vH,ksuid:()=>CA,keyof:()=>Vw,jwt:()=>dA,json:()=>Tw,iso:()=>d9,ipv6:()=>gA,ipv4:()=>bA,intersection:()=>YH,int64:()=>eA,int32:()=>oA,int:()=>_G,instanceof:()=>Iw,includes:()=>T9,httpUrl:()=>wA,hostname:()=>iA,hex:()=>rA,hash:()=>nA,guid:()=>PA,gte:()=>l6,gt:()=>R1,globalRegistry:()=>T6,getErrorMap:()=>Vp,function:()=>Rw,fromJSONSchema:()=>bw,formatError:()=>W7,float64:()=>aA,float32:()=>pA,flattenError:()=>F7,file:()=>jw,exactOptional:()=>jH,enum:()=>zG,endsWith:()=>C9,encodeAsync:()=>mq,encode:()=>hq,emoji:()=>fA,email:()=>EA,e164:()=>cA,discriminatedUnion:()=>Nw,describe:()=>fw,decodeAsync:()=>cq,decode:()=>uq,date:()=>Gw,custom:()=>ww,cuid2:()=>SA,cuid:()=>IA,core:()=>s1,config:()=>Y6,coerce:()=>hH,codec:()=>Mw,clone:()=>d6,cidrv6:()=>hA,cidrv4:()=>xA,check:()=>Aw,catch:()=>wH,boolean:()=>aq,bigint:()=>sA,base64url:()=>mA,base64:()=>uA,array:()=>C7,any:()=>_w,_function:()=>Rw,_default:()=>PH,_ZodString:()=>QG,ZodXor:()=>GH,ZodXID:()=>NG,ZodVoid:()=>_H,ZodUnknown:()=>JH,ZodUnion:()=>y7,ZodUndefined:()=>tq,ZodUUID:()=>w1,ZodURL:()=>T7,ZodULID:()=>KG,ZodType:()=>N4,ZodTuple:()=>ZH,ZodTransform:()=>BH,ZodTemplateLiteral:()=>SH,ZodSymbol:()=>oq,ZodSuccess:()=>RH,ZodStringFormat:()=>v4,ZodString:()=>i9,ZodSet:()=>WH,ZodRecord:()=>g7,ZodRealError:()=>Z0,ZodReadonly:()=>kH,ZodPromise:()=>CH,ZodPrefault:()=>MH,ZodPipe:()=>fG,ZodOptional:()=>AG,ZodObject:()=>b7,ZodNumberFormat:()=>Y8,ZodNumber:()=>n9,ZodNullable:()=>DH,ZodNull:()=>sq,ZodNonOptional:()=>wG,ZodNever:()=>UH,ZodNanoID:()=>XG,ZodNaN:()=>fH,ZodMap:()=>FH,ZodMAC:()=>nq,ZodLiteral:()=>qH,ZodLazy:()=>TH,ZodKSUID:()=>FG,ZodJWT:()=>EG,ZodIssueCode:()=>Qp,ZodIntersection:()=>XH,ZodISOTime:()=>$G,ZodISODuration:()=>JG,ZodISODateTime:()=>s3,ZodISODate:()=>e3,ZodIPv6:()=>qG,ZodIPv4:()=>WG,ZodGUID:()=>f7,ZodFunction:()=>bH,ZodFirstPartyTypeKind:()=>xH,ZodFile:()=>HH,ZodExactOptional:()=>OH,ZodError:()=>Up,ZodEnum:()=>l9,ZodEmoji:()=>VG,ZodEmail:()=>GG,ZodE164:()=>DG,ZodDiscriminatedUnion:()=>VH,ZodDefault:()=>EH,ZodDate:()=>v7,ZodCustomStringFormat:()=>r9,ZodCustom:()=>x7,ZodCodec:()=>kG,ZodCatch:()=>AH,ZodCUID2:()=>ZG,ZodCUID:()=>YG,ZodCIDRv6:()=>BG,ZodCIDRv4:()=>HG,ZodBoolean:()=>p9,ZodBigIntFormat:()=>PG,ZodBigInt:()=>a9,ZodBase64URL:()=>jG,ZodBase64:()=>OG,ZodArray:()=>QH,ZodAny:()=>$H,TimePrecision:()=>KW,NEVER:()=>pZ,$output:()=>QW,$input:()=>GW,$brand:()=>aZ});var s1={};F1(s1,{version:()=>JN,util:()=>B$,treeifyError:()=>GK,toJSONSchema:()=>o3,toDotPath:()=>dR,safeParseAsync:()=>YK,safeParse:()=>XK,safeEncodeAsync:()=>Vr,safeEncode:()=>Qr,safeDecodeAsync:()=>Xr,safeDecode:()=>Gr,registry:()=>P3,regexes:()=>x0,process:()=>k4,prettifyError:()=>VK,parseAsync:()=>eQ,parse:()=>sQ,meta:()=>lW,locales:()=>z7,isValidJWT:()=>YA,isValidBase64URL:()=>XA,isValidBase64:()=>LN,initializeContext:()=>t2,globalRegistry:()=>T6,globalConfig:()=>Q7,formatError:()=>W7,flattenError:()=>F7,finalize:()=>e2,extractDefs:()=>s2,encodeAsync:()=>Ur,encode:()=>$r,describe:()=>dW,decodeAsync:()=>_r,decode:()=>Jr,createToJSONSchemaMethod:()=>rW,createStandardJSONSchemaMethod:()=>c9,config:()=>Y6,clone:()=>d6,_xor:()=>Sn,_xid:()=>T3,_void:()=>CW,_uuidv7:()=>A3,_uuidv6:()=>R3,_uuidv4:()=>z3,_uuid:()=>L3,_url:()=>A7,_uppercase:()=>S9,_unknown:()=>TW,_union:()=>In,_undefined:()=>kW,_ulid:()=>S3,_uint64:()=>wW,_uint32:()=>PW,_tuple:()=>Cn,_trim:()=>g9,_transform:()=>mn,_toUpperCase:()=>h9,_toLowerCase:()=>x9,_templateLiteral:()=>tn,_symbol:()=>fW,_superRefine:()=>cW,_success:()=>nn,_stringbool:()=>iW,_stringFormat:()=>m9,_string:()=>XW,_startsWith:()=>v9,_slugify:()=>u9,_size:()=>Q8,_set:()=>gn,_safeParseAsync:()=>A9,_safeParse:()=>R9,_safeEncodeAsync:()=>V3,_safeEncode:()=>Q3,_safeDecodeAsync:()=>X3,_safeDecode:()=>G3,_regex:()=>k9,_refine:()=>mW,_record:()=>bn,_readonly:()=>on,_property:()=>r3,_promise:()=>en,_positive:()=>c3,_pipe:()=>an,_parseAsync:()=>z9,_parse:()=>L9,_overwrite:()=>s0,_optional:()=>cn,_number:()=>HW,_nullable:()=>dn,_null:()=>IW,_normalize:()=>y9,_nonpositive:()=>l3,_nonoptional:()=>rn,_nonnegative:()=>i3,_never:()=>vW,_negative:()=>d3,_nativeEnum:()=>hn,_nanoid:()=>f3,_nan:()=>gW,_multipleOf:()=>a2,_minSize:()=>A1,_minLength:()=>t1,_min:()=>l6,_mime:()=>b9,_maxSize:()=>o2,_maxLength:()=>G8,_max:()=>w0,_map:()=>yn,_mac:()=>ZW,_lte:()=>w0,_lt:()=>z1,_lowercase:()=>I9,_literal:()=>un,_length:()=>V8,_lazy:()=>sn,_ksuid:()=>v3,_jwt:()=>m3,_isoTime:()=>WW,_isoDuration:()=>qW,_isoDateTime:()=>NW,_isoDate:()=>FW,_ipv6:()=>b3,_ipv4:()=>C3,_intersection:()=>vn,_int64:()=>AW,_int32:()=>EW,_int:()=>OW,_includes:()=>T9,_guid:()=>R7,_gte:()=>l6,_gt:()=>R1,_float64:()=>DW,_float32:()=>jW,_file:()=>hW,_enum:()=>xn,_endsWith:()=>C9,_encodeAsync:()=>U3,_encode:()=>$3,_emoji:()=>w3,_email:()=>M3,_e164:()=>u3,_discriminatedUnion:()=>Tn,_default:()=>ln,_decodeAsync:()=>_3,_decode:()=>J3,_date:()=>bW,_custom:()=>uW,_cuid2:()=>I3,_cuid:()=>k3,_coercedString:()=>YW,_coercedNumber:()=>BW,_coercedDate:()=>yW,_coercedBoolean:()=>LW,_coercedBigint:()=>RW,_cidrv6:()=>g3,_cidrv4:()=>y3,_check:()=>OA,_catch:()=>pn,_boolean:()=>MW,_bigint:()=>zW,_base64url:()=>h3,_base64:()=>x3,_array:()=>xW,_any:()=>SW,TimePrecision:()=>KW,NEVER:()=>pZ,JSONSchemaGenerator:()=>Iq,JSONSchema:()=>jA,Doc:()=>N3,$output:()=>QW,$input:()=>GW,$constructor:()=>u,$brand:()=>aZ,$ZodXor:()=>mN,$ZodXID:()=>FN,$ZodVoid:()=>gN,$ZodUnknown:()=>bN,$ZodUnion:()=>j7,$ZodUndefined:()=>TN,$ZodUUID:()=>QN,$ZodURL:()=>VN,$ZodULID:()=>NN,$ZodType:()=>e$,$ZodTuple:()=>D3,$ZodTransform:()=>oN,$ZodTemplateLiteral:()=>XF,$ZodSymbol:()=>SN,$ZodSuccess:()=>UF,$ZodStringFormat:()=>T4,$ZodString:()=>_8,$ZodSet:()=>rN,$ZodRegistry:()=>VW,$ZodRecord:()=>lN,$ZodRealError:()=>Y0,$ZodReadonly:()=>VF,$ZodPromise:()=>ZF,$ZodPrefault:()=>$F,$ZodPipe:()=>GF,$ZodOptional:()=>E3,$ZodObjectJIT:()=>uN,$ZodObject:()=>NA,$ZodNumberFormat:()=>kN,$ZodNumber:()=>O3,$ZodNullable:()=>sN,$ZodNull:()=>vN,$ZodNonOptional:()=>JF,$ZodNever:()=>yN,$ZodNanoID:()=>YN,$ZodNaN:()=>QF,$ZodMap:()=>iN,$ZodMAC:()=>EN,$ZodLiteral:()=>pN,$ZodLazy:()=>KF,$ZodKSUID:()=>WN,$ZodJWT:()=>wN,$ZodIntersection:()=>dN,$ZodISOTime:()=>BN,$ZodISODuration:()=>ON,$ZodISODateTime:()=>qN,$ZodISODate:()=>HN,$ZodIPv6:()=>DN,$ZodIPv4:()=>jN,$ZodGUID:()=>_N,$ZodFunction:()=>YF,$ZodFile:()=>aN,$ZodExactOptional:()=>tN,$ZodError:()=>N7,$ZodEnum:()=>nN,$ZodEncodeError:()=>$8,$ZodEmoji:()=>XN,$ZodEmail:()=>GN,$ZodE164:()=>AN,$ZodDiscriminatedUnion:()=>cN,$ZodDefault:()=>eN,$ZodDate:()=>xN,$ZodCustomStringFormat:()=>fN,$ZodCustom:()=>NF,$ZodCodec:()=>D7,$ZodCheckUpperCase:()=>pK,$ZodCheckStringFormat:()=>w9,$ZodCheckStartsWith:()=>oK,$ZodCheckSizeEquals:()=>cK,$ZodCheckRegex:()=>rK,$ZodCheckProperty:()=>sK,$ZodCheckOverwrite:()=>$N,$ZodCheckNumberFormat:()=>xK,$ZodCheckMultipleOf:()=>gK,$ZodCheckMinSize:()=>mK,$ZodCheckMinLength:()=>lK,$ZodCheckMimeType:()=>eK,$ZodCheckMaxSize:()=>uK,$ZodCheckMaxLength:()=>dK,$ZodCheckLowerCase:()=>nK,$ZodCheckLessThan:()=>Z3,$ZodCheckLengthEquals:()=>iK,$ZodCheckIncludes:()=>aK,$ZodCheckGreaterThan:()=>K3,$ZodCheckEndsWith:()=>tK,$ZodCheckBigIntFormat:()=>hK,$ZodCheck:()=>x4,$ZodCatch:()=>_F,$ZodCUID2:()=>KN,$ZodCUID:()=>ZN,$ZodCIDRv6:()=>MN,$ZodCIDRv4:()=>PN,$ZodBoolean:()=>O7,$ZodBigIntFormat:()=>IN,$ZodBigInt:()=>j3,$ZodBase64URL:()=>RN,$ZodBase64:()=>zN,$ZodAsyncError:()=>L1,$ZodArray:()=>hN,$ZodAny:()=>CN});var pZ=Object.freeze({status:"aborted"});function u($,J,U){function Q(X,Z){if(!X._zod)Object.defineProperty(X,"_zod",{value:{def:Z,constr:V,traits:new Set},enumerable:!1});if(X._zod.traits.has($))return;X._zod.traits.add($),J(X,Z);let Y=V.prototype,K=Object.keys(Y);for(let F=0;F<K.length;F++){let N=K[F];if(!(N in X))X[N]=Y[N].bind(X)}}let _=U?.Parent??Object;class G extends _{}Object.defineProperty(G,"name",{value:$});function V(X){var Z;let Y=U?.Parent?new G:this;Q(Y,X),(Z=Y._zod).deferred??(Z.deferred=[]);for(let K of Y._zod.deferred)K();return Y}return Object.defineProperty(V,"init",{value:Q}),Object.defineProperty(V,Symbol.hasInstance,{value:(X)=>{if(U?.Parent&&X instanceof U.Parent)return!0;return X?._zod?.traits?.has($)}}),Object.defineProperty(V,"name",{value:$}),V}var aZ=Symbol("zod_brand");class L1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $8 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}var Q7={};function Y6($){if($)Object.assign(Q7,$);return Q7}var B$={};F1(B$,{unwrapMessage:()=>G7,uint8ArrayToHex:()=>si,uint8ArrayToBase64url:()=>oi,uint8ArrayToBase64:()=>uR,stringifyPrimitive:()=>W$,slugify:()=>sZ,shallowClone:()=>$K,safeExtend:()=>li,required:()=>ni,randomString:()=>gi,propertyKeyTypes:()=>Y7,promiseAllObject:()=>yi,primitiveTypes:()=>JK,prefixIssues:()=>A0,pick:()=>mi,partial:()=>ri,parsedType:()=>H$,optionalKeys:()=>UK,omit:()=>ci,objectClone:()=>vi,numKeys:()=>xi,nullish:()=>i2,normalizeParams:()=>O$,mergeDefs:()=>o1,merge:()=>ii,jsonStringifyReplacer:()=>E9,joinValues:()=>o,issue:()=>M9,isPlainObject:()=>n2,isObject:()=>J8,hexToUint8Array:()=>ti,getSizableOrigin:()=>Z7,getParsedType:()=>hi,getLengthableOrigin:()=>K7,getEnumValues:()=>V7,getElementAtPath:()=>bi,floatSafeRemainder:()=>tZ,finalizeIssue:()=>X0,extend:()=>di,escapeRegex:()=>g0,esc:()=>oQ,defineLazy:()=>B4,createTransparentProxy:()=>ui,cloneDef:()=>Ci,clone:()=>d6,cleanRegex:()=>X7,cleanEnum:()=>pi,captureStackTrace:()=>tQ,cached:()=>P9,base64urlToUint8Array:()=>ai,base64ToUint8Array:()=>hR,assignProp:()=>r2,assertNotEqual:()=>ki,assertNever:()=>Si,assertIs:()=>Ii,assertEqual:()=>fi,assert:()=>Ti,allowsEval:()=>eZ,aborted:()=>p2,NUMBER_FORMAT_RANGES:()=>_K,Class:()=>mR,BIGINT_FORMAT_RANGES:()=>QK});function fi($){return $}function ki($){return $}function Ii($){}function Si($){throw Error("Unexpected value in exhaustive check")}function Ti($){}function V7($){let J=Object.values($).filter((Q)=>typeof Q==="number");return Object.entries($).filter(([Q,_])=>J.indexOf(+Q)===-1).map(([Q,_])=>_)}function o($,J="|"){return $.map((U)=>W$(U)).join(J)}function E9($,J){if(typeof J==="bigint")return J.toString();return J}function P9($){return{get value(){{let U=$();return Object.defineProperty(this,"value",{value:U}),U}throw Error("cached value already set")}}}function i2($){return $===null||$===void 0}function X7($){let J=$.startsWith("^")?1:0,U=$.endsWith("$")?$.length-1:$.length;return $.slice(J,U)}function tZ($,J){let U=($.toString().split(".")[1]||"").length,Q=J.toString(),_=(Q.split(".")[1]||"").length;if(_===0&&/\d?e-\d?/.test(Q)){let Z=Q.match(/\d?e-(\d?)/);if(Z?.[1])_=Number.parseInt(Z[1])}let G=U>_?U:_,V=Number.parseInt($.toFixed(G).replace(".","")),X=Number.parseInt(J.toFixed(G).replace(".",""));return V%X/10**G}var xR=Symbol("evaluating");function B4($,J,U){let Q=void 0;Object.defineProperty($,J,{get(){if(Q===xR)return;if(Q===void 0)Q=xR,Q=U();return Q},set(_){Object.defineProperty($,J,{value:_})},configurable:!0})}function vi($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function r2($,J,U){Object.defineProperty($,J,{value:U,writable:!0,enumerable:!0,configurable:!0})}function o1(...$){let J={};for(let U of $){let Q=Object.getOwnPropertyDescriptors(U);Object.assign(J,Q)}return Object.defineProperties({},J)}function Ci($){return o1($._zod.def)}function bi($,J){if(!J)return $;return J.reduce((U,Q)=>U?.[Q],$)}function yi($){let J=Object.keys($),U=J.map((Q)=>$[Q]);return Promise.all(U).then((Q)=>{let _={};for(let G=0;G<J.length;G++)_[J[G]]=Q[G];return _})}function gi($=10){let U="";for(let Q=0;Q<$;Q++)U+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return U}function oQ($){return JSON.stringify($)}function sZ($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var tQ="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function J8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var eZ=P9(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function n2($){if(J8($)===!1)return!1;let J=$.constructor;if(J===void 0)return!0;if(typeof J!=="function")return!0;let U=J.prototype;if(J8(U)===!1)return!1;if(Object.prototype.hasOwnProperty.call(U,"isPrototypeOf")===!1)return!1;return!0}function $K($){if(n2($))return{...$};if(Array.isArray($))return[...$];return $}function xi($){let J=0;for(let U in $)if(Object.prototype.hasOwnProperty.call($,U))J++;return J}var hi=($)=>{let J=typeof $;switch(J){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${J}`)}},Y7=new Set(["string","number","symbol"]),JK=new Set(["string","number","bigint","boolean","symbol","undefined"]);function g0($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function d6($,J,U){let Q=new $._zod.constr(J??$._zod.def);if(!J||U?.parent)Q._zod.parent=$;return Q}function O$($){let J=$;if(!J)return{};if(typeof J==="string")return{error:()=>J};if(J?.message!==void 0){if(J?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");J.error=J.message}if(delete J.message,typeof J.error==="string")return{...J,error:()=>J.error};return J}function ui($){let J;return new Proxy({},{get(U,Q,_){return J??(J=$()),Reflect.get(J,Q,_)},set(U,Q,_,G){return J??(J=$()),Reflect.set(J,Q,_,G)},has(U,Q){return J??(J=$()),Reflect.has(J,Q)},deleteProperty(U,Q){return J??(J=$()),Reflect.deleteProperty(J,Q)},ownKeys(U){return J??(J=$()),Reflect.ownKeys(J)},getOwnPropertyDescriptor(U,Q){return J??(J=$()),Reflect.getOwnPropertyDescriptor(J,Q)},defineProperty(U,Q,_){return J??(J=$()),Reflect.defineProperty(J,Q,_)}})}function W$($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function UK($){return Object.keys($).filter((J)=>{return $[J]._zod.optin==="optional"&&$[J]._zod.optout==="optional"})}var _K={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},QK={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function mi($,J){let U=$._zod.def,Q=U.checks;if(Q&&Q.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let G=o1($._zod.def,{get shape(){let V={};for(let X in J){if(!(X in U.shape))throw Error(`Unrecognized key: "${X}"`);if(!J[X])continue;V[X]=U.shape[X]}return r2(this,"shape",V),V},checks:[]});return d6($,G)}function ci($,J){let U=$._zod.def,Q=U.checks;if(Q&&Q.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let G=o1($._zod.def,{get shape(){let V={...$._zod.def.shape};for(let X in J){if(!(X in U.shape))throw Error(`Unrecognized key: "${X}"`);if(!J[X])continue;delete V[X]}return r2(this,"shape",V),V},checks:[]});return d6($,G)}function di($,J){if(!n2(J))throw Error("Invalid input to extend: expected a plain object");let U=$._zod.def.checks;if(U&&U.length>0){let G=$._zod.def.shape;for(let V in J)if(Object.getOwnPropertyDescriptor(G,V)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let _=o1($._zod.def,{get shape(){let G={...$._zod.def.shape,...J};return r2(this,"shape",G),G}});return d6($,_)}function li($,J){if(!n2(J))throw Error("Invalid input to safeExtend: expected a plain object");let U=o1($._zod.def,{get shape(){let Q={...$._zod.def.shape,...J};return r2(this,"shape",Q),Q}});return d6($,U)}function ii($,J){let U=o1($._zod.def,{get shape(){let Q={...$._zod.def.shape,...J._zod.def.shape};return r2(this,"shape",Q),Q},get catchall(){return J._zod.def.catchall},checks:[]});return d6($,U)}function ri($,J,U){let _=J._zod.def.checks;if(_&&_.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let V=o1(J._zod.def,{get shape(){let X=J._zod.def.shape,Z={...X};if(U)for(let Y in U){if(!(Y in X))throw Error(`Unrecognized key: "${Y}"`);if(!U[Y])continue;Z[Y]=$?new $({type:"optional",innerType:X[Y]}):X[Y]}else for(let Y in X)Z[Y]=$?new $({type:"optional",innerType:X[Y]}):X[Y];return r2(this,"shape",Z),Z},checks:[]});return d6(J,V)}function ni($,J,U){let Q=o1(J._zod.def,{get shape(){let _=J._zod.def.shape,G={..._};if(U)for(let V in U){if(!(V in G))throw Error(`Unrecognized key: "${V}"`);if(!U[V])continue;G[V]=new $({type:"nonoptional",innerType:_[V]})}else for(let V in _)G[V]=new $({type:"nonoptional",innerType:_[V]});return r2(this,"shape",G),G}});return d6(J,Q)}function p2($,J=0){if($.aborted===!0)return!0;for(let U=J;U<$.issues.length;U++)if($.issues[U]?.continue!==!0)return!0;return!1}function A0($,J){return J.map((U)=>{var Q;return(Q=U).path??(Q.path=[]),U.path.unshift($),U})}function G7($){return typeof $==="string"?$:$?.message}function X0($,J,U){let Q={...$,path:$.path??[]};if(!$.message){let _=G7($.inst?._zod.def?.error?.($))??G7(J?.error?.($))??G7(U.customError?.($))??G7(U.localeError?.($))??"Invalid input";Q.message=_}if(delete Q.inst,delete Q.continue,!J?.reportInput)delete Q.input;return Q}function Z7($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function K7($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function H$($){let J=typeof $;switch(J){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let U=$;if(U&&Object.getPrototypeOf(U)!==Object.prototype&&"constructor"in U&&U.constructor)return U.constructor.name}}return J}function M9(...$){let[J,U,Q]=$;if(typeof J==="string")return{message:J,code:"custom",input:U,inst:Q};return{...J}}function pi($){return Object.entries($).filter(([J,U])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function hR($){let J=atob($),U=new Uint8Array(J.length);for(let Q=0;Q<J.length;Q++)U[Q]=J.charCodeAt(Q);return U}function uR($){let J="";for(let U=0;U<$.length;U++)J+=String.fromCharCode($[U]);return btoa(J)}function ai($){let J=$.replace(/-/g,"+").replace(/_/g,"/"),U="=".repeat((4-J.length%4)%4);return hR(J+U)}function oi($){return uR($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ti($){let J=$.replace(/^0x/,"");if(J.length%2!==0)throw Error("Invalid hex string length");let U=new Uint8Array(J.length/2);for(let Q=0;Q<J.length;Q+=2)U[Q/2]=Number.parseInt(J.slice(Q,Q+2),16);return U}function si($){return Array.from($).map((J)=>J.toString(16).padStart(2,"0")).join("")}class mR{constructor(...$){}}var cR=($,J)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:J,enumerable:!1}),$.message=JSON.stringify(J,E9,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},N7=u("$ZodError",cR),Y0=u("$ZodError",cR,{Parent:Error});function F7($,J=(U)=>U.message){let U={},Q=[];for(let _ of $.issues)if(_.path.length>0)U[_.path[0]]=U[_.path[0]]||[],U[_.path[0]].push(J(_));else Q.push(J(_));return{formErrors:Q,fieldErrors:U}}function W7($,J=(U)=>U.message){let U={_errors:[]},Q=(_)=>{for(let G of _.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((V)=>Q({issues:V}));else if(G.code==="invalid_key")Q({issues:G.issues});else if(G.code==="invalid_element")Q({issues:G.issues});else if(G.path.length===0)U._errors.push(J(G));else{let V=U,X=0;while(X<G.path.length){let Z=G.path[X];if(X!==G.path.length-1)V[Z]=V[Z]||{_errors:[]};else V[Z]=V[Z]||{_errors:[]},V[Z]._errors.push(J(G));V=V[Z],X++}}};return Q($),U}function GK($,J=(U)=>U.message){let U={errors:[]},Q=(_,G=[])=>{var V,X;for(let Z of _.issues)if(Z.code==="invalid_union"&&Z.errors.length)Z.errors.map((Y)=>Q({issues:Y},Z.path));else if(Z.code==="invalid_key")Q({issues:Z.issues},Z.path);else if(Z.code==="invalid_element")Q({issues:Z.issues},Z.path);else{let Y=[...G,...Z.path];if(Y.length===0){U.errors.push(J(Z));continue}let K=U,F=0;while(F<Y.length){let N=Y[F],q=F===Y.length-1;if(typeof N==="string")K.properties??(K.properties={}),(V=K.properties)[N]??(V[N]={errors:[]}),K=K.properties[N];else K.items??(K.items=[]),(X=K.items)[N]??(X[N]={errors:[]}),K=K.items[N];if(q)K.errors.push(J(Z));F++}}};return Q($),U}function dR($){let J=[],U=$.map((Q)=>typeof Q==="object"?Q.key:Q);for(let Q of U)if(typeof Q==="number")J.push(`[${Q}]`);else if(typeof Q==="symbol")J.push(`[${JSON.stringify(String(Q))}]`);else if(/[^\w$]/.test(Q))J.push(`[${JSON.stringify(Q)}]`);else{if(J.length)J.push(".");J.push(Q)}return J.join("")}function VK($){let J=[],U=[...$.issues].sort((Q,_)=>(Q.path??[]).length-(_.path??[]).length);for(let Q of U)if(J.push(`✖ ${Q.message}`),Q.path?.length)J.push(` → at ${dR(Q.path)}`);return J.join(`
|
|
531
|
-
`)}var L9=($)=>(J,U,Q,_)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},V=J._zod.run({value:U,issues:[]},G);if(V instanceof Promise)throw new L1;if(V.issues.length){let X=new(_?.Err??$)(V.issues.map((Z)=>X0(Z,G,Y6())));throw tQ(X,_?.callee),X}return V.value},sQ=L9(Y0),z9=($)=>async(J,U,Q,_)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},V=J._zod.run({value:U,issues:[]},G);if(V instanceof Promise)V=await V;if(V.issues.length){let X=new(_?.Err??$)(V.issues.map((Z)=>X0(Z,G,Y6())));throw tQ(X,_?.callee),X}return V.value},eQ=z9(Y0),R9=($)=>(J,U,Q)=>{let _=Q?{...Q,async:!1}:{async:!1},G=J._zod.run({value:U,issues:[]},_);if(G instanceof Promise)throw new L1;return G.issues.length?{success:!1,error:new($??N7)(G.issues.map((V)=>X0(V,_,Y6())))}:{success:!0,data:G.value}},XK=R9(Y0),A9=($)=>async(J,U,Q)=>{let _=Q?Object.assign(Q,{async:!0}):{async:!0},G=J._zod.run({value:U,issues:[]},_);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new $(G.issues.map((V)=>X0(V,_,Y6())))}:{success:!0,data:G.value}},YK=A9(Y0),$3=($)=>(J,U,Q)=>{let _=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return L9($)(J,U,_)},$r=$3(Y0),J3=($)=>(J,U,Q)=>{return L9($)(J,U,Q)},Jr=J3(Y0),U3=($)=>async(J,U,Q)=>{let _=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return z9($)(J,U,_)},Ur=U3(Y0),_3=($)=>async(J,U,Q)=>{return z9($)(J,U,Q)},_r=_3(Y0),Q3=($)=>(J,U,Q)=>{let _=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return R9($)(J,U,_)},Qr=Q3(Y0),G3=($)=>(J,U,Q)=>{return R9($)(J,U,Q)},Gr=G3(Y0),V3=($)=>async(J,U,Q)=>{let _=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return A9($)(J,U,_)},Vr=V3(Y0),X3=($)=>async(J,U,Q)=>{return A9($)(J,U,Q)},Xr=X3(Y0);var x0={};F1(x0,{xid:()=>FK,uuid7:()=>Nr,uuid6:()=>Kr,uuid4:()=>Zr,uuid:()=>U8,uppercase:()=>yK,unicodeEmail:()=>lR,undefined:()=>CK,ulid:()=>NK,time:()=>wK,string:()=>kK,sha512_hex:()=>Tr,sha512_base64url:()=>Cr,sha512_base64:()=>vr,sha384_hex:()=>kr,sha384_base64url:()=>Sr,sha384_base64:()=>Ir,sha256_hex:()=>Ar,sha256_base64url:()=>fr,sha256_base64:()=>wr,sha1_hex:()=>Lr,sha1_base64url:()=>Rr,sha1_base64:()=>zr,rfc5322Email:()=>Wr,number:()=>q7,null:()=>vK,nanoid:()=>qK,md5_hex:()=>Er,md5_base64url:()=>Mr,md5_base64:()=>Pr,mac:()=>PK,lowercase:()=>bK,ksuid:()=>WK,ipv6:()=>EK,ipv4:()=>DK,integer:()=>SK,idnEmail:()=>qr,html5Email:()=>Fr,hostname:()=>Or,hex:()=>Dr,guid:()=>BK,extendedDuration:()=>Yr,emoji:()=>jK,email:()=>OK,e164:()=>RK,duration:()=>HK,domain:()=>jr,datetime:()=>fK,date:()=>AK,cuid2:()=>KK,cuid:()=>ZK,cidrv6:()=>LK,cidrv4:()=>MK,browserEmail:()=>Hr,boolean:()=>TK,bigint:()=>IK,base64url:()=>Y3,base64:()=>zK});var ZK=/^[cC][^\s-]{8,}$/,KK=/^[0-9a-z]+$/,NK=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,FK=/^[0-9a-vA-V]{20}$/,WK=/^[A-Za-z0-9]{27}$/,qK=/^[a-zA-Z0-9_-]{21}$/,HK=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Yr=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,BK=/^([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})$/,U8=($)=>{if(!$)return/^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Zr=U8(4),Kr=U8(6),Nr=U8(7),OK=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Fr=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Wr=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,lR=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,qr=lR,Hr=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Br="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jK(){return new RegExp(Br,"u")}var DK=/^(?:(?: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])$/,EK=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,PK=($)=>{let J=g0($??":");return new RegExp(`^(?:[0-9A-F]{2}${J}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${J}){5}[0-9a-f]{2}$`)},MK=/^((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])$/,LK=/^(([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])$/,zK=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Y3=/^[A-Za-z0-9_-]*$/,Or=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,jr=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,RK=/^\+[1-9]\d{6,14}$/,iR="(?:(?:\\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])))",AK=new RegExp(`^${iR}$`);function rR($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function wK($){return new RegExp(`^${rR($)}$`)}function fK($){let J=rR({precision:$.precision}),U=["Z"];if($.local)U.push("");if($.offset)U.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${J}(?:${U.join("|")})`;return new RegExp(`^${iR}T(?:${Q})$`)}var kK=($)=>{let J=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)},IK=/^-?\d+n?$/,SK=/^-?\d+$/,q7=/^-?\d+(?:\.\d+)?$/,TK=/^(?:true|false)$/i,vK=/^null$/i;var CK=/^undefined$/i;var bK=/^[^A-Z]*$/,yK=/^[^a-z]*$/,Dr=/^[0-9a-fA-F]*$/;function H7($,J){return new RegExp(`^[A-Za-z0-9+/]{${$}}${J}$`)}function B7($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var Er=/^[0-9a-fA-F]{32}$/,Pr=H7(22,"=="),Mr=B7(22),Lr=/^[0-9a-fA-F]{40}$/,zr=H7(27,"="),Rr=B7(27),Ar=/^[0-9a-fA-F]{64}$/,wr=H7(43,"="),fr=B7(43),kr=/^[0-9a-fA-F]{96}$/,Ir=H7(64,""),Sr=B7(64),Tr=/^[0-9a-fA-F]{128}$/,vr=H7(86,"=="),Cr=B7(86);var x4=u("$ZodCheck",($,J)=>{var U;$._zod??($._zod={}),$._zod.def=J,(U=$._zod).onattach??(U.onattach=[])}),pR={number:"number",bigint:"bigint",object:"date"},Z3=u("$ZodCheckLessThan",($,J)=>{x4.init($,J);let U=pR[typeof J.value];$._zod.onattach.push((Q)=>{let _=Q._zod.bag,G=(J.inclusive?_.maximum:_.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<G)if(J.inclusive)_.maximum=J.value;else _.exclusiveMaximum=J.value}),$._zod.check=(Q)=>{if(J.inclusive?Q.value<=J.value:Q.value<J.value)return;Q.issues.push({origin:U,code:"too_big",maximum:typeof J.value==="object"?J.value.getTime():J.value,input:Q.value,inclusive:J.inclusive,inst:$,continue:!J.abort})}}),K3=u("$ZodCheckGreaterThan",($,J)=>{x4.init($,J);let U=pR[typeof J.value];$._zod.onattach.push((Q)=>{let _=Q._zod.bag,G=(J.inclusive?_.minimum:_.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>G)if(J.inclusive)_.minimum=J.value;else _.exclusiveMinimum=J.value}),$._zod.check=(Q)=>{if(J.inclusive?Q.value>=J.value:Q.value>J.value)return;Q.issues.push({origin:U,code:"too_small",minimum:typeof J.value==="object"?J.value.getTime():J.value,input:Q.value,inclusive:J.inclusive,inst:$,continue:!J.abort})}}),gK=u("$ZodCheckMultipleOf",($,J)=>{x4.init($,J),$._zod.onattach.push((U)=>{var Q;(Q=U._zod.bag).multipleOf??(Q.multipleOf=J.value)}),$._zod.check=(U)=>{if(typeof U.value!==typeof J.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof U.value==="bigint"?U.value%J.value===BigInt(0):tZ(U.value,J.value)===0)return;U.issues.push({origin:typeof U.value,code:"not_multiple_of",divisor:J.value,input:U.value,inst:$,continue:!J.abort})}}),xK=u("$ZodCheckNumberFormat",($,J)=>{x4.init($,J),J.format=J.format||"float64";let U=J.format?.includes("int"),Q=U?"int":"number",[_,G]=_K[J.format];$._zod.onattach.push((V)=>{let X=V._zod.bag;if(X.format=J.format,X.minimum=_,X.maximum=G,U)X.pattern=SK}),$._zod.check=(V)=>{let X=V.value;if(U){if(!Number.isInteger(X)){V.issues.push({expected:Q,format:J.format,code:"invalid_type",continue:!1,input:X,inst:$});return}if(!Number.isSafeInteger(X)){if(X>0)V.issues.push({input:X,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:Q,inclusive:!0,continue:!J.abort});else V.issues.push({input:X,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:Q,inclusive:!0,continue:!J.abort});return}}if(X<_)V.issues.push({origin:"number",input:X,code:"too_small",minimum:_,inclusive:!0,inst:$,continue:!J.abort});if(X>G)V.issues.push({origin:"number",input:X,code:"too_big",maximum:G,inclusive:!0,inst:$,continue:!J.abort})}}),hK=u("$ZodCheckBigIntFormat",($,J)=>{x4.init($,J);let[U,Q]=QK[J.format];$._zod.onattach.push((_)=>{let G=_._zod.bag;G.format=J.format,G.minimum=U,G.maximum=Q}),$._zod.check=(_)=>{let G=_.value;if(G<U)_.issues.push({origin:"bigint",input:G,code:"too_small",minimum:U,inclusive:!0,inst:$,continue:!J.abort});if(G>Q)_.issues.push({origin:"bigint",input:G,code:"too_big",maximum:Q,inclusive:!0,inst:$,continue:!J.abort})}}),uK=u("$ZodCheckMaxSize",($,J)=>{var U;x4.init($,J),(U=$._zod.def).when??(U.when=(Q)=>{let _=Q.value;return!i2(_)&&_.size!==void 0}),$._zod.onattach.push((Q)=>{let _=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<_)Q._zod.bag.maximum=J.maximum}),$._zod.check=(Q)=>{let _=Q.value;if(_.size<=J.maximum)return;Q.issues.push({origin:Z7(_),code:"too_big",maximum:J.maximum,inclusive:!0,input:_,inst:$,continue:!J.abort})}}),mK=u("$ZodCheckMinSize",($,J)=>{var U;x4.init($,J),(U=$._zod.def).when??(U.when=(Q)=>{let _=Q.value;return!i2(_)&&_.size!==void 0}),$._zod.onattach.push((Q)=>{let _=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>_)Q._zod.bag.minimum=J.minimum}),$._zod.check=(Q)=>{let _=Q.value;if(_.size>=J.minimum)return;Q.issues.push({origin:Z7(_),code:"too_small",minimum:J.minimum,inclusive:!0,input:_,inst:$,continue:!J.abort})}}),cK=u("$ZodCheckSizeEquals",($,J)=>{var U;x4.init($,J),(U=$._zod.def).when??(U.when=(Q)=>{let _=Q.value;return!i2(_)&&_.size!==void 0}),$._zod.onattach.push((Q)=>{let _=Q._zod.bag;_.minimum=J.size,_.maximum=J.size,_.size=J.size}),$._zod.check=(Q)=>{let _=Q.value,G=_.size;if(G===J.size)return;let V=G>J.size;Q.issues.push({origin:Z7(_),...V?{code:"too_big",maximum:J.size}:{code:"too_small",minimum:J.size},inclusive:!0,exact:!0,input:Q.value,inst:$,continue:!J.abort})}}),dK=u("$ZodCheckMaxLength",($,J)=>{var U;x4.init($,J),(U=$._zod.def).when??(U.when=(Q)=>{let _=Q.value;return!i2(_)&&_.length!==void 0}),$._zod.onattach.push((Q)=>{let _=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<_)Q._zod.bag.maximum=J.maximum}),$._zod.check=(Q)=>{let _=Q.value;if(_.length<=J.maximum)return;let V=K7(_);Q.issues.push({origin:V,code:"too_big",maximum:J.maximum,inclusive:!0,input:_,inst:$,continue:!J.abort})}}),lK=u("$ZodCheckMinLength",($,J)=>{var U;x4.init($,J),(U=$._zod.def).when??(U.when=(Q)=>{let _=Q.value;return!i2(_)&&_.length!==void 0}),$._zod.onattach.push((Q)=>{let _=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>_)Q._zod.bag.minimum=J.minimum}),$._zod.check=(Q)=>{let _=Q.value;if(_.length>=J.minimum)return;let V=K7(_);Q.issues.push({origin:V,code:"too_small",minimum:J.minimum,inclusive:!0,input:_,inst:$,continue:!J.abort})}}),iK=u("$ZodCheckLengthEquals",($,J)=>{var U;x4.init($,J),(U=$._zod.def).when??(U.when=(Q)=>{let _=Q.value;return!i2(_)&&_.length!==void 0}),$._zod.onattach.push((Q)=>{let _=Q._zod.bag;_.minimum=J.length,_.maximum=J.length,_.length=J.length}),$._zod.check=(Q)=>{let _=Q.value,G=_.length;if(G===J.length)return;let V=K7(_),X=G>J.length;Q.issues.push({origin:V,...X?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:Q.value,inst:$,continue:!J.abort})}}),w9=u("$ZodCheckStringFormat",($,J)=>{var U,Q;if(x4.init($,J),$._zod.onattach.push((_)=>{let G=_._zod.bag;if(G.format=J.format,J.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(J.pattern)}),J.pattern)(U=$._zod).check??(U.check=(_)=>{if(J.pattern.lastIndex=0,J.pattern.test(_.value))return;_.issues.push({origin:"string",code:"invalid_format",format:J.format,input:_.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:$,continue:!J.abort})});else(Q=$._zod).check??(Q.check=()=>{})}),rK=u("$ZodCheckRegex",($,J)=>{w9.init($,J),$._zod.check=(U)=>{if(J.pattern.lastIndex=0,J.pattern.test(U.value))return;U.issues.push({origin:"string",code:"invalid_format",format:"regex",input:U.value,pattern:J.pattern.toString(),inst:$,continue:!J.abort})}}),nK=u("$ZodCheckLowerCase",($,J)=>{J.pattern??(J.pattern=bK),w9.init($,J)}),pK=u("$ZodCheckUpperCase",($,J)=>{J.pattern??(J.pattern=yK),w9.init($,J)}),aK=u("$ZodCheckIncludes",($,J)=>{x4.init($,J);let U=g0(J.includes),Q=new RegExp(typeof J.position==="number"?`^.{${J.position}}${U}`:U);J.pattern=Q,$._zod.onattach.push((_)=>{let G=_._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),$._zod.check=(_)=>{if(_.value.includes(J.includes,J.position))return;_.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:_.value,inst:$,continue:!J.abort})}}),oK=u("$ZodCheckStartsWith",($,J)=>{x4.init($,J);let U=new RegExp(`^${g0(J.prefix)}.*`);J.pattern??(J.pattern=U),$._zod.onattach.push((Q)=>{let _=Q._zod.bag;_.patterns??(_.patterns=new Set),_.patterns.add(U)}),$._zod.check=(Q)=>{if(Q.value.startsWith(J.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:Q.value,inst:$,continue:!J.abort})}}),tK=u("$ZodCheckEndsWith",($,J)=>{x4.init($,J);let U=new RegExp(`.*${g0(J.suffix)}$`);J.pattern??(J.pattern=U),$._zod.onattach.push((Q)=>{let _=Q._zod.bag;_.patterns??(_.patterns=new Set),_.patterns.add(U)}),$._zod.check=(Q)=>{if(Q.value.endsWith(J.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:Q.value,inst:$,continue:!J.abort})}});function nR($,J,U){if($.issues.length)J.issues.push(...A0(U,$.issues))}var sK=u("$ZodCheckProperty",($,J)=>{x4.init($,J),$._zod.check=(U)=>{let Q=J.schema._zod.run({value:U.value[J.property],issues:[]},{});if(Q instanceof Promise)return Q.then((_)=>nR(_,U,J.property));nR(Q,U,J.property);return}}),eK=u("$ZodCheckMimeType",($,J)=>{x4.init($,J);let U=new Set(J.mime);$._zod.onattach.push((Q)=>{Q._zod.bag.mime=J.mime}),$._zod.check=(Q)=>{if(U.has(Q.value.type))return;Q.issues.push({code:"invalid_value",values:J.mime,input:Q.value.type,inst:$,continue:!J.abort})}}),$N=u("$ZodCheckOverwrite",($,J)=>{x4.init($,J),$._zod.check=(U)=>{U.value=J.tx(U.value)}});class N3{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let U=$.split(`
|
|
532
|
-
`).filter((G)=>G),Q=Math.min(...U.map((G)=>G.length-G.trimStart().length)),_=U.map((G)=>G.slice(Q)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of _)this.content.push(G)}compile(){let $=Function,J=this?.args,Q=[...(this?.content??[""]).map((_)=>` ${_}`)];return new $(...J,Q.join(`
|
|
533
|
-
`))}}var JN={major:4,minor:3,patch:5};var e$=u("$ZodType",($,J)=>{var U;$??($={}),$._zod.def=J,$._zod.bag=$._zod.bag||{},$._zod.version=JN;let Q=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))Q.unshift($);for(let _ of Q)for(let G of _._zod.onattach)G($);if(Q.length===0)(U=$._zod).deferred??(U.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let _=(V,X,Z)=>{let Y=p2(V),K;for(let F of X){if(F._zod.def.when){if(!F._zod.def.when(V))continue}else if(Y)continue;let N=V.issues.length,q=F._zod.check(V);if(q instanceof Promise&&Z?.async===!1)throw new L1;if(K||q instanceof Promise)K=(K??Promise.resolve()).then(async()=>{if(await q,V.issues.length===N)return;if(!Y)Y=p2(V,N)});else{if(V.issues.length===N)continue;if(!Y)Y=p2(V,N)}}if(K)return K.then(()=>{return V});return V},G=(V,X,Z)=>{if(p2(V))return V.aborted=!0,V;let Y=_(X,Q,Z);if(Y instanceof Promise){if(Z.async===!1)throw new L1;return Y.then((K)=>$._zod.parse(K,Z))}return $._zod.parse(Y,Z)};$._zod.run=(V,X)=>{if(X.skipChecks)return $._zod.parse(V,X);if(X.direction==="backward"){let Y=$._zod.parse({value:V.value,issues:[]},{...X,skipChecks:!0});if(Y instanceof Promise)return Y.then((K)=>{return G(K,V,X)});return G(Y,V,X)}let Z=$._zod.parse(V,X);if(Z instanceof Promise){if(X.async===!1)throw new L1;return Z.then((Y)=>_(Y,Q,X))}return _(Z,Q,X)}}B4($,"~standard",()=>({validate:(_)=>{try{let G=XK($,_);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return YK($,_).then((V)=>V.success?{value:V.data}:{issues:V.error?.issues})}},vendor:"zod",version:1}))}),_8=u("$ZodString",($,J)=>{e$.init($,J),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??kK($._zod.bag),$._zod.parse=(U,Q)=>{if(J.coerce)try{U.value=String(U.value)}catch(_){}if(typeof U.value==="string")return U;return U.issues.push({expected:"string",code:"invalid_type",input:U.value,inst:$}),U}}),T4=u("$ZodStringFormat",($,J)=>{w9.init($,J),_8.init($,J)}),_N=u("$ZodGUID",($,J)=>{J.pattern??(J.pattern=BK),T4.init($,J)}),QN=u("$ZodUUID",($,J)=>{if(J.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[J.version];if(Q===void 0)throw Error(`Invalid UUID version: "${J.version}"`);J.pattern??(J.pattern=U8(Q))}else J.pattern??(J.pattern=U8());T4.init($,J)}),GN=u("$ZodEmail",($,J)=>{J.pattern??(J.pattern=OK),T4.init($,J)}),VN=u("$ZodURL",($,J)=>{T4.init($,J),$._zod.check=(U)=>{try{let Q=U.value.trim(),_=new URL(Q);if(J.hostname){if(J.hostname.lastIndex=0,!J.hostname.test(_.hostname))U.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:J.hostname.source,input:U.value,inst:$,continue:!J.abort})}if(J.protocol){if(J.protocol.lastIndex=0,!J.protocol.test(_.protocol.endsWith(":")?_.protocol.slice(0,-1):_.protocol))U.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:J.protocol.source,input:U.value,inst:$,continue:!J.abort})}if(J.normalize)U.value=_.href;else U.value=Q;return}catch(Q){U.issues.push({code:"invalid_format",format:"url",input:U.value,inst:$,continue:!J.abort})}}}),XN=u("$ZodEmoji",($,J)=>{J.pattern??(J.pattern=jK()),T4.init($,J)}),YN=u("$ZodNanoID",($,J)=>{J.pattern??(J.pattern=qK),T4.init($,J)}),ZN=u("$ZodCUID",($,J)=>{J.pattern??(J.pattern=ZK),T4.init($,J)}),KN=u("$ZodCUID2",($,J)=>{J.pattern??(J.pattern=KK),T4.init($,J)}),NN=u("$ZodULID",($,J)=>{J.pattern??(J.pattern=NK),T4.init($,J)}),FN=u("$ZodXID",($,J)=>{J.pattern??(J.pattern=FK),T4.init($,J)}),WN=u("$ZodKSUID",($,J)=>{J.pattern??(J.pattern=WK),T4.init($,J)}),qN=u("$ZodISODateTime",($,J)=>{J.pattern??(J.pattern=fK(J)),T4.init($,J)}),HN=u("$ZodISODate",($,J)=>{J.pattern??(J.pattern=AK),T4.init($,J)}),BN=u("$ZodISOTime",($,J)=>{J.pattern??(J.pattern=wK(J)),T4.init($,J)}),ON=u("$ZodISODuration",($,J)=>{J.pattern??(J.pattern=HK),T4.init($,J)}),jN=u("$ZodIPv4",($,J)=>{J.pattern??(J.pattern=DK),T4.init($,J),$._zod.bag.format="ipv4"}),DN=u("$ZodIPv6",($,J)=>{J.pattern??(J.pattern=EK),T4.init($,J),$._zod.bag.format="ipv6",$._zod.check=(U)=>{try{new URL(`http://[${U.value}]`)}catch{U.issues.push({code:"invalid_format",format:"ipv6",input:U.value,inst:$,continue:!J.abort})}}}),EN=u("$ZodMAC",($,J)=>{J.pattern??(J.pattern=PK(J.delimiter)),T4.init($,J),$._zod.bag.format="mac"}),PN=u("$ZodCIDRv4",($,J)=>{J.pattern??(J.pattern=MK),T4.init($,J)}),MN=u("$ZodCIDRv6",($,J)=>{J.pattern??(J.pattern=LK),T4.init($,J),$._zod.check=(U)=>{let Q=U.value.split("/");try{if(Q.length!==2)throw Error();let[_,G]=Q;if(!G)throw Error();let V=Number(G);if(`${V}`!==G)throw Error();if(V<0||V>128)throw Error();new URL(`http://[${_}]`)}catch{U.issues.push({code:"invalid_format",format:"cidrv6",input:U.value,inst:$,continue:!J.abort})}}});function LN($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var zN=u("$ZodBase64",($,J)=>{J.pattern??(J.pattern=zK),T4.init($,J),$._zod.bag.contentEncoding="base64",$._zod.check=(U)=>{if(LN(U.value))return;U.issues.push({code:"invalid_format",format:"base64",input:U.value,inst:$,continue:!J.abort})}});function XA($){if(!Y3.test($))return!1;let J=$.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),U=J.padEnd(Math.ceil(J.length/4)*4,"=");return LN(U)}var RN=u("$ZodBase64URL",($,J)=>{J.pattern??(J.pattern=Y3),T4.init($,J),$._zod.bag.contentEncoding="base64url",$._zod.check=(U)=>{if(XA(U.value))return;U.issues.push({code:"invalid_format",format:"base64url",input:U.value,inst:$,continue:!J.abort})}}),AN=u("$ZodE164",($,J)=>{J.pattern??(J.pattern=RK),T4.init($,J)});function YA($,J=null){try{let U=$.split(".");if(U.length!==3)return!1;let[Q]=U;if(!Q)return!1;let _=JSON.parse(atob(Q));if("typ"in _&&_?.typ!=="JWT")return!1;if(!_.alg)return!1;if(J&&(!("alg"in _)||_.alg!==J))return!1;return!0}catch{return!1}}var wN=u("$ZodJWT",($,J)=>{T4.init($,J),$._zod.check=(U)=>{if(YA(U.value,J.alg))return;U.issues.push({code:"invalid_format",format:"jwt",input:U.value,inst:$,continue:!J.abort})}}),fN=u("$ZodCustomStringFormat",($,J)=>{T4.init($,J),$._zod.check=(U)=>{if(J.fn(U.value))return;U.issues.push({code:"invalid_format",format:J.format,input:U.value,inst:$,continue:!J.abort})}}),O3=u("$ZodNumber",($,J)=>{e$.init($,J),$._zod.pattern=$._zod.bag.pattern??q7,$._zod.parse=(U,Q)=>{if(J.coerce)try{U.value=Number(U.value)}catch(V){}let _=U.value;if(typeof _==="number"&&!Number.isNaN(_)&&Number.isFinite(_))return U;let G=typeof _==="number"?Number.isNaN(_)?"NaN":!Number.isFinite(_)?"Infinity":void 0:void 0;return U.issues.push({expected:"number",code:"invalid_type",input:_,inst:$,...G?{received:G}:{}}),U}}),kN=u("$ZodNumberFormat",($,J)=>{xK.init($,J),O3.init($,J)}),O7=u("$ZodBoolean",($,J)=>{e$.init($,J),$._zod.pattern=TK,$._zod.parse=(U,Q)=>{if(J.coerce)try{U.value=Boolean(U.value)}catch(G){}let _=U.value;if(typeof _==="boolean")return U;return U.issues.push({expected:"boolean",code:"invalid_type",input:_,inst:$}),U}}),j3=u("$ZodBigInt",($,J)=>{e$.init($,J),$._zod.pattern=IK,$._zod.parse=(U,Q)=>{if(J.coerce)try{U.value=BigInt(U.value)}catch(_){}if(typeof U.value==="bigint")return U;return U.issues.push({expected:"bigint",code:"invalid_type",input:U.value,inst:$}),U}}),IN=u("$ZodBigIntFormat",($,J)=>{hK.init($,J),j3.init($,J)}),SN=u("$ZodSymbol",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{let _=U.value;if(typeof _==="symbol")return U;return U.issues.push({expected:"symbol",code:"invalid_type",input:_,inst:$}),U}}),TN=u("$ZodUndefined",($,J)=>{e$.init($,J),$._zod.pattern=CK,$._zod.values=new Set([void 0]),$._zod.optin="optional",$._zod.optout="optional",$._zod.parse=(U,Q)=>{let _=U.value;if(typeof _>"u")return U;return U.issues.push({expected:"undefined",code:"invalid_type",input:_,inst:$}),U}}),vN=u("$ZodNull",($,J)=>{e$.init($,J),$._zod.pattern=vK,$._zod.values=new Set([null]),$._zod.parse=(U,Q)=>{let _=U.value;if(_===null)return U;return U.issues.push({expected:"null",code:"invalid_type",input:_,inst:$}),U}}),CN=u("$ZodAny",($,J)=>{e$.init($,J),$._zod.parse=(U)=>U}),bN=u("$ZodUnknown",($,J)=>{e$.init($,J),$._zod.parse=(U)=>U}),yN=u("$ZodNever",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{return U.issues.push({expected:"never",code:"invalid_type",input:U.value,inst:$}),U}}),gN=u("$ZodVoid",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{let _=U.value;if(typeof _>"u")return U;return U.issues.push({expected:"void",code:"invalid_type",input:_,inst:$}),U}}),xN=u("$ZodDate",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{if(J.coerce)try{U.value=new Date(U.value)}catch(X){}let _=U.value,G=_ instanceof Date;if(G&&!Number.isNaN(_.getTime()))return U;return U.issues.push({expected:"date",code:"invalid_type",input:_,...G?{received:"Invalid Date"}:{},inst:$}),U}});function oR($,J,U){if($.issues.length)J.issues.push(...A0(U,$.issues));J.value[U]=$.value}var hN=u("$ZodArray",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{let _=U.value;if(!Array.isArray(_))return U.issues.push({expected:"array",code:"invalid_type",input:_,inst:$}),U;U.value=Array(_.length);let G=[];for(let V=0;V<_.length;V++){let X=_[V],Z=J.element._zod.run({value:X,issues:[]},Q);if(Z instanceof Promise)G.push(Z.then((Y)=>oR(Y,U,V)));else oR(Z,U,V)}if(G.length)return Promise.all(G).then(()=>U);return U}});function B3($,J,U,Q,_){if($.issues.length){if(_&&!(U in Q))return;J.issues.push(...A0(U,$.issues))}if($.value===void 0){if(U in Q)J.value[U]=void 0}else J.value[U]=$.value}function ZA($){let J=Object.keys($.shape);for(let Q of J)if(!$.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let U=UK($.shape);return{...$,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set(U)}}function KA($,J,U,Q,_,G){let V=[],X=_.keySet,Z=_.catchall._zod,Y=Z.def.type,K=Z.optout==="optional";for(let F in J){if(X.has(F))continue;if(Y==="never"){V.push(F);continue}let N=Z.run({value:J[F],issues:[]},Q);if(N instanceof Promise)$.push(N.then((q)=>B3(q,U,F,J,K)));else B3(N,U,F,J,K)}if(V.length)U.issues.push({code:"unrecognized_keys",keys:V,input:J,inst:G});if(!$.length)return U;return Promise.all($).then(()=>{return U})}var NA=u("$ZodObject",($,J)=>{if(e$.init($,J),!Object.getOwnPropertyDescriptor(J,"shape")?.get){let X=J.shape;Object.defineProperty(J,"shape",{get:()=>{let Z={...X};return Object.defineProperty(J,"shape",{value:Z}),Z}})}let Q=P9(()=>ZA(J));B4($._zod,"propValues",()=>{let X=J.shape,Z={};for(let Y in X){let K=X[Y]._zod;if(K.values){Z[Y]??(Z[Y]=new Set);for(let F of K.values)Z[Y].add(F)}}return Z});let _=J8,G=J.catchall,V;$._zod.parse=(X,Z)=>{V??(V=Q.value);let Y=X.value;if(!_(Y))return X.issues.push({expected:"object",code:"invalid_type",input:Y,inst:$}),X;X.value={};let K=[],F=V.shape;for(let N of V.keys){let q=F[N],H=q._zod.optout==="optional",E=q._zod.run({value:Y[N],issues:[]},Z);if(E instanceof Promise)K.push(E.then((D)=>B3(D,X,N,Y,H)));else B3(E,X,N,Y,H)}if(!G)return K.length?Promise.all(K).then(()=>X):X;return KA(K,Y,X,Z,Q.value,$)}}),uN=u("$ZodObjectJIT",($,J)=>{NA.init($,J);let U=$._zod.parse,Q=P9(()=>ZA(J)),_=(N)=>{let q=new N3(["shape","payload","ctx"]),H=Q.value,E=(f)=>{let R=oQ(f);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};q.write("const input = payload.value;");let D=Object.create(null),B=0;for(let f of H.keys)D[f]=`key_${B++}`;q.write("const newResult = {};");for(let f of H.keys){let R=D[f],I=oQ(f),T=N[f]?._zod?.optout==="optional";if(q.write(`const ${R} = ${E(f)};`),T)q.write(`
|
|
534
|
-
if (${R}.issues.length) {
|
|
535
|
-
if (${I} in input) {
|
|
536
|
-
payload.issues = payload.issues.concat(${R}.issues.map(iss => ({
|
|
537
|
-
...iss,
|
|
538
|
-
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
539
|
-
})));
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
if (${R}.value === undefined) {
|
|
544
|
-
if (${I} in input) {
|
|
545
|
-
newResult[${I}] = undefined;
|
|
546
|
-
}
|
|
547
|
-
} else {
|
|
548
|
-
newResult[${I}] = ${R}.value;
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
`);else q.write(`
|
|
552
|
-
if (${R}.issues.length) {
|
|
553
|
-
payload.issues = payload.issues.concat(${R}.issues.map(iss => ({
|
|
554
|
-
...iss,
|
|
555
|
-
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
556
|
-
})));
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
if (${R}.value === undefined) {
|
|
560
|
-
if (${I} in input) {
|
|
561
|
-
newResult[${I}] = undefined;
|
|
562
|
-
}
|
|
563
|
-
} else {
|
|
564
|
-
newResult[${I}] = ${R}.value;
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
`)}q.write("payload.value = newResult;"),q.write("return payload;");let j=q.compile();return(f,R)=>j(N,f,R)},G,V=J8,X=!Q7.jitless,Y=X&&eZ.value,K=J.catchall,F;$._zod.parse=(N,q)=>{F??(F=Q.value);let H=N.value;if(!V(H))return N.issues.push({expected:"object",code:"invalid_type",input:H,inst:$}),N;if(X&&Y&&q?.async===!1&&q.jitless!==!0){if(!G)G=_(J.shape);if(N=G(N,q),!K)return N;return KA([],H,N,q,F,$)}return U(N,q)}});function tR($,J,U,Q){for(let G of $)if(G.issues.length===0)return J.value=G.value,J;let _=$.filter((G)=>!p2(G));if(_.length===1)return J.value=_[0].value,_[0];return J.issues.push({code:"invalid_union",input:J.value,inst:U,errors:$.map((G)=>G.issues.map((V)=>X0(V,Q,Y6())))}),J}var j7=u("$ZodUnion",($,J)=>{e$.init($,J),B4($._zod,"optin",()=>J.options.some((_)=>_._zod.optin==="optional")?"optional":void 0),B4($._zod,"optout",()=>J.options.some((_)=>_._zod.optout==="optional")?"optional":void 0),B4($._zod,"values",()=>{if(J.options.every((_)=>_._zod.values))return new Set(J.options.flatMap((_)=>Array.from(_._zod.values)));return}),B4($._zod,"pattern",()=>{if(J.options.every((_)=>_._zod.pattern)){let _=J.options.map((G)=>G._zod.pattern);return new RegExp(`^(${_.map((G)=>X7(G.source)).join("|")})$`)}return});let U=J.options.length===1,Q=J.options[0]._zod.run;$._zod.parse=(_,G)=>{if(U)return Q(_,G);let V=!1,X=[];for(let Z of J.options){let Y=Z._zod.run({value:_.value,issues:[]},G);if(Y instanceof Promise)X.push(Y),V=!0;else{if(Y.issues.length===0)return Y;X.push(Y)}}if(!V)return tR(X,_,$,G);return Promise.all(X).then((Z)=>{return tR(Z,_,$,G)})}});function sR($,J,U,Q){let _=$.filter((G)=>G.issues.length===0);if(_.length===1)return J.value=_[0].value,J;if(_.length===0)J.issues.push({code:"invalid_union",input:J.value,inst:U,errors:$.map((G)=>G.issues.map((V)=>X0(V,Q,Y6())))});else J.issues.push({code:"invalid_union",input:J.value,inst:U,errors:[],inclusive:!1});return J}var mN=u("$ZodXor",($,J)=>{j7.init($,J),J.inclusive=!1;let U=J.options.length===1,Q=J.options[0]._zod.run;$._zod.parse=(_,G)=>{if(U)return Q(_,G);let V=!1,X=[];for(let Z of J.options){let Y=Z._zod.run({value:_.value,issues:[]},G);if(Y instanceof Promise)X.push(Y),V=!0;else X.push(Y)}if(!V)return sR(X,_,$,G);return Promise.all(X).then((Z)=>{return sR(Z,_,$,G)})}}),cN=u("$ZodDiscriminatedUnion",($,J)=>{J.inclusive=!1,j7.init($,J);let U=$._zod.parse;B4($._zod,"propValues",()=>{let _={};for(let G of J.options){let V=G._zod.propValues;if(!V||Object.keys(V).length===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(G)}"`);for(let[X,Z]of Object.entries(V)){if(!_[X])_[X]=new Set;for(let Y of Z)_[X].add(Y)}}return _});let Q=P9(()=>{let _=J.options,G=new Map;for(let V of _){let X=V._zod.propValues?.[J.discriminator];if(!X||X.size===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(V)}"`);for(let Z of X){if(G.has(Z))throw Error(`Duplicate discriminator value "${String(Z)}"`);G.set(Z,V)}}return G});$._zod.parse=(_,G)=>{let V=_.value;if(!J8(V))return _.issues.push({code:"invalid_type",expected:"object",input:V,inst:$}),_;let X=Q.value.get(V?.[J.discriminator]);if(X)return X._zod.run(_,G);if(J.unionFallback)return U(_,G);return _.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:J.discriminator,input:V,path:[J.discriminator],inst:$}),_}}),dN=u("$ZodIntersection",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{let _=U.value,G=J.left._zod.run({value:_,issues:[]},Q),V=J.right._zod.run({value:_,issues:[]},Q);if(G instanceof Promise||V instanceof Promise)return Promise.all([G,V]).then(([Z,Y])=>{return eR(U,Z,Y)});return eR(U,G,V)}});function UN($,J){if($===J)return{valid:!0,data:$};if($ instanceof Date&&J instanceof Date&&+$===+J)return{valid:!0,data:$};if(n2($)&&n2(J)){let U=Object.keys(J),Q=Object.keys($).filter((G)=>U.indexOf(G)!==-1),_={...$,...J};for(let G of Q){let V=UN($[G],J[G]);if(!V.valid)return{valid:!1,mergeErrorPath:[G,...V.mergeErrorPath]};_[G]=V.data}return{valid:!0,data:_}}if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let Q=0;Q<$.length;Q++){let _=$[Q],G=J[Q],V=UN(_,G);if(!V.valid)return{valid:!1,mergeErrorPath:[Q,...V.mergeErrorPath]};U.push(V.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function eR($,J,U){let Q=new Map,_;for(let X of J.issues)if(X.code==="unrecognized_keys"){_??(_=X);for(let Z of X.keys){if(!Q.has(Z))Q.set(Z,{});Q.get(Z).l=!0}}else $.issues.push(X);for(let X of U.issues)if(X.code==="unrecognized_keys")for(let Z of X.keys){if(!Q.has(Z))Q.set(Z,{});Q.get(Z).r=!0}else $.issues.push(X);let G=[...Q].filter(([,X])=>X.l&&X.r).map(([X])=>X);if(G.length&&_)$.issues.push({..._,keys:G});if(p2($))return $;let V=UN(J.value,U.value);if(!V.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(V.mergeErrorPath)}`);return $.value=V.data,$}var D3=u("$ZodTuple",($,J)=>{e$.init($,J);let U=J.items;$._zod.parse=(Q,_)=>{let G=Q.value;if(!Array.isArray(G))return Q.issues.push({input:G,inst:$,expected:"tuple",code:"invalid_type"}),Q;Q.value=[];let V=[],X=[...U].reverse().findIndex((K)=>K._zod.optin!=="optional"),Z=X===-1?0:U.length-X;if(!J.rest){let K=G.length>U.length,F=G.length<Z-1;if(K||F)return Q.issues.push({...K?{code:"too_big",maximum:U.length,inclusive:!0}:{code:"too_small",minimum:U.length},input:G,inst:$,origin:"array"}),Q}let Y=-1;for(let K of U){if(Y++,Y>=G.length){if(Y>=Z)continue}let F=K._zod.run({value:G[Y],issues:[]},_);if(F instanceof Promise)V.push(F.then((N)=>F3(N,Q,Y)));else F3(F,Q,Y)}if(J.rest){let K=G.slice(U.length);for(let F of K){Y++;let N=J.rest._zod.run({value:F,issues:[]},_);if(N instanceof Promise)V.push(N.then((q)=>F3(q,Q,Y)));else F3(N,Q,Y)}}if(V.length)return Promise.all(V).then(()=>Q);return Q}});function F3($,J,U){if($.issues.length)J.issues.push(...A0(U,$.issues));J.value[U]=$.value}var lN=u("$ZodRecord",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{let _=U.value;if(!n2(_))return U.issues.push({expected:"record",code:"invalid_type",input:_,inst:$}),U;let G=[],V=J.keyType._zod.values;if(V){U.value={};let X=new Set;for(let Y of V)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){X.add(typeof Y==="number"?Y.toString():Y);let K=J.valueType._zod.run({value:_[Y],issues:[]},Q);if(K instanceof Promise)G.push(K.then((F)=>{if(F.issues.length)U.issues.push(...A0(Y,F.issues));U.value[Y]=F.value}));else{if(K.issues.length)U.issues.push(...A0(Y,K.issues));U.value[Y]=K.value}}let Z;for(let Y in _)if(!X.has(Y))Z=Z??[],Z.push(Y);if(Z&&Z.length>0)U.issues.push({code:"unrecognized_keys",input:_,inst:$,keys:Z})}else{U.value={};for(let X of Reflect.ownKeys(_)){if(X==="__proto__")continue;let Z=J.keyType._zod.run({value:X,issues:[]},Q);if(Z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof X==="string"&&q7.test(X)&&Z.issues.length&&Z.issues.some((F)=>F.code==="invalid_type"&&F.expected==="number")){let F=J.keyType._zod.run({value:Number(X),issues:[]},Q);if(F instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(F.issues.length===0)Z=F}if(Z.issues.length){if(J.mode==="loose")U.value[X]=_[X];else U.issues.push({code:"invalid_key",origin:"record",issues:Z.issues.map((F)=>X0(F,Q,Y6())),input:X,path:[X],inst:$});continue}let K=J.valueType._zod.run({value:_[X],issues:[]},Q);if(K instanceof Promise)G.push(K.then((F)=>{if(F.issues.length)U.issues.push(...A0(X,F.issues));U.value[Z.value]=F.value}));else{if(K.issues.length)U.issues.push(...A0(X,K.issues));U.value[Z.value]=K.value}}}if(G.length)return Promise.all(G).then(()=>U);return U}}),iN=u("$ZodMap",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{let _=U.value;if(!(_ instanceof Map))return U.issues.push({expected:"map",code:"invalid_type",input:_,inst:$}),U;let G=[];U.value=new Map;for(let[V,X]of _){let Z=J.keyType._zod.run({value:V,issues:[]},Q),Y=J.valueType._zod.run({value:X,issues:[]},Q);if(Z instanceof Promise||Y instanceof Promise)G.push(Promise.all([Z,Y]).then(([K,F])=>{$A(K,F,U,V,_,$,Q)}));else $A(Z,Y,U,V,_,$,Q)}if(G.length)return Promise.all(G).then(()=>U);return U}});function $A($,J,U,Q,_,G,V){if($.issues.length)if(Y7.has(typeof Q))U.issues.push(...A0(Q,$.issues));else U.issues.push({code:"invalid_key",origin:"map",input:_,inst:G,issues:$.issues.map((X)=>X0(X,V,Y6()))});if(J.issues.length)if(Y7.has(typeof Q))U.issues.push(...A0(Q,J.issues));else U.issues.push({origin:"map",code:"invalid_element",input:_,inst:G,key:Q,issues:J.issues.map((X)=>X0(X,V,Y6()))});U.value.set($.value,J.value)}var rN=u("$ZodSet",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{let _=U.value;if(!(_ instanceof Set))return U.issues.push({input:_,inst:$,expected:"set",code:"invalid_type"}),U;let G=[];U.value=new Set;for(let V of _){let X=J.valueType._zod.run({value:V,issues:[]},Q);if(X instanceof Promise)G.push(X.then((Z)=>JA(Z,U)));else JA(X,U)}if(G.length)return Promise.all(G).then(()=>U);return U}});function JA($,J){if($.issues.length)J.issues.push(...$.issues);J.value.add($.value)}var nN=u("$ZodEnum",($,J)=>{e$.init($,J);let U=V7(J.entries),Q=new Set(U);$._zod.values=Q,$._zod.pattern=new RegExp(`^(${U.filter((_)=>Y7.has(typeof _)).map((_)=>typeof _==="string"?g0(_):_.toString()).join("|")})$`),$._zod.parse=(_,G)=>{let V=_.value;if(Q.has(V))return _;return _.issues.push({code:"invalid_value",values:U,input:V,inst:$}),_}}),pN=u("$ZodLiteral",($,J)=>{if(e$.init($,J),J.values.length===0)throw Error("Cannot create literal schema with no valid values");let U=new Set(J.values);$._zod.values=U,$._zod.pattern=new RegExp(`^(${J.values.map((Q)=>typeof Q==="string"?g0(Q):Q?g0(Q.toString()):String(Q)).join("|")})$`),$._zod.parse=(Q,_)=>{let G=Q.value;if(U.has(G))return Q;return Q.issues.push({code:"invalid_value",values:J.values,input:G,inst:$}),Q}}),aN=u("$ZodFile",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{let _=U.value;if(_ instanceof File)return U;return U.issues.push({expected:"file",code:"invalid_type",input:_,inst:$}),U}}),oN=u("$ZodTransform",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{if(Q.direction==="backward")throw new $8($.constructor.name);let _=J.transform(U.value,U);if(Q.async)return(_ instanceof Promise?_:Promise.resolve(_)).then((V)=>{return U.value=V,U});if(_ instanceof Promise)throw new L1;return U.value=_,U}});function UA($,J){if($.issues.length&&J===void 0)return{issues:[],value:void 0};return $}var E3=u("$ZodOptional",($,J)=>{e$.init($,J),$._zod.optin="optional",$._zod.optout="optional",B4($._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,void 0]):void 0}),B4($._zod,"pattern",()=>{let U=J.innerType._zod.pattern;return U?new RegExp(`^(${X7(U.source)})?$`):void 0}),$._zod.parse=(U,Q)=>{if(J.innerType._zod.optin==="optional"){let _=J.innerType._zod.run(U,Q);if(_ instanceof Promise)return _.then((G)=>UA(G,U.value));return UA(_,U.value)}if(U.value===void 0)return U;return J.innerType._zod.run(U,Q)}}),tN=u("$ZodExactOptional",($,J)=>{E3.init($,J),B4($._zod,"values",()=>J.innerType._zod.values),B4($._zod,"pattern",()=>J.innerType._zod.pattern),$._zod.parse=(U,Q)=>{return J.innerType._zod.run(U,Q)}}),sN=u("$ZodNullable",($,J)=>{e$.init($,J),B4($._zod,"optin",()=>J.innerType._zod.optin),B4($._zod,"optout",()=>J.innerType._zod.optout),B4($._zod,"pattern",()=>{let U=J.innerType._zod.pattern;return U?new RegExp(`^(${X7(U.source)}|null)$`):void 0}),B4($._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,null]):void 0}),$._zod.parse=(U,Q)=>{if(U.value===null)return U;return J.innerType._zod.run(U,Q)}}),eN=u("$ZodDefault",($,J)=>{e$.init($,J),$._zod.optin="optional",B4($._zod,"values",()=>J.innerType._zod.values),$._zod.parse=(U,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(U,Q);if(U.value===void 0)return U.value=J.defaultValue,U;let _=J.innerType._zod.run(U,Q);if(_ instanceof Promise)return _.then((G)=>_A(G,J));return _A(_,J)}});function _A($,J){if($.value===void 0)$.value=J.defaultValue;return $}var $F=u("$ZodPrefault",($,J)=>{e$.init($,J),$._zod.optin="optional",B4($._zod,"values",()=>J.innerType._zod.values),$._zod.parse=(U,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(U,Q);if(U.value===void 0)U.value=J.defaultValue;return J.innerType._zod.run(U,Q)}}),JF=u("$ZodNonOptional",($,J)=>{e$.init($,J),B4($._zod,"values",()=>{let U=J.innerType._zod.values;return U?new Set([...U].filter((Q)=>Q!==void 0)):void 0}),$._zod.parse=(U,Q)=>{let _=J.innerType._zod.run(U,Q);if(_ instanceof Promise)return _.then((G)=>QA(G,$));return QA(_,$)}});function QA($,J){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:J});return $}var UF=u("$ZodSuccess",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{if(Q.direction==="backward")throw new $8("ZodSuccess");let _=J.innerType._zod.run(U,Q);if(_ instanceof Promise)return _.then((G)=>{return U.value=G.issues.length===0,U});return U.value=_.issues.length===0,U}}),_F=u("$ZodCatch",($,J)=>{e$.init($,J),B4($._zod,"optin",()=>J.innerType._zod.optin),B4($._zod,"optout",()=>J.innerType._zod.optout),B4($._zod,"values",()=>J.innerType._zod.values),$._zod.parse=(U,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(U,Q);let _=J.innerType._zod.run(U,Q);if(_ instanceof Promise)return _.then((G)=>{if(U.value=G.value,G.issues.length)U.value=J.catchValue({...U,error:{issues:G.issues.map((V)=>X0(V,Q,Y6()))},input:U.value}),U.issues=[];return U});if(U.value=_.value,_.issues.length)U.value=J.catchValue({...U,error:{issues:_.issues.map((G)=>X0(G,Q,Y6()))},input:U.value}),U.issues=[];return U}}),QF=u("$ZodNaN",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{if(typeof U.value!=="number"||!Number.isNaN(U.value))return U.issues.push({input:U.value,inst:$,expected:"nan",code:"invalid_type"}),U;return U}}),GF=u("$ZodPipe",($,J)=>{e$.init($,J),B4($._zod,"values",()=>J.in._zod.values),B4($._zod,"optin",()=>J.in._zod.optin),B4($._zod,"optout",()=>J.out._zod.optout),B4($._zod,"propValues",()=>J.in._zod.propValues),$._zod.parse=(U,Q)=>{if(Q.direction==="backward"){let G=J.out._zod.run(U,Q);if(G instanceof Promise)return G.then((V)=>W3(V,J.in,Q));return W3(G,J.in,Q)}let _=J.in._zod.run(U,Q);if(_ instanceof Promise)return _.then((G)=>W3(G,J.out,Q));return W3(_,J.out,Q)}});function W3($,J,U){if($.issues.length)return $.aborted=!0,$;return J._zod.run({value:$.value,issues:$.issues},U)}var D7=u("$ZodCodec",($,J)=>{e$.init($,J),B4($._zod,"values",()=>J.in._zod.values),B4($._zod,"optin",()=>J.in._zod.optin),B4($._zod,"optout",()=>J.out._zod.optout),B4($._zod,"propValues",()=>J.in._zod.propValues),$._zod.parse=(U,Q)=>{if((Q.direction||"forward")==="forward"){let G=J.in._zod.run(U,Q);if(G instanceof Promise)return G.then((V)=>q3(V,J,Q));return q3(G,J,Q)}else{let G=J.out._zod.run(U,Q);if(G instanceof Promise)return G.then((V)=>q3(V,J,Q));return q3(G,J,Q)}}});function q3($,J,U){if($.issues.length)return $.aborted=!0,$;if((U.direction||"forward")==="forward"){let _=J.transform($.value,$);if(_ instanceof Promise)return _.then((G)=>H3($,G,J.out,U));return H3($,_,J.out,U)}else{let _=J.reverseTransform($.value,$);if(_ instanceof Promise)return _.then((G)=>H3($,G,J.in,U));return H3($,_,J.in,U)}}function H3($,J,U,Q){if($.issues.length)return $.aborted=!0,$;return U._zod.run({value:J,issues:$.issues},Q)}var VF=u("$ZodReadonly",($,J)=>{e$.init($,J),B4($._zod,"propValues",()=>J.innerType._zod.propValues),B4($._zod,"values",()=>J.innerType._zod.values),B4($._zod,"optin",()=>J.innerType?._zod?.optin),B4($._zod,"optout",()=>J.innerType?._zod?.optout),$._zod.parse=(U,Q)=>{if(Q.direction==="backward")return J.innerType._zod.run(U,Q);let _=J.innerType._zod.run(U,Q);if(_ instanceof Promise)return _.then(GA);return GA(_)}});function GA($){return $.value=Object.freeze($.value),$}var XF=u("$ZodTemplateLiteral",($,J)=>{e$.init($,J);let U=[];for(let Q of J.parts)if(typeof Q==="object"&&Q!==null){if(!Q._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...Q._zod.traits].shift()}`);let _=Q._zod.pattern instanceof RegExp?Q._zod.pattern.source:Q._zod.pattern;if(!_)throw Error(`Invalid template literal part: ${Q._zod.traits}`);let G=_.startsWith("^")?1:0,V=_.endsWith("$")?_.length-1:_.length;U.push(_.slice(G,V))}else if(Q===null||JK.has(typeof Q))U.push(g0(`${Q}`));else throw Error(`Invalid template literal part: ${Q}`);$._zod.pattern=new RegExp(`^${U.join("")}$`),$._zod.parse=(Q,_)=>{if(typeof Q.value!=="string")return Q.issues.push({input:Q.value,inst:$,expected:"string",code:"invalid_type"}),Q;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(Q.value))return Q.issues.push({input:Q.value,inst:$,code:"invalid_format",format:J.format??"template_literal",pattern:$._zod.pattern.source}),Q;return Q}}),YF=u("$ZodFunction",($,J)=>{return e$.init($,J),$._def=J,$._zod.def=J,$.implement=(U)=>{if(typeof U!=="function")throw Error("implement() must be called with a function");return function(...Q){let _=$._def.input?sQ($._def.input,Q):Q,G=Reflect.apply(U,this,_);if($._def.output)return sQ($._def.output,G);return G}},$.implementAsync=(U)=>{if(typeof U!=="function")throw Error("implementAsync() must be called with a function");return async function(...Q){let _=$._def.input?await eQ($._def.input,Q):Q,G=await Reflect.apply(U,this,_);if($._def.output)return await eQ($._def.output,G);return G}},$._zod.parse=(U,Q)=>{if(typeof U.value!=="function")return U.issues.push({code:"invalid_type",expected:"function",input:U.value,inst:$}),U;if($._def.output&&$._def.output._zod.def.type==="promise")U.value=$.implementAsync(U.value);else U.value=$.implement(U.value);return U},$.input=(...U)=>{let Q=$.constructor;if(Array.isArray(U[0]))return new Q({type:"function",input:new D3({type:"tuple",items:U[0],rest:U[1]}),output:$._def.output});return new Q({type:"function",input:U[0],output:$._def.output})},$.output=(U)=>{return new $.constructor({type:"function",input:$._def.input,output:U})},$}),ZF=u("$ZodPromise",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{return Promise.resolve(U.value).then((_)=>J.innerType._zod.run({value:_,issues:[]},Q))}}),KF=u("$ZodLazy",($,J)=>{e$.init($,J),B4($._zod,"innerType",()=>J.getter()),B4($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),B4($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),B4($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),B4($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(U,Q)=>{return $._zod.innerType._zod.run(U,Q)}}),NF=u("$ZodCustom",($,J)=>{x4.init($,J),e$.init($,J),$._zod.parse=(U,Q)=>{return U},$._zod.check=(U)=>{let Q=U.value,_=J.fn(Q);if(_ instanceof Promise)return _.then((G)=>VA(G,U,Q,$));VA(_,U,Q,$);return}});function VA($,J,U,Q){if(!$){let _={code:"custom",input:U,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)_.params=Q._zod.def.params;J.issues.push(M9(_))}}var z7={};F1(z7,{zhTW:()=>UW,zhCN:()=>JW,yo:()=>_W,vi:()=>$W,uz:()=>eF,ur:()=>sF,uk:()=>L7,ua:()=>tF,tr:()=>oF,th:()=>aF,ta:()=>pF,sv:()=>nF,sl:()=>rF,ru:()=>iF,pt:()=>lF,ps:()=>cF,pl:()=>dF,ota:()=>mF,no:()=>uF,nl:()=>hF,ms:()=>xF,mk:()=>gF,lt:()=>yF,ko:()=>bF,km:()=>P7,kh:()=>CF,ka:()=>vF,ja:()=>TF,it:()=>SF,is:()=>IF,id:()=>kF,hy:()=>fF,hu:()=>wF,he:()=>AF,frCA:()=>RF,fr:()=>zF,fi:()=>LF,fa:()=>MF,es:()=>PF,eo:()=>EF,en:()=>E7,de:()=>DF,da:()=>jF,cs:()=>OF,ca:()=>BF,bg:()=>HF,be:()=>qF,az:()=>WF,ar:()=>FF});var yr=()=>{let $={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function J(_){return $[_]??null}let U={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${_.expected}، ولكن تم إدخال ${X}`;return`مدخلات غير مقبولة: يفترض إدخال ${G}، ولكن تم إدخال ${X}`}case"invalid_value":if(_.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${W$(_.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return` أكبر من اللازم: يفترض أن تكون ${_.origin??"القيمة"} ${G} ${_.maximum.toString()} ${V.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${_.origin??"القيمة"} ${G} ${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`أصغر من اللازم: يفترض لـ ${_.origin} أن يكون ${G} ${_.minimum.toString()} ${V.unit}`;return`أصغر من اللازم: يفترض لـ ${_.origin} أن يكون ${G} ${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${_.prefix}"`;if(G.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${G.suffix}"`;if(G.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${G.includes}"`;if(G.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${G.pattern}`;return`${U[G.format]??_.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${_.divisor}`;case"unrecognized_keys":return`معرف${_.keys.length>1?"ات":""} غريب${_.keys.length>1?"ة":""}: ${o(_.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${_.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${_.origin}`;default:return"مدخل غير مقبول"}}};function FF(){return{localeError:yr()}}var gr=()=>{let $={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function J(_){return $[_]??null}let U={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Yanlış dəyər: gözlənilən instanceof ${_.expected}, daxil olan ${X}`;return`Yanlış dəyər: gözlənilən ${G}, daxil olan ${X}`}case"invalid_value":if(_.values.length===1)return`Yanlış dəyər: gözlənilən ${W$(_.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Çox böyük: gözlənilən ${_.origin??"dəyər"} ${G}${_.maximum.toString()} ${V.unit??"element"}`;return`Çox böyük: gözlənilən ${_.origin??"dəyər"} ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Çox kiçik: gözlənilən ${_.origin} ${G}${_.minimum.toString()} ${V.unit}`;return`Çox kiçik: gözlənilən ${_.origin} ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Yanlış mətn: "${G.prefix}" ilə başlamalıdır`;if(G.format==="ends_with")return`Yanlış mətn: "${G.suffix}" ilə bitməlidir`;if(G.format==="includes")return`Yanlış mətn: "${G.includes}" daxil olmalıdır`;if(G.format==="regex")return`Yanlış mətn: ${G.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${U[G.format]??_.format}`}case"not_multiple_of":return`Yanlış ədəd: ${_.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${_.keys.length>1?"lar":""}: ${o(_.keys,", ")}`;case"invalid_key":return`${_.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${_.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function WF(){return{localeError:gr()}}function FA($,J,U,Q){let _=Math.abs($),G=_%10,V=_%100;if(V>=11&&V<=19)return Q;if(G===1)return J;if(G>=2&&G<=4)return U;return Q}var xr=()=>{let $={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function J(_){return $[_]??null}let U={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},Q={nan:"NaN",number:"лік",array:"масіў"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Няправільны ўвод: чакаўся instanceof ${_.expected}, атрымана ${X}`;return`Няправільны ўвод: чакаўся ${G}, атрымана ${X}`}case"invalid_value":if(_.values.length===1)return`Няправільны ўвод: чакалася ${W$(_.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V){let X=Number(_.maximum),Z=FA(X,V.unit.one,V.unit.few,V.unit.many);return`Занадта вялікі: чакалася, што ${_.origin??"значэнне"} павінна ${V.verb} ${G}${_.maximum.toString()} ${Z}`}return`Занадта вялікі: чакалася, што ${_.origin??"значэнне"} павінна быць ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V){let X=Number(_.minimum),Z=FA(X,V.unit.one,V.unit.few,V.unit.many);return`Занадта малы: чакалася, што ${_.origin} павінна ${V.verb} ${G}${_.minimum.toString()} ${Z}`}return`Занадта малы: чакалася, што ${_.origin} павінна быць ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${G.prefix}"`;if(G.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${G.suffix}"`;if(G.format==="includes")return`Няправільны радок: павінен змяшчаць "${G.includes}"`;if(G.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${G.pattern}`;return`Няправільны ${U[G.format]??_.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${_.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${_.keys.length>1?"ключы":"ключ"}: ${o(_.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${_.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${_.origin}`;default:return"Няправільны ўвод"}}};function qF(){return{localeError:xr()}}var hr=()=>{let $={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function J(_){return $[_]??null}let U={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},Q={nan:"NaN",number:"число",array:"масив"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Невалиден вход: очакван instanceof ${_.expected}, получен ${X}`;return`Невалиден вход: очакван ${G}, получен ${X}`}case"invalid_value":if(_.values.length===1)return`Невалиден вход: очакван ${W$(_.values[0])}`;return`Невалидна опция: очаквано едно от ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Твърде голямо: очаква се ${_.origin??"стойност"} да съдържа ${G}${_.maximum.toString()} ${V.unit??"елемента"}`;return`Твърде голямо: очаква се ${_.origin??"стойност"} да бъде ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Твърде малко: очаква се ${_.origin} да съдържа ${G}${_.minimum.toString()} ${V.unit}`;return`Твърде малко: очаква се ${_.origin} да бъде ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Невалиден низ: трябва да започва с "${G.prefix}"`;if(G.format==="ends_with")return`Невалиден низ: трябва да завършва с "${G.suffix}"`;if(G.format==="includes")return`Невалиден низ: трябва да включва "${G.includes}"`;if(G.format==="regex")return`Невалиден низ: трябва да съвпада с ${G.pattern}`;let V="Невалиден";if(G.format==="emoji")V="Невалидно";if(G.format==="datetime")V="Невалидно";if(G.format==="date")V="Невалидна";if(G.format==="time")V="Невалидно";if(G.format==="duration")V="Невалидна";return`${V} ${U[G.format]??_.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${_.divisor}`;case"unrecognized_keys":return`Неразпознат${_.keys.length>1?"и":""} ключ${_.keys.length>1?"ове":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${_.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${_.origin}`;default:return"Невалиден вход"}}};function HF(){return{localeError:hr()}}var ur=()=>{let $={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function J(_){return $[_]??null}let U={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Tipus invàlid: s'esperava instanceof ${_.expected}, s'ha rebut ${X}`;return`Tipus invàlid: s'esperava ${G}, s'ha rebut ${X}`}case"invalid_value":if(_.values.length===1)return`Valor invàlid: s'esperava ${W$(_.values[0])}`;return`Opció invàlida: s'esperava una de ${o(_.values," o ")}`;case"too_big":{let G=_.inclusive?"com a màxim":"menys de",V=J(_.origin);if(V)return`Massa gran: s'esperava que ${_.origin??"el valor"} contingués ${G} ${_.maximum.toString()} ${V.unit??"elements"}`;return`Massa gran: s'esperava que ${_.origin??"el valor"} fos ${G} ${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?"com a mínim":"més de",V=J(_.origin);if(V)return`Massa petit: s'esperava que ${_.origin} contingués ${G} ${_.minimum.toString()} ${V.unit}`;return`Massa petit: s'esperava que ${_.origin} fos ${G} ${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Format invàlid: ha de començar amb "${G.prefix}"`;if(G.format==="ends_with")return`Format invàlid: ha d'acabar amb "${G.suffix}"`;if(G.format==="includes")return`Format invàlid: ha d'incloure "${G.includes}"`;if(G.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${G.pattern}`;return`Format invàlid per a ${U[G.format]??_.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${_.divisor}`;case"unrecognized_keys":return`Clau${_.keys.length>1?"s":""} no reconeguda${_.keys.length>1?"s":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${_.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${_.origin}`;default:return"Entrada invàlida"}}};function BF(){return{localeError:ur()}}var mr=()=>{let $={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function J(_){return $[_]??null}let U={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},Q={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Neplatný vstup: očekáváno instanceof ${_.expected}, obdrženo ${X}`;return`Neplatný vstup: očekáváno ${G}, obdrženo ${X}`}case"invalid_value":if(_.values.length===1)return`Neplatný vstup: očekáváno ${W$(_.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Hodnota je příliš velká: ${_.origin??"hodnota"} musí mít ${G}${_.maximum.toString()} ${V.unit??"prvků"}`;return`Hodnota je příliš velká: ${_.origin??"hodnota"} musí být ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Hodnota je příliš malá: ${_.origin??"hodnota"} musí mít ${G}${_.minimum.toString()} ${V.unit??"prvků"}`;return`Hodnota je příliš malá: ${_.origin??"hodnota"} musí být ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Neplatný řetězec: musí začínat na "${G.prefix}"`;if(G.format==="ends_with")return`Neplatný řetězec: musí končit na "${G.suffix}"`;if(G.format==="includes")return`Neplatný řetězec: musí obsahovat "${G.includes}"`;if(G.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${G.pattern}`;return`Neplatný formát ${U[G.format]??_.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${_.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${o(_.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${_.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${_.origin}`;default:return"Neplatný vstup"}}};function OF(){return{localeError:mr()}}var cr=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function J(_){return $[_]??null}let U={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Ugyldigt input: forventede instanceof ${_.expected}, fik ${X}`;return`Ugyldigt input: forventede ${G}, fik ${X}`}case"invalid_value":if(_.values.length===1)return`Ugyldig værdi: forventede ${W$(_.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin),X=Q[_.origin]??_.origin;if(V)return`For stor: forventede ${X??"value"} ${V.verb} ${G} ${_.maximum.toString()} ${V.unit??"elementer"}`;return`For stor: forventede ${X??"value"} havde ${G} ${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin),X=Q[_.origin]??_.origin;if(V)return`For lille: forventede ${X} ${V.verb} ${G} ${_.minimum.toString()} ${V.unit}`;return`For lille: forventede ${X} havde ${G} ${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Ugyldig streng: skal starte med "${G.prefix}"`;if(G.format==="ends_with")return`Ugyldig streng: skal ende med "${G.suffix}"`;if(G.format==="includes")return`Ugyldig streng: skal indeholde "${G.includes}"`;if(G.format==="regex")return`Ugyldig streng: skal matche mønsteret ${G.pattern}`;return`Ugyldig ${U[G.format]??_.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${_.divisor}`;case"unrecognized_keys":return`${_.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${o(_.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${_.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${_.origin}`;default:return"Ugyldigt input"}}};function jF(){return{localeError:cr()}}var dr=()=>{let $={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function J(_){return $[_]??null}let U={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},Q={nan:"NaN",number:"Zahl",array:"Array"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Ungültige Eingabe: erwartet instanceof ${_.expected}, erhalten ${X}`;return`Ungültige Eingabe: erwartet ${G}, erhalten ${X}`}case"invalid_value":if(_.values.length===1)return`Ungültige Eingabe: erwartet ${W$(_.values[0])}`;return`Ungültige Option: erwartet eine von ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Zu groß: erwartet, dass ${_.origin??"Wert"} ${G}${_.maximum.toString()} ${V.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${_.origin??"Wert"} ${G}${_.maximum.toString()} ist`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Zu klein: erwartet, dass ${_.origin} ${G}${_.minimum.toString()} ${V.unit} hat`;return`Zu klein: erwartet, dass ${_.origin} ${G}${_.minimum.toString()} ist`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Ungültiger String: muss mit "${G.prefix}" beginnen`;if(G.format==="ends_with")return`Ungültiger String: muss mit "${G.suffix}" enden`;if(G.format==="includes")return`Ungültiger String: muss "${G.includes}" enthalten`;if(G.format==="regex")return`Ungültiger String: muss dem Muster ${G.pattern} entsprechen`;return`Ungültig: ${U[G.format]??_.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${_.divisor} sein`;case"unrecognized_keys":return`${_.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${o(_.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${_.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${_.origin}`;default:return"Ungültige Eingabe"}}};function DF(){return{localeError:dr()}}var lr=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function J(_){return $[_]??null}let U={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;return`Invalid input: expected ${G}, received ${X}`}case"invalid_value":if(_.values.length===1)return`Invalid input: expected ${W$(_.values[0])}`;return`Invalid option: expected one of ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Too big: expected ${_.origin??"value"} to have ${G}${_.maximum.toString()} ${V.unit??"elements"}`;return`Too big: expected ${_.origin??"value"} to be ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Too small: expected ${_.origin} to have ${G}${_.minimum.toString()} ${V.unit}`;return`Too small: expected ${_.origin} to be ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${U[G.format]??_.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${_.divisor}`;case"unrecognized_keys":return`Unrecognized key${_.keys.length>1?"s":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Invalid key in ${_.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${_.origin}`;default:return"Invalid input"}}};function E7(){return{localeError:lr()}}var ir=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function J(_){return $[_]??null}let U={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},Q={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Nevalida enigo: atendiĝis instanceof ${_.expected}, riceviĝis ${X}`;return`Nevalida enigo: atendiĝis ${G}, riceviĝis ${X}`}case"invalid_value":if(_.values.length===1)return`Nevalida enigo: atendiĝis ${W$(_.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Tro granda: atendiĝis ke ${_.origin??"valoro"} havu ${G}${_.maximum.toString()} ${V.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${_.origin??"valoro"} havu ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Tro malgranda: atendiĝis ke ${_.origin} havu ${G}${_.minimum.toString()} ${V.unit}`;return`Tro malgranda: atendiĝis ke ${_.origin} estu ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${G.prefix}"`;if(G.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${G.suffix}"`;if(G.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${G.includes}"`;if(G.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${G.pattern}`;return`Nevalida ${U[G.format]??_.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${_.divisor}`;case"unrecognized_keys":return`Nekonata${_.keys.length>1?"j":""} ŝlosilo${_.keys.length>1?"j":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${_.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${_.origin}`;default:return"Nevalida enigo"}}};function EF(){return{localeError:ir()}}var rr=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function J(_){return $[_]??null}let U={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},Q={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Entrada inválida: se esperaba instanceof ${_.expected}, recibido ${X}`;return`Entrada inválida: se esperaba ${G}, recibido ${X}`}case"invalid_value":if(_.values.length===1)return`Entrada inválida: se esperaba ${W$(_.values[0])}`;return`Opción inválida: se esperaba una de ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin),X=Q[_.origin]??_.origin;if(V)return`Demasiado grande: se esperaba que ${X??"valor"} tuviera ${G}${_.maximum.toString()} ${V.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${X??"valor"} fuera ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin),X=Q[_.origin]??_.origin;if(V)return`Demasiado pequeño: se esperaba que ${X} tuviera ${G}${_.minimum.toString()} ${V.unit}`;return`Demasiado pequeño: se esperaba que ${X} fuera ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Cadena inválida: debe comenzar con "${G.prefix}"`;if(G.format==="ends_with")return`Cadena inválida: debe terminar en "${G.suffix}"`;if(G.format==="includes")return`Cadena inválida: debe incluir "${G.includes}"`;if(G.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${G.pattern}`;return`Inválido ${U[G.format]??_.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${_.divisor}`;case"unrecognized_keys":return`Llave${_.keys.length>1?"s":""} desconocida${_.keys.length>1?"s":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Llave inválida en ${Q[_.origin]??_.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${Q[_.origin]??_.origin}`;default:return"Entrada inválida"}}};function PF(){return{localeError:rr()}}var nr=()=>{let $={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function J(_){return $[_]??null}let U={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},Q={nan:"NaN",number:"عدد",array:"آرایه"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`ورودی نامعتبر: میبایست instanceof ${_.expected} میبود، ${X} دریافت شد`;return`ورودی نامعتبر: میبایست ${G} میبود، ${X} دریافت شد`}case"invalid_value":if(_.values.length===1)return`ورودی نامعتبر: میبایست ${W$(_.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${o(_.values,"|")} میبود`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`خیلی بزرگ: ${_.origin??"مقدار"} باید ${G}${_.maximum.toString()} ${V.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${_.origin??"مقدار"} باید ${G}${_.maximum.toString()} باشد`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`خیلی کوچک: ${_.origin} باید ${G}${_.minimum.toString()} ${V.unit} باشد`;return`خیلی کوچک: ${_.origin} باید ${G}${_.minimum.toString()} باشد`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`رشته نامعتبر: باید با "${G.prefix}" شروع شود`;if(G.format==="ends_with")return`رشته نامعتبر: باید با "${G.suffix}" تمام شود`;if(G.format==="includes")return`رشته نامعتبر: باید شامل "${G.includes}" باشد`;if(G.format==="regex")return`رشته نامعتبر: باید با الگوی ${G.pattern} مطابقت داشته باشد`;return`${U[G.format]??_.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${_.divisor} باشد`;case"unrecognized_keys":return`کلید${_.keys.length>1?"های":""} ناشناس: ${o(_.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${_.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${_.origin}`;default:return"ورودی نامعتبر"}}};function MF(){return{localeError:nr()}}var pr=()=>{let $={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function J(_){return $[_]??null}let U={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Virheellinen tyyppi: odotettiin instanceof ${_.expected}, oli ${X}`;return`Virheellinen tyyppi: odotettiin ${G}, oli ${X}`}case"invalid_value":if(_.values.length===1)return`Virheellinen syöte: täytyy olla ${W$(_.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Liian suuri: ${V.subject} täytyy olla ${G}${_.maximum.toString()} ${V.unit}`.trim();return`Liian suuri: arvon täytyy olla ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Liian pieni: ${V.subject} täytyy olla ${G}${_.minimum.toString()} ${V.unit}`.trim();return`Liian pieni: arvon täytyy olla ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${G.prefix}"`;if(G.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${G.suffix}"`;if(G.format==="includes")return`Virheellinen syöte: täytyy sisältää "${G.includes}"`;if(G.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${G.pattern}`;return`Virheellinen ${U[G.format]??_.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${_.divisor} monikerta`;case"unrecognized_keys":return`${_.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${o(_.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function LF(){return{localeError:pr()}}var ar=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function J(_){return $[_]??null}let U={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},Q={nan:"NaN",number:"nombre",array:"tableau"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Entrée invalide : instanceof ${_.expected} attendu, ${X} reçu`;return`Entrée invalide : ${G} attendu, ${X} reçu`}case"invalid_value":if(_.values.length===1)return`Entrée invalide : ${W$(_.values[0])} attendu`;return`Option invalide : une valeur parmi ${o(_.values,"|")} attendue`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Trop grand : ${_.origin??"valeur"} doit ${V.verb} ${G}${_.maximum.toString()} ${V.unit??"élément(s)"}`;return`Trop grand : ${_.origin??"valeur"} doit être ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Trop petit : ${_.origin} doit ${V.verb} ${G}${_.minimum.toString()} ${V.unit}`;return`Trop petit : ${_.origin} doit être ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Chaîne invalide : doit commencer par "${G.prefix}"`;if(G.format==="ends_with")return`Chaîne invalide : doit se terminer par "${G.suffix}"`;if(G.format==="includes")return`Chaîne invalide : doit inclure "${G.includes}"`;if(G.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${G.pattern}`;return`${U[G.format]??_.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${_.divisor}`;case"unrecognized_keys":return`Clé${_.keys.length>1?"s":""} non reconnue${_.keys.length>1?"s":""} : ${o(_.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${_.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${_.origin}`;default:return"Entrée invalide"}}};function zF(){return{localeError:ar()}}var or=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function J(_){return $[_]??null}let U={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Entrée invalide : attendu instanceof ${_.expected}, reçu ${X}`;return`Entrée invalide : attendu ${G}, reçu ${X}`}case"invalid_value":if(_.values.length===1)return`Entrée invalide : attendu ${W$(_.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"≤":"<",V=J(_.origin);if(V)return`Trop grand : attendu que ${_.origin??"la valeur"} ait ${G}${_.maximum.toString()} ${V.unit}`;return`Trop grand : attendu que ${_.origin??"la valeur"} soit ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?"≥":">",V=J(_.origin);if(V)return`Trop petit : attendu que ${_.origin} ait ${G}${_.minimum.toString()} ${V.unit}`;return`Trop petit : attendu que ${_.origin} soit ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Chaîne invalide : doit commencer par "${G.prefix}"`;if(G.format==="ends_with")return`Chaîne invalide : doit se terminer par "${G.suffix}"`;if(G.format==="includes")return`Chaîne invalide : doit inclure "${G.includes}"`;if(G.format==="regex")return`Chaîne invalide : doit correspondre au motif ${G.pattern}`;return`${U[G.format]??_.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${_.divisor}`;case"unrecognized_keys":return`Clé${_.keys.length>1?"s":""} non reconnue${_.keys.length>1?"s":""} : ${o(_.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${_.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${_.origin}`;default:return"Entrée invalide"}}};function RF(){return{localeError:or()}}var tr=()=>{let $={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},J={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},U=(Y)=>Y?$[Y]:void 0,Q=(Y)=>{let K=U(Y);if(K)return K.label;return Y??$.unknown.label},_=(Y)=>`ה${Q(Y)}`,G=(Y)=>{return(U(Y)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},V=(Y)=>{if(!Y)return null;return J[Y]??null},X={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},Z={nan:"NaN"};return(Y)=>{switch(Y.code){case"invalid_type":{let K=Y.expected,F=Z[K??""]??Q(K),N=H$(Y.input),q=Z[N]??$[N]?.label??N;if(/^[A-Z]/.test(Y.expected))return`קלט לא תקין: צריך להיות instanceof ${Y.expected}, התקבל ${q}`;return`קלט לא תקין: צריך להיות ${F}, התקבל ${q}`}case"invalid_value":{if(Y.values.length===1)return`ערך לא תקין: הערך חייב להיות ${W$(Y.values[0])}`;let K=Y.values.map((q)=>W$(q));if(Y.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${K[0]} או ${K[1]}`;let F=K[K.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${K.slice(0,-1).join(", ")} או ${F}`}case"too_big":{let K=V(Y.origin),F=_(Y.origin??"value");if(Y.origin==="string")return`${K?.longLabel??"ארוך"} מדי: ${F} צריכה להכיל ${Y.maximum.toString()} ${K?.unit??""} ${Y.inclusive?"או פחות":"לכל היותר"}`.trim();if(Y.origin==="number"){let H=Y.inclusive?`קטן או שווה ל-${Y.maximum}`:`קטן מ-${Y.maximum}`;return`גדול מדי: ${F} צריך להיות ${H}`}if(Y.origin==="array"||Y.origin==="set"){let H=Y.origin==="set"?"צריכה":"צריך",E=Y.inclusive?`${Y.maximum} ${K?.unit??""} או פחות`:`פחות מ-${Y.maximum} ${K?.unit??""}`;return`גדול מדי: ${F} ${H} להכיל ${E}`.trim()}let N=Y.inclusive?"<=":"<",q=G(Y.origin??"value");if(K?.unit)return`${K.longLabel} מדי: ${F} ${q} ${N}${Y.maximum.toString()} ${K.unit}`;return`${K?.longLabel??"גדול"} מדי: ${F} ${q} ${N}${Y.maximum.toString()}`}case"too_small":{let K=V(Y.origin),F=_(Y.origin??"value");if(Y.origin==="string")return`${K?.shortLabel??"קצר"} מדי: ${F} צריכה להכיל ${Y.minimum.toString()} ${K?.unit??""} ${Y.inclusive?"או יותר":"לפחות"}`.trim();if(Y.origin==="number"){let H=Y.inclusive?`גדול או שווה ל-${Y.minimum}`:`גדול מ-${Y.minimum}`;return`קטן מדי: ${F} צריך להיות ${H}`}if(Y.origin==="array"||Y.origin==="set"){let H=Y.origin==="set"?"צריכה":"צריך";if(Y.minimum===1&&Y.inclusive){let D=Y.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${F} ${H} להכיל ${D}`}let E=Y.inclusive?`${Y.minimum} ${K?.unit??""} או יותר`:`יותר מ-${Y.minimum} ${K?.unit??""}`;return`קטן מדי: ${F} ${H} להכיל ${E}`.trim()}let N=Y.inclusive?">=":">",q=G(Y.origin??"value");if(K?.unit)return`${K.shortLabel} מדי: ${F} ${q} ${N}${Y.minimum.toString()} ${K.unit}`;return`${K?.shortLabel??"קטן"} מדי: ${F} ${q} ${N}${Y.minimum.toString()}`}case"invalid_format":{let K=Y;if(K.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${K.prefix}"`;if(K.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${K.suffix}"`;if(K.format==="includes")return`המחרוזת חייבת לכלול "${K.includes}"`;if(K.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${K.pattern}`;let F=X[K.format],N=F?.label??K.format,H=(F?.gender??"m")==="f"?"תקינה":"תקין";return`${N} לא ${H}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${Y.divisor}`;case"unrecognized_keys":return`מפתח${Y.keys.length>1?"ות":""} לא מזוה${Y.keys.length>1?"ים":"ה"}: ${o(Y.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${_(Y.origin??"array")}`;default:return"קלט לא תקין"}}};function AF(){return{localeError:tr()}}var sr=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function J(_){return $[_]??null}let U={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},Q={nan:"NaN",number:"szám",array:"tömb"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Érvénytelen bemenet: a várt érték instanceof ${_.expected}, a kapott érték ${X}`;return`Érvénytelen bemenet: a várt érték ${G}, a kapott érték ${X}`}case"invalid_value":if(_.values.length===1)return`Érvénytelen bemenet: a várt érték ${W$(_.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Túl nagy: ${_.origin??"érték"} mérete túl nagy ${G}${_.maximum.toString()} ${V.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${_.origin??"érték"} túl nagy: ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Túl kicsi: a bemeneti érték ${_.origin} mérete túl kicsi ${G}${_.minimum.toString()} ${V.unit}`;return`Túl kicsi: a bemeneti érték ${_.origin} túl kicsi ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Érvénytelen string: "${G.prefix}" értékkel kell kezdődnie`;if(G.format==="ends_with")return`Érvénytelen string: "${G.suffix}" értékkel kell végződnie`;if(G.format==="includes")return`Érvénytelen string: "${G.includes}" értéket kell tartalmaznia`;if(G.format==="regex")return`Érvénytelen string: ${G.pattern} mintának kell megfelelnie`;return`Érvénytelen ${U[G.format]??_.format}`}case"not_multiple_of":return`Érvénytelen szám: ${_.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${_.keys.length>1?"s":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${_.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${_.origin}`;default:return"Érvénytelen bemenet"}}};function wF(){return{localeError:sr()}}function WA($,J,U){return Math.abs($)===1?J:U}function f9($){if(!$)return"";let J=["ա","ե","ը","ի","ո","ու","օ"],U=$[$.length-1];return $+(J.includes(U)?"ն":"ը")}var er=()=>{let $={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function J(_){return $[_]??null}let U={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},Q={nan:"NaN",number:"թիվ",array:"զանգված"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${_.expected}, ստացվել է ${X}`;return`Սխալ մուտքագրում․ սպասվում էր ${G}, ստացվել է ${X}`}case"invalid_value":if(_.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${W$(_.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V){let X=Number(_.maximum),Z=WA(X,V.unit.one,V.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${f9(_.origin??"արժեք")} կունենա ${G}${_.maximum.toString()} ${Z}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${f9(_.origin??"արժեք")} լինի ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V){let X=Number(_.minimum),Z=WA(X,V.unit.one,V.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${f9(_.origin)} կունենա ${G}${_.minimum.toString()} ${Z}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${f9(_.origin)} լինի ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${G.prefix}"-ով`;if(G.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${G.suffix}"-ով`;if(G.format==="includes")return`Սխալ տող․ պետք է պարունակի "${G.includes}"`;if(G.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${G.pattern} ձևաչափին`;return`Սխալ ${U[G.format]??_.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${_.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${_.keys.length>1?"ներ":""}. ${o(_.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${f9(_.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${f9(_.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function fF(){return{localeError:er()}}var $n=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function J(_){return $[_]??null}let U={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Input tidak valid: diharapkan instanceof ${_.expected}, diterima ${X}`;return`Input tidak valid: diharapkan ${G}, diterima ${X}`}case"invalid_value":if(_.values.length===1)return`Input tidak valid: diharapkan ${W$(_.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Terlalu besar: diharapkan ${_.origin??"value"} memiliki ${G}${_.maximum.toString()} ${V.unit??"elemen"}`;return`Terlalu besar: diharapkan ${_.origin??"value"} menjadi ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Terlalu kecil: diharapkan ${_.origin} memiliki ${G}${_.minimum.toString()} ${V.unit}`;return`Terlalu kecil: diharapkan ${_.origin} menjadi ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`String tidak valid: harus dimulai dengan "${G.prefix}"`;if(G.format==="ends_with")return`String tidak valid: harus berakhir dengan "${G.suffix}"`;if(G.format==="includes")return`String tidak valid: harus menyertakan "${G.includes}"`;if(G.format==="regex")return`String tidak valid: harus sesuai pola ${G.pattern}`;return`${U[G.format]??_.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${_.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${_.keys.length>1?"s":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${_.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${_.origin}`;default:return"Input tidak valid"}}};function kF(){return{localeError:$n()}}var Jn=()=>{let $={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function J(_){return $[_]??null}let U={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},Q={nan:"NaN",number:"númer",array:"fylki"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Rangt gildi: Þú slóst inn ${X} þar sem á að vera instanceof ${_.expected}`;return`Rangt gildi: Þú slóst inn ${X} þar sem á að vera ${G}`}case"invalid_value":if(_.values.length===1)return`Rangt gildi: gert ráð fyrir ${W$(_.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Of stórt: gert er ráð fyrir að ${_.origin??"gildi"} hafi ${G}${_.maximum.toString()} ${V.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${_.origin??"gildi"} sé ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Of lítið: gert er ráð fyrir að ${_.origin} hafi ${G}${_.minimum.toString()} ${V.unit}`;return`Of lítið: gert er ráð fyrir að ${_.origin} sé ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Ógildur strengur: verður að byrja á "${G.prefix}"`;if(G.format==="ends_with")return`Ógildur strengur: verður að enda á "${G.suffix}"`;if(G.format==="includes")return`Ógildur strengur: verður að innihalda "${G.includes}"`;if(G.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${G.pattern}`;return`Rangt ${U[G.format]??_.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${_.divisor}`;case"unrecognized_keys":return`Óþekkt ${_.keys.length>1?"ir lyklar":"ur lykill"}: ${o(_.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${_.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${_.origin}`;default:return"Rangt gildi"}}};function IF(){return{localeError:Jn()}}var Un=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function J(_){return $[_]??null}let U={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"numero",array:"vettore"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Input non valido: atteso instanceof ${_.expected}, ricevuto ${X}`;return`Input non valido: atteso ${G}, ricevuto ${X}`}case"invalid_value":if(_.values.length===1)return`Input non valido: atteso ${W$(_.values[0])}`;return`Opzione non valida: atteso uno tra ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Troppo grande: ${_.origin??"valore"} deve avere ${G}${_.maximum.toString()} ${V.unit??"elementi"}`;return`Troppo grande: ${_.origin??"valore"} deve essere ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Troppo piccolo: ${_.origin} deve avere ${G}${_.minimum.toString()} ${V.unit}`;return`Troppo piccolo: ${_.origin} deve essere ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Stringa non valida: deve iniziare con "${G.prefix}"`;if(G.format==="ends_with")return`Stringa non valida: deve terminare con "${G.suffix}"`;if(G.format==="includes")return`Stringa non valida: deve includere "${G.includes}"`;if(G.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${G.pattern}`;return`Invalid ${U[G.format]??_.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${_.divisor}`;case"unrecognized_keys":return`Chiav${_.keys.length>1?"i":"e"} non riconosciut${_.keys.length>1?"e":"a"}: ${o(_.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${_.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${_.origin}`;default:return"Input non valido"}}};function SF(){return{localeError:Un()}}var _n=()=>{let $={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function J(_){return $[_]??null}let U={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},Q={nan:"NaN",number:"数値",array:"配列"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`無効な入力: instanceof ${_.expected}が期待されましたが、${X}が入力されました`;return`無効な入力: ${G}が期待されましたが、${X}が入力されました`}case"invalid_value":if(_.values.length===1)return`無効な入力: ${W$(_.values[0])}が期待されました`;return`無効な選択: ${o(_.values,"、")}のいずれかである必要があります`;case"too_big":{let G=_.inclusive?"以下である":"より小さい",V=J(_.origin);if(V)return`大きすぎる値: ${_.origin??"値"}は${_.maximum.toString()}${V.unit??"要素"}${G}必要があります`;return`大きすぎる値: ${_.origin??"値"}は${_.maximum.toString()}${G}必要があります`}case"too_small":{let G=_.inclusive?"以上である":"より大きい",V=J(_.origin);if(V)return`小さすぎる値: ${_.origin}は${_.minimum.toString()}${V.unit}${G}必要があります`;return`小さすぎる値: ${_.origin}は${_.minimum.toString()}${G}必要があります`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`無効な文字列: "${G.prefix}"で始まる必要があります`;if(G.format==="ends_with")return`無効な文字列: "${G.suffix}"で終わる必要があります`;if(G.format==="includes")return`無効な文字列: "${G.includes}"を含む必要があります`;if(G.format==="regex")return`無効な文字列: パターン${G.pattern}に一致する必要があります`;return`無効な${U[G.format]??_.format}`}case"not_multiple_of":return`無効な数値: ${_.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${_.keys.length>1?"群":""}: ${o(_.keys,"、")}`;case"invalid_key":return`${_.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${_.origin}内の無効な値`;default:return"無効な入力"}}};function TF(){return{localeError:_n()}}var Qn=()=>{let $={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function J(_){return $[_]??null}let U={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},Q={nan:"NaN",number:"რიცხვი",string:"სტრინგი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${_.expected}, მიღებული ${X}`;return`არასწორი შეყვანა: მოსალოდნელი ${G}, მიღებული ${X}`}case"invalid_value":if(_.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${W$(_.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${o(_.values,"|")}-დან`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`ზედმეტად დიდი: მოსალოდნელი ${_.origin??"მნიშვნელობა"} ${V.verb} ${G}${_.maximum.toString()} ${V.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${_.origin??"მნიშვნელობა"} იყოს ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`ზედმეტად პატარა: მოსალოდნელი ${_.origin} ${V.verb} ${G}${_.minimum.toString()} ${V.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${_.origin} იყოს ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${G.prefix}"-ით`;if(G.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${G.suffix}"-ით`;if(G.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${G.includes}"-ს`;if(G.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${G.pattern}`;return`არასწორი ${U[G.format]??_.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${_.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${_.keys.length>1?"ები":"ი"}: ${o(_.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${_.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${_.origin}-ში`;default:return"არასწორი შეყვანა"}}};function vF(){return{localeError:Qn()}}var Gn=()=>{let $={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function J(_){return $[_]??null}let U={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},Q={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${_.expected} ប៉ុន្តែទទួលបាន ${X}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${G} ប៉ុន្តែទទួលបាន ${X}`}case"invalid_value":if(_.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${W$(_.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`ធំពេក៖ ត្រូវការ ${_.origin??"តម្លៃ"} ${G} ${_.maximum.toString()} ${V.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${_.origin??"តម្លៃ"} ${G} ${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`តូចពេក៖ ត្រូវការ ${_.origin} ${G} ${_.minimum.toString()} ${V.unit}`;return`តូចពេក៖ ត្រូវការ ${_.origin} ${G} ${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${G.prefix}"`;if(G.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${G.suffix}"`;if(G.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${G.includes}"`;if(G.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${G.pattern}`;return`មិនត្រឹមត្រូវ៖ ${U[G.format]??_.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${_.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${o(_.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${_.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${_.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function P7(){return{localeError:Gn()}}function CF(){return P7()}var Vn=()=>{let $={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function J(_){return $[_]??null}let U={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`잘못된 입력: 예상 타입은 instanceof ${_.expected}, 받은 타입은 ${X}입니다`;return`잘못된 입력: 예상 타입은 ${G}, 받은 타입은 ${X}입니다`}case"invalid_value":if(_.values.length===1)return`잘못된 입력: 값은 ${W$(_.values[0])} 이어야 합니다`;return`잘못된 옵션: ${o(_.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let G=_.inclusive?"이하":"미만",V=G==="미만"?"이어야 합니다":"여야 합니다",X=J(_.origin),Z=X?.unit??"요소";if(X)return`${_.origin??"값"}이 너무 큽니다: ${_.maximum.toString()}${Z} ${G}${V}`;return`${_.origin??"값"}이 너무 큽니다: ${_.maximum.toString()} ${G}${V}`}case"too_small":{let G=_.inclusive?"이상":"초과",V=G==="이상"?"이어야 합니다":"여야 합니다",X=J(_.origin),Z=X?.unit??"요소";if(X)return`${_.origin??"값"}이 너무 작습니다: ${_.minimum.toString()}${Z} ${G}${V}`;return`${_.origin??"값"}이 너무 작습니다: ${_.minimum.toString()} ${G}${V}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`잘못된 문자열: "${G.prefix}"(으)로 시작해야 합니다`;if(G.format==="ends_with")return`잘못된 문자열: "${G.suffix}"(으)로 끝나야 합니다`;if(G.format==="includes")return`잘못된 문자열: "${G.includes}"을(를) 포함해야 합니다`;if(G.format==="regex")return`잘못된 문자열: 정규식 ${G.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${U[G.format]??_.format}`}case"not_multiple_of":return`잘못된 숫자: ${_.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${o(_.keys,", ")}`;case"invalid_key":return`잘못된 키: ${_.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${_.origin}`;default:return"잘못된 입력"}}};function bF(){return{localeError:Vn()}}var M7=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function qA($){let J=Math.abs($),U=J%10,Q=J%100;if(Q>=11&&Q<=19||U===0)return"many";if(U===1)return"one";return"few"}var Xn=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function J(_,G,V,X){let Z=$[_]??null;if(Z===null)return Z;return{unit:Z.unit[G],verb:Z.verb[X][V?"inclusive":"notInclusive"]}}let U={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},Q={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Gautas tipas ${X}, o tikėtasi - instanceof ${_.expected}`;return`Gautas tipas ${X}, o tikėtasi - ${G}`}case"invalid_value":if(_.values.length===1)return`Privalo būti ${W$(_.values[0])}`;return`Privalo būti vienas iš ${o(_.values,"|")} pasirinkimų`;case"too_big":{let G=Q[_.origin]??_.origin,V=J(_.origin,qA(Number(_.maximum)),_.inclusive??!1,"smaller");if(V?.verb)return`${M7(G??_.origin??"reikšmė")} ${V.verb} ${_.maximum.toString()} ${V.unit??"elementų"}`;let X=_.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${M7(G??_.origin??"reikšmė")} turi būti ${X} ${_.maximum.toString()} ${V?.unit}`}case"too_small":{let G=Q[_.origin]??_.origin,V=J(_.origin,qA(Number(_.minimum)),_.inclusive??!1,"bigger");if(V?.verb)return`${M7(G??_.origin??"reikšmė")} ${V.verb} ${_.minimum.toString()} ${V.unit??"elementų"}`;let X=_.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${M7(G??_.origin??"reikšmė")} turi būti ${X} ${_.minimum.toString()} ${V?.unit}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Eilutė privalo prasidėti "${G.prefix}"`;if(G.format==="ends_with")return`Eilutė privalo pasibaigti "${G.suffix}"`;if(G.format==="includes")return`Eilutė privalo įtraukti "${G.includes}"`;if(G.format==="regex")return`Eilutė privalo atitikti ${G.pattern}`;return`Neteisingas ${U[G.format]??_.format}`}case"not_multiple_of":return`Skaičius privalo būti ${_.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${_.keys.length>1?"i":"as"} rakt${_.keys.length>1?"ai":"as"}: ${o(_.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let G=Q[_.origin]??_.origin;return`${M7(G??_.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function yF(){return{localeError:Xn()}}var Yn=()=>{let $={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function J(_){return $[_]??null}let U={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},Q={nan:"NaN",number:"број",array:"низа"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Грешен внес: се очекува instanceof ${_.expected}, примено ${X}`;return`Грешен внес: се очекува ${G}, примено ${X}`}case"invalid_value":if(_.values.length===1)return`Invalid input: expected ${W$(_.values[0])}`;return`Грешана опција: се очекува една ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Премногу голем: се очекува ${_.origin??"вредноста"} да има ${G}${_.maximum.toString()} ${V.unit??"елементи"}`;return`Премногу голем: се очекува ${_.origin??"вредноста"} да биде ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Премногу мал: се очекува ${_.origin} да има ${G}${_.minimum.toString()} ${V.unit}`;return`Премногу мал: се очекува ${_.origin} да биде ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Неважечка низа: мора да започнува со "${G.prefix}"`;if(G.format==="ends_with")return`Неважечка низа: мора да завршува со "${G.suffix}"`;if(G.format==="includes")return`Неважечка низа: мора да вклучува "${G.includes}"`;if(G.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${G.pattern}`;return`Invalid ${U[G.format]??_.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${_.divisor}`;case"unrecognized_keys":return`${_.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${o(_.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${_.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${_.origin}`;default:return"Грешен внес"}}};function gF(){return{localeError:Yn()}}var Zn=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function J(_){return $[_]??null}let U={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"nombor"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Input tidak sah: dijangka instanceof ${_.expected}, diterima ${X}`;return`Input tidak sah: dijangka ${G}, diterima ${X}`}case"invalid_value":if(_.values.length===1)return`Input tidak sah: dijangka ${W$(_.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Terlalu besar: dijangka ${_.origin??"nilai"} ${V.verb} ${G}${_.maximum.toString()} ${V.unit??"elemen"}`;return`Terlalu besar: dijangka ${_.origin??"nilai"} adalah ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Terlalu kecil: dijangka ${_.origin} ${V.verb} ${G}${_.minimum.toString()} ${V.unit}`;return`Terlalu kecil: dijangka ${_.origin} adalah ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`String tidak sah: mesti bermula dengan "${G.prefix}"`;if(G.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${G.suffix}"`;if(G.format==="includes")return`String tidak sah: mesti mengandungi "${G.includes}"`;if(G.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${G.pattern}`;return`${U[G.format]??_.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${_.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${o(_.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${_.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${_.origin}`;default:return"Input tidak sah"}}};function xF(){return{localeError:Zn()}}var Kn=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function J(_){return $[_]??null}let U={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},Q={nan:"NaN",number:"getal"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Ongeldige invoer: verwacht instanceof ${_.expected}, ontving ${X}`;return`Ongeldige invoer: verwacht ${G}, ontving ${X}`}case"invalid_value":if(_.values.length===1)return`Ongeldige invoer: verwacht ${W$(_.values[0])}`;return`Ongeldige optie: verwacht één van ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin),X=_.origin==="date"?"laat":_.origin==="string"?"lang":"groot";if(V)return`Te ${X}: verwacht dat ${_.origin??"waarde"} ${G}${_.maximum.toString()} ${V.unit??"elementen"} ${V.verb}`;return`Te ${X}: verwacht dat ${_.origin??"waarde"} ${G}${_.maximum.toString()} is`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin),X=_.origin==="date"?"vroeg":_.origin==="string"?"kort":"klein";if(V)return`Te ${X}: verwacht dat ${_.origin} ${G}${_.minimum.toString()} ${V.unit} ${V.verb}`;return`Te ${X}: verwacht dat ${_.origin} ${G}${_.minimum.toString()} is`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Ongeldige tekst: moet met "${G.prefix}" beginnen`;if(G.format==="ends_with")return`Ongeldige tekst: moet op "${G.suffix}" eindigen`;if(G.format==="includes")return`Ongeldige tekst: moet "${G.includes}" bevatten`;if(G.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${G.pattern}`;return`Ongeldig: ${U[G.format]??_.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${_.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${_.keys.length>1?"s":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${_.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${_.origin}`;default:return"Ongeldige invoer"}}};function hF(){return{localeError:Kn()}}var Nn=()=>{let $={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function J(_){return $[_]??null}let U={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"tall",array:"liste"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Ugyldig input: forventet instanceof ${_.expected}, fikk ${X}`;return`Ugyldig input: forventet ${G}, fikk ${X}`}case"invalid_value":if(_.values.length===1)return`Ugyldig verdi: forventet ${W$(_.values[0])}`;return`Ugyldig valg: forventet en av ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`For stor(t): forventet ${_.origin??"value"} til å ha ${G}${_.maximum.toString()} ${V.unit??"elementer"}`;return`For stor(t): forventet ${_.origin??"value"} til å ha ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`For lite(n): forventet ${_.origin} til å ha ${G}${_.minimum.toString()} ${V.unit}`;return`For lite(n): forventet ${_.origin} til å ha ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Ugyldig streng: må starte med "${G.prefix}"`;if(G.format==="ends_with")return`Ugyldig streng: må ende med "${G.suffix}"`;if(G.format==="includes")return`Ugyldig streng: må inneholde "${G.includes}"`;if(G.format==="regex")return`Ugyldig streng: må matche mønsteret ${G.pattern}`;return`Ugyldig ${U[G.format]??_.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${_.divisor}`;case"unrecognized_keys":return`${_.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${o(_.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${_.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${_.origin}`;default:return"Ugyldig input"}}};function uF(){return{localeError:Nn()}}var Fn=()=>{let $={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function J(_){return $[_]??null}let U={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},Q={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Fâsit giren: umulan instanceof ${_.expected}, alınan ${X}`;return`Fâsit giren: umulan ${G}, alınan ${X}`}case"invalid_value":if(_.values.length===1)return`Fâsit giren: umulan ${W$(_.values[0])}`;return`Fâsit tercih: mûteberler ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Fazla büyük: ${_.origin??"value"}, ${G}${_.maximum.toString()} ${V.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${_.origin??"value"}, ${G}${_.maximum.toString()} olmalıydı.`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Fazla küçük: ${_.origin}, ${G}${_.minimum.toString()} ${V.unit} sahip olmalıydı.`;return`Fazla küçük: ${_.origin}, ${G}${_.minimum.toString()} olmalıydı.`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Fâsit metin: "${G.prefix}" ile başlamalı.`;if(G.format==="ends_with")return`Fâsit metin: "${G.suffix}" ile bitmeli.`;if(G.format==="includes")return`Fâsit metin: "${G.includes}" ihtivâ etmeli.`;if(G.format==="regex")return`Fâsit metin: ${G.pattern} nakşına uymalı.`;return`Fâsit ${U[G.format]??_.format}`}case"not_multiple_of":return`Fâsit sayı: ${_.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${_.keys.length>1?"s":""}: ${o(_.keys,", ")}`;case"invalid_key":return`${_.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${_.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function mF(){return{localeError:Fn()}}var Wn=()=>{let $={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function J(_){return $[_]??null}let U={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},Q={nan:"NaN",number:"عدد",array:"ارې"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`ناسم ورودي: باید instanceof ${_.expected} وای, مګر ${X} ترلاسه شو`;return`ناسم ورودي: باید ${G} وای, مګر ${X} ترلاسه شو`}case"invalid_value":if(_.values.length===1)return`ناسم ورودي: باید ${W$(_.values[0])} وای`;return`ناسم انتخاب: باید یو له ${o(_.values,"|")} څخه وای`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`ډیر لوی: ${_.origin??"ارزښت"} باید ${G}${_.maximum.toString()} ${V.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${_.origin??"ارزښت"} باید ${G}${_.maximum.toString()} وي`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`ډیر کوچنی: ${_.origin} باید ${G}${_.minimum.toString()} ${V.unit} ولري`;return`ډیر کوچنی: ${_.origin} باید ${G}${_.minimum.toString()} وي`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`ناسم متن: باید د "${G.prefix}" سره پیل شي`;if(G.format==="ends_with")return`ناسم متن: باید د "${G.suffix}" سره پای ته ورسيږي`;if(G.format==="includes")return`ناسم متن: باید "${G.includes}" ولري`;if(G.format==="regex")return`ناسم متن: باید د ${G.pattern} سره مطابقت ولري`;return`${U[G.format]??_.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${_.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${_.keys.length>1?"کلیډونه":"کلیډ"}: ${o(_.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${_.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${_.origin} کې`;default:return"ناسمه ورودي"}}};function cF(){return{localeError:Wn()}}var qn=()=>{let $={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function J(_){return $[_]??null}let U={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},Q={nan:"NaN",number:"liczba",array:"tablica"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${_.expected}, otrzymano ${X}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${G}, otrzymano ${X}`}case"invalid_value":if(_.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${W$(_.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Za duża wartość: oczekiwano, że ${_.origin??"wartość"} będzie mieć ${G}${_.maximum.toString()} ${V.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${_.origin??"wartość"} będzie wynosić ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Za mała wartość: oczekiwano, że ${_.origin??"wartość"} będzie mieć ${G}${_.minimum.toString()} ${V.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${_.origin??"wartość"} będzie wynosić ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${G.prefix}"`;if(G.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${G.suffix}"`;if(G.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${G.includes}"`;if(G.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${G.pattern}`;return`Nieprawidłow(y/a/e) ${U[G.format]??_.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${_.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${_.keys.length>1?"s":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${_.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${_.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function dF(){return{localeError:qn()}}var Hn=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function J(_){return $[_]??null}let U={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},Q={nan:"NaN",number:"número",null:"nulo"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Tipo inválido: esperado instanceof ${_.expected}, recebido ${X}`;return`Tipo inválido: esperado ${G}, recebido ${X}`}case"invalid_value":if(_.values.length===1)return`Entrada inválida: esperado ${W$(_.values[0])}`;return`Opção inválida: esperada uma das ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Muito grande: esperado que ${_.origin??"valor"} tivesse ${G}${_.maximum.toString()} ${V.unit??"elementos"}`;return`Muito grande: esperado que ${_.origin??"valor"} fosse ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Muito pequeno: esperado que ${_.origin} tivesse ${G}${_.minimum.toString()} ${V.unit}`;return`Muito pequeno: esperado que ${_.origin} fosse ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Texto inválido: deve começar com "${G.prefix}"`;if(G.format==="ends_with")return`Texto inválido: deve terminar com "${G.suffix}"`;if(G.format==="includes")return`Texto inválido: deve incluir "${G.includes}"`;if(G.format==="regex")return`Texto inválido: deve corresponder ao padrão ${G.pattern}`;return`${U[G.format]??_.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${_.divisor}`;case"unrecognized_keys":return`Chave${_.keys.length>1?"s":""} desconhecida${_.keys.length>1?"s":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Chave inválida em ${_.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${_.origin}`;default:return"Campo inválido"}}};function lF(){return{localeError:Hn()}}function HA($,J,U,Q){let _=Math.abs($),G=_%10,V=_%100;if(V>=11&&V<=19)return Q;if(G===1)return J;if(G>=2&&G<=4)return U;return Q}var Bn=()=>{let $={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function J(_){return $[_]??null}let U={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},Q={nan:"NaN",number:"число",array:"массив"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Неверный ввод: ожидалось instanceof ${_.expected}, получено ${X}`;return`Неверный ввод: ожидалось ${G}, получено ${X}`}case"invalid_value":if(_.values.length===1)return`Неверный ввод: ожидалось ${W$(_.values[0])}`;return`Неверный вариант: ожидалось одно из ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V){let X=Number(_.maximum),Z=HA(X,V.unit.one,V.unit.few,V.unit.many);return`Слишком большое значение: ожидалось, что ${_.origin??"значение"} будет иметь ${G}${_.maximum.toString()} ${Z}`}return`Слишком большое значение: ожидалось, что ${_.origin??"значение"} будет ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V){let X=Number(_.minimum),Z=HA(X,V.unit.one,V.unit.few,V.unit.many);return`Слишком маленькое значение: ожидалось, что ${_.origin} будет иметь ${G}${_.minimum.toString()} ${Z}`}return`Слишком маленькое значение: ожидалось, что ${_.origin} будет ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Неверная строка: должна начинаться с "${G.prefix}"`;if(G.format==="ends_with")return`Неверная строка: должна заканчиваться на "${G.suffix}"`;if(G.format==="includes")return`Неверная строка: должна содержать "${G.includes}"`;if(G.format==="regex")return`Неверная строка: должна соответствовать шаблону ${G.pattern}`;return`Неверный ${U[G.format]??_.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${_.divisor}`;case"unrecognized_keys":return`Нераспознанн${_.keys.length>1?"ые":"ый"} ключ${_.keys.length>1?"и":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${_.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${_.origin}`;default:return"Неверные входные данные"}}};function iF(){return{localeError:Bn()}}var On=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function J(_){return $[_]??null}let U={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},Q={nan:"NaN",number:"število",array:"tabela"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Neveljaven vnos: pričakovano instanceof ${_.expected}, prejeto ${X}`;return`Neveljaven vnos: pričakovano ${G}, prejeto ${X}`}case"invalid_value":if(_.values.length===1)return`Neveljaven vnos: pričakovano ${W$(_.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Preveliko: pričakovano, da bo ${_.origin??"vrednost"} imelo ${G}${_.maximum.toString()} ${V.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${_.origin??"vrednost"} ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Premajhno: pričakovano, da bo ${_.origin} imelo ${G}${_.minimum.toString()} ${V.unit}`;return`Premajhno: pričakovano, da bo ${_.origin} ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Neveljaven niz: mora se začeti z "${G.prefix}"`;if(G.format==="ends_with")return`Neveljaven niz: mora se končati z "${G.suffix}"`;if(G.format==="includes")return`Neveljaven niz: mora vsebovati "${G.includes}"`;if(G.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${G.pattern}`;return`Neveljaven ${U[G.format]??_.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${_.divisor}`;case"unrecognized_keys":return`Neprepoznan${_.keys.length>1?"i ključi":" ključ"}: ${o(_.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${_.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${_.origin}`;default:return"Neveljaven vnos"}}};function rF(){return{localeError:On()}}var jn=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function J(_){return $[_]??null}let U={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},Q={nan:"NaN",number:"antal",array:"lista"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Ogiltig inmatning: förväntat instanceof ${_.expected}, fick ${X}`;return`Ogiltig inmatning: förväntat ${G}, fick ${X}`}case"invalid_value":if(_.values.length===1)return`Ogiltig inmatning: förväntat ${W$(_.values[0])}`;return`Ogiltigt val: förväntade en av ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`För stor(t): förväntade ${_.origin??"värdet"} att ha ${G}${_.maximum.toString()} ${V.unit??"element"}`;return`För stor(t): förväntat ${_.origin??"värdet"} att ha ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`För lite(t): förväntade ${_.origin??"värdet"} att ha ${G}${_.minimum.toString()} ${V.unit}`;return`För lite(t): förväntade ${_.origin??"värdet"} att ha ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Ogiltig sträng: måste börja med "${G.prefix}"`;if(G.format==="ends_with")return`Ogiltig sträng: måste sluta med "${G.suffix}"`;if(G.format==="includes")return`Ogiltig sträng: måste innehålla "${G.includes}"`;if(G.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${G.pattern}"`;return`Ogiltig(t) ${U[G.format]??_.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${_.divisor}`;case"unrecognized_keys":return`${_.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${o(_.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${_.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${_.origin??"värdet"}`;default:return"Ogiltig input"}}};function nF(){return{localeError:jn()}}var Dn=()=>{let $={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function J(_){return $[_]??null}let U={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${_.expected}, பெறப்பட்டது ${X}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${G}, பெறப்பட்டது ${X}`}case"invalid_value":if(_.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${W$(_.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${o(_.values,"|")} இல் ஒன்று`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${_.origin??"மதிப்பு"} ${G}${_.maximum.toString()} ${V.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${_.origin??"மதிப்பு"} ${G}${_.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${_.origin} ${G}${_.minimum.toString()} ${V.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${_.origin} ${G}${_.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`தவறான சரம்: "${G.prefix}" இல் தொடங்க வேண்டும்`;if(G.format==="ends_with")return`தவறான சரம்: "${G.suffix}" இல் முடிவடைய வேண்டும்`;if(G.format==="includes")return`தவறான சரம்: "${G.includes}" ஐ உள்ளடக்க வேண்டும்`;if(G.format==="regex")return`தவறான சரம்: ${G.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${U[G.format]??_.format}`}case"not_multiple_of":return`தவறான எண்: ${_.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${_.keys.length>1?"கள்":""}: ${o(_.keys,", ")}`;case"invalid_key":return`${_.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${_.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function pF(){return{localeError:Dn()}}var En=()=>{let $={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function J(_){return $[_]??null}let U={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},Q={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${_.expected} แต่ได้รับ ${X}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${G} แต่ได้รับ ${X}`}case"invalid_value":if(_.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${W$(_.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"ไม่เกิน":"น้อยกว่า",V=J(_.origin);if(V)return`เกินกำหนด: ${_.origin??"ค่า"} ควรมี${G} ${_.maximum.toString()} ${V.unit??"รายการ"}`;return`เกินกำหนด: ${_.origin??"ค่า"} ควรมี${G} ${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?"อย่างน้อย":"มากกว่า",V=J(_.origin);if(V)return`น้อยกว่ากำหนด: ${_.origin} ควรมี${G} ${_.minimum.toString()} ${V.unit}`;return`น้อยกว่ากำหนด: ${_.origin} ควรมี${G} ${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${G.prefix}"`;if(G.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${G.suffix}"`;if(G.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${G.includes}" อยู่ในข้อความ`;if(G.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${G.pattern}`;return`รูปแบบไม่ถูกต้อง: ${U[G.format]??_.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${_.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${o(_.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${_.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${_.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function aF(){return{localeError:En()}}var Pn=()=>{let $={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function J(_){return $[_]??null}let U={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Geçersiz değer: beklenen instanceof ${_.expected}, alınan ${X}`;return`Geçersiz değer: beklenen ${G}, alınan ${X}`}case"invalid_value":if(_.values.length===1)return`Geçersiz değer: beklenen ${W$(_.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Çok büyük: beklenen ${_.origin??"değer"} ${G}${_.maximum.toString()} ${V.unit??"öğe"}`;return`Çok büyük: beklenen ${_.origin??"değer"} ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Çok küçük: beklenen ${_.origin} ${G}${_.minimum.toString()} ${V.unit}`;return`Çok küçük: beklenen ${_.origin} ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Geçersiz metin: "${G.prefix}" ile başlamalı`;if(G.format==="ends_with")return`Geçersiz metin: "${G.suffix}" ile bitmeli`;if(G.format==="includes")return`Geçersiz metin: "${G.includes}" içermeli`;if(G.format==="regex")return`Geçersiz metin: ${G.pattern} desenine uymalı`;return`Geçersiz ${U[G.format]??_.format}`}case"not_multiple_of":return`Geçersiz sayı: ${_.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${_.keys.length>1?"lar":""}: ${o(_.keys,", ")}`;case"invalid_key":return`${_.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${_.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function oF(){return{localeError:Pn()}}var Mn=()=>{let $={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function J(_){return $[_]??null}let U={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},Q={nan:"NaN",number:"число",array:"масив"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Неправильні вхідні дані: очікується instanceof ${_.expected}, отримано ${X}`;return`Неправильні вхідні дані: очікується ${G}, отримано ${X}`}case"invalid_value":if(_.values.length===1)return`Неправильні вхідні дані: очікується ${W$(_.values[0])}`;return`Неправильна опція: очікується одне з ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Занадто велике: очікується, що ${_.origin??"значення"} ${V.verb} ${G}${_.maximum.toString()} ${V.unit??"елементів"}`;return`Занадто велике: очікується, що ${_.origin??"значення"} буде ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Занадто мале: очікується, що ${_.origin} ${V.verb} ${G}${_.minimum.toString()} ${V.unit}`;return`Занадто мале: очікується, що ${_.origin} буде ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Неправильний рядок: повинен починатися з "${G.prefix}"`;if(G.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${G.suffix}"`;if(G.format==="includes")return`Неправильний рядок: повинен містити "${G.includes}"`;if(G.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${G.pattern}`;return`Неправильний ${U[G.format]??_.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${_.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${_.keys.length>1?"і":""}: ${o(_.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${_.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${_.origin}`;default:return"Неправильні вхідні дані"}}};function L7(){return{localeError:Mn()}}function tF(){return L7()}var Ln=()=>{let $={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function J(_){return $[_]??null}let U={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},Q={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`غلط ان پٹ: instanceof ${_.expected} متوقع تھا، ${X} موصول ہوا`;return`غلط ان پٹ: ${G} متوقع تھا، ${X} موصول ہوا`}case"invalid_value":if(_.values.length===1)return`غلط ان پٹ: ${W$(_.values[0])} متوقع تھا`;return`غلط آپشن: ${o(_.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`بہت بڑا: ${_.origin??"ویلیو"} کے ${G}${_.maximum.toString()} ${V.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${_.origin??"ویلیو"} کا ${G}${_.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`بہت چھوٹا: ${_.origin} کے ${G}${_.minimum.toString()} ${V.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${_.origin} کا ${G}${_.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`غلط سٹرنگ: "${G.prefix}" سے شروع ہونا چاہیے`;if(G.format==="ends_with")return`غلط سٹرنگ: "${G.suffix}" پر ختم ہونا چاہیے`;if(G.format==="includes")return`غلط سٹرنگ: "${G.includes}" شامل ہونا چاہیے`;if(G.format==="regex")return`غلط سٹرنگ: پیٹرن ${G.pattern} سے میچ ہونا چاہیے`;return`غلط ${U[G.format]??_.format}`}case"not_multiple_of":return`غلط نمبر: ${_.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${_.keys.length>1?"ز":""}: ${o(_.keys,"، ")}`;case"invalid_key":return`${_.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${_.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function sF(){return{localeError:Ln()}}var zn=()=>{let $={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"}};function J(_){return $[_]??null}let U={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},Q={nan:"NaN",number:"raqam",array:"massiv"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${_.expected}, qabul qilingan ${X}`;return`Noto‘g‘ri kirish: kutilgan ${G}, qabul qilingan ${X}`}case"invalid_value":if(_.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${W$(_.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Juda katta: kutilgan ${_.origin??"qiymat"} ${G}${_.maximum.toString()} ${V.unit} ${V.verb}`;return`Juda katta: kutilgan ${_.origin??"qiymat"} ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Juda kichik: kutilgan ${_.origin} ${G}${_.minimum.toString()} ${V.unit} ${V.verb}`;return`Juda kichik: kutilgan ${_.origin} ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Noto‘g‘ri satr: "${G.prefix}" bilan boshlanishi kerak`;if(G.format==="ends_with")return`Noto‘g‘ri satr: "${G.suffix}" bilan tugashi kerak`;if(G.format==="includes")return`Noto‘g‘ri satr: "${G.includes}" ni o‘z ichiga olishi kerak`;if(G.format==="regex")return`Noto‘g‘ri satr: ${G.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${U[G.format]??_.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${_.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${_.keys.length>1?"lar":""}: ${o(_.keys,", ")}`;case"invalid_key":return`${_.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${_.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function eF(){return{localeError:zn()}}var Rn=()=>{let $={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function J(_){return $[_]??null}let U={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},Q={nan:"NaN",number:"số",array:"mảng"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${_.expected}, nhận được ${X}`;return`Đầu vào không hợp lệ: mong đợi ${G}, nhận được ${X}`}case"invalid_value":if(_.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${W$(_.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Quá lớn: mong đợi ${_.origin??"giá trị"} ${V.verb} ${G}${_.maximum.toString()} ${V.unit??"phần tử"}`;return`Quá lớn: mong đợi ${_.origin??"giá trị"} ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Quá nhỏ: mong đợi ${_.origin} ${V.verb} ${G}${_.minimum.toString()} ${V.unit}`;return`Quá nhỏ: mong đợi ${_.origin} ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${G.prefix}"`;if(G.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${G.suffix}"`;if(G.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${G.includes}"`;if(G.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${G.pattern}`;return`${U[G.format]??_.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${_.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${o(_.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${_.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${_.origin}`;default:return"Đầu vào không hợp lệ"}}};function $W(){return{localeError:Rn()}}var An=()=>{let $={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function J(_){return $[_]??null}let U={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},Q={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`无效输入:期望 instanceof ${_.expected},实际接收 ${X}`;return`无效输入:期望 ${G},实际接收 ${X}`}case"invalid_value":if(_.values.length===1)return`无效输入:期望 ${W$(_.values[0])}`;return`无效选项:期望以下之一 ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`数值过大:期望 ${_.origin??"值"} ${G}${_.maximum.toString()} ${V.unit??"个元素"}`;return`数值过大:期望 ${_.origin??"值"} ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`数值过小:期望 ${_.origin} ${G}${_.minimum.toString()} ${V.unit}`;return`数值过小:期望 ${_.origin} ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`无效字符串:必须以 "${G.prefix}" 开头`;if(G.format==="ends_with")return`无效字符串:必须以 "${G.suffix}" 结尾`;if(G.format==="includes")return`无效字符串:必须包含 "${G.includes}"`;if(G.format==="regex")return`无效字符串:必须满足正则表达式 ${G.pattern}`;return`无效${U[G.format]??_.format}`}case"not_multiple_of":return`无效数字:必须是 ${_.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${o(_.keys,", ")}`;case"invalid_key":return`${_.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${_.origin} 中包含无效值(value)`;default:return"无效输入"}}};function JW(){return{localeError:An()}}var wn=()=>{let $={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function J(_){return $[_]??null}let U={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},Q={nan:"NaN"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`無效的輸入值:預期為 instanceof ${_.expected},但收到 ${X}`;return`無效的輸入值:預期為 ${G},但收到 ${X}`}case"invalid_value":if(_.values.length===1)return`無效的輸入值:預期為 ${W$(_.values[0])}`;return`無效的選項:預期為以下其中之一 ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`數值過大:預期 ${_.origin??"值"} 應為 ${G}${_.maximum.toString()} ${V.unit??"個元素"}`;return`數值過大:預期 ${_.origin??"值"} 應為 ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`數值過小:預期 ${_.origin} 應為 ${G}${_.minimum.toString()} ${V.unit}`;return`數值過小:預期 ${_.origin} 應為 ${G}${_.minimum.toString()}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`無效的字串:必須以 "${G.prefix}" 開頭`;if(G.format==="ends_with")return`無效的字串:必須以 "${G.suffix}" 結尾`;if(G.format==="includes")return`無效的字串:必須包含 "${G.includes}"`;if(G.format==="regex")return`無效的字串:必須符合格式 ${G.pattern}`;return`無效的 ${U[G.format]??_.format}`}case"not_multiple_of":return`無效的數字:必須為 ${_.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${_.keys.length>1?"們":""}:${o(_.keys,"、")}`;case"invalid_key":return`${_.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${_.origin} 中有無效的值`;default:return"無效的輸入值"}}};function UW(){return{localeError:wn()}}var fn=()=>{let $={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function J(_){return $[_]??null}let U={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},Q={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(_)=>{switch(_.code){case"invalid_type":{let G=Q[_.expected]??_.expected,V=H$(_.input),X=Q[V]??V;if(/^[A-Z]/.test(_.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${_.expected}, àmọ̀ a rí ${X}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${G}, àmọ̀ a rí ${X}`}case"invalid_value":if(_.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${W$(_.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${o(_.values,"|")}`;case"too_big":{let G=_.inclusive?"<=":"<",V=J(_.origin);if(V)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${_.origin??"iye"} ${V.verb} ${G}${_.maximum} ${V.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${G}${_.maximum}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V)return`Kéré ju: a ní láti jẹ́ pé ${_.origin} ${V.verb} ${G}${_.minimum} ${V.unit}`;return`Kéré ju: a ní láti jẹ́ ${G}${_.minimum}`}case"invalid_format":{let G=_;if(G.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${G.prefix}"`;if(G.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${G.suffix}"`;if(G.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${G.includes}"`;if(G.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${G.pattern}`;return`Aṣìṣe: ${U[G.format]??_.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${_.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${o(_.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${_.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${_.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function _W(){return{localeError:fn()}}var BA,QW=Symbol("ZodOutput"),GW=Symbol("ZodInput");class VW{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...J){let U=J[0];if(this._map.set($,U),U&&typeof U==="object"&&"id"in U)this._idmap.set(U.id,$);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let J=this._map.get($);if(J&&typeof J==="object"&&"id"in J)this._idmap.delete(J.id);return this._map.delete($),this}get($){let J=$._zod.parent;if(J){let U={...this.get(J)??{}};delete U.id;let Q={...U,...this._map.get($)};return Object.keys(Q).length?Q:void 0}return this._map.get($)}has($){return this._map.has($)}}function P3(){return new VW}(BA=globalThis).__zod_globalRegistry??(BA.__zod_globalRegistry=P3());var T6=globalThis.__zod_globalRegistry;function XW($,J){return new $({type:"string",...O$(J)})}function YW($,J){return new $({type:"string",coerce:!0,...O$(J)})}function M3($,J){return new $({type:"string",format:"email",check:"string_format",abort:!1,...O$(J)})}function R7($,J){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...O$(J)})}function L3($,J){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...O$(J)})}function z3($,J){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...O$(J)})}function R3($,J){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...O$(J)})}function A3($,J){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...O$(J)})}function A7($,J){return new $({type:"string",format:"url",check:"string_format",abort:!1,...O$(J)})}function w3($,J){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...O$(J)})}function f3($,J){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...O$(J)})}function k3($,J){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...O$(J)})}function I3($,J){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...O$(J)})}function S3($,J){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...O$(J)})}function T3($,J){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...O$(J)})}function v3($,J){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...O$(J)})}function C3($,J){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...O$(J)})}function b3($,J){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...O$(J)})}function ZW($,J){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...O$(J)})}function y3($,J){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...O$(J)})}function g3($,J){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...O$(J)})}function x3($,J){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...O$(J)})}function h3($,J){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...O$(J)})}function u3($,J){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...O$(J)})}function m3($,J){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...O$(J)})}var KW={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function NW($,J){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...O$(J)})}function FW($,J){return new $({type:"string",format:"date",check:"string_format",...O$(J)})}function WW($,J){return new $({type:"string",format:"time",check:"string_format",precision:null,...O$(J)})}function qW($,J){return new $({type:"string",format:"duration",check:"string_format",...O$(J)})}function HW($,J){return new $({type:"number",checks:[],...O$(J)})}function BW($,J){return new $({type:"number",coerce:!0,checks:[],...O$(J)})}function OW($,J){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...O$(J)})}function jW($,J){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...O$(J)})}function DW($,J){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...O$(J)})}function EW($,J){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...O$(J)})}function PW($,J){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...O$(J)})}function MW($,J){return new $({type:"boolean",...O$(J)})}function LW($,J){return new $({type:"boolean",coerce:!0,...O$(J)})}function zW($,J){return new $({type:"bigint",...O$(J)})}function RW($,J){return new $({type:"bigint",coerce:!0,...O$(J)})}function AW($,J){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...O$(J)})}function wW($,J){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...O$(J)})}function fW($,J){return new $({type:"symbol",...O$(J)})}function kW($,J){return new $({type:"undefined",...O$(J)})}function IW($,J){return new $({type:"null",...O$(J)})}function SW($){return new $({type:"any"})}function TW($){return new $({type:"unknown"})}function vW($,J){return new $({type:"never",...O$(J)})}function CW($,J){return new $({type:"void",...O$(J)})}function bW($,J){return new $({type:"date",...O$(J)})}function yW($,J){return new $({type:"date",coerce:!0,...O$(J)})}function gW($,J){return new $({type:"nan",...O$(J)})}function z1($,J){return new Z3({check:"less_than",...O$(J),value:$,inclusive:!1})}function w0($,J){return new Z3({check:"less_than",...O$(J),value:$,inclusive:!0})}function R1($,J){return new K3({check:"greater_than",...O$(J),value:$,inclusive:!1})}function l6($,J){return new K3({check:"greater_than",...O$(J),value:$,inclusive:!0})}function c3($){return R1(0,$)}function d3($){return z1(0,$)}function l3($){return w0(0,$)}function i3($){return l6(0,$)}function a2($,J){return new gK({check:"multiple_of",...O$(J),value:$})}function o2($,J){return new uK({check:"max_size",...O$(J),maximum:$})}function A1($,J){return new mK({check:"min_size",...O$(J),minimum:$})}function Q8($,J){return new cK({check:"size_equals",...O$(J),size:$})}function G8($,J){return new dK({check:"max_length",...O$(J),maximum:$})}function t1($,J){return new lK({check:"min_length",...O$(J),minimum:$})}function V8($,J){return new iK({check:"length_equals",...O$(J),length:$})}function k9($,J){return new rK({check:"string_format",format:"regex",...O$(J),pattern:$})}function I9($){return new nK({check:"string_format",format:"lowercase",...O$($)})}function S9($){return new pK({check:"string_format",format:"uppercase",...O$($)})}function T9($,J){return new aK({check:"string_format",format:"includes",...O$(J),includes:$})}function v9($,J){return new oK({check:"string_format",format:"starts_with",...O$(J),prefix:$})}function C9($,J){return new tK({check:"string_format",format:"ends_with",...O$(J),suffix:$})}function r3($,J,U){return new sK({check:"property",property:$,schema:J,...O$(U)})}function b9($,J){return new eK({check:"mime_type",mime:$,...O$(J)})}function s0($){return new $N({check:"overwrite",tx:$})}function y9($){return s0((J)=>J.normalize($))}function g9(){return s0(($)=>$.trim())}function x9(){return s0(($)=>$.toLowerCase())}function h9(){return s0(($)=>$.toUpperCase())}function u9(){return s0(($)=>sZ($))}function xW($,J,U){return new $({type:"array",element:J,...O$(U)})}function In($,J,U){return new $({type:"union",options:J,...O$(U)})}function Sn($,J,U){return new $({type:"union",options:J,inclusive:!1,...O$(U)})}function Tn($,J,U,Q){return new $({type:"union",options:U,discriminator:J,...O$(Q)})}function vn($,J,U){return new $({type:"intersection",left:J,right:U})}function Cn($,J,U,Q){let _=U instanceof e$;return new $({type:"tuple",items:J,rest:_?U:null,...O$(_?Q:U)})}function bn($,J,U,Q){return new $({type:"record",keyType:J,valueType:U,...O$(Q)})}function yn($,J,U,Q){return new $({type:"map",keyType:J,valueType:U,...O$(Q)})}function gn($,J,U){return new $({type:"set",valueType:J,...O$(U)})}function xn($,J,U){let Q=Array.isArray(J)?Object.fromEntries(J.map((_)=>[_,_])):J;return new $({type:"enum",entries:Q,...O$(U)})}function hn($,J,U){return new $({type:"enum",entries:J,...O$(U)})}function un($,J,U){return new $({type:"literal",values:Array.isArray(J)?J:[J],...O$(U)})}function hW($,J){return new $({type:"file",...O$(J)})}function mn($,J){return new $({type:"transform",transform:J})}function cn($,J){return new $({type:"optional",innerType:J})}function dn($,J){return new $({type:"nullable",innerType:J})}function ln($,J,U){return new $({type:"default",innerType:J,get defaultValue(){return typeof U==="function"?U():$K(U)}})}function rn($,J,U){return new $({type:"nonoptional",innerType:J,...O$(U)})}function nn($,J){return new $({type:"success",innerType:J})}function pn($,J,U){return new $({type:"catch",innerType:J,catchValue:typeof U==="function"?U:()=>U})}function an($,J,U){return new $({type:"pipe",in:J,out:U})}function on($,J){return new $({type:"readonly",innerType:J})}function tn($,J,U){return new $({type:"template_literal",parts:J,...O$(U)})}function sn($,J){return new $({type:"lazy",getter:J})}function en($,J){return new $({type:"promise",innerType:J})}function uW($,J,U){let Q=O$(U);return Q.abort??(Q.abort=!0),new $({type:"custom",check:"custom",fn:J,...Q})}function mW($,J,U){return new $({type:"custom",check:"custom",fn:J,...O$(U)})}function cW($){let J=OA((U)=>{return U.addIssue=(Q)=>{if(typeof Q==="string")U.issues.push(M9(Q,U.value,J._zod.def));else{let _=Q;if(_.fatal)_.continue=!1;_.code??(_.code="custom"),_.input??(_.input=U.value),_.inst??(_.inst=J),_.continue??(_.continue=!J._zod.def.abort),U.issues.push(M9(_))}},$(U.value,U)});return J}function OA($,J){let U=new x4({check:"custom",...O$(J)});return U._zod.check=$,U}function dW($){let J=new x4({check:"describe"});return J._zod.onattach=[(U)=>{let Q=T6.get(U)??{};T6.add(U,{...Q,description:$})}],J._zod.check=()=>{},J}function lW($){let J=new x4({check:"meta"});return J._zod.onattach=[(U)=>{let Q=T6.get(U)??{};T6.add(U,{...Q,...$})}],J._zod.check=()=>{},J}function iW($,J){let U=O$(J),Q=U.truthy??["true","1","yes","on","y","enabled"],_=U.falsy??["false","0","no","off","n","disabled"];if(U.case!=="sensitive")Q=Q.map((q)=>typeof q==="string"?q.toLowerCase():q),_=_.map((q)=>typeof q==="string"?q.toLowerCase():q);let G=new Set(Q),V=new Set(_),X=$.Codec??D7,Z=$.Boolean??O7,K=new($.String??_8)({type:"string",error:U.error}),F=new Z({type:"boolean",error:U.error}),N=new X({type:"pipe",in:K,out:F,transform:(q,H)=>{let E=q;if(U.case!=="sensitive")E=E.toLowerCase();if(G.has(E))return!0;else if(V.has(E))return!1;else return H.issues.push({code:"invalid_value",expected:"stringbool",values:[...G,...V],input:H.value,inst:N,continue:!1}),{}},reverseTransform:(q,H)=>{if(q===!0)return Q[0]||"true";else return _[0]||"false"},error:U.error});return N}function m9($,J,U,Q={}){let _=O$(Q),G={...O$(Q),check:"string_format",type:"string",format:J,fn:typeof U==="function"?U:(X)=>U.test(X),..._};if(U instanceof RegExp)G.pattern=U;return new $(G)}function t2($){let J=$?.target??"draft-2020-12";if(J==="draft-4")J="draft-04";if(J==="draft-7")J="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??T6,target:J,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,cycles:$?.cycles??"ref",reused:$?.reused??"inline",external:$?.external??void 0}}function k4($,J,U={path:[],schemaPath:[]}){var Q;let _=$._zod.def,G=J.seen.get($);if(G){if(G.count++,U.schemaPath.includes($))G.cycle=U.path;return G.schema}let V={schema:{},count:1,cycle:void 0,path:U.path};J.seen.set($,V);let X=$._zod.toJSONSchema?.();if(X)V.schema=X;else{let K={...U,schemaPath:[...U.schemaPath,$],path:U.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(J,V.schema,K);else{let N=V.schema,q=J.processors[_.type];if(!q)throw Error(`[toJSONSchema]: Non-representable type encountered: ${_.type}`);q($,J,N,K)}let F=$._zod.parent;if(F){if(!V.ref)V.ref=F;k4(F,J,K),J.seen.get(F).isParent=!0}}let Z=J.metadataRegistry.get($);if(Z)Object.assign(V.schema,Z);if(J.io==="input"&&i6($))delete V.schema.examples,delete V.schema.default;if(J.io==="input"&&V.schema._prefault)(Q=V.schema).default??(Q.default=V.schema._prefault);return delete V.schema._prefault,J.seen.get($).schema}function s2($,J){let U=$.seen.get(J);if(!U)throw Error("Unprocessed schema. This is a bug in Zod.");let Q=new Map;for(let V of $.seen.entries()){let X=$.metadataRegistry.get(V[0])?.id;if(X){let Z=Q.get(X);if(Z&&Z!==V[0])throw Error(`Duplicate schema id "${X}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);Q.set(X,V[0])}}let _=(V)=>{let X=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let F=$.external.registry.get(V[0])?.id,N=$.external.uri??((H)=>H);if(F)return{ref:N(F)};let q=V[1].defId??V[1].schema.id??`schema${$.counter++}`;return V[1].defId=q,{defId:q,ref:`${N("__shared")}#/${X}/${q}`}}if(V[1]===U)return{ref:"#"};let Y=`${"#"}/${X}/`,K=V[1].schema.id??`__schema${$.counter++}`;return{defId:K,ref:Y+K}},G=(V)=>{if(V[1].schema.$ref)return;let X=V[1],{ref:Z,defId:Y}=_(V);if(X.def={...X.schema},Y)X.defId=Y;let K=X.schema;for(let F in K)delete K[F];K.$ref=Z};if($.cycles==="throw")for(let V of $.seen.entries()){let X=V[1];if(X.cycle)throw Error(`Cycle detected: #/${X.cycle?.join("/")}/<root>
|
|
568
|
-
|
|
569
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let V of $.seen.entries()){let X=V[1];if(J===V[0]){G(V);continue}if($.external){let Y=$.external.registry.get(V[0])?.id;if(J!==V[0]&&Y){G(V);continue}}if($.metadataRegistry.get(V[0])?.id){G(V);continue}if(X.cycle){G(V);continue}if(X.count>1){if($.reused==="ref"){G(V);continue}}}}function e2($,J){let U=$.seen.get(J);if(!U)throw Error("Unprocessed schema. This is a bug in Zod.");let Q=(V)=>{let X=$.seen.get(V);if(X.ref===null)return;let Z=X.def??X.schema,Y={...Z},K=X.ref;if(X.ref=null,K){Q(K);let N=$.seen.get(K),q=N.schema;if(q.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))Z.allOf=Z.allOf??[],Z.allOf.push(q);else Object.assign(Z,q);if(Object.assign(Z,Y),V._zod.parent===K)for(let E in Z){if(E==="$ref"||E==="allOf")continue;if(!(E in Y))delete Z[E]}if(q.$ref)for(let E in Z){if(E==="$ref"||E==="allOf")continue;if(E in N.def&&JSON.stringify(Z[E])===JSON.stringify(N.def[E]))delete Z[E]}}let F=V._zod.parent;if(F&&F!==K){Q(F);let N=$.seen.get(F);if(N?.schema.$ref){if(Z.$ref=N.schema.$ref,N.def)for(let q in Z){if(q==="$ref"||q==="allOf")continue;if(q in N.def&&JSON.stringify(Z[q])===JSON.stringify(N.def[q]))delete Z[q]}}}$.override({zodSchema:V,jsonSchema:Z,path:X.path??[]})};for(let V of[...$.seen.entries()].reverse())Q(V[0]);let _={};if($.target==="draft-2020-12")_.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")_.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")_.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let V=$.external.registry.get(J)?.id;if(!V)throw Error("Schema is missing an `id` property");_.$id=$.external.uri(V)}Object.assign(_,U.def??U.schema);let G=$.external?.defs??{};for(let V of $.seen.entries()){let X=V[1];if(X.def&&X.defId)G[X.defId]=X.def}if($.external);else if(Object.keys(G).length>0)if($.target==="draft-2020-12")_.$defs=G;else _.definitions=G;try{let V=JSON.parse(JSON.stringify(_));return Object.defineProperty(V,"~standard",{value:{...J["~standard"],jsonSchema:{input:c9(J,"input",$.processors),output:c9(J,"output",$.processors)}},enumerable:!1,writable:!1}),V}catch(V){throw Error("Error converting schema to JSON.")}}function i6($,J){let U=J??{seen:new Set};if(U.seen.has($))return!1;U.seen.add($);let Q=$._zod.def;if(Q.type==="transform")return!0;if(Q.type==="array")return i6(Q.element,U);if(Q.type==="set")return i6(Q.valueType,U);if(Q.type==="lazy")return i6(Q.getter(),U);if(Q.type==="promise"||Q.type==="optional"||Q.type==="nonoptional"||Q.type==="nullable"||Q.type==="readonly"||Q.type==="default"||Q.type==="prefault")return i6(Q.innerType,U);if(Q.type==="intersection")return i6(Q.left,U)||i6(Q.right,U);if(Q.type==="record"||Q.type==="map")return i6(Q.keyType,U)||i6(Q.valueType,U);if(Q.type==="pipe")return i6(Q.in,U)||i6(Q.out,U);if(Q.type==="object"){for(let _ in Q.shape)if(i6(Q.shape[_],U))return!0;return!1}if(Q.type==="union"){for(let _ of Q.options)if(i6(_,U))return!0;return!1}if(Q.type==="tuple"){for(let _ of Q.items)if(i6(_,U))return!0;if(Q.rest&&i6(Q.rest,U))return!0;return!1}return!1}var rW=($,J={})=>(U)=>{let Q=t2({...U,processors:J});return k4($,Q),s2(Q,$),e2(Q,$)},c9=($,J,U={})=>(Q)=>{let{libraryOptions:_,target:G}=Q??{},V=t2({..._??{},target:G,io:J,processors:U});return k4($,V),s2(V,$),e2(V,$)};var $p={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},nW=($,J,U,Q)=>{let _=U;_.type="string";let{minimum:G,maximum:V,format:X,patterns:Z,contentEncoding:Y}=$._zod.bag;if(typeof G==="number")_.minLength=G;if(typeof V==="number")_.maxLength=V;if(X){if(_.format=$p[X]??X,_.format==="")delete _.format;if(X==="time")delete _.format}if(Y)_.contentEncoding=Y;if(Z&&Z.size>0){let K=[...Z];if(K.length===1)_.pattern=K[0].source;else if(K.length>1)_.allOf=[...K.map((F)=>({...J.target==="draft-07"||J.target==="draft-04"||J.target==="openapi-3.0"?{type:"string"}:{},pattern:F.source}))]}},pW=($,J,U,Q)=>{let _=U,{minimum:G,maximum:V,format:X,multipleOf:Z,exclusiveMaximum:Y,exclusiveMinimum:K}=$._zod.bag;if(typeof X==="string"&&X.includes("int"))_.type="integer";else _.type="number";if(typeof K==="number")if(J.target==="draft-04"||J.target==="openapi-3.0")_.minimum=K,_.exclusiveMinimum=!0;else _.exclusiveMinimum=K;if(typeof G==="number"){if(_.minimum=G,typeof K==="number"&&J.target!=="draft-04")if(K>=G)delete _.minimum;else delete _.exclusiveMinimum}if(typeof Y==="number")if(J.target==="draft-04"||J.target==="openapi-3.0")_.maximum=Y,_.exclusiveMaximum=!0;else _.exclusiveMaximum=Y;if(typeof V==="number"){if(_.maximum=V,typeof Y==="number"&&J.target!=="draft-04")if(Y<=V)delete _.maximum;else delete _.exclusiveMaximum}if(typeof Z==="number")_.multipleOf=Z},aW=($,J,U,Q)=>{U.type="boolean"},oW=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},tW=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},sW=($,J,U,Q)=>{if(J.target==="openapi-3.0")U.type="string",U.nullable=!0,U.enum=[null];else U.type="null"},eW=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},$q=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Jq=($,J,U,Q)=>{U.not={}},Uq=($,J,U,Q)=>{},_q=($,J,U,Q)=>{},Qq=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Gq=($,J,U,Q)=>{let _=$._zod.def,G=V7(_.entries);if(G.every((V)=>typeof V==="number"))U.type="number";if(G.every((V)=>typeof V==="string"))U.type="string";U.enum=G},Vq=($,J,U,Q)=>{let _=$._zod.def,G=[];for(let V of _.values)if(V===void 0){if(J.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof V==="bigint")if(J.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else G.push(Number(V));else G.push(V);if(G.length===0);else if(G.length===1){let V=G[0];if(U.type=V===null?"null":typeof V,J.target==="draft-04"||J.target==="openapi-3.0")U.enum=[V];else U.const=V}else{if(G.every((V)=>typeof V==="number"))U.type="number";if(G.every((V)=>typeof V==="string"))U.type="string";if(G.every((V)=>typeof V==="boolean"))U.type="boolean";if(G.every((V)=>V===null))U.type="null";U.enum=G}},Xq=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},Yq=($,J,U,Q)=>{let _=U,G=$._zod.pattern;if(!G)throw Error("Pattern not found in template literal");_.type="string",_.pattern=G.source},Zq=($,J,U,Q)=>{let _=U,G={type:"string",format:"binary",contentEncoding:"binary"},{minimum:V,maximum:X,mime:Z}=$._zod.bag;if(V!==void 0)G.minLength=V;if(X!==void 0)G.maxLength=X;if(Z)if(Z.length===1)G.contentMediaType=Z[0],Object.assign(_,G);else Object.assign(_,G),_.anyOf=Z.map((Y)=>({contentMediaType:Y}));else Object.assign(_,G)},Kq=($,J,U,Q)=>{U.type="boolean"},Nq=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Fq=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Wq=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},qq=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},Hq=($,J,U,Q)=>{if(J.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Bq=($,J,U,Q)=>{let _=U,G=$._zod.def,{minimum:V,maximum:X}=$._zod.bag;if(typeof V==="number")_.minItems=V;if(typeof X==="number")_.maxItems=X;_.type="array",_.items=k4(G.element,J,{...Q,path:[...Q.path,"items"]})},Oq=($,J,U,Q)=>{let _=U,G=$._zod.def;_.type="object",_.properties={};let V=G.shape;for(let Y in V)_.properties[Y]=k4(V[Y],J,{...Q,path:[...Q.path,"properties",Y]});let X=new Set(Object.keys(V)),Z=new Set([...X].filter((Y)=>{let K=G.shape[Y]._zod;if(J.io==="input")return K.optin===void 0;else return K.optout===void 0}));if(Z.size>0)_.required=Array.from(Z);if(G.catchall?._zod.def.type==="never")_.additionalProperties=!1;else if(!G.catchall){if(J.io==="output")_.additionalProperties=!1}else if(G.catchall)_.additionalProperties=k4(G.catchall,J,{...Q,path:[...Q.path,"additionalProperties"]})},p3=($,J,U,Q)=>{let _=$._zod.def,G=_.inclusive===!1,V=_.options.map((X,Z)=>k4(X,J,{...Q,path:[...Q.path,G?"oneOf":"anyOf",Z]}));if(G)U.oneOf=V;else U.anyOf=V},jq=($,J,U,Q)=>{let _=$._zod.def,G=k4(_.left,J,{...Q,path:[...Q.path,"allOf",0]}),V=k4(_.right,J,{...Q,path:[...Q.path,"allOf",1]}),X=(Y)=>("allOf"in Y)&&Object.keys(Y).length===1,Z=[...X(G)?G.allOf:[G],...X(V)?V.allOf:[V]];U.allOf=Z},Dq=($,J,U,Q)=>{let _=U,G=$._zod.def;_.type="array";let V=J.target==="draft-2020-12"?"prefixItems":"items",X=J.target==="draft-2020-12"?"items":J.target==="openapi-3.0"?"items":"additionalItems",Z=G.items.map((N,q)=>k4(N,J,{...Q,path:[...Q.path,V,q]})),Y=G.rest?k4(G.rest,J,{...Q,path:[...Q.path,X,...J.target==="openapi-3.0"?[G.items.length]:[]]}):null;if(J.target==="draft-2020-12"){if(_.prefixItems=Z,Y)_.items=Y}else if(J.target==="openapi-3.0"){if(_.items={anyOf:Z},Y)_.items.anyOf.push(Y);if(_.minItems=Z.length,!Y)_.maxItems=Z.length}else if(_.items=Z,Y)_.additionalItems=Y;let{minimum:K,maximum:F}=$._zod.bag;if(typeof K==="number")_.minItems=K;if(typeof F==="number")_.maxItems=F},Eq=($,J,U,Q)=>{let _=U,G=$._zod.def;_.type="object";let V=G.keyType,Z=V._zod.bag?.patterns;if(G.mode==="loose"&&Z&&Z.size>0){let K=k4(G.valueType,J,{...Q,path:[...Q.path,"patternProperties","*"]});_.patternProperties={};for(let F of Z)_.patternProperties[F.source]=K}else{if(J.target==="draft-07"||J.target==="draft-2020-12")_.propertyNames=k4(G.keyType,J,{...Q,path:[...Q.path,"propertyNames"]});_.additionalProperties=k4(G.valueType,J,{...Q,path:[...Q.path,"additionalProperties"]})}let Y=V._zod.values;if(Y){let K=[...Y].filter((F)=>typeof F==="string"||typeof F==="number");if(K.length>0)_.required=K}},Pq=($,J,U,Q)=>{let _=$._zod.def,G=k4(_.innerType,J,Q),V=J.seen.get($);if(J.target==="openapi-3.0")V.ref=_.innerType,U.nullable=!0;else U.anyOf=[G,{type:"null"}]},Mq=($,J,U,Q)=>{let _=$._zod.def;k4(_.innerType,J,Q);let G=J.seen.get($);G.ref=_.innerType},Lq=($,J,U,Q)=>{let _=$._zod.def;k4(_.innerType,J,Q);let G=J.seen.get($);G.ref=_.innerType,U.default=JSON.parse(JSON.stringify(_.defaultValue))},zq=($,J,U,Q)=>{let _=$._zod.def;k4(_.innerType,J,Q);let G=J.seen.get($);if(G.ref=_.innerType,J.io==="input")U._prefault=JSON.parse(JSON.stringify(_.defaultValue))},Rq=($,J,U,Q)=>{let _=$._zod.def;k4(_.innerType,J,Q);let G=J.seen.get($);G.ref=_.innerType;let V;try{V=_.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}U.default=V},Aq=($,J,U,Q)=>{let _=$._zod.def,G=J.io==="input"?_.in._zod.def.type==="transform"?_.out:_.in:_.out;k4(G,J,Q);let V=J.seen.get($);V.ref=G},wq=($,J,U,Q)=>{let _=$._zod.def;k4(_.innerType,J,Q);let G=J.seen.get($);G.ref=_.innerType,U.readOnly=!0},fq=($,J,U,Q)=>{let _=$._zod.def;k4(_.innerType,J,Q);let G=J.seen.get($);G.ref=_.innerType},a3=($,J,U,Q)=>{let _=$._zod.def;k4(_.innerType,J,Q);let G=J.seen.get($);G.ref=_.innerType},kq=($,J,U,Q)=>{let _=$._zod.innerType;k4(_,J,Q);let G=J.seen.get($);G.ref=_},n3={string:nW,number:pW,boolean:aW,bigint:oW,symbol:tW,null:sW,undefined:eW,void:$q,never:Jq,any:Uq,unknown:_q,date:Qq,enum:Gq,literal:Vq,nan:Xq,template_literal:Yq,file:Zq,success:Kq,custom:Nq,function:Fq,transform:Wq,map:qq,set:Hq,array:Bq,object:Oq,union:p3,intersection:jq,tuple:Dq,record:Eq,nullable:Pq,nonoptional:Mq,default:Lq,prefault:zq,catch:Rq,pipe:Aq,readonly:wq,promise:fq,optional:a3,lazy:kq};function o3($,J){if("_idmap"in $){let Q=$,_=t2({...J,processors:n3}),G={};for(let Z of Q._idmap.entries()){let[Y,K]=Z;k4(K,_)}let V={},X={registry:Q,uri:J?.uri,defs:G};_.external=X;for(let Z of Q._idmap.entries()){let[Y,K]=Z;s2(_,K),V[Y]=e2(_,K)}if(Object.keys(G).length>0){let Z=_.target==="draft-2020-12"?"$defs":"definitions";V.__shared={[Z]:G}}return{schemas:V}}let U=t2({...J,processors:n3});return k4($,U),s2(U,$),e2(U,$)}class Iq{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter($){this.ctx.counter=$}get seen(){return this.ctx.seen}constructor($){let J=$?.target??"draft-2020-12";if(J==="draft-4")J="draft-04";if(J==="draft-7")J="draft-07";this.ctx=t2({processors:n3,target:J,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,J={path:[],schemaPath:[]}){return k4($,this.ctx,J)}emit($,J){if(J){if(J.cycles)this.ctx.cycles=J.cycles;if(J.reused)this.ctx.reused=J.reused;if(J.external)this.ctx.external=J.external}s2(this.ctx,$);let U=e2(this.ctx,$),{"~standard":Q,..._}=U;return _}}var jA={};var w7={};F1(w7,{xor:()=>Kw,xid:()=>vA,void:()=>Qw,uuidv7:()=>RA,uuidv6:()=>zA,uuidv4:()=>LA,uuid:()=>MA,url:()=>AA,unknown:()=>X8,union:()=>LG,undefined:()=>Uw,ulid:()=>TA,uint64:()=>$w,uint32:()=>tA,tuple:()=>KH,transform:()=>RG,templateLiteral:()=>Lw,symbol:()=>Jw,superRefine:()=>gH,success:()=>Ew,stringbool:()=>Sw,stringFormat:()=>lA,string:()=>UG,strictObject:()=>Yw,set:()=>Hw,refine:()=>yH,record:()=>NH,readonly:()=>IH,promise:()=>zw,preprocess:()=>vw,prefault:()=>LH,pipe:()=>S7,partialRecord:()=>Fw,optional:()=>k7,object:()=>Xw,number:()=>pq,nullish:()=>Dw,nullable:()=>I7,null:()=>eq,nonoptional:()=>zH,never:()=>MG,nativeEnum:()=>Bw,nanoid:()=>kA,nan:()=>Pw,meta:()=>kw,map:()=>qw,mac:()=>yA,looseRecord:()=>Ww,looseObject:()=>Zw,literal:()=>Ow,lazy:()=>vH,ksuid:()=>CA,keyof:()=>Vw,jwt:()=>dA,json:()=>Tw,ipv6:()=>gA,ipv4:()=>bA,intersection:()=>YH,int64:()=>eA,int32:()=>oA,int:()=>_G,instanceof:()=>Iw,httpUrl:()=>wA,hostname:()=>iA,hex:()=>rA,hash:()=>nA,guid:()=>PA,function:()=>Rw,float64:()=>aA,float32:()=>pA,file:()=>jw,exactOptional:()=>jH,enum:()=>zG,emoji:()=>fA,email:()=>EA,e164:()=>cA,discriminatedUnion:()=>Nw,describe:()=>fw,date:()=>Gw,custom:()=>ww,cuid2:()=>SA,cuid:()=>IA,codec:()=>Mw,cidrv6:()=>hA,cidrv4:()=>xA,check:()=>Aw,catch:()=>wH,boolean:()=>aq,bigint:()=>sA,base64url:()=>mA,base64:()=>uA,array:()=>C7,any:()=>_w,_function:()=>Rw,_default:()=>PH,_ZodString:()=>QG,ZodXor:()=>GH,ZodXID:()=>NG,ZodVoid:()=>_H,ZodUnknown:()=>JH,ZodUnion:()=>y7,ZodUndefined:()=>tq,ZodUUID:()=>w1,ZodURL:()=>T7,ZodULID:()=>KG,ZodType:()=>N4,ZodTuple:()=>ZH,ZodTransform:()=>BH,ZodTemplateLiteral:()=>SH,ZodSymbol:()=>oq,ZodSuccess:()=>RH,ZodStringFormat:()=>v4,ZodString:()=>i9,ZodSet:()=>WH,ZodRecord:()=>g7,ZodReadonly:()=>kH,ZodPromise:()=>CH,ZodPrefault:()=>MH,ZodPipe:()=>fG,ZodOptional:()=>AG,ZodObject:()=>b7,ZodNumberFormat:()=>Y8,ZodNumber:()=>n9,ZodNullable:()=>DH,ZodNull:()=>sq,ZodNonOptional:()=>wG,ZodNever:()=>UH,ZodNanoID:()=>XG,ZodNaN:()=>fH,ZodMap:()=>FH,ZodMAC:()=>nq,ZodLiteral:()=>qH,ZodLazy:()=>TH,ZodKSUID:()=>FG,ZodJWT:()=>EG,ZodIntersection:()=>XH,ZodIPv6:()=>qG,ZodIPv4:()=>WG,ZodGUID:()=>f7,ZodFunction:()=>bH,ZodFile:()=>HH,ZodExactOptional:()=>OH,ZodEnum:()=>l9,ZodEmoji:()=>VG,ZodEmail:()=>GG,ZodE164:()=>DG,ZodDiscriminatedUnion:()=>VH,ZodDefault:()=>EH,ZodDate:()=>v7,ZodCustomStringFormat:()=>r9,ZodCustom:()=>x7,ZodCodec:()=>kG,ZodCatch:()=>AH,ZodCUID2:()=>ZG,ZodCUID:()=>YG,ZodCIDRv6:()=>BG,ZodCIDRv4:()=>HG,ZodBoolean:()=>p9,ZodBigIntFormat:()=>PG,ZodBigInt:()=>a9,ZodBase64URL:()=>jG,ZodBase64:()=>OG,ZodArray:()=>QH,ZodAny:()=>$H});var t3={};F1(t3,{uppercase:()=>S9,trim:()=>g9,toUpperCase:()=>h9,toLowerCase:()=>x9,startsWith:()=>v9,slugify:()=>u9,size:()=>Q8,regex:()=>k9,property:()=>r3,positive:()=>c3,overwrite:()=>s0,normalize:()=>y9,nonpositive:()=>l3,nonnegative:()=>i3,negative:()=>d3,multipleOf:()=>a2,minSize:()=>A1,minLength:()=>t1,mime:()=>b9,maxSize:()=>o2,maxLength:()=>G8,lte:()=>w0,lt:()=>z1,lowercase:()=>I9,length:()=>V8,includes:()=>T9,gte:()=>l6,gt:()=>R1,endsWith:()=>C9});var d9={};F1(d9,{time:()=>vq,duration:()=>Cq,datetime:()=>Sq,date:()=>Tq,ZodISOTime:()=>$G,ZodISODuration:()=>JG,ZodISODateTime:()=>s3,ZodISODate:()=>e3});var s3=u("ZodISODateTime",($,J)=>{qN.init($,J),v4.init($,J)});function Sq($){return NW(s3,$)}var e3=u("ZodISODate",($,J)=>{HN.init($,J),v4.init($,J)});function Tq($){return FW(e3,$)}var $G=u("ZodISOTime",($,J)=>{BN.init($,J),v4.init($,J)});function vq($){return WW($G,$)}var JG=u("ZodISODuration",($,J)=>{ON.init($,J),v4.init($,J)});function Cq($){return qW(JG,$)}var DA=($,J)=>{N7.init($,J),$.name="ZodError",Object.defineProperties($,{format:{value:(U)=>W7($,U)},flatten:{value:(U)=>F7($,U)},addIssue:{value:(U)=>{$.issues.push(U),$.message=JSON.stringify($.issues,E9,2)}},addIssues:{value:(U)=>{$.issues.push(...U),$.message=JSON.stringify($.issues,E9,2)}},isEmpty:{get(){return $.issues.length===0}}})},Up=u("ZodError",DA),Z0=u("ZodError",DA,{Parent:Error});var bq=L9(Z0),yq=z9(Z0),gq=R9(Z0),xq=A9(Z0),hq=$3(Z0),uq=J3(Z0),mq=U3(Z0),cq=_3(Z0),dq=Q3(Z0),lq=G3(Z0),iq=V3(Z0),rq=X3(Z0);var N4=u("ZodType",($,J)=>{return e$.init($,J),Object.assign($["~standard"],{jsonSchema:{input:c9($,"input"),output:c9($,"output")}}),$.toJSONSchema=rW($,{}),$.def=J,$.type=J.type,Object.defineProperty($,"_def",{value:J}),$.check=(...U)=>{return $.clone(B$.mergeDefs(J,{checks:[...J.checks??[],...U.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]}),{parent:!0})},$.with=$.check,$.clone=(U,Q)=>d6($,U,Q),$.brand=()=>$,$.register=(U,Q)=>{return U.add($,Q),$},$.parse=(U,Q)=>bq($,U,Q,{callee:$.parse}),$.safeParse=(U,Q)=>gq($,U,Q),$.parseAsync=async(U,Q)=>yq($,U,Q,{callee:$.parseAsync}),$.safeParseAsync=async(U,Q)=>xq($,U,Q),$.spa=$.safeParseAsync,$.encode=(U,Q)=>hq($,U,Q),$.decode=(U,Q)=>uq($,U,Q),$.encodeAsync=async(U,Q)=>mq($,U,Q),$.decodeAsync=async(U,Q)=>cq($,U,Q),$.safeEncode=(U,Q)=>dq($,U,Q),$.safeDecode=(U,Q)=>lq($,U,Q),$.safeEncodeAsync=async(U,Q)=>iq($,U,Q),$.safeDecodeAsync=async(U,Q)=>rq($,U,Q),$.refine=(U,Q)=>$.check(yH(U,Q)),$.superRefine=(U)=>$.check(gH(U)),$.overwrite=(U)=>$.check(s0(U)),$.optional=()=>k7($),$.exactOptional=()=>jH($),$.nullable=()=>I7($),$.nullish=()=>k7(I7($)),$.nonoptional=(U)=>zH($,U),$.array=()=>C7($),$.or=(U)=>LG([$,U]),$.and=(U)=>YH($,U),$.transform=(U)=>S7($,RG(U)),$.default=(U)=>PH($,U),$.prefault=(U)=>LH($,U),$.catch=(U)=>wH($,U),$.pipe=(U)=>S7($,U),$.readonly=()=>IH($),$.describe=(U)=>{let Q=$.clone();return T6.add(Q,{description:U}),Q},Object.defineProperty($,"description",{get(){return T6.get($)?.description},configurable:!0}),$.meta=(...U)=>{if(U.length===0)return T6.get($);let Q=$.clone();return T6.add(Q,U[0]),Q},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$.apply=(U)=>U($),$}),QG=u("_ZodString",($,J)=>{_8.init($,J),N4.init($,J),$._zod.processJSONSchema=(Q,_,G)=>nW($,Q,_,G);let U=$._zod.bag;$.format=U.format??null,$.minLength=U.minimum??null,$.maxLength=U.maximum??null,$.regex=(...Q)=>$.check(k9(...Q)),$.includes=(...Q)=>$.check(T9(...Q)),$.startsWith=(...Q)=>$.check(v9(...Q)),$.endsWith=(...Q)=>$.check(C9(...Q)),$.min=(...Q)=>$.check(t1(...Q)),$.max=(...Q)=>$.check(G8(...Q)),$.length=(...Q)=>$.check(V8(...Q)),$.nonempty=(...Q)=>$.check(t1(1,...Q)),$.lowercase=(Q)=>$.check(I9(Q)),$.uppercase=(Q)=>$.check(S9(Q)),$.trim=()=>$.check(g9()),$.normalize=(...Q)=>$.check(y9(...Q)),$.toLowerCase=()=>$.check(x9()),$.toUpperCase=()=>$.check(h9()),$.slugify=()=>$.check(u9())}),i9=u("ZodString",($,J)=>{_8.init($,J),QG.init($,J),$.email=(U)=>$.check(M3(GG,U)),$.url=(U)=>$.check(A7(T7,U)),$.jwt=(U)=>$.check(m3(EG,U)),$.emoji=(U)=>$.check(w3(VG,U)),$.guid=(U)=>$.check(R7(f7,U)),$.uuid=(U)=>$.check(L3(w1,U)),$.uuidv4=(U)=>$.check(z3(w1,U)),$.uuidv6=(U)=>$.check(R3(w1,U)),$.uuidv7=(U)=>$.check(A3(w1,U)),$.nanoid=(U)=>$.check(f3(XG,U)),$.guid=(U)=>$.check(R7(f7,U)),$.cuid=(U)=>$.check(k3(YG,U)),$.cuid2=(U)=>$.check(I3(ZG,U)),$.ulid=(U)=>$.check(S3(KG,U)),$.base64=(U)=>$.check(x3(OG,U)),$.base64url=(U)=>$.check(h3(jG,U)),$.xid=(U)=>$.check(T3(NG,U)),$.ksuid=(U)=>$.check(v3(FG,U)),$.ipv4=(U)=>$.check(C3(WG,U)),$.ipv6=(U)=>$.check(b3(qG,U)),$.cidrv4=(U)=>$.check(y3(HG,U)),$.cidrv6=(U)=>$.check(g3(BG,U)),$.e164=(U)=>$.check(u3(DG,U)),$.datetime=(U)=>$.check(Sq(U)),$.date=(U)=>$.check(Tq(U)),$.time=(U)=>$.check(vq(U)),$.duration=(U)=>$.check(Cq(U))});function UG($){return XW(i9,$)}var v4=u("ZodStringFormat",($,J)=>{T4.init($,J),QG.init($,J)}),GG=u("ZodEmail",($,J)=>{GN.init($,J),v4.init($,J)});function EA($){return M3(GG,$)}var f7=u("ZodGUID",($,J)=>{_N.init($,J),v4.init($,J)});function PA($){return R7(f7,$)}var w1=u("ZodUUID",($,J)=>{QN.init($,J),v4.init($,J)});function MA($){return L3(w1,$)}function LA($){return z3(w1,$)}function zA($){return R3(w1,$)}function RA($){return A3(w1,$)}var T7=u("ZodURL",($,J)=>{VN.init($,J),v4.init($,J)});function AA($){return A7(T7,$)}function wA($){return A7(T7,{protocol:/^https?$/,hostname:x0.domain,...B$.normalizeParams($)})}var VG=u("ZodEmoji",($,J)=>{XN.init($,J),v4.init($,J)});function fA($){return w3(VG,$)}var XG=u("ZodNanoID",($,J)=>{YN.init($,J),v4.init($,J)});function kA($){return f3(XG,$)}var YG=u("ZodCUID",($,J)=>{ZN.init($,J),v4.init($,J)});function IA($){return k3(YG,$)}var ZG=u("ZodCUID2",($,J)=>{KN.init($,J),v4.init($,J)});function SA($){return I3(ZG,$)}var KG=u("ZodULID",($,J)=>{NN.init($,J),v4.init($,J)});function TA($){return S3(KG,$)}var NG=u("ZodXID",($,J)=>{FN.init($,J),v4.init($,J)});function vA($){return T3(NG,$)}var FG=u("ZodKSUID",($,J)=>{WN.init($,J),v4.init($,J)});function CA($){return v3(FG,$)}var WG=u("ZodIPv4",($,J)=>{jN.init($,J),v4.init($,J)});function bA($){return C3(WG,$)}var nq=u("ZodMAC",($,J)=>{EN.init($,J),v4.init($,J)});function yA($){return ZW(nq,$)}var qG=u("ZodIPv6",($,J)=>{DN.init($,J),v4.init($,J)});function gA($){return b3(qG,$)}var HG=u("ZodCIDRv4",($,J)=>{PN.init($,J),v4.init($,J)});function xA($){return y3(HG,$)}var BG=u("ZodCIDRv6",($,J)=>{MN.init($,J),v4.init($,J)});function hA($){return g3(BG,$)}var OG=u("ZodBase64",($,J)=>{zN.init($,J),v4.init($,J)});function uA($){return x3(OG,$)}var jG=u("ZodBase64URL",($,J)=>{RN.init($,J),v4.init($,J)});function mA($){return h3(jG,$)}var DG=u("ZodE164",($,J)=>{AN.init($,J),v4.init($,J)});function cA($){return u3(DG,$)}var EG=u("ZodJWT",($,J)=>{wN.init($,J),v4.init($,J)});function dA($){return m3(EG,$)}var r9=u("ZodCustomStringFormat",($,J)=>{fN.init($,J),v4.init($,J)});function lA($,J,U={}){return m9(r9,$,J,U)}function iA($){return m9(r9,"hostname",x0.hostname,$)}function rA($){return m9(r9,"hex",x0.hex,$)}function nA($,J){let U=J?.enc??"hex",Q=`${$}_${U}`,_=x0[Q];if(!_)throw Error(`Unrecognized hash format: ${Q}`);return m9(r9,Q,_,J)}var n9=u("ZodNumber",($,J)=>{O3.init($,J),N4.init($,J),$._zod.processJSONSchema=(Q,_,G)=>pW($,Q,_,G),$.gt=(Q,_)=>$.check(R1(Q,_)),$.gte=(Q,_)=>$.check(l6(Q,_)),$.min=(Q,_)=>$.check(l6(Q,_)),$.lt=(Q,_)=>$.check(z1(Q,_)),$.lte=(Q,_)=>$.check(w0(Q,_)),$.max=(Q,_)=>$.check(w0(Q,_)),$.int=(Q)=>$.check(_G(Q)),$.safe=(Q)=>$.check(_G(Q)),$.positive=(Q)=>$.check(R1(0,Q)),$.nonnegative=(Q)=>$.check(l6(0,Q)),$.negative=(Q)=>$.check(z1(0,Q)),$.nonpositive=(Q)=>$.check(w0(0,Q)),$.multipleOf=(Q,_)=>$.check(a2(Q,_)),$.step=(Q,_)=>$.check(a2(Q,_)),$.finite=()=>$;let U=$._zod.bag;$.minValue=Math.max(U.minimum??Number.NEGATIVE_INFINITY,U.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(U.maximum??Number.POSITIVE_INFINITY,U.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(U.format??"").includes("int")||Number.isSafeInteger(U.multipleOf??0.5),$.isFinite=!0,$.format=U.format??null});function pq($){return HW(n9,$)}var Y8=u("ZodNumberFormat",($,J)=>{kN.init($,J),n9.init($,J)});function _G($){return OW(Y8,$)}function pA($){return jW(Y8,$)}function aA($){return DW(Y8,$)}function oA($){return EW(Y8,$)}function tA($){return PW(Y8,$)}var p9=u("ZodBoolean",($,J)=>{O7.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>aW($,U,Q,_)});function aq($){return MW(p9,$)}var a9=u("ZodBigInt",($,J)=>{j3.init($,J),N4.init($,J),$._zod.processJSONSchema=(Q,_,G)=>oW($,Q,_,G),$.gte=(Q,_)=>$.check(l6(Q,_)),$.min=(Q,_)=>$.check(l6(Q,_)),$.gt=(Q,_)=>$.check(R1(Q,_)),$.gte=(Q,_)=>$.check(l6(Q,_)),$.min=(Q,_)=>$.check(l6(Q,_)),$.lt=(Q,_)=>$.check(z1(Q,_)),$.lte=(Q,_)=>$.check(w0(Q,_)),$.max=(Q,_)=>$.check(w0(Q,_)),$.positive=(Q)=>$.check(R1(BigInt(0),Q)),$.negative=(Q)=>$.check(z1(BigInt(0),Q)),$.nonpositive=(Q)=>$.check(w0(BigInt(0),Q)),$.nonnegative=(Q)=>$.check(l6(BigInt(0),Q)),$.multipleOf=(Q,_)=>$.check(a2(Q,_));let U=$._zod.bag;$.minValue=U.minimum??null,$.maxValue=U.maximum??null,$.format=U.format??null});function sA($){return zW(a9,$)}var PG=u("ZodBigIntFormat",($,J)=>{IN.init($,J),a9.init($,J)});function eA($){return AW(PG,$)}function $w($){return wW(PG,$)}var oq=u("ZodSymbol",($,J)=>{SN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>tW($,U,Q,_)});function Jw($){return fW(oq,$)}var tq=u("ZodUndefined",($,J)=>{TN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>eW($,U,Q,_)});function Uw($){return kW(tq,$)}var sq=u("ZodNull",($,J)=>{vN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>sW($,U,Q,_)});function eq($){return IW(sq,$)}var $H=u("ZodAny",($,J)=>{CN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Uq($,U,Q,_)});function _w(){return SW($H)}var JH=u("ZodUnknown",($,J)=>{bN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>_q($,U,Q,_)});function X8(){return TW(JH)}var UH=u("ZodNever",($,J)=>{yN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Jq($,U,Q,_)});function MG($){return vW(UH,$)}var _H=u("ZodVoid",($,J)=>{gN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>$q($,U,Q,_)});function Qw($){return CW(_H,$)}var v7=u("ZodDate",($,J)=>{xN.init($,J),N4.init($,J),$._zod.processJSONSchema=(Q,_,G)=>Qq($,Q,_,G),$.min=(Q,_)=>$.check(l6(Q,_)),$.max=(Q,_)=>$.check(w0(Q,_));let U=$._zod.bag;$.minDate=U.minimum?new Date(U.minimum):null,$.maxDate=U.maximum?new Date(U.maximum):null});function Gw($){return bW(v7,$)}var QH=u("ZodArray",($,J)=>{hN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Bq($,U,Q,_),$.element=J.element,$.min=(U,Q)=>$.check(t1(U,Q)),$.nonempty=(U)=>$.check(t1(1,U)),$.max=(U,Q)=>$.check(G8(U,Q)),$.length=(U,Q)=>$.check(V8(U,Q)),$.unwrap=()=>$.element});function C7($,J){return xW(QH,$,J)}function Vw($){let J=$._zod.def.shape;return zG(Object.keys(J))}var b7=u("ZodObject",($,J)=>{uN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Oq($,U,Q,_),B$.defineLazy($,"shape",()=>{return J.shape}),$.keyof=()=>zG(Object.keys($._zod.def.shape)),$.catchall=(U)=>$.clone({...$._zod.def,catchall:U}),$.passthrough=()=>$.clone({...$._zod.def,catchall:X8()}),$.loose=()=>$.clone({...$._zod.def,catchall:X8()}),$.strict=()=>$.clone({...$._zod.def,catchall:MG()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(U)=>{return B$.extend($,U)},$.safeExtend=(U)=>{return B$.safeExtend($,U)},$.merge=(U)=>B$.merge($,U),$.pick=(U)=>B$.pick($,U),$.omit=(U)=>B$.omit($,U),$.partial=(...U)=>B$.partial(AG,$,U[0]),$.required=(...U)=>B$.required(wG,$,U[0])});function Xw($,J){let U={type:"object",shape:$??{},...B$.normalizeParams(J)};return new b7(U)}function Yw($,J){return new b7({type:"object",shape:$,catchall:MG(),...B$.normalizeParams(J)})}function Zw($,J){return new b7({type:"object",shape:$,catchall:X8(),...B$.normalizeParams(J)})}var y7=u("ZodUnion",($,J)=>{j7.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>p3($,U,Q,_),$.options=J.options});function LG($,J){return new y7({type:"union",options:$,...B$.normalizeParams(J)})}var GH=u("ZodXor",($,J)=>{y7.init($,J),mN.init($,J),$._zod.processJSONSchema=(U,Q,_)=>p3($,U,Q,_),$.options=J.options});function Kw($,J){return new GH({type:"union",options:$,inclusive:!1,...B$.normalizeParams(J)})}var VH=u("ZodDiscriminatedUnion",($,J)=>{y7.init($,J),cN.init($,J)});function Nw($,J,U){return new VH({type:"union",options:J,discriminator:$,...B$.normalizeParams(U)})}var XH=u("ZodIntersection",($,J)=>{dN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>jq($,U,Q,_)});function YH($,J){return new XH({type:"intersection",left:$,right:J})}var ZH=u("ZodTuple",($,J)=>{D3.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Dq($,U,Q,_),$.rest=(U)=>$.clone({...$._zod.def,rest:U})});function KH($,J,U){let Q=J instanceof e$,_=Q?U:J;return new ZH({type:"tuple",items:$,rest:Q?J:null,...B$.normalizeParams(_)})}var g7=u("ZodRecord",($,J)=>{lN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Eq($,U,Q,_),$.keyType=J.keyType,$.valueType=J.valueType});function NH($,J,U){return new g7({type:"record",keyType:$,valueType:J,...B$.normalizeParams(U)})}function Fw($,J,U){let Q=d6($);return Q._zod.values=void 0,new g7({type:"record",keyType:Q,valueType:J,...B$.normalizeParams(U)})}function Ww($,J,U){return new g7({type:"record",keyType:$,valueType:J,mode:"loose",...B$.normalizeParams(U)})}var FH=u("ZodMap",($,J)=>{iN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>qq($,U,Q,_),$.keyType=J.keyType,$.valueType=J.valueType,$.min=(...U)=>$.check(A1(...U)),$.nonempty=(U)=>$.check(A1(1,U)),$.max=(...U)=>$.check(o2(...U)),$.size=(...U)=>$.check(Q8(...U))});function qw($,J,U){return new FH({type:"map",keyType:$,valueType:J,...B$.normalizeParams(U)})}var WH=u("ZodSet",($,J)=>{rN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Hq($,U,Q,_),$.min=(...U)=>$.check(A1(...U)),$.nonempty=(U)=>$.check(A1(1,U)),$.max=(...U)=>$.check(o2(...U)),$.size=(...U)=>$.check(Q8(...U))});function Hw($,J){return new WH({type:"set",valueType:$,...B$.normalizeParams(J)})}var l9=u("ZodEnum",($,J)=>{nN.init($,J),N4.init($,J),$._zod.processJSONSchema=(Q,_,G)=>Gq($,Q,_,G),$.enum=J.entries,$.options=Object.values(J.entries);let U=new Set(Object.keys(J.entries));$.extract=(Q,_)=>{let G={};for(let V of Q)if(U.has(V))G[V]=J.entries[V];else throw Error(`Key ${V} not found in enum`);return new l9({...J,checks:[],...B$.normalizeParams(_),entries:G})},$.exclude=(Q,_)=>{let G={...J.entries};for(let V of Q)if(U.has(V))delete G[V];else throw Error(`Key ${V} not found in enum`);return new l9({...J,checks:[],...B$.normalizeParams(_),entries:G})}});function zG($,J){let U=Array.isArray($)?Object.fromEntries($.map((Q)=>[Q,Q])):$;return new l9({type:"enum",entries:U,...B$.normalizeParams(J)})}function Bw($,J){return new l9({type:"enum",entries:$,...B$.normalizeParams(J)})}var qH=u("ZodLiteral",($,J)=>{pN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Vq($,U,Q,_),$.values=new Set(J.values),Object.defineProperty($,"value",{get(){if(J.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return J.values[0]}})});function Ow($,J){return new qH({type:"literal",values:Array.isArray($)?$:[$],...B$.normalizeParams(J)})}var HH=u("ZodFile",($,J)=>{aN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Zq($,U,Q,_),$.min=(U,Q)=>$.check(A1(U,Q)),$.max=(U,Q)=>$.check(o2(U,Q)),$.mime=(U,Q)=>$.check(b9(Array.isArray(U)?U:[U],Q))});function jw($){return hW(HH,$)}var BH=u("ZodTransform",($,J)=>{oN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Wq($,U,Q,_),$._zod.parse=(U,Q)=>{if(Q.direction==="backward")throw new $8($.constructor.name);U.addIssue=(G)=>{if(typeof G==="string")U.issues.push(B$.issue(G,U.value,J));else{let V=G;if(V.fatal)V.continue=!1;V.code??(V.code="custom"),V.input??(V.input=U.value),V.inst??(V.inst=$),U.issues.push(B$.issue(V))}};let _=J.transform(U.value,U);if(_ instanceof Promise)return _.then((G)=>{return U.value=G,U});return U.value=_,U}});function RG($){return new BH({type:"transform",transform:$})}var AG=u("ZodOptional",($,J)=>{E3.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>a3($,U,Q,_),$.unwrap=()=>$._zod.def.innerType});function k7($){return new AG({type:"optional",innerType:$})}var OH=u("ZodExactOptional",($,J)=>{tN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>a3($,U,Q,_),$.unwrap=()=>$._zod.def.innerType});function jH($){return new OH({type:"optional",innerType:$})}var DH=u("ZodNullable",($,J)=>{sN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Pq($,U,Q,_),$.unwrap=()=>$._zod.def.innerType});function I7($){return new DH({type:"nullable",innerType:$})}function Dw($){return k7(I7($))}var EH=u("ZodDefault",($,J)=>{eN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Lq($,U,Q,_),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function PH($,J){return new EH({type:"default",innerType:$,get defaultValue(){return typeof J==="function"?J():B$.shallowClone(J)}})}var MH=u("ZodPrefault",($,J)=>{$F.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>zq($,U,Q,_),$.unwrap=()=>$._zod.def.innerType});function LH($,J){return new MH({type:"prefault",innerType:$,get defaultValue(){return typeof J==="function"?J():B$.shallowClone(J)}})}var wG=u("ZodNonOptional",($,J)=>{JF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Mq($,U,Q,_),$.unwrap=()=>$._zod.def.innerType});function zH($,J){return new wG({type:"nonoptional",innerType:$,...B$.normalizeParams(J)})}var RH=u("ZodSuccess",($,J)=>{UF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Kq($,U,Q,_),$.unwrap=()=>$._zod.def.innerType});function Ew($){return new RH({type:"success",innerType:$})}var AH=u("ZodCatch",($,J)=>{_F.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Rq($,U,Q,_),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function wH($,J){return new AH({type:"catch",innerType:$,catchValue:typeof J==="function"?J:()=>J})}var fH=u("ZodNaN",($,J)=>{QF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Xq($,U,Q,_)});function Pw($){return gW(fH,$)}var fG=u("ZodPipe",($,J)=>{GF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Aq($,U,Q,_),$.in=J.in,$.out=J.out});function S7($,J){return new fG({type:"pipe",in:$,out:J})}var kG=u("ZodCodec",($,J)=>{fG.init($,J),D7.init($,J)});function Mw($,J,U){return new kG({type:"pipe",in:$,out:J,transform:U.decode,reverseTransform:U.encode})}var kH=u("ZodReadonly",($,J)=>{VF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>wq($,U,Q,_),$.unwrap=()=>$._zod.def.innerType});function IH($){return new kH({type:"readonly",innerType:$})}var SH=u("ZodTemplateLiteral",($,J)=>{XF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Yq($,U,Q,_)});function Lw($,J){return new SH({type:"template_literal",parts:$,...B$.normalizeParams(J)})}var TH=u("ZodLazy",($,J)=>{KF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>kq($,U,Q,_),$.unwrap=()=>$._zod.def.getter()});function vH($){return new TH({type:"lazy",getter:$})}var CH=u("ZodPromise",($,J)=>{ZF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>fq($,U,Q,_),$.unwrap=()=>$._zod.def.innerType});function zw($){return new CH({type:"promise",innerType:$})}var bH=u("ZodFunction",($,J)=>{YF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Fq($,U,Q,_)});function Rw($){return new bH({type:"function",input:Array.isArray($?.input)?KH($?.input):$?.input??C7(X8()),output:$?.output??X8()})}var x7=u("ZodCustom",($,J)=>{NF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Nq($,U,Q,_)});function Aw($){let J=new x4({check:"custom"});return J._zod.check=$,J}function ww($,J){return uW(x7,$??(()=>!0),J)}function yH($,J={}){return mW(x7,$,J)}function gH($){return cW($)}var fw=dW,kw=lW;function Iw($,J={}){let U=new x7({type:"custom",check:"custom",fn:(Q)=>Q instanceof $,abort:!0,...B$.normalizeParams(J)});return U._zod.bag.Class=$,U._zod.check=(Q)=>{if(!(Q.value instanceof $))Q.issues.push({code:"invalid_type",expected:$.name,input:Q.value,inst:U,path:[...U._zod.def.path??[]]})},U}var Sw=(...$)=>iW({Codec:kG,Boolean:p9,String:i9},...$);function Tw($){let J=vH(()=>{return LG([UG($),pq(),aq(),eq(),C7(J),NH(UG(),J)])});return J}function vw($,J){return S7(RG($),J)}var Qp={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function Gp($){Y6({customError:$})}function Vp(){return Y6().customError}var xH;(function($){})(xH||(xH={}));var R$={...w7,...t3,iso:d9},Xp=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function Yp($,J){let U=$.$schema;if(U==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(U==="http://json-schema.org/draft-07/schema#")return"draft-7";if(U==="http://json-schema.org/draft-04/schema#")return"draft-4";return J??"draft-2020-12"}function Zp($,J){if(!$.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let U=$.slice(1).split("/").filter(Boolean);if(U.length===0)return J.rootSchema;let Q=J.version==="draft-2020-12"?"$defs":"definitions";if(U[0]===Q){let _=U[1];if(!_||!J.defs[_])throw Error(`Reference not found: ${$}`);return J.defs[_]}throw Error(`Reference not found: ${$}`)}function Cw($,J){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return R$.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if($.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if($.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if($.if!==void 0||$.then!==void 0||$.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if($.dependentSchemas!==void 0||$.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if($.$ref){let _=$.$ref;if(J.refs.has(_))return J.refs.get(_);if(J.processing.has(_))return R$.lazy(()=>{if(!J.refs.has(_))throw Error(`Circular reference not resolved: ${_}`);return J.refs.get(_)});J.processing.add(_);let G=Zp(_,J),V=x6(G,J);return J.refs.set(_,V),J.processing.delete(_),V}if($.enum!==void 0){let _=$.enum;if(J.version==="openapi-3.0"&&$.nullable===!0&&_.length===1&&_[0]===null)return R$.null();if(_.length===0)return R$.never();if(_.length===1)return R$.literal(_[0]);if(_.every((V)=>typeof V==="string"))return R$.enum(_);let G=_.map((V)=>R$.literal(V));if(G.length<2)return G[0];return R$.union([G[0],G[1],...G.slice(2)])}if($.const!==void 0)return R$.literal($.const);let U=$.type;if(Array.isArray(U)){let _=U.map((G)=>{let V={...$,type:G};return Cw(V,J)});if(_.length===0)return R$.never();if(_.length===1)return _[0];return R$.union(_)}if(!U)return R$.any();let Q;switch(U){case"string":{let _=R$.string();if($.format){let G=$.format;if(G==="email")_=_.check(R$.email());else if(G==="uri"||G==="uri-reference")_=_.check(R$.url());else if(G==="uuid"||G==="guid")_=_.check(R$.uuid());else if(G==="date-time")_=_.check(R$.iso.datetime());else if(G==="date")_=_.check(R$.iso.date());else if(G==="time")_=_.check(R$.iso.time());else if(G==="duration")_=_.check(R$.iso.duration());else if(G==="ipv4")_=_.check(R$.ipv4());else if(G==="ipv6")_=_.check(R$.ipv6());else if(G==="mac")_=_.check(R$.mac());else if(G==="cidr")_=_.check(R$.cidrv4());else if(G==="cidr-v6")_=_.check(R$.cidrv6());else if(G==="base64")_=_.check(R$.base64());else if(G==="base64url")_=_.check(R$.base64url());else if(G==="e164")_=_.check(R$.e164());else if(G==="jwt")_=_.check(R$.jwt());else if(G==="emoji")_=_.check(R$.emoji());else if(G==="nanoid")_=_.check(R$.nanoid());else if(G==="cuid")_=_.check(R$.cuid());else if(G==="cuid2")_=_.check(R$.cuid2());else if(G==="ulid")_=_.check(R$.ulid());else if(G==="xid")_=_.check(R$.xid());else if(G==="ksuid")_=_.check(R$.ksuid())}if(typeof $.minLength==="number")_=_.min($.minLength);if(typeof $.maxLength==="number")_=_.max($.maxLength);if($.pattern)_=_.regex(new RegExp($.pattern));Q=_;break}case"number":case"integer":{let _=U==="integer"?R$.number().int():R$.number();if(typeof $.minimum==="number")_=_.min($.minimum);if(typeof $.maximum==="number")_=_.max($.maximum);if(typeof $.exclusiveMinimum==="number")_=_.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")_=_.gt($.minimum);if(typeof $.exclusiveMaximum==="number")_=_.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")_=_.lt($.maximum);if(typeof $.multipleOf==="number")_=_.multipleOf($.multipleOf);Q=_;break}case"boolean":{Q=R$.boolean();break}case"null":{Q=R$.null();break}case"object":{let _={},G=$.properties||{},V=new Set($.required||[]);for(let[Z,Y]of Object.entries(G)){let K=x6(Y,J);_[Z]=V.has(Z)?K:K.optional()}if($.propertyNames){let Z=x6($.propertyNames,J),Y=$.additionalProperties&&typeof $.additionalProperties==="object"?x6($.additionalProperties,J):R$.any();if(Object.keys(_).length===0){Q=R$.record(Z,Y);break}let K=R$.object(_).passthrough(),F=R$.looseRecord(Z,Y);Q=R$.intersection(K,F);break}if($.patternProperties){let Z=$.patternProperties,Y=Object.keys(Z),K=[];for(let N of Y){let q=x6(Z[N],J),H=R$.string().regex(new RegExp(N));K.push(R$.looseRecord(H,q))}let F=[];if(Object.keys(_).length>0)F.push(R$.object(_).passthrough());if(F.push(...K),F.length===0)Q=R$.object({}).passthrough();else if(F.length===1)Q=F[0];else{let N=R$.intersection(F[0],F[1]);for(let q=2;q<F.length;q++)N=R$.intersection(N,F[q]);Q=N}break}let X=R$.object(_);if($.additionalProperties===!1)Q=X.strict();else if(typeof $.additionalProperties==="object")Q=X.catchall(x6($.additionalProperties,J));else Q=X.passthrough();break}case"array":{let{prefixItems:_,items:G}=$;if(_&&Array.isArray(_)){let V=_.map((Z)=>x6(Z,J)),X=G&&typeof G==="object"&&!Array.isArray(G)?x6(G,J):void 0;if(X)Q=R$.tuple(V).rest(X);else Q=R$.tuple(V);if(typeof $.minItems==="number")Q=Q.check(R$.minLength($.minItems));if(typeof $.maxItems==="number")Q=Q.check(R$.maxLength($.maxItems))}else if(Array.isArray(G)){let V=G.map((Z)=>x6(Z,J)),X=$.additionalItems&&typeof $.additionalItems==="object"?x6($.additionalItems,J):void 0;if(X)Q=R$.tuple(V).rest(X);else Q=R$.tuple(V);if(typeof $.minItems==="number")Q=Q.check(R$.minLength($.minItems));if(typeof $.maxItems==="number")Q=Q.check(R$.maxLength($.maxItems))}else if(G!==void 0){let V=x6(G,J),X=R$.array(V);if(typeof $.minItems==="number")X=X.min($.minItems);if(typeof $.maxItems==="number")X=X.max($.maxItems);Q=X}else Q=R$.array(R$.any());break}default:throw Error(`Unsupported type: ${U}`)}if($.description)Q=Q.describe($.description);if($.default!==void 0)Q=Q.default($.default);return Q}function x6($,J){if(typeof $==="boolean")return $?R$.any():R$.never();let U=Cw($,J),Q=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let X=$.anyOf.map((Y)=>x6(Y,J)),Z=R$.union(X);U=Q?R$.intersection(U,Z):Z}if($.oneOf&&Array.isArray($.oneOf)){let X=$.oneOf.map((Y)=>x6(Y,J)),Z=R$.xor(X);U=Q?R$.intersection(U,Z):Z}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)U=Q?U:R$.any();else{let X=Q?U:x6($.allOf[0],J),Z=Q?0:1;for(let Y=Z;Y<$.allOf.length;Y++)X=R$.intersection(X,x6($.allOf[Y],J));U=X}if($.nullable===!0&&J.version==="openapi-3.0")U=R$.nullable(U);if($.readOnly===!0)U=R$.readonly(U);let _={},G=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let X of G)if(X in $)_[X]=$[X];let V=["contentEncoding","contentMediaType","contentSchema"];for(let X of V)if(X in $)_[X]=$[X];for(let X of Object.keys($))if(!Xp.has(X))_[X]=$[X];if(Object.keys(_).length>0)J.registry.add(U,_);return U}function bw($,J){if(typeof $==="boolean")return $?R$.any():R$.never();let U=Yp($,J?.defaultTarget),Q=$.$defs||$.definitions||{},_={version:U,defs:Q,refs:new Map,processing:new Set,rootSchema:$,registry:J?.registry??T6};return x6($,_)}var hH={};F1(hH,{string:()=>Kp,number:()=>Np,date:()=>qp,boolean:()=>Fp,bigint:()=>Wp});function Kp($){return YW(i9,$)}function Np($){return BW(n9,$)}function Fp($){return LW(p9,$)}function Wp($){return RW(a9,$)}function qp($){return yW(v7,$)}Y6(E7());var o4={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},M6={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"};var Bp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),description:W.union([W.string(),W.null()]).optional(),id:W.string(),name:W.string()}),mH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),methodId:W.string()}),Op=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),jp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),blob:W.string(),mimeType:W.union([W.string(),W.null()]).optional(),uri:W.string()}),Dp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),terminalId:W.string()}),Ep=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),newText:W.string(),oldText:W.union([W.string(),W.null()]).optional(),path:W.string()}),yw=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),name:W.string(),value:W.string()}),Pp=W.union([W.literal(-32700),W.literal(-32600),W.literal(-32601),W.literal(-32602),W.literal(-32603),W.literal(-32800),W.literal(-32000),W.literal(-32002),W.number().int()]),gw=W.object({code:Pp,data:W.unknown().optional(),message:W.string()}),xw=W.unknown(),hw=W.unknown(),uw=W.unknown(),Mp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),readTextFile:W.boolean().optional().default(!1),writeTextFile:W.boolean().optional().default(!1)}),Lp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),fs:Mp.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:W.boolean().optional().default(!1)}),mw=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),name:W.string(),value:W.string()}),cw=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),name:W.string(),title:W.union([W.string(),W.null()]).optional(),version:W.string()}),zp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),cH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),cursor:W.union([W.string(),W.null()]).optional(),cwd:W.union([W.string(),W.null()]).optional()}),Rp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),http:W.boolean().optional().default(!1),sse:W.boolean().optional().default(!1)}),Ap=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),headers:W.array(mw),name:W.string(),url:W.string()}),wp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),headers:W.array(mw),name:W.string(),url:W.string()}),fp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),args:W.array(W.string()),command:W.string(),env:W.array(yw),name:W.string()}),IG=W.union([Ap.and(W.object({type:W.literal("http")})),wp.and(W.object({type:W.literal("sse")})),fp]),dH=W.string(),kp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),description:W.union([W.string(),W.null()]).optional(),modelId:dH,name:W.string()}),lH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),cwd:W.string(),mcpServers:W.array(IG)}),dw=W.string(),Ip=W.union([W.literal("allow_once"),W.literal("allow_always"),W.literal("reject_once"),W.literal("reject_always")]),Sp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),kind:Ip,name:W.string(),optionId:dw}),Tp=W.union([W.literal("high"),W.literal("medium"),W.literal("low")]),vp=W.union([W.literal("pending"),W.literal("in_progress"),W.literal("completed")]),Cp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:W.string(),priority:Tp,status:vp}),bp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),entries:W.array(Cp)}),yp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),audio:W.boolean().optional().default(!1),embeddedContext:W.boolean().optional().default(!1),image:W.boolean().optional().default(!1)}),lw=W.number().int().gte(0).lte(65535),iH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),clientCapabilities:Lp.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:W.union([cw,W.null()]).optional(),protocolVersion:lw}),gp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:W.string()}),xp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),Z8=W.union([W.null(),W.coerce.bigint(),W.string()]),$F$=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),requestId:Z8}),hp=W.enum(["assistant","user"]),h7=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),audience:W.union([W.array(hp),W.null()]).optional(),lastModified:W.union([W.string(),W.null()]).optional(),priority:W.union([W.number(),W.null()]).optional()}),up=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h7,W.null()]).optional(),data:W.string(),mimeType:W.string()}),mp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h7,W.null()]).optional(),data:W.string(),mimeType:W.string(),uri:W.union([W.string(),W.null()]).optional()}),cp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h7,W.null()]).optional(),description:W.union([W.string(),W.null()]).optional(),mimeType:W.union([W.string(),W.null()]).optional(),name:W.string(),size:W.union([W.coerce.bigint(),W.null()]).optional(),title:W.union([W.string(),W.null()]).optional(),uri:W.string()}),dp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),optionId:dw}),lp=W.union([W.object({outcome:W.literal("cancelled")}),dp.and(W.object({outcome:W.literal("selected")}))]),ip=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),outcome:lp}),rp=W.string(),iw=W.string(),rH=W.string(),rw=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),description:W.union([W.string(),W.null()]).optional(),name:W.string(),value:rH}),np=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),group:rp,name:W.string(),options:W.array(rw)}),pp=W.union([W.array(rw),W.array(np)]),ap=W.object({currentValue:rH,options:pp}),o9=ap.and(W.object({type:W.literal("select")})).and(W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),description:W.union([W.string(),W.null()]).optional(),id:iw,name:W.string()})),op=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.array(o9)}),tp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),O6=W.string(),nH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),sessionId:O6}),JF$=W.object({method:W.string(),params:W.union([W.union([nH,xw]),W.null()]).optional()}),pH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),args:W.array(W.string()).optional(),command:W.string(),cwd:W.union([W.string(),W.null()]).optional(),env:W.array(yw).optional(),outputByteLimit:W.union([W.number().int().gte(0),W.null()]).optional(),sessionId:O6}),aH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),cwd:W.string(),mcpServers:W.array(IG).optional(),sessionId:O6}),oH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),sessionId:O6,terminalId:W.string()}),tH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),cwd:W.string(),mcpServers:W.array(IG),sessionId:O6}),sH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),limit:W.union([W.number().int().gte(0),W.null()]).optional(),line:W.union([W.number().int().gte(0),W.null()]).optional(),path:W.string(),sessionId:O6}),eH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),sessionId:O6,terminalId:W.string()}),$B=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),cwd:W.string(),mcpServers:W.array(IG).optional(),sessionId:O6}),sp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),cwd:W.string(),sessionId:O6,title:W.union([W.string(),W.null()]).optional(),updatedAt:W.union([W.string(),W.null()]).optional()}),ep=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),nextCursor:W.union([W.string(),W.null()]).optional(),sessions:W.array(sp)}),$a=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),title:W.union([W.string(),W.null()]).optional(),updatedAt:W.union([W.string(),W.null()]).optional()}),Ja=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),SG=W.string(),Ua=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),currentModeId:SG}),_a=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),description:W.union([W.string(),W.null()]).optional(),id:SG,name:W.string()}),TG=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),availableModes:W.array(_a),currentModeId:SG}),vG=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),availableModels:W.array(kp),currentModelId:dH}),Qa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.union([W.array(o9),W.null()]).optional(),models:W.union([vG,W.null()]).optional(),modes:W.union([TG,W.null()]).optional(),sessionId:O6}),Ga=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.union([W.array(o9),W.null()]).optional(),models:W.union([vG,W.null()]).optional(),modes:W.union([TG,W.null()]).optional()}),Va=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.union([W.array(o9),W.null()]).optional(),models:W.union([vG,W.null()]).optional(),modes:W.union([TG,W.null()]).optional(),sessionId:O6}),Xa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.union([W.array(o9),W.null()]).optional(),models:W.union([vG,W.null()]).optional(),modes:W.union([TG,W.null()]).optional()}),Ya=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),Za=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),fork:W.union([tp,W.null()]).optional(),list:W.union([Ja,W.null()]).optional(),resume:W.union([Ya,W.null()]).optional()}),Ka=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),loadSession:W.boolean().optional().default(!1),mcpCapabilities:Rp.optional().default({http:!1,sse:!1}),promptCapabilities:yp.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:Za.optional().default({})}),Na=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),agentCapabilities:Ka.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:W.union([cw,W.null()]).optional(),authMethods:W.array(Bp).optional().default([]),protocolVersion:lw}),Fa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configId:iw,sessionId:O6,value:rH}),Wa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.array(o9)}),JB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),modeId:SG,sessionId:O6}),qa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),UB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),modelId:dH,sessionId:O6}),Ha=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),Ba=W.union([W.literal("end_turn"),W.literal("max_tokens"),W.literal("max_turn_requests"),W.literal("refusal"),W.literal("cancelled")]),Oa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),stopReason:Ba}),UF$=W.union([W.object({id:Z8,result:W.union([Na,Op,Va,Ga,ep,Qa,Xa,qa,Wa,Oa,Ha,uw])}),W.object({error:gw,id:Z8})]),ja=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),terminalId:W.string()}),Da=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),exitCode:W.union([W.number().int().gte(0),W.null()]).optional(),signal:W.union([W.string(),W.null()]).optional()}),_B=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),sessionId:O6,terminalId:W.string()}),Ea=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),exitStatus:W.union([Da,W.null()]).optional(),output:W.string(),truncated:W.boolean()}),Pa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h7,W.null()]).optional(),text:W.string()}),Ma=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),mimeType:W.union([W.string(),W.null()]).optional(),text:W.string(),uri:W.string()}),La=W.union([Ma,jp]),za=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h7,W.null()]).optional(),resource:La}),QB=W.union([Pa.and(W.object({type:W.literal("text")})),mp.and(W.object({type:W.literal("image")})),up.and(W.object({type:W.literal("audio")})),cp.and(W.object({type:W.literal("resource_link")})),za.and(W.object({type:W.literal("resource")}))]),Ra=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:QB}),uH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:QB}),GB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),prompt:W.array(QB),sessionId:O6}),_F$=W.object({id:Z8,method:W.string(),params:W.union([W.union([iH,mH,lH,tH,cH,aH,$B,JB,Fa,GB,UB,hw]),W.null()]).optional()}),nw=W.union([Ra.and(W.object({type:W.literal("content")})),Ep.and(W.object({type:W.literal("diff")})),ja.and(W.object({type:W.literal("terminal")}))]),pw=W.string(),aw=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),line:W.union([W.number().int().gte(0),W.null()]).optional(),path:W.string()}),ow=W.union([W.literal("pending"),W.literal("in_progress"),W.literal("completed"),W.literal("failed")]),tw=W.union([W.literal("read"),W.literal("edit"),W.literal("delete"),W.literal("move"),W.literal("search"),W.literal("execute"),W.literal("think"),W.literal("fetch"),W.literal("switch_mode"),W.literal("other")]),Aa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:W.array(nw).optional(),kind:tw.optional(),locations:W.array(aw).optional(),rawInput:W.unknown().optional(),rawOutput:W.unknown().optional(),status:ow.optional(),title:W.string(),toolCallId:pw}),sw=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:W.union([W.array(nw),W.null()]).optional(),kind:W.union([tw,W.null()]).optional(),locations:W.union([W.array(aw),W.null()]).optional(),rawInput:W.unknown().optional(),rawOutput:W.unknown().optional(),status:W.union([ow,W.null()]).optional(),title:W.union([W.string(),W.null()]).optional(),toolCallId:pw}),VB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),options:W.array(Sp),sessionId:O6,toolCall:sw}),wa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),hint:W.string()}),fa=wa,ka=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),description:W.string(),input:W.union([fa,W.null()]).optional(),name:W.string()}),Ia=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),availableCommands:W.array(ka)}),Sa=W.union([uH.and(W.object({sessionUpdate:W.literal("user_message_chunk")})),uH.and(W.object({sessionUpdate:W.literal("agent_message_chunk")})),uH.and(W.object({sessionUpdate:W.literal("agent_thought_chunk")})),Aa.and(W.object({sessionUpdate:W.literal("tool_call")})),sw.and(W.object({sessionUpdate:W.literal("tool_call_update")})),bp.and(W.object({sessionUpdate:W.literal("plan")})),Ia.and(W.object({sessionUpdate:W.literal("available_commands_update")})),Ua.and(W.object({sessionUpdate:W.literal("current_mode_update")})),op.and(W.object({sessionUpdate:W.literal("config_option_update")})),$a.and(W.object({sessionUpdate:W.literal("session_info_update")}))]),XB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),sessionId:O6,update:Sa}),QF$=W.object({method:W.string(),params:W.union([W.union([XB,xw]),W.null()]).optional()}),YB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),sessionId:O6,terminalId:W.string()}),Ta=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),exitCode:W.union([W.number().int().gte(0),W.null()]).optional(),signal:W.union([W.string(),W.null()]).optional()}),ZB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:W.string(),path:W.string(),sessionId:O6}),GF$=W.object({id:Z8,method:W.string(),params:W.union([W.union([ZB,sH,VB,pH,_B,eH,YB,oH,hw]),W.null()]).optional()}),va=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),VF$=W.union([W.object({id:Z8,result:W.union([va,gp,ip,Dp,Ea,xp,Ta,zp,uw])}),W.object({error:gw,id:Z8})]);function ew($,J){let U=new TextEncoder,Q=new TextDecoder,_=new ReadableStream({async start(V){let X="",Z=J.getReader();try{while(!0){let{value:Y,done:K}=await Z.read();if(K)break;if(!Y)continue;X+=Q.decode(Y,{stream:!0});let F=X.split(`
|
|
570
|
-
`);X=F.pop()||"";for(let N of F){let q=N.trim();if(q)try{let H=JSON.parse(q);V.enqueue(H)}catch(H){console.error("Failed to parse JSON message:",q,H)}}}}finally{Z.releaseLock(),V.close()}}}),G=new WritableStream({async write(V){let X=JSON.stringify(V)+`
|
|
571
|
-
`,Z=$.getWriter();try{await Z.write(U.encode(X))}finally{Z.releaseLock()}}});return{readable:_,writable:G}}class KB{#$;constructor($,J){let U=$(this),Q=async(G,V)=>{switch(G){case o4.initialize:{let X=iH.parse(V);return U.initialize(X)}case o4.session_new:{let X=lH.parse(V);return U.newSession(X)}case o4.session_load:{if(!U.loadSession)throw C4.methodNotFound(G);let X=tH.parse(V);return U.loadSession(X)}case o4.session_list:{if(!U.unstable_listSessions)throw C4.methodNotFound(G);let X=cH.parse(V);return U.unstable_listSessions(X)}case o4.session_fork:{if(!U.unstable_forkSession)throw C4.methodNotFound(G);let X=aH.parse(V);return U.unstable_forkSession(X)}case o4.session_resume:{if(!U.unstable_resumeSession)throw C4.methodNotFound(G);let X=$B.parse(V);return U.unstable_resumeSession(X)}case o4.session_set_mode:{if(!U.setSessionMode)throw C4.methodNotFound(G);let X=JB.parse(V);return await U.setSessionMode(X)??{}}case o4.authenticate:{let X=mH.parse(V);return await U.authenticate(X)??{}}case o4.session_prompt:{let X=GB.parse(V);return U.prompt(X)}case o4.session_set_model:{if(!U.unstable_setSessionModel)throw C4.methodNotFound(G);let X=UB.parse(V);return await U.unstable_setSessionModel(X)??{}}default:if(G.startsWith("_")){if(!U.extMethod)throw C4.methodNotFound(G);return U.extMethod(G.substring(1),V)}throw C4.methodNotFound(G)}},_=async(G,V)=>{switch(G){case o4.session_cancel:{let X=nH.parse(V);return U.cancel(X)}default:if(G.startsWith("_")){if(!U.extNotification)return;return U.extNotification(G.substring(1),V)}throw C4.methodNotFound(G)}};this.#$=new NB(Q,_,J)}async sessionUpdate($){return await this.#$.sendNotification(M6.session_update,$)}async requestPermission($){return await this.#$.sendRequest(M6.session_request_permission,$)}async readTextFile($){return await this.#$.sendRequest(M6.fs_read_text_file,$)}async writeTextFile($){return await this.#$.sendRequest(M6.fs_write_text_file,$)??{}}async createTerminal($){let J=await this.#$.sendRequest(M6.terminal_create,$);return new $f(J.terminalId,$.sessionId,this.#$)}async extMethod($,J){return await this.#$.sendRequest(`_${$}`,J)}async extNotification($,J){return await this.#$.sendNotification(`_${$}`,J)}get signal(){return this.#$.signal}get closed(){return this.#$.closed}}class $f{id;#$;#J;constructor($,J,U){this.id=$,this.#$=J,this.#J=U}async currentOutput(){return await this.#J.sendRequest(M6.terminal_output,{sessionId:this.#$,terminalId:this.id})}async waitForExit(){return await this.#J.sendRequest(M6.terminal_wait_for_exit,{sessionId:this.#$,terminalId:this.id})}async kill(){return await this.#J.sendRequest(M6.terminal_kill,{sessionId:this.#$,terminalId:this.id})??{}}async release(){return await this.#J.sendRequest(M6.terminal_release,{sessionId:this.#$,terminalId:this.id})??{}}async[Symbol.asyncDispose](){await this.release()}}class ba{#$;constructor($,J){let U=$(this),Q=async(G,V)=>{switch(G){case M6.fs_write_text_file:{let X=ZB.parse(V);return U.writeTextFile?.(X)}case M6.fs_read_text_file:{let X=sH.parse(V);return U.readTextFile?.(X)}case M6.session_request_permission:{let X=VB.parse(V);return U.requestPermission(X)}case M6.terminal_create:{let X=pH.parse(V);return U.createTerminal?.(X)}case M6.terminal_output:{let X=_B.parse(V);return U.terminalOutput?.(X)}case M6.terminal_release:{let X=eH.parse(V);return await U.releaseTerminal?.(X)??{}}case M6.terminal_wait_for_exit:{let X=YB.parse(V);return U.waitForTerminalExit?.(X)}case M6.terminal_kill:{let X=oH.parse(V);return await U.killTerminal?.(X)??{}}default:if(G.startsWith("_")){let X=G.substring(1);if(!U.extMethod)throw C4.methodNotFound(G);return U.extMethod(X,V)}throw C4.methodNotFound(G)}},_=async(G,V)=>{switch(G){case M6.session_update:{let X=XB.parse(V);return U.sessionUpdate(X)}default:if(G.startsWith("_")){let X=G.substring(1);if(!U.extNotification)return;return U.extNotification(X,V)}throw C4.methodNotFound(G)}};this.#$=new NB(Q,_,J)}async initialize($){return await this.#$.sendRequest(o4.initialize,$)}async newSession($){return await this.#$.sendRequest(o4.session_new,$)}async loadSession($){return await this.#$.sendRequest(o4.session_load,$)??{}}async unstable_forkSession($){return await this.#$.sendRequest(o4.session_fork,$)}async unstable_listSessions($){return await this.#$.sendRequest(o4.session_list,$)}async unstable_resumeSession($){return await this.#$.sendRequest(o4.session_resume,$)}async setSessionMode($){return await this.#$.sendRequest(o4.session_set_mode,$)??{}}async unstable_setSessionModel($){return await this.#$.sendRequest(o4.session_set_model,$)??{}}async authenticate($){return await this.#$.sendRequest(o4.authenticate,$)??{}}async prompt($){return await this.#$.sendRequest(o4.session_prompt,$)}async cancel($){return await this.#$.sendNotification(o4.session_cancel,$)}async extMethod($,J){return await this.#$.sendRequest(`_${$}`,J)}async extNotification($,J){return await this.#$.sendNotification(`_${$}`,J)}get signal(){return this.#$.signal}get closed(){return this.#$.closed}}class NB{#$=new Map;#J=0;#V;#X;#_;#Q=Promise.resolve();#G=new AbortController;#Y;constructor($,J,U){this.#V=$,this.#X=J,this.#_=U,this.#Y=new Promise((Q)=>{this.#G.signal.addEventListener("abort",()=>Q())}),this.#Z()}get signal(){return this.#G.signal}get closed(){return this.#Y}async#Z(){let $=this.#_.readable.getReader();try{while(!0){let{value:J,done:U}=await $.read();if(U)break;if(!J)continue;try{this.#K(J)}catch(Q){if(console.error("Unexpected error during message processing:",J,Q),"id"in J&&J.id!==void 0)this.#U({jsonrpc:"2.0",id:J.id,error:{code:-32700,message:"Parse error"}})}}}finally{$.releaseLock(),this.#G.abort()}}async#K($){if("method"in $&&"id"in $){let J=await this.#N($.method,$.params);if("error"in J)console.error("Error handling request",$,J.error);await this.#U({jsonrpc:"2.0",id:$.id,...J})}else if("method"in $){let J=await this.#F($.method,$.params);if("error"in J)console.error("Error handling notification",$,J.error)}else if("id"in $)this.#W($);else console.error("Invalid message",{message:$})}async#N($,J){try{return{result:await this.#V($,J)??null}}catch(U){if(U instanceof C4)return U.toResult();if(U instanceof W.ZodError)return C4.invalidParams(U.format()).toResult();let Q;if(U instanceof Error)Q=U.message;else if(typeof U==="object"&&U!=null&&"message"in U&&typeof U.message==="string")Q=U.message;try{return C4.internalError(Q?JSON.parse(Q):{}).toResult()}catch{return C4.internalError({details:Q}).toResult()}}}async#F($,J){try{return await this.#X($,J),{result:null}}catch(U){if(U instanceof C4)return U.toResult();if(U instanceof W.ZodError)return C4.invalidParams(U.format()).toResult();let Q;if(U instanceof Error)Q=U.message;else if(typeof U==="object"&&U!=null&&"message"in U&&typeof U.message==="string")Q=U.message;try{return C4.internalError(Q?JSON.parse(Q):{}).toResult()}catch{return C4.internalError({details:Q}).toResult()}}}#W($){let J=this.#$.get($.id);if(J){if("result"in $)J.resolve($.result);else if("error"in $)J.reject($.error);this.#$.delete($.id)}else console.error("Got response to unknown request",$.id)}async sendRequest($,J){let U=this.#J++,Q=new Promise((_,G)=>{this.#$.set(U,{resolve:_,reject:G})});return await this.#U({jsonrpc:"2.0",id:U,method:$,params:J}),Q}async sendNotification($,J){await this.#U({jsonrpc:"2.0",method:$,params:J})}async#U($){return this.#Q=this.#Q.then(async()=>{let J=this.#_.writable.getWriter();try{await J.write($)}finally{J.releaseLock()}}).catch((J)=>{console.error("ACP write error:",J)}),this.#Q}}class C4 extends Error{code;data;constructor($,J,U){super(J);this.code=$,this.name="RequestError",this.data=U}static parseError($,J){return new C4(-32700,`Parse error${J?`: ${J}`:""}`,$)}static invalidRequest($,J){return new C4(-32600,`Invalid request${J?`: ${J}`:""}`,$)}static methodNotFound($){return new C4(-32601,`"Method not found": ${$}`,{method:$})}static invalidParams($,J){return new C4(-32602,`Invalid params${J?`: ${J}`:""}`,$)}static internalError($,J){return new C4(-32603,`Internal error${J?`: ${J}`:""}`,$)}static authRequired($,J){return new C4(-32000,`Authentication required${J?`: ${J}`:""}`,$)}static resourceNotFound($){return new C4(-32002,`Resource not found${$?`: ${$}`:""}`,$&&{uri:$})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}}class e1{tools=new Map;register($){if(this.tools.has($.name))throw Error(`Tool "${$.name}" already registered`);this.tools.set($.name,$)}unregister($){return this.tools.delete($)}get($){return this.tools.get($)}list(){return Array.from(this.tools.values())}has($){return this.tools.has($)}get size(){return this.tools.size}toOpenAIFormat(){return this.list().map(($)=>({type:"function",function:{name:$.name,description:$.description,parameters:$.parameters}}))}}var xF$=U4(Ff(),1),BB=v6.env.ACP_DEBUG==="true",s9=v6.env.ACP_STICKY_SESSION==="true";function M4(...$){if(BB)console.error("[ACP Server]",...$)}var qB="plan-mode",Wo="agent",Of=[{id:"agent",name:"Agent",description:"Standard agent mode with full tool access."},{id:"plan",name:"Plan",description:"Planning mode with read-only tooling and plan helpers."}],qo=new Set(Of.map(($)=>$.id));function Ho($){return qo.has($)?$:null}function bG($){return{currentModeId:$,availableModes:Of}}function jf(){let $=K9({baseUrl:v6.env.OPENAI_API_BASE_URL,apiKey:v6.env.OPENAI_API_KEY,defaultModelId:v6.env.MODEL_ID||"gpt-4o-mini",compat:{interleavedThinking:!0}});return g8({adapter:$})}function Bo(){let $=K9({baseUrl:v6.env.OPENAI_API_BASE_URL,apiKey:v6.env.OPENAI_API_KEY,defaultModelId:v6.env.SUB_MODEL_ID||"gpt-4o-mini",compat:{interleavedThinking:!0}});return g8({adapter:$})}function Wf($,J){if($==="end_turn"||$==="max_tokens"||$==="max_turn_requests"||$==="refusal"||$==="cancelled")return $;switch($){case"final_response":case"stop":case"tool_call":return"end_turn";case"length":return"max_tokens";case"max_iterations":return"max_turn_requests";case"approval_required":case"error":return"end_turn";default:return J}}var qf="acp-history";function Oo($){if(!$)return"";if(typeof $==="string")return $;if(Array.isArray($)){let J=$.map((U)=>U&&typeof U.text==="string"?U.text:"").filter(Boolean);if(J.length>0)return J.join("");return JSON.stringify($)}return JSON.stringify($)}function Hf($){if($.outcome!=="selected")return null;let J=$._meta;if(J&&typeof J==="object"&&"answers"in J&&J.answers&&typeof J.answers==="object")return J.answers;return null}function Bf($,J,U,Q){let _=[],G=new Map;(Array.isArray($.options)?$.options:[]).forEach((Y,K)=>{let F=`q${J}:opt${K}`;if(U.has(F))return;let N=typeof Y?.label==="string"&&Y.label.trim()?Y.label.trim():`Option ${K+1}`;G.set(F,N),_.push({optionId:F,name:N,kind:"allow_once"})});let X=`q${J}:other`;if(!U.has(X))G.set(X,"Other"),_.push({optionId:X,name:"Other",kind:"allow_once"});let Z;if(Q)Z=`q${J}:done`,_.push({optionId:Z,name:"Done",kind:"reject_once"});if(_.length===0){let Y=`q${J}:ok`;G.set(Y,"OK"),_.push({optionId:Y,name:"OK",kind:"allow_once"})}return{options:_,optionLabelById:G,doneOptionId:Z}}async function jo($,J,U,Q,_){let G={};for(let V=0;V<Q.length;V++){let X=Q[V],Z=typeof X.header==="string"&&X.header.trim()?X.header.trim():"User Input Required",Y={question:X,questionIndex:V};if(X.multiSelect){let E=[],D=new Set;while(!0){let{options:B,optionLabelById:j,doneOptionId:f}=Bf(X,V,D,!0),R=await $.requestPermission({sessionId:J,toolCall:{toolCallId:U,title:Z,kind:_,status:"pending",rawInput:Y},options:B}),I=Hf(R.outcome);if(I)return I;if(R.outcome.outcome==="cancelled")return null;let w=R.outcome.optionId;if(f&&w===f)break;let T=j.get(w)??w;if(E.push(T),D.add(w),B.filter((S)=>S.optionId!==f).length<=D.size)break}G[String(V)]=E;continue}let{options:K,optionLabelById:F}=Bf(X,V,new Set,!1),N=await $.requestPermission({sessionId:J,toolCall:{toolCallId:U,title:Z,kind:_,status:"pending",rawInput:Y},options:K}),q=Hf(N.outcome);if(q)return q;if(N.outcome.outcome==="cancelled")return null;let H=N.outcome.optionId;G[String(V)]=F.get(H)??H}return G}function Do($,J){let U=[];for(let Q=0;Q<$.length;Q++){let _=J[String(Q)];if(!_)continue;let G=$[Q]?.header?.trim()||`Q${Q+1}`,V=Array.isArray(_)?_.join(", "):_;U.push(`${G}: ${V}`)}return U.length>0?U.join("; "):"User answers received."}function Eo($){let J=`tool:${$}:allow`,U=`tool:${$}:deny`;return{allowOptionId:J,denyOptionId:U,options:[{optionId:J,name:"Allow",kind:"allow_once"},{optionId:U,name:"Deny",kind:"reject_once"}]}}async function Po($,J,U){let Q={};for(let _ of U){let{options:G,allowOptionId:V}=Eo(_.toolCallId),X=_.riskLevel?`${_.title} (${_.riskLevel})`:_.title,Z=await $.requestPermission({sessionId:J,toolCall:{toolCallId:_.toolCallId,title:X,kind:_.kind,status:"pending",rawInput:_.rawInput},options:G});if(Z.outcome.outcome==="cancelled")return null;let Y=Z.outcome.optionId;Q[_.toolCallId]={approved:Y===V}}return Q}class Df{acpAgent;connection=null;sessions=new Map;stickySessionId=null;currentModeId=Wo;currentWorkspaceCwd=null;availableCommands=[{name:"new",description:"Start a fresh conversation (creates a new session)."},{name:"agent",description:"Switch to agent mode."},{name:"plan",description:"Switch to plan mode."},{name:"commit",description:"Generate a git commit with auto-generated message based on staged changes."}];constructor($){this.acpAgent=$}setConnection($){this.connection=$}async initialize($){return M4("initialize called"),{protocolVersion:1,agentCapabilities:{loadSession:!0,sessionCapabilities:{resume:{}}},agentInfo:{name:"GoatChain Agent",version:"0.0.2"}}}async newSession($){if(this.applyWorkspaceCwd($.cwd),s9&&!this.stickySessionId){let Q=await this.findMostRecentSessionId();if(Q)this.stickySessionId=Q}if(s9&&this.stickySessionId)return await this.restoreSession(this.stickySessionId),M4("newSession reuse:",this.stickySessionId),this.scheduleAvailableCommands(this.stickySessionId),{sessionId:this.stickySessionId,modes:bG(this.currentModeId)};let J=this.generateSessionId();M4("newSession:",J);let U={conversationHistory:[],pendingAbort:null,createdAt:Date.now(),agentSessionId:J,currentModeId:this.currentModeId};if(this.sessions.set(J,U),await this.saveSessionHistory(J,U),s9)this.stickySessionId=J;return this.scheduleAvailableCommands(J),{sessionId:J,modes:bG(this.currentModeId)}}async loadSession($){if(!this.connection)throw Error("Connection not set");M4("loadSession:",$.sessionId);let J=await this.restoreSession($.sessionId);if(await this.sendHistory($.sessionId,J.conversationHistory),s9)this.stickySessionId=J.agentSessionId;return await this.sendAvailableCommands($.sessionId),{modes:bG(this.currentModeId)}}async unstable_resumeSession($){M4("resumeSession:",$.sessionId);let J=await this.restoreSession($.sessionId);if(s9)this.stickySessionId=J.agentSessionId;return await this.sendAvailableCommands($.sessionId),{modes:bG(this.currentModeId)}}async authenticate($){M4("authenticate called")}async setSessionMode($){M4("setSessionMode called",$);let J=Ho($.modeId);if(!J)throw Error(`Unsupported session mode: ${$.modeId}`);if(await this.restoreSession($.sessionId),this.currentModeId!==J)this.currentModeId=J,await this.applySessionMode(J),this.closeAllActiveSessions();for(let Q of this.sessions.values())Q.currentModeId=this.currentModeId;await this.sendCurrentModeUpdate($.sessionId)}async prompt($){if(!this.connection)throw Error("Connection not set");let J=this.connection,{sessionId:U,prompt:Q}=$;M4("prompt called for session:",U,"prompt blocks:",Q.length);let _=this.sessions.get(U);if(!_)throw Error(`Session ${U} not found`);if(await this.sendAvailableCommands(U),_.pendingAbort)_.pendingAbort.abort(),this.acpAgent.getSession(_.agentSessionId)?.cancel();_.pendingAbort=new AbortController;let G=!1;try{let V=Q.filter((B)=>B.type==="text").map((B)=>B.text).join(`
|
|
572
|
-
`),Z=V.trim().toLowerCase();if(Z==="/new")return await this.startNewSession(U),G=!0,await J.sessionUpdate({sessionId:U,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"New session started. Send your next message to begin."}}}),{stopReason:"end_turn"};if(Z==="/plan"||Z==="/agent"){let B=Z.slice(1);return await this.setSessionMode({sessionId:U,modeId:B}),await J.sessionUpdate({sessionId:U,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Switched to ${B} mode.`}}}),{stopReason:"end_turn"}}if(Z==="/commit")return G=!0,{stopReason:(await this.executeCommitWorkflow(U,J)).cancelled?"cancelled":"end_turn"};let Y={role:"user",content:V};_.conversationHistory.push(Y),M4("User message added to history");let K=new Map,F=new Set,N=new Map,q=[],H="end_turn",E=null,D=null;while(!0){H="end_turn";let B=D?this.acpAgent.receiveWithApprovals(D,{session_id:_.agentSessionId}):this.acpAgent.receiveMessage(E??_.conversationHistory,{session_id:_.agentSessionId});E=null,D=null;let j=null,f=null,R=!1,I=!1;for await(let w of B){if(I)continue;if(_.pendingAbort.signal.aborted){H="cancelled";break}let T=w.metadata?.subagent===!0,z=typeof w.metadata?.subagentId==="string"?w.metadata?.subagentId:void 0,S=typeof w.metadata?.subagentType==="string"?w.metadata?.subagentType.trim():void 0,O=typeof w.metadata?.taskDescription==="string"?w.metadata?.taskDescription.trim():void 0,M=T?z??`${S||"subagent"}:${O??""}`:null,P=T&&(S||O)?`[${[S,O].filter(Boolean).join(": ")}]`:null,A=T?`[SUBAGENT${S?`:${S}`:""}${O?`:${O}`:""}]`:"";M4("Received response:",w.role,A,w.metadata?.done?"(done)":"");let k=w.content&&w.content.length>0,L=w.tool_calls&&w.tool_calls.length>0,v=w.role==="assistant"&&w.metadata?.done&&!k&&!L,C=w.role==="tool"&&!!w.tool_call_id&&F.has(w.tool_call_id)&&w.metadata?.error===!0;if(!v&&!C)_.conversationHistory.push(w);if(v){if(w.metadata?.done){if(w.metadata.stopReason)H=Wf(w.metadata.stopReason,H);I=!0}continue}if(w.role==="assistant"){if(k){let b=typeof w.content==="string"?w.content:JSON.stringify(w.content);if(b.trim()){let y=w.metadata?.thinking===!0,c=T&&P&&M!==f?`${P} ${b}`:b;if(await J.sessionUpdate({sessionId:U,update:{sessionUpdate:y?"agent_thought_chunk":"agent_message_chunk",content:{type:"text",text:c}}}),!y)f=M}}if(!T&&k)f=null;if(w.metadata?.approval_requested===!0){let b=w.metadata,y=typeof b.tool_call_id==="string"?b.tool_call_id:j,x=typeof b.tool_name==="string"?b.tool_name:y?K.get(y)?.name:void 0,c=y?K.get(y):void 0;if(y&&x){let s=typeof b.risk_level==="string"?b.risk_level:void 0;if(!N.has(y))q.push(y);N.set(y,{toolCallId:y,toolName:x,title:c?.title??x,kind:c?.kind??"other",rawInput:c?.rawInput??{},riskLevel:s})}else M4("Tool approval requested without toolCallId or toolName")}if(w.metadata?.requires_action&&w.metadata?.kind==="ask_user"){let b=typeof w.metadata.tool_call_id==="string"?w.metadata.tool_call_id:j,y=Array.isArray(w.metadata.questions)?w.metadata.questions:[],c=(b?K.get(b):void 0)?.kind??"other";if(!b||y.length===0)M4("AskUserQuestion requires_action missing toolCallId or questions");else{M4("AskUserQuestion requires_action detected, requesting user input");let s=await jo(J,U,b,y,c);if(!s){await J.sessionUpdate({sessionId:U,update:{sessionUpdate:"tool_call_update",toolCallId:b,status:"failed"}}),H="cancelled";break}let F$=Do(y,s),K$={role:"tool",tool_call_id:b,content:JSON.stringify({answers:s})},V$={role:"user",content:`User answers: ${F$}
|
|
573
|
-
Please continue.`};_.conversationHistory.push(K$),_.conversationHistory.push(V$),await J.sessionUpdate({sessionId:U,update:{sessionUpdate:"tool_call_update",toolCallId:b,status:"completed",content:[{type:"content",content:{type:"text",text:"User answers received"}}]}}),E=[V$,K$],R=!0;break}}if(w.metadata?.requires_action&&w.metadata?.kind==="tool_approval"){let y=(q.length>0?q:Array.from(N.keys())).map((c)=>N.get(c)).filter((c)=>Boolean(c));if(y.length===0){let c=typeof w.metadata.tool_call_id==="string"?w.metadata.tool_call_id:j,s=c?K.get(c):void 0;if(c&&s)y=[{toolCallId:c,toolName:s.name,title:s.title,kind:s.kind,rawInput:s.rawInput}];else{M4("Tool approval required but no pending requests found"),H="cancelled";break}}let x=await Po(J,U,y);if(N.clear(),q.length=0,!x){for(let c of y)await J.sessionUpdate({sessionId:U,update:{sessionUpdate:"tool_call_update",toolCallId:c.toolCallId,status:"failed"}});H="cancelled";break}D=x,R=!0;continue}if(L&&w.tool_calls){for(let b of w.tool_calls){j=b.id;let y={};try{y=typeof b.function.arguments==="string"?JSON.parse(b.function.arguments):b.function.arguments}catch(u$){M4("Failed to parse tool call arguments:",u$),y={error:"Invalid JSON arguments"}}let x="search",c=b.function.name;if(c.includes("Read")||c.includes("Grep")||c.includes("Glob")||c.includes("AstGrepSearch"))x="read";else if(c.includes("Write")||c.includes("Edit")||c.includes("AstGrepReplace"))x="edit";else if(c.includes("Search"))x="search";else if(c.includes("ExitPlanMode")||c.includes("EnterPlanMode"))x="other";let s=c==="Task"||c.endsWith(":Task"),F$=[];if(s&&y&&typeof y==="object"){if(typeof y.description==="string"&&y.description.trim())F$.push(y.description.trim());if(typeof y.subagent_type==="string"&&y.subagent_type.trim())F$.push(y.subagent_type.trim())}let K$=F$.length>0?` (${F$.join(" | ")})`:"",V$=`${c}${K$}`,Y$=P?`${P} ${V$}`:V$;if(K.set(b.id,{name:c,rawInput:y,kind:x,title:Y$}),c==="AskUserQuestion")F.add(b.id);await J.sessionUpdate({sessionId:U,update:{sessionUpdate:"tool_call",toolCallId:b.id,title:Y$,kind:x,status:"pending",rawInput:y}})}f=null}}else if(w.role==="tool"){if(j||w.tool_call_id){let b=w.tool_call_id||j;if(F.has(b)&&w.metadata?.error)continue;let y=typeof w.content==="string"?w.content:w.content?JSON.stringify(w.content):"",x=T&&S?`[${S}] ${y}`:y;await J.sessionUpdate({sessionId:U,update:{sessionUpdate:"tool_call_update",toolCallId:b,status:"completed",content:[{type:"content",content:{type:"text",text:x}}]}})}f=null}if(w.metadata?.done){if(w.metadata.stopReason)H=Wf(w.metadata.stopReason,H);I=!0}}if(!R)break}return _.pendingAbort=null,{stopReason:H}}catch(V){if(M4("Error in prompt:",V),_.pendingAbort?.signal.aborted)return{stopReason:"cancelled"};throw V}finally{if(!G)await this.saveSessionHistory(_.agentSessionId,_)}}async cancel($){M4("cancel called for session:",$.sessionId);let J=this.sessions.get($.sessionId);if(J?.pendingAbort)J.pendingAbort.abort();let U=J?.agentSessionId??$.sessionId;this.acpAgent.getSession(U)?.cancel()}applyWorkspaceCwd($){if(!$||typeof $!=="string")return;if(!HB.isAbsolute($)){M4("Ignoring non-absolute cwd from ACP session:",$);return}let J=HB.resolve($);if(this.currentWorkspaceCwd===J)return;this.currentWorkspaceCwd=J;let U=this.acpAgent.getAgent().tools;if(U){for(let Q of U.list())if(typeof Q.setCwd==="function")Q.setCwd(J)}l2.systemPrompt=nZ(J),M4("Workspace updated:",J)}async applySessionMode($){let J=this.acpAgent.getAgent(),U=J.middlewares,Q=U.filter((K)=>K.name!==qB),_=$==="plan",G=U.find((K)=>K.name===qB)?.fn??j9({insertEveryIteration:!0}),V=_?[{name:qB,fn:G},...Q]:Q,X=U.map((K)=>K.name),Z=V.map((K)=>K.name);if(X.length===Z.length&&X.every((K,F)=>K===Z[F]))return;J.clearMiddlewares();for(let K of V)await J.use(K.fn,K.name)}closeAllActiveSessions(){for(let $ of this.acpAgent.getSessionInfo().activeSessions)this.acpAgent.closeSession($)}async sendCurrentModeUpdate($){if(!this.connection)return;await this.connection.sessionUpdate({sessionId:$,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentModeId}})}generateSessionId(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}getStateStore(){return this.acpAgent.getAgent().stateStore}async restoreSession($){let J=this.sessions.get($);if(J)return J;let U=await this.loadSessionHistory($),Q={conversationHistory:U?.messages??[],pendingAbort:null,createdAt:U?.createdAt??Date.now(),agentSessionId:$,currentModeId:this.currentModeId};return this.sessions.set($,Q),Q}async loadSessionHistory($){let J=this.getStateStore();if(!J)return null;try{let U=await J.load($,qf);if(!U||!Array.isArray(U.messages))return null;return{sessionId:typeof U.sessionId==="string"?U.sessionId:$,createdAt:typeof U.createdAt==="number"?U.createdAt:Date.now(),updatedAt:typeof U.updatedAt==="number"?U.updatedAt:Date.now(),messages:U.messages}}catch(U){return M4("Failed to load session history:",$,U),null}}async findMostRecentSessionId(){let $=this.getStateStore();if(!$)return null;try{let J=await $.listSessions(),U=null,Q=0;for(let _ of J){let V=(await this.loadSessionHistory(_))?.updatedAt??0;if(V>Q)Q=V,U=_}return U}catch(J){return M4("Failed to list sessions:",J),null}}async startNewSession($){let J=this.sessions.get($),U=J?.agentSessionId??$;if(J?.pendingAbort)J.pendingAbort.abort();if(U)this.acpAgent.closeSession(U);let Q=this.generateSessionId(),_={conversationHistory:[],pendingAbort:null,createdAt:Date.now(),agentSessionId:Q,currentModeId:this.currentModeId};if(this.sessions.set($,_),await this.saveSessionHistory(Q,_),s9)this.stickySessionId=Q}async sendAvailableCommands($){if(!this.connection)return;if(this.availableCommands.length===0)return;await this.connection.sessionUpdate({sessionId:$,update:{sessionUpdate:"available_commands_update",availableCommands:this.availableCommands}})}scheduleAvailableCommands($){setTimeout(()=>{this.sendAvailableCommands($)},0)}async saveSessionHistory($,J){let U=this.getStateStore();if(!U)return;try{let Q={sessionId:$,createdAt:J.createdAt,updatedAt:Date.now(),messages:J.conversationHistory};await U.save($,qf,Q)}catch(Q){M4("Failed to save session history:",$,Q)}}async sendHistory($,J){if(!this.connection)return;for(let U of J){if(U.role==="system")continue;let Q=Oo(U.content);if(!Q.trim())continue;let _=U.role==="user"?"user_message_chunk":"agent_message_chunk";await this.connection.sessionUpdate({sessionId:$,update:{sessionUpdate:_,content:{type:"text",text:Q}}})}}async executeCommitWorkflow($,J){M4("Executing /commit workflow");let U=this.currentWorkspaceCwd||v6.cwd(),Q=jf(),_=new j1({name:"CommitAgent",systemPrompt:"You are a git commit assistant.",model:Q,tools:new e1});await _.use(vY({model:Q,defaultLanguage:"Chinese",defaultAutoStage:!0,fetchBeforeCommit:!0,allowBehindRemote:!1,cwd:U}));try{let G=await _.createSession({requestParams:{temperature:0.7}});G.send("请帮我创建一个 git commit");let V="",X="",Z=!1,Y=!1;for await(let K of G.receive()){if(K.type==="text_delta"&&K.delta)Y=!0,await J.sessionUpdate({sessionId:$,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:K.delta}}});if(K.type==="thinking_delta"&&K.delta)await J.sessionUpdate({sessionId:$,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:K.delta}}});if(K.type==="done"){if(V=K.finalResponse||"",!Y&&V.trim())await J.sessionUpdate({sessionId:$,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:V}}});let F=V.match(/Commit Hash:\s*([a-f0-9]+)/i);if(F)X=F[1];if(V.includes("✗")||V.includes("Error"))Z=!0;break}}return M4("Commit workflow completed:",{hasCommit:!!X,hasError:Z,hasStreamedContent:Y}),{cancelled:!1}}catch(G){return M4("Commit workflow error:",G),await J.sessionUpdate({sessionId:$,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
574
|
-
|
|
575
|
-
✗ Commit 失败: ${G instanceof Error?G.message:String(G)}`}}}),{cancelled:!1}}}}async function Ef(){M4("Starting GoatChain ACP Server...");let $=v6.env.WORKSPACE_CWD||v6.cwd();M4("Workspace:",$);let J=new e1,U=jf(),Q=new A2({dir:HB.join($,".goatchain","state"),deleteOnComplete:!0});J.register(new d2({cwd:$})),J.register(new h2({cwd:$})),J.register(new v2({cwd:$})),J.register(new T2({cwd:$})),J.register(new C2({cwd:$})),J.register(new x2({cwd:$})),J.register(new S2({cwd:$})),J.register(new I2({cwd:$})),J.register(new u2),J.register(new m2),J.register(new f2);let _=new e1,G=new Set(l2.blockedTools||[]);for(let D of l2.tools||[]){if(G.has(D))continue;let B=J.get(D);if(B)_.register(B)}let V=Bo(),X=D9({subagents:[l2],globalToolRegistry:J,model:V,debug:BB}),Y=new j1({name:"GoatChain",systemPrompt:`You are GoatChain CLI, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
576
|
-
|
|
577
|
-
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
|
|
578
|
-
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
|
|
579
|
-
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
|
580
|
-
|
|
581
|
-
If the user asks for help or wants to give feedback inform them of the following:
|
|
582
|
-
- /help: Get help with using GoatChain CLI
|
|
583
|
-
|
|
584
|
-
When the user directly asks about GoatChain CLI (eg 'can GoatChain CLI do...', 'does GoatChain CLI have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the /help command to provide the user with information about GoatChain CLI's features and capabilities.
|
|
585
|
-
|
|
586
|
-
# Tone and style
|
|
587
|
-
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
|
|
588
|
-
Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
|
589
|
-
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
|
|
590
|
-
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
|
|
591
|
-
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
|
592
|
-
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
|
|
593
|
-
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
|
|
594
|
-
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
|
|
595
|
-
<example>
|
|
596
|
-
user: 2 + 2
|
|
597
|
-
assistant: 4
|
|
598
|
-
</example>
|
|
599
|
-
|
|
600
|
-
<example>
|
|
601
|
-
user: what is 2+2?
|
|
602
|
-
assistant: 4
|
|
603
|
-
</example>
|
|
604
|
-
|
|
605
|
-
<example>
|
|
606
|
-
user: is 11 a prime number?
|
|
607
|
-
assistant: Yes
|
|
608
|
-
</example>
|
|
609
|
-
|
|
610
|
-
<example>
|
|
611
|
-
user: what command should I run to list files in the current directory?
|
|
612
|
-
assistant: ls
|
|
613
|
-
</example>
|
|
614
|
-
|
|
615
|
-
<example>
|
|
616
|
-
user: what command should I run to watch files in the current directory?
|
|
617
|
-
assistant: [use the bash tool to run ls to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
|
|
618
|
-
npm run dev
|
|
619
|
-
</example>
|
|
620
|
-
|
|
621
|
-
<example>
|
|
622
|
-
user: How many golf balls fit inside a jetta?
|
|
623
|
-
assistant: 150000
|
|
624
|
-
</example>
|
|
625
|
-
|
|
626
|
-
<example>
|
|
627
|
-
user: what files are in the directory src/?
|
|
628
|
-
assistant: [runs bash tool with ls command and sees foo.c, bar.c, baz.c]
|
|
629
|
-
user: which file contains the implementation of foo?
|
|
630
|
-
assistant: src/foo.c
|
|
631
|
-
</example>
|
|
632
|
-
|
|
633
|
-
<example>
|
|
634
|
-
user: write tests for new feature
|
|
635
|
-
assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
|
|
636
|
-
</example>
|
|
637
|
-
|
|
638
|
-
# Proactiveness
|
|
639
|
-
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
|
640
|
-
1. Doing the right thing when asked, including taking actions and follow-up actions
|
|
641
|
-
2. Not surprising the user with actions you take without asking
|
|
642
|
-
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
|
|
643
|
-
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
|
|
644
|
-
|
|
645
|
-
# Following conventions
|
|
646
|
-
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
|
|
647
|
-
- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
|
|
648
|
-
- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
|
|
649
|
-
- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
|
|
650
|
-
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
|
|
651
|
-
|
|
652
|
-
# Code style
|
|
653
|
-
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
|
|
654
|
-
|
|
655
|
-
# Doing tasks
|
|
656
|
-
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
|
657
|
-
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
|
|
658
|
-
- Implement the solution using all tools available to you
|
|
659
|
-
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
|
|
660
|
-
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
|
|
661
|
-
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
|
662
|
-
|
|
663
|
-
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
|
|
664
|
-
|
|
665
|
-
# Tool usage policy
|
|
666
|
-
- When doing file search, prefer to use the Task tool in order to reduce context usage.
|
|
667
|
-
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tool calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
|
|
668
|
-
|
|
669
|
-
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
|
670
|
-
|
|
671
|
-
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
|
|
672
|
-
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
|
|
673
|
-
|
|
674
|
-
# Code References
|
|
675
|
-
|
|
676
|
-
When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` to allow the user to easily navigate to the source code location.
|
|
677
|
-
|
|
678
|
-
<example>
|
|
679
|
-
user: Where are errors from the client handled?
|
|
680
|
-
assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
|
|
681
|
-
</example>`,model:U,tools:J,stateStore:Q});await Y.use(X),await Y.use(zJ({maxTokens:128000,protectedTurns:2,model:U,stateStore:Q})),M4("Agent initialized with tools:",Array.from(J.list().map((D)=>D.name))),M4("Agent initialized with middlewares:",Y.middlewareNames.join(", "));let K=new aQ(Y,{debug:BB,maxIterations:1e4}),F=new Df(K),N=No.toWeb(v6.stdin),q=Fo.toWeb(v6.stdout),H=ew(q,N);M4("Creating AgentSideConnection...");let E=new KB((D)=>{return M4("Agent connection established"),F.setConnection(D),F},H);M4("ACP Server ready and listening on stdio"),await E.closed,M4("Connection closed"),K.destroy()}var Mo=import.meta.url===`file://${v6.argv[1]}`||v6.argv[1]?.endsWith("acp-server.ts")||v6.argv[1]?.endsWith("acp-server.js");if(Mo)Ef().catch(($)=>{console.error("[ACP Server] Fatal error:",$),v6.exit(1)});async function*Pf($){try{let J=$.toolContext?.approval?.decisions;if(J&&typeof $.session?.receiveWithApprovals==="function")yield*$.convertEventStream($.session.receiveWithApprovals(J,{toolContext:$.toolContext,...$.signal?{signal:$.signal}:null}));else yield*$.convertEventStream($.session.receive({toolContext:$.toolContext,...$.signal?{signal:$.signal}:null}))}catch(J){yield{role:"assistant",content:["# GoatChain error","","```text","Unable to resume after approval (no pending checkpoint found). This can happen if the session was recreated (e.g. after changing settings) before the approval was resolved. Please retry the last message.","",`debug: ${J instanceof Error?J.stack||J.message:String(J)}`,"```"].join(`
|
|
682
|
-
`),metadata:{done:!0,error:!0,stopReason:"error",originalEventType:"done"}}}}import{chmod as zf,mkdir as Rf,readFile as zo,writeFile as Af}from"node:fs/promises";import EB from"node:path";var m7="goatchain-oauth-dummy-key";async function PB(){let $=await OB();return EB.join($,"auth.json")}async function MB(){try{let $=await PB(),J=await zo($,"utf8"),U=JSON.parse(J);return U&&typeof U==="object"?U:{}}catch{return{}}}async function $U($){return(await MB())[$]}async function gG($,J){let U=await PB(),Q=await MB();Q[$]=J;let _=EB.dirname(U);await Rf(_,{recursive:!0});let G=`${U}.tmp.${Date.now()}`,V=`${JSON.stringify(Q,null,2)}
|
|
683
|
-
`;await Af(G,V,{encoding:"utf8",mode:384});let{rename:X}=await import("node:fs/promises");await X(G,U);try{await zf(U,384)}catch{}}async function wf($){let J=await PB(),U=await MB();delete U[$];let Q=EB.dirname(J);await Rf(Q,{recursive:!0});let _=`${J}.tmp.${Date.now()}`,G=`${JSON.stringify(U,null,2)}
|
|
684
|
-
`;await Af(_,G,{encoding:"utf8",mode:384});let{rename:V}=await import("node:fs/promises");await V(_,J);try{await zf(J,384)}catch{}}var N8="https://chatgpt.com/backend-api";var J2=[{id:"gpt-5.1-codex-max",name:"GPT-5.1 Codex Max",description:"Most capable Codex model"},{id:"gpt-5.1-codex-mini",name:"GPT-5.1 Codex Mini",description:"Faster, lighter Codex model"},{id:"gpt-5.2",name:"GPT-5.2",description:"Latest GPT-5 model"},{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",description:"Latest Codex model"}];async function If(){let $=Ro(43),U=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",U),_=Sf(Q);return{verifier:$,challenge:_}}function Ro($){let U=crypto.getRandomValues(new Uint8Array($));return Array.from(U).map((Q)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[Q%66]).join("")}function Sf($){let J=new Uint8Array($),U=String.fromCharCode(...J);return btoa(U).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Tf(){return Sf(crypto.getRandomValues(new Uint8Array(32)).buffer)}function vf($,J,U){return`https://auth.openai.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:"app_EMoamEEZ73f0CkXaXp7hrann",redirect_uri:$,scope:"openid profile email offline_access",code_challenge:J.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:U,originator:"opencode"}).toString()}`}async function Ao($,J,U){let Q=await fetch("https://auth.openai.com/oauth/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:J,client_id:"app_EMoamEEZ73f0CkXaXp7hrann",code_verifier:U.verifier}).toString()});if(!Q.ok)throw Error(`Token exchange failed: ${Q.status}`);return Q.json()}async function Cf($){let J=await fetch("https://auth.openai.com/oauth/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:"app_EMoamEEZ73f0CkXaXp7hrann"}).toString()});if(!J.ok)throw Error(`Token refresh failed: ${J.status}`);return J.json()}function xG($){let J=$.split(".");if(J.length!==3)return;try{return JSON.parse(Buffer.from(J[1],"base64url").toString())}catch{return}}function ff($){return $.chatgpt_account_id||$["https://api.openai.com/auth"]?.chatgpt_account_id||$.organizations?.[0]?.id}function hG($){if($.id_token){let J=xG($.id_token),U=J&&ff(J);if(U)return U}if($.access_token){let J=xG($.access_token);return J?ff(J):void 0}return}function uG($){if($.id_token){let J=xG($.id_token);if(J?.email)return J.email}if($.access_token)return xG($.access_token)?.email;return}var wo=`<!doctype html>
|
|
685
|
-
<html>
|
|
686
|
-
<head>
|
|
687
|
-
<title>GoatChain - Codex Authorization Successful</title>
|
|
688
|
-
<style>
|
|
689
|
-
body {
|
|
690
|
-
font-family:
|
|
691
|
-
system-ui,
|
|
692
|
-
-apple-system,
|
|
693
|
-
sans-serif;
|
|
694
|
-
display: flex;
|
|
695
|
-
justify-content: center;
|
|
696
|
-
align-items: center;
|
|
697
|
-
height: 100vh;
|
|
698
|
-
margin: 0;
|
|
699
|
-
background: #131010;
|
|
700
|
-
color: #f1ecec;
|
|
701
|
-
}
|
|
702
|
-
.container {
|
|
703
|
-
text-align: center;
|
|
704
|
-
padding: 2rem;
|
|
705
|
-
}
|
|
706
|
-
h1 {
|
|
707
|
-
color: #f1ecec;
|
|
708
|
-
margin-bottom: 1rem;
|
|
709
|
-
}
|
|
710
|
-
p {
|
|
711
|
-
color: #b7b1b1;
|
|
712
|
-
}
|
|
713
|
-
</style>
|
|
714
|
-
</head>
|
|
715
|
-
<body>
|
|
716
|
-
<div class="container">
|
|
717
|
-
<h1>Authorization Successful</h1>
|
|
718
|
-
<p>You can close this window and return to GoatChain.</p>
|
|
719
|
-
</div>
|
|
720
|
-
<script>
|
|
721
|
-
setTimeout(() => window.close(), 2000)
|
|
722
|
-
</script>
|
|
723
|
-
</body>
|
|
724
|
-
</html>`;function LB($){return`<!doctype html>
|
|
725
|
-
<html>
|
|
726
|
-
<head>
|
|
727
|
-
<title>GoatChain - Codex Authorization Failed</title>
|
|
728
|
-
<style>
|
|
729
|
-
body {
|
|
730
|
-
font-family:
|
|
731
|
-
system-ui,
|
|
732
|
-
-apple-system,
|
|
733
|
-
sans-serif;
|
|
734
|
-
display: flex;
|
|
735
|
-
justify-content: center;
|
|
736
|
-
align-items: center;
|
|
737
|
-
height: 100vh;
|
|
738
|
-
margin: 0;
|
|
739
|
-
background: #131010;
|
|
740
|
-
color: #f1ecec;
|
|
741
|
-
}
|
|
742
|
-
.container {
|
|
743
|
-
text-align: center;
|
|
744
|
-
padding: 2rem;
|
|
745
|
-
}
|
|
746
|
-
h1 {
|
|
747
|
-
color: #fc533a;
|
|
748
|
-
margin-bottom: 1rem;
|
|
749
|
-
}
|
|
750
|
-
p {
|
|
751
|
-
color: #b7b1b1;
|
|
752
|
-
}
|
|
753
|
-
.error {
|
|
754
|
-
color: #ff917b;
|
|
755
|
-
font-family: monospace;
|
|
756
|
-
margin-top: 1rem;
|
|
757
|
-
padding: 1rem;
|
|
758
|
-
background: #3c140d;
|
|
759
|
-
border-radius: 0.5rem;
|
|
760
|
-
}
|
|
761
|
-
</style>
|
|
762
|
-
</head>
|
|
763
|
-
<body>
|
|
764
|
-
<div class="container">
|
|
765
|
-
<h1>Authorization Failed</h1>
|
|
766
|
-
<p>An error occurred during authorization.</p>
|
|
767
|
-
<div class="error">${$}</div>
|
|
768
|
-
</div>
|
|
769
|
-
</body>
|
|
770
|
-
</html>`}var e0,r6;async function bf(){if(e0)return{port:1455,redirectUri:"http://localhost:1455/auth/callback"};if(typeof globalThis.Bun<"u"){let J=globalThis.Bun;try{e0=J.serve({port:1455,fetch(U){let Q=new URL(U.url);return kf(Q)}})}catch(U){if(U?.code==="EADDRINUSE")throw Error("Port 1455 is already in use. Please stop the process using this port and try again.");throw U}}else e0=(await import("node:http")).createServer(async(U,Q)=>{try{let _=new URL(U.url||"/","http://localhost:1455"),G=kf(_);Q.statusCode=G.status;let V=Object.fromEntries(G.headers.entries());for(let[Z,Y]of Object.entries(V))Q.setHeader(Z,Y);let X=await G.text();Q.end(X)}catch{Q.statusCode=500,Q.end("Internal Server Error")}}),await new Promise((U,Q)=>{e0.listen(1455,()=>U()),e0.on("error",(_)=>{if(_?.code==="EADDRINUSE")Q(Error("Port 1455 is already in use. Please stop the process using this port and try again."));else Q(_)})});return{port:1455,redirectUri:"http://localhost:1455/auth/callback"}}function kf($){if($.pathname==="/auth/callback"){let J=$.searchParams.get("code"),U=$.searchParams.get("state"),Q=$.searchParams.get("error"),_=$.searchParams.get("error_description");if(Q){let V=_||Q;return r6?.reject(Error(V)),r6=void 0,new Response(LB(V),{headers:{"Content-Type":"text/html"}})}if(!J)return r6?.reject(Error("Missing authorization code")),r6=void 0,new Response(LB("Missing authorization code"),{status:400,headers:{"Content-Type":"text/html"}});if(!r6||U!==r6.state)return r6?.reject(Error("Invalid state - potential CSRF attack")),r6=void 0,new Response(LB("Invalid state - potential CSRF attack"),{status:400,headers:{"Content-Type":"text/html"}});let G=r6;return r6=void 0,Ao(J,"http://localhost:1455/auth/callback",G.pkce).then((V)=>G.resolve(V)).catch((V)=>G.reject(V)),new Response(wo,{headers:{"Content-Type":"text/html"}})}if($.pathname==="/cancel")return r6?.reject(Error("Login cancelled")),r6=void 0,new Response("Login cancelled",{status:200});return new Response("Not found",{status:404})}function c7(){if(e0){if(typeof e0.stop==="function")e0.stop();else if(typeof e0.close==="function")e0.close();e0=void 0}}function yf($,J){return new Promise((U,Q)=>{let _=setTimeout(()=>{if(r6)r6=void 0,Q(Error("OAuth callback timeout - authorization took too long"))},300000);r6={pkce:$,state:J,resolve:(G)=>{clearTimeout(_),U(G)},reject:(G)=>{clearTimeout(_),Q(G)}}})}function gf($,J){if(!$||typeof $!=="object")return $;let U={};for(let[V,X]of Object.entries(J))if(typeof X==="number"&&Number.isFinite(X))U[V]=X;if(Object.keys(U).length===0)return $;let Q=(V)=>V!=null&&typeof V==="object"&&!Array.isArray(V),_=(V)=>{if(!Q(V))return;for(let[X,Z]of Object.entries(U))if(!(X in V))V[X]=Z},G=(V)=>{if(typeof V!=="function")return V;return(...X)=>{for(let Z of X){if(!Q(Z))continue;if("body"in Z&&Q(Z.body)){_(Z.body);break}if("messages"in Z||"model"in Z||"input"in Z||"prompt"in Z){_(Z);break}}return V(...X)}};for(let V of["request","createChatCompletion","chat","complete","responses","completions"])if(typeof $[V]==="function")$[V]=G($[V].bind($));return $}async function xf($,J){let U=J.baseUrl?.includes("https://chatgpt.com/backend-api");if(U){let{createCodexAdapter:G}=await import("goatchain"),V=async()=>{let Y=await $U("codex");if(!Y)throw Error("Codex OAuth tokens not found. Please login via Settings.");if(Y.expires<Date.now())try{let K=await Cf(Y.refresh),F=hG(K)||Y.accountId,N=uG(K)||Y.email;Y={type:"oauth",refresh:K.refresh_token,access:K.access_token,expires:Date.now()+(K.expires_in??3600)*1000,accountId:F,email:N},await gG("codex",Y)}catch(K){throw Error(`Failed to refresh OAuth token: ${K?.message||"Unknown error"}`)}return Y.access},X=async()=>{let Y=await $U("codex");if(!Y?.accountId)throw Error("Codex account ID not found");return Y.accountId},Z=G({baseUrl:J.baseUrl,accessToken:V,accountId:X,defaultModelId:J.modelId});return gf(Z,{temperature:J.temperature}),Z}let Q=U?"goatchain-oauth-dummy-key":J.apiKey,_=$({defaultModelId:J.modelId,baseUrl:J.baseUrl,apiKey:Q,compat:{interleavedThinking:J.interleavedThinking}});return gf(_,{temperature:J.temperature}),_}function hf($){return{async list(){let J=await $.ensureSharedStateStore();if(!J)return[];let U=await $.sessionStorageKey(),Q=await(J.listSessions?.()??[]),_=[];for(let G of Q)try{let V=await J.load(G,U);if(V)_.push(V)}catch{}return _},async get(J){let U=await $.ensureSharedStateStore();if(!U)return null;let Q=String(J??"").trim();if(!Q)return null;let _=await $.sessionStorageKey();try{return await U.load(Q,_)??null}catch{return null}},async create(){let J=await $.ensureSharedStateStore();if(!J)return null;let U=await $.sessionStorageKey(),Q=Date.now(),_=$.createId(),G=$.createEmptySessionSnapshot(_,Q);return await J.save(_,U,G),G},async destroy(J){let U=await $.ensureSharedStateStore();if(!U)return;let Q=String(J??"").trim();if(!Q)return;await U.deleteSession(Q)},async createWithMessages(J){let U=await $.ensureSharedStateStore();if(!U)return null;let Q=await $.sessionStorageKey(),_=Date.now(),G=$.createId(),V=$.createEmptySessionSnapshot(G,_);return $.applyMessagesToSnapshot(V,Array.isArray(J)?J:[],_),await U.save(G,Q,V),V}}}function ko(){let $=globalThis.process;return!!$&&typeof $?.versions?.node==="string"}function mG(){return globalThis.process?.env??{}}var uf="plan-mode";function $1($){return String($??"").trim()||void 0}function mf($){let J=String($??"").trim();if(!J)return;let U=Number.parseFloat(J);return Number.isFinite(U)?U:void 0}function Io($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="object"&&J&&"text"in J)return String(J.text??"");return JSON.stringify(J)}).join(`
|
|
771
|
-
`);try{return JSON.stringify($,null,2)}catch{return String($)}}function So($,J){if(!J||typeof $?.cancel!=="function")return()=>{};if(J.aborted){try{$.cancel()}catch{}return()=>{}}let U=()=>{try{$.cancel()}catch{}};return J.addEventListener("abort",U,{once:!0}),()=>{try{J.removeEventListener("abort",U)}catch{}}}function To($){return{id:String($?.id??""),type:"function",function:{name:String($?.function?.name??""),arguments:$?.function?.arguments}}}function vo($){let J={};for(let U of $){if(U.role!=="tool"||!U.tool_call_id)continue;let Q=typeof U.content==="string"?U.content:U.content?JSON.stringify(U.content):"";try{let _=JSON.parse(Q);if(_&&typeof _==="object"&&_.answers&&typeof _.answers==="object")J[U.tool_call_id]=_.answers}catch{}}return J}function zB($){if(!$)return"";if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>String(J?.text??"")).join("");return String($)}function RB($){if(!$||typeof $!=="object")return null;let J=$.usage;if(J&&typeof J==="object")return J;let U=$.stats?.usage;if(U&&typeof U==="object")return U;try{let _=(typeof $.toSnapshot==="function"?$.toSnapshot():null)?.stats?.usage;if(_&&typeof _==="object")return _}catch{}return null}function cf($){if(!ko())throw Error("GoatChain embedded agent is Node-only");let J=$.debug===!0,U=$.cliTools!==!1,Q=$.planMode===!0,_=$.subagents===!0,G=$1($.stateDir||mG().GOATCHAIN_STATE_DIR||mG().GOATCHAIN_STATE_DIR),V=null,X=Q?"plan":"agent",Z=null,Y=null,K=null,F=null,N={current:globalThis.process?.cwd?.()??"."};function q(P,A){let k=P.filter((y)=>y.role!=="system"),L=(()=>{for(let y=k.length-1;y>=0;y--)if(k[y]?.role==="user")return y;return-1})(),v=String(A??"").trim(),C=L===k.length-1&&v.length>0,b=[];for(let y=0;y<k.length;y++){if(C&&y===L)continue;let x=k[y];if(!x)continue;if(x.role==="user")b.push({role:"user",content:zB(x.content)});else if(x.role==="assistant"){let c={role:"assistant",content:zB(x.content)};if(Array.isArray(x.tool_calls)&&x.tool_calls.length)c.tool_calls=x.tool_calls;b.push(c)}else if(x.role==="tool")b.push({role:"tool",tool_call_id:String(x.tool_call_id??""),content:zB(x.content),...x.metadata?.error===!0?{isError:!0}:{}})}return b}function H(P,A,k){try{if(!P||!Array.isArray(P.messages))return;let L=q(A,k);if(L.length===0)return;if(P.messages.length>=L.length)return;P.messages=L}catch{}}function E(P){let A=P?.env;if(!A||typeof A!=="object")return;let k=globalThis.process;if(!k?.env)return;for(let[L,v]of Object.entries(A)){let C=String(L??"").trim();if(!C)continue;let b=v==null?"":String(v);if(!b)delete k.env[C];else k.env[C]=b}}let D=new Map;async function B(){if(V)return V;if(G&&typeof A2==="function")try{return V=new A2({dir:G,deleteOnComplete:!1}),V}catch(P){if(J)console.warn("[goatchain-node] Failed to init FileStateStore:",P);V=null}if(!V&&typeof w2==="function")try{V=new w2({deleteOnComplete:!1})}catch(P){if(J)console.warn("[goatchain-node] Failed to init InMemoryStateStore:",P);V=null}return V}function j(P,A){let k=String(N.current??"").trim();return{id:P,createdAt:A,state:{status:"active",updatedAt:A,lastActiveAt:A},context:{messages:[],messageCount:0,toolCallCount:0},stats:{usage:{promptTokens:0,completionTokens:0,totalTokens:0},responseCount:0},metadata:k?{cwd:k}:void 0}}function f(P){if(!Array.isArray(P)||P.length===0)return;for(let A=P.length-1;A>=0;A--){let k=P[A],L=String(k?.role??"");if(L!=="user"&&L!=="assistant"&&L!=="system"&&L!=="tool")continue;let v=k?.content;if(typeof v==="string"){let C=v.replace(/\s+/g," ").trim();if(C)return C.slice(0,200)}if(Array.isArray(v)){let C=v.filter((b)=>b&&typeof b==="object"&&b.type==="text"&&typeof b.text==="string").map((b)=>b.text).join(" ").replace(/\s+/g," ").trim();if(C)return C.slice(0,200)}}return}async function R(){let P=I6?.SESSION;return typeof P==="string"&&P.trim()?P:"session"}function I(){let P=mG(),A=String(P.GOATCHAIN_INTERLEAVED_THINKING??"").toLowerCase(),k=A==="1"||A==="true"||A==="yes"||A==="on";return{modelId:String(P.GOATCHAIN_MODEL||$.modelId),baseUrl:$1(P.GOATCHAIN_OPENAI_BASE_URL||P.OPENAI_BASE_URL||$.baseUrl),apiKey:$1(P.OPENAI_API_KEY||$.apiKey),temperature:mf(P.GOATCHAIN_TEMPERATURE),interleavedThinking:k?!0:void 0}}function w(P){return JSON.stringify({modelId:P.modelId,baseUrl:P.baseUrl??null,apiKey:P.apiKey?"***":null,temperature:P.temperature??null,interleavedThinking:P.interleavedThinking??null})}async function T(P){await B();let A=new e1,k=(y)=>{if(!y)return;try{A.register(new y)}catch(x){if(J)console.warn("[goatchain-node] Failed to register tool:",y?.name??"(unknown)",x)}};if(k(T2),k(x2),k(h2),k(C2),k(f2),k(u2),k(m2),U)k(d2),k(v2),k(S2),k(I2);let L=await xf(K9,P),v=g8({adapter:L}),C=[];if(typeof jQ==="function")try{C.push(jQ({cwd:()=>N.current,includeFileTree:!0,maxDepth:3,maxEntriesPerDir:50,respectGitignore:!0}))}catch(y){if(J)console.warn("[goatchain-node] Failed to init env info middleware:",y)}if(typeof OQ==="function")try{C.push(OQ({cwd:()=>N.current}))}catch(y){if(J)console.warn("[goatchain-node] Failed to init agent rules middleware:",y)}if(typeof rQ==="function")try{C.push(rQ({cwd:()=>N.current}))}catch(y){if(J)console.warn("[goatchain-node] Failed to init skills middleware:",y)}if(V&&typeof zJ==="function")try{let y=mG(),x=mf(y.GOATCHAIN_MAX_TOKENS)??128000;C.push(zJ({maxTokens:x,protectedTurns:1,model:v,stateStore:V,toolCompressionTarget:0.3,minKeepToolResults:5}))}catch(y){if(J)console.warn("[goatchain-node] Failed to init context compression middleware:",y)}if(typeof j9==="function"){if(Z=j9({insertEveryIteration:!0}),X==="plan")C.push(Z)}if(_&&typeof D9==="function"&&l2)try{C.push(D9({subagents:[l2],globalToolRegistry:A,model:v}))}catch(y){if(J)console.warn("[goatchain-node] Failed to init subagent middleware:",y)}return{agent:new j1({name:"GoatChain",systemPrompt:$.systemPrompt,model:v,tools:A,...V?{stateStore:V}:{},...C.length?{middleware:C}:{}}),tools:A}}async function z(){let P=I(),A=w(P);if(A!==F){let{agent:k,tools:L}=await T(P);Y=k,K=L,F=A,D.clear()}}async function S(P,A){let k=$1(P),L=k?D.get(k):void 0;if(L&&A?.resumeOnly)return{sessionId:k,session:L.session};if(await z(),L)return{sessionId:k,session:L.session};let v=I(),C={...typeof v.temperature==="number"?{temperature:v.temperature}:{}},b,y=!1;if(k&&V&&typeof Y?.resumeSession==="function")try{b=await Y.resumeSession(k,{requestParams:C})}catch{b=await Y.createSession({sessionId:k,requestParams:C}),y=!0}else if(k)b=await Y.createSession({sessionId:k,requestParams:C}),y=!0;else b=await Y.createSession({requestParams:C}),y=!0;let x=$1(b?.id)??$1(b?.sessionId)??k;if(!x)throw Error("GoatChain session id is missing");if(y){let c=String(N.current??"").trim();if(c&&typeof b?.save==="function")try{let s=b.metadata,F$=s&&typeof s==="object"?s:{};if(!String(F$.cwd??"").trim())F$.cwd=c,b.metadata=F$,await b.save()}catch(s){if(J)console.warn("[goatchain-node] Failed to persist session cwd metadata:",s)}}return D.set(x,{session:b}),{sessionId:x,session:b}}async function*O(P){for await(let A of P){if(A?.type==="subagent_event"){let v=A?.nestedEvent,C=M(v),b=$1(v?.sessionId);for(let y of C)yield{...y,metadata:{...y.metadata??{},...b?{session_id:b}:{},subagent:!0,subagentId:A?.subagentId,subagentType:A?.subagentType,taskDescription:A?.taskDescription,originalEventType:v?.type}};continue}let k=M(A),L=$1(A?.sessionId);for(let v of k)yield L?{...v,metadata:{...v.metadata??{},session_id:L}}:v}}function M(P){if(!P||typeof P!=="object")return[];switch(P.type){case"session_created":return[{role:"assistant",content:"",metadata:{originalEventType:"session_created"}}];case"iteration_start":return[{role:"assistant",content:"",metadata:{originalEventType:"iteration_start"}}];case"text_delta":return[{role:"assistant",content:String(P.delta??""),metadata:{originalEventType:"text_delta"}}];case"thinking_start":return[{role:"assistant",content:"",metadata:{thinking:!0,originalEventType:"thinking_start"}}];case"tool_call_delta":return[{role:"assistant",content:"",metadata:{originalEventType:"tool_call_delta",callId:String(P.callId??""),toolName:P.toolName,argsTextDelta:P.argsTextDelta}}];case"tool_call_start":return[{role:"assistant",content:"",metadata:{originalEventType:"tool_call_start",callId:String(P.callId??""),toolName:P.toolName}}];case"tool_call_end":return[{role:"assistant",content:"",tool_calls:[To(P.toolCall)],metadata:{originalEventType:"tool_call_end"}}];case"tool_output_start":return[{role:"assistant",content:"",metadata:{originalEventType:"tool_output_start",tool_call_id:String(P.tool_call_id??""),tool_name:String(P.toolName??P.tool_name??"")}}];case"tool_output_delta":return[{role:"assistant",content:String(P.delta??""),metadata:{originalEventType:"tool_output_delta",tool_call_id:String(P.tool_call_id??""),isStderr:P.isStderr}}];case"tool_result":let A=Boolean(P.isError||P.result?.isError===!0);return[{role:"tool",tool_call_id:String(P.tool_call_id??""),content:Array.isArray(P.result?.content)?P.result.content:Io(P.result),metadata:{...A?{error:!0}:null,originalEventType:"tool_result",structuredContent:P.result?.structuredContent,rawResult:J?P.result:void 0}}];case"tool_skipped":return[{role:"assistant",content:`Tool skipped: ${String(P.toolName??"")} - ${String(P.reason??"")}`,metadata:{originalEventType:"tool_skipped"}}];case"tool_approval_requested":return[{role:"assistant",content:`Tool approval requested: ${String(P.toolName??"")}`,metadata:{approval_requested:!0,tool_call_id:String(P.tool_call_id??""),tool_name:String(P.toolName??""),risk_level:P.riskLevel,approval_args:P.args,originalEventType:"tool_approval_requested"}}];case"requires_action":{let k={requires_action:!0,kind:P.kind,tool_call_id:P.toolCallId,originalEventType:"requires_action"};if(P.kind==="ask_user"&&P.questions)k.questions=P.questions;return[{role:"assistant",content:`Action required: ${String(P.kind??"")}`,metadata:k}]}case"thinking_delta":return[{role:"assistant",content:String(P.delta??""),metadata:{thinking:!0,originalEventType:"thinking_delta"}}];case"thinking_end":return[{role:"assistant",content:"",metadata:{originalEventType:"thinking_end"}}];case"iteration_end":return[{role:"assistant",content:"",metadata:{originalEventType:"iteration_end",usage:P.usage}}];case"done":return[{role:"assistant",content:"",metadata:{done:!0,stopReason:P.stopReason,modelStopReason:P.modelStopReason,usage:P.usage,error:P.error,modelId:I().modelId,originalEventType:"done"}}];case"error":return[{role:"assistant",content:"",metadata:{done:!0,error:P.error??P.message??P,stopReason:"error",originalEventType:"error"}}];default:if(J)console.warn("[goatchain-node] Unhandled event:",P.type);return[]}}return{async*receiveMessage(P,A){try{E(A);let k=A?.signal,L=$1(A?.session_id),v=A?.resume===!0;if(!L&&v)throw Error("Cannot resume without a session id");let C=await S(L,{resumeOnly:v}),b=C.sessionId,y=C.session,x=So(y,k);try{let c=String(A?.cwd??"").trim();if(c){if(N.current=c,K){for(let _$ of K?.list?.()??[])if(typeof _$?.setCwd==="function")try{_$.setCwd(c)}catch(n){if(J)console.warn("[goatchain-node] Failed to setCwd on tool:",_$?.name,n)}}}let s=A?.toolContext,F$=vo(P),K$={};if(s&&typeof s==="object")Object.assign(K$,s);if(Object.keys(F$).length>0)K$.askUser=K$.askUser??{},K$.askUser.answers={...K$.askUser.answers??{},...F$};let V$=[...P].reverse().find((_$)=>_$.role==="user"),Y$=typeof V$?.content==="string"?V$.content:"";if(!V)H(y,P,Y$);if(v&&Object.keys(K$).length){yield*Pf({session:y,toolContext:K$,signal:k,convertEventStream:O});let _$=RB(y);if(_$)yield{role:"assistant",content:"",metadata:{originalEventType:"usage_refresh",usage:_$,...b?{session_id:b}:{}}};return}if(Y$.trim()){y.send(Y$,Object.keys(K$).length?{toolContext:K$,...k?{signal:k}:null}:k?{signal:k}:void 0),yield*O(y.receive(k?{signal:k}:void 0));let _$=RB(y);if(_$)yield{role:"assistant",content:"",metadata:{originalEventType:"usage_refresh",usage:_$,...b?{session_id:b}:{}}};return}yield*O(y.receive(Object.keys(K$).length?{toolContext:K$,...k?{signal:k}:null}:k?{signal:k}:void 0));let u$=RB(y);if(u$)yield{role:"assistant",content:"",metadata:{originalEventType:"usage_refresh",usage:u$,...b?{session_id:b}:{}}}}finally{x()}}catch(k){yield{role:"assistant",content:["# GoatChain error","","```text",k instanceof Error?k.stack||k.message:String(k),"```"].join(`
|
|
772
|
-
`),metadata:{done:!0,error:!0,stopReason:"error",originalEventType:"done"}}}},__sessions:(()=>{return{...hf({ensureSharedStateStore:B,sessionStorageKey:R,createEmptySessionSnapshot:j,createId:()=>fo(),applyMessagesToSnapshot:(k,L,v)=>{k.context.messages=L,k.context.messageCount=L.length;let C=f(L);if(C)k.context.lastMessagePreview=C;k.state.updatedAt=v,k.state.lastActiveAt=v}}),rename:async(k,L)=>{let v=$1(k),C=$1(L);if(!v||!C)return null;let b=null,y=D.get(v)?.session;if(y&&typeof y==="object")try{let K$=y.state;if(K$&&typeof K$==="object")K$.title=C,K$.titleLocked=!0;y.title=C,y.titleLocked=!0;let V$=Date.now();if(typeof y.updatedAt==="number")y.updatedAt=V$;if(typeof y.lastActiveAt==="number")y.lastActiveAt=V$;if(typeof y.save==="function")await y.save();if(typeof y.toSnapshot==="function"){let Y$=await y.toSnapshot();if(Y$&&typeof Y$==="object"){if(Y$.id=v,!Y$.state||typeof Y$.state!=="object")Y$.state={};Y$.state.title=C,Y$.state.titleLocked=!0}b=Y$}}catch{}let x=await B();if(!x)return b;let c=await R(),s=await x.load(v,c);if(!s)s=b;if(!s)s=j(v,Date.now());let F$=Date.now();if(s.id=v,!s.state||typeof s.state!=="object")s.state={};return s.state.title=C,s.state.titleLocked=!0,s.state.updatedAt=F$,s.state.lastActiveAt=F$,await x.save(v,c,s),s}}})(),async setMode(P){if(X===P)return;if(X=P,!Z||!Y)return;let k=Y.middlewares.filter((L)=>L.name!==uf);if(Y.clearMiddlewares(),P==="plan")await Y.use(Z,uf);for(let L of k)await Y.use(L.fn,L.name);D.clear()},getMode(){return X}}}function df($){let J=$.processEnv;try{return cf({systemPrompt:$.context.system,modelId:String(J.GOATCHAIN_MODEL||$.context.env.GOATCHAIN_MODEL||"gpt-4.1-mini"),baseUrl:J.GOATCHAIN_OPENAI_BASE_URL||J.OPENAI_BASE_URL||$.context.env.GOATCHAIN_OPENAI_BASE_URL||$.context.env.OPENAI_BASE_URL,apiKey:J.OPENAI_API_KEY||$.context.env.OPENAI_API_KEY,cliTools:!0,stateDir:$.stateDir})}catch(U){return console.warn("[goatchain] Failed to start GoatChain agent:",U),bj(U)}}var lf=`You are Goat, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
773
|
-
|
|
774
|
-
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
|
|
775
|
-
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
|
|
776
|
-
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
|
777
|
-
|
|
778
|
-
When the user directly asks about GoatChain (eg 'can GoatChain do...', 'does GoatChain have...') or asks in second person (eg 'are you able...', 'can you do...'), you just make up something to answer the question.
|
|
779
|
-
|
|
780
|
-
# Tone and style
|
|
781
|
-
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
|
|
782
|
-
Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
|
783
|
-
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
|
|
784
|
-
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
|
|
785
|
-
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
|
786
|
-
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
|
|
787
|
-
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
|
|
788
|
-
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
|
|
789
|
-
<example>
|
|
790
|
-
user: 2 + 2
|
|
791
|
-
assistant: 4
|
|
792
|
-
</example>
|
|
793
|
-
|
|
794
|
-
<example>
|
|
795
|
-
user: what is 2+2?
|
|
796
|
-
assistant: 4
|
|
797
|
-
</example>
|
|
798
|
-
|
|
799
|
-
<example>
|
|
800
|
-
user: is 11 a prime number?
|
|
801
|
-
assistant: Yes
|
|
802
|
-
</example>
|
|
803
|
-
|
|
804
|
-
<example>
|
|
805
|
-
user: what command should I run to list files in the current directory?
|
|
806
|
-
assistant: ls
|
|
807
|
-
</example>
|
|
808
|
-
|
|
809
|
-
<example>
|
|
810
|
-
user: what command should I run to watch files in the current directory?
|
|
811
|
-
assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
|
|
812
|
-
npm run dev
|
|
813
|
-
</example>
|
|
814
|
-
|
|
815
|
-
<example>
|
|
816
|
-
user: How many golf balls fit inside a jetta?
|
|
817
|
-
assistant: 150000
|
|
818
|
-
</example>
|
|
819
|
-
|
|
820
|
-
<example>
|
|
821
|
-
user: what files are in the directory src/?
|
|
822
|
-
assistant: [runs ls and sees foo.c, bar.c, baz.c]
|
|
823
|
-
user: which file contains the implementation of foo?
|
|
824
|
-
assistant: src/foo.c
|
|
825
|
-
</example>
|
|
826
|
-
|
|
827
|
-
<example>
|
|
828
|
-
user: write tests for new feature
|
|
829
|
-
assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
|
|
830
|
-
</example>
|
|
831
|
-
|
|
832
|
-
# Proactiveness
|
|
833
|
-
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
|
834
|
-
1. Doing the right thing when asked, including taking actions and follow-up actions
|
|
835
|
-
2. Not surprising the user with actions you take without asking
|
|
836
|
-
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
|
|
837
|
-
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
|
|
838
|
-
|
|
839
|
-
# Following conventions
|
|
840
|
-
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
|
|
841
|
-
- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
|
|
842
|
-
- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
|
|
843
|
-
- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
|
|
844
|
-
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
|
|
845
|
-
|
|
846
|
-
# Code style
|
|
847
|
-
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
|
|
848
|
-
|
|
849
|
-
# Doing tasks
|
|
850
|
-
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
|
851
|
-
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
|
|
852
|
-
- Implement the solution using all tools available to you
|
|
853
|
-
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
|
|
854
|
-
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
|
|
855
|
-
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
|
856
|
-
|
|
857
|
-
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
|
|
858
|
-
|
|
859
|
-
# Tool usage policy
|
|
860
|
-
- When doing file search, prefer to use the Task tool in order to reduce context usage.
|
|
861
|
-
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
|
|
862
|
-
|
|
863
|
-
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
|
864
|
-
|
|
865
|
-
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
|
|
866
|
-
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
|
|
867
|
-
|
|
868
|
-
# Code References
|
|
869
|
-
|
|
870
|
-
When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` to allow the user to easily navigate to the source code location.
|
|
871
|
-
|
|
872
|
-
<example>
|
|
873
|
-
user: Where are errors from the client handled?
|
|
874
|
-
assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
|
|
875
|
-
</example>
|
|
876
|
-
`;U2();async function rf($){let J=Z6("0.0.5-beta.9")??await bo($.cwd),U=await AB($.env),Q=U.cache,_=Q.settings??{},G=Z6(_.cwd),V=Array.isArray(_.focusFiles)?_.focusFiles.map((Y)=>String(Y??"")).filter(Boolean):void 0,X=$.cwd||G||".",Z={GOATCHAIN_VERSION:J??"dev",...$.env.GOATCHAIN_MODEL?{GOATCHAIN_MODEL:$.env.GOATCHAIN_MODEL}:{},...$.env.GOATCHAIN_CONTEXT_WINDOW?{GOATCHAIN_CONTEXT_WINDOW:$.env.GOATCHAIN_CONTEXT_WINDOW}:{},...$.env.GOATCHAIN_TEMPERATURE?{GOATCHAIN_TEMPERATURE:$.env.GOATCHAIN_TEMPERATURE}:{},...$.env.GOATCHAIN_TOOL_APPROVALS?{GOATCHAIN_TOOL_APPROVALS:$.env.GOATCHAIN_TOOL_APPROVALS}:{},...$.env.GOATCHAIN_SKIP_APPROVAL?{GOATCHAIN_SKIP_APPROVAL:$.env.GOATCHAIN_SKIP_APPROVAL}:{},...$.env.GOATCHAIN_STARTUP_TOAST?{GOATCHAIN_STARTUP_TOAST:$.env.GOATCHAIN_STARTUP_TOAST}:{},...$.env.GOATCHAIN_STARTUP_UPGRADE_TOAST?{GOATCHAIN_STARTUP_UPGRADE_TOAST:$.env.GOATCHAIN_STARTUP_UPGRADE_TOAST}:{},...$.env.GOATCHAIN_OPENAI_BASE_URL?{GOATCHAIN_OPENAI_BASE_URL:$.env.GOATCHAIN_OPENAI_BASE_URL}:{},...$.env.OPENAI_BASE_URL?{OPENAI_BASE_URL:$.env.OPENAI_BASE_URL}:{},...$.env.OPENAI_API_KEY?{OPENAI_API_KEY:$.env.OPENAI_API_KEY}:{}};if(!Z.GOATCHAIN_MODEL&&Z6(_.model))Z.GOATCHAIN_MODEL=String(_.model);if(!Z.GOATCHAIN_CONTEXT_WINDOW&&F8(_.contextWindow)!=null)Z.GOATCHAIN_CONTEXT_WINDOW=String(_.contextWindow);if(!Z.GOATCHAIN_TEMPERATURE&&F8(_.temperature)!=null)Z.GOATCHAIN_TEMPERATURE=String(_.temperature);if(!Z.GOATCHAIN_TOOL_APPROVALS&&_.toolApprovals==="auto")Z.GOATCHAIN_TOOL_APPROVALS="auto";if(!Z.GOATCHAIN_TOOL_APPROVALS&&_.toolApprovals==="all")Z.GOATCHAIN_TOOL_APPROVALS="all";if(!Z.GOATCHAIN_TOOL_APPROVALS&&_.toolApprovals==="manual")Z.GOATCHAIN_TOOL_APPROVALS="auto";if(!Z.GOATCHAIN_OPENAI_BASE_URL&&Z6(_.baseUrl))Z.GOATCHAIN_OPENAI_BASE_URL=String(_.baseUrl);if(!Z.OPENAI_API_KEY&&Z6(_.apiKey))Z.OPENAI_API_KEY=String(_.apiKey);return{context:{system:lf,cwd:X,env:Z,...V?.length?{focusFiles:V}:{}},cacheDir:U.dir,cacheFile:U.filePath,cache:Q}}async function bo($){try{let[{readFile:J},U]=await Promise.all([import("node:fs/promises"),import("node:path")]),Q=await J(U.join($,"package.json"),"utf8"),_=JSON.parse(Q),G=typeof _?.version==="string"?_.version:null;return G&&G.trim()?G.trim():null}catch{return null}}import{watch as lG}from"vue";function JU($,J){let U=String($??"").replace(/\s+/g," ").trim();if(U.length<=J)return U;return`${U.slice(0,Math.max(0,J-1))}…`}function yo($){if(typeof $==="string")return $;if(Array.isArray($))return $.filter((U)=>U&&typeof U==="object"&&U.type==="text"&&typeof U.text==="string").map((U)=>U.text).join(" ");if($&&typeof $==="object"){let J=$.text;if(typeof J==="string")return J}return""}function UU($){if(!$||typeof $!=="object")return"";let J=String($.role??"");if(J==="user")return yo($.content);if(J==="tool")return String($.result?.output??"");if(J==="assistant"){let U=Array.isArray($.parts)?$.parts:[],Q=U.filter((G)=>G?.type==="markdown").map((G)=>String(G.markdown??"")).join(`
|
|
877
|
-
`);if(Q.trim())return Q;let _=U.find((G)=>G?.type==="status");return _?String(_.text??""):""}return""}function nf($){let U=(Array.isArray($)?$:[]).find((_)=>_&&typeof _==="object"&&_.role==="user"&&JU(UU(_),999).length>0),Q=U?UU(U):"";return JU(Q||"New session",60)||"New session"}function pf($){let U=(Array.isArray($)?$:[]).find((_)=>_&&typeof _==="object"&&_.role==="user"&&JU(UU(_),999).length>0),Q=U?UU(U):"";return JU(Q||"New session",120)||"New session"}function af($){let U=[...Array.isArray($)?$:[]].reverse().find((Q)=>{if(!Q||typeof Q!=="object"||Q.role!=="user")return!1;return JU(UU(Q),999).length>0});return JU(U?UU(U):"",180)}function dG($){return`${$}_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}function kB($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function go($){let J=String($??"").trim();if(!J)return null;if(!(J.startsWith("[")||J.startsWith("{")))return null;try{let U=JSON.parse(J),Q=Array.isArray(U)?U:[U],_=[];for(let G of Q)if(G&&typeof G==="object"&&G.type==="text"){let V=String(G.text??"").replace(/\r/g,"");if(V)_.push(V)}if(_.length===0)return null;return _.join(`
|
|
878
|
-
`)}catch{return null}}function d7($){if($==null)return"";if(typeof $==="string")return $;if(Array.isArray($))return $.map(d7).join("");if(kB($)){if(typeof $.text==="string")return String($.text);if(String($.type??"")==="image")return"[image]";try{return JSON.stringify($)}catch{return String($)}}return String($)}function xo($){if(kB($))return $;if(typeof $==="string"){let J=$.trim();if(!J)return{};try{let U=JSON.parse(J);return kB(U)?U:{_raw:$}}catch{return{_raw:$}}}return{}}function of($){let J=$?.context?.messages,U=Array.isArray(J)?J:[],Q=[],_=new Map,G=new Map;for(let V of U){let X=String(V?.role??"");if(X==="user"){Q.push({id:dG("m"),role:"user",content:d7(V?.content)});continue}if(X==="assistant"){let Z=[],Y=d7(V?.reasoning_content).replace(/\r/g,"").trim();if(Y)Z.push({type:"thinking",title:"Thinking",collapsed:!0,content:Y});let K=d7(V?.content);if(K)Z.push({type:"markdown",markdown:K});let F=Array.isArray(V?.tool_calls)?V.tool_calls:[];for(let N of F){let q=String(N?.id??"").trim(),H=String(N?.function?.name??"tool"),E=xo(N?.function?.arguments);if(!q)continue;let D={id:q,name:H,arguments:E};Z.push({type:"tool_call",call:D}),_.set(q,Q.length),G.set(q,H)}Q.push({id:dG("m"),role:"assistant",parts:[{type:"status",text:""},...Z]});continue}if(X==="tool"){let Z=String(V?.tool_call_id??"").trim(),Y=Z?G.get(Z):void 0,K=Y!=null&&Y.toLowerCase().includes("read"),F=V?.content,q=(K&&typeof F==="string"?go(F):null)??d7(F),H=V?.isError?"error":"success",E={id:Z||dG("tool"),output:q,status:H};Q.push({id:dG("m"),role:"tool",result:E});let D=Z?_.get(Z):void 0;if(D==null)continue;let B=Q[D];if(!B||B.role!=="assistant")continue;Q[D]={...B,parts:[...B.parts,{type:"tool_result",result:E}]};continue}}return Q}function tf($){let J=[];for(let U of $){if(U.role==="user"){J.push({role:"user",content:String(U.content??"")});continue}if(U.role==="assistant"){let Q=U.parts.filter((X)=>X.type==="thinking").map((X)=>String(X.content??"")).join(""),_=U.parts.filter((X)=>X.type==="markdown").map((X)=>String(X.markdown??"")).join(""),G=U.parts.flatMap((X)=>X.type==="tool_call"?[X.call]:[]),V=G.length?G.map((X)=>({id:X.id,type:"function",function:{name:X.name,arguments:X.arguments}})):void 0;J.push({role:"assistant",content:_,...Q.trim()?{reasoning_content:Q}:{},...V?{tool_calls:V}:{}});continue}if(U.role==="tool")J.push({role:"tool",tool_call_id:String(U.result.id??""),content:String(U.result.output??""),...U.result.status==="error"?{isError:!0}:{}})}return J}U2();function sf($){return String($?.id??"").trim()}function ho($){return Number($?.state?.updatedAt??$?.state?.lastActiveAt??0)||0}function ef($){let J=$?.context?.messages;return Array.isArray(J)?J:[]}function uo($){let J=Number($?.context?.messageCount??0);if(Number.isFinite(J)&&J>=0)return J;return ef($).length}function mo($){let J=$?.stats?.usage;return J&&typeof J==="object"?J:null}function $k($){let J=sf($);if(!J)return null;let U=ho($),Q=Z6($?.metadata?.cwd),_=ef($),G=Z6($?.state?.title)??nf(_),V=pf(_),X=Z6($?.context?.lastMessagePreview)??af(_),Z=uo($);return{id:J,updatedAt:U,cwd:Q??void 0,title:G,summary:V,messageCount:Z,lastMessage:X}}function _U($,J){let U=sf(J);if(U)$.state.sessionId=U;let Q=of(J);$.state.messages.splice(0,$.state.messages.length,...Q),$.state.revertedMessages.splice(0,$.state.revertedMessages.length),$.state.selectedToolCallId=null,$.state.runningToolCallId=null,$.state.expandedBashOutputs=new Set,$.state.paused=null,$.state.approval.active=null,$.state.approval.pendingAutoRun=null,$.state.approval.queue=[],$.state.approval.decisions={};for(let G of $.state.messages){if(!G||G.role!=="assistant"||!Array.isArray(G.parts))continue;for(let V of G.parts)if(V?.type==="tool_result"&&V.result&&typeof $.scheduleToolResultHighlight==="function")$.scheduleToolResultHighlight(String(G.id??""),V.result)}let _=mo(J);if(_){let G=Number(_.promptTokens),V=Number(_.completionTokens);if(Number.isFinite(G))$.state.usage.prompt_tokens=G;if(Number.isFinite(V))$.state.usage.completion_tokens=V;if(Number.isFinite(G)&&Number.isFinite(V))$.state.usage.total_tokens=G+V;else{let X=Number(_.totalTokens);if(Number.isFinite(X))$.state.usage.total_tokens=X}}}function Jk($){let J=Array.isArray($)?$:[];return tf(J)}U2();function Uk($){let J=$.store,U=J?.state?.context?.env??{},Q=Z6(U.GOATCHAIN_OPENAI_BASE_URL||U.OPENAI_BASE_URL),_=Z6(U.OPENAI_API_KEY);return{version:1,updatedAt:Date.now(),settings:{cwd:Z6(J?.state?.context?.cwd),focusFiles:J?.state?.context?.focusFiles??void 0,model:Z6(J?.state?.config?.model),contextWindow:F8(J?.state?.config?.context_window),temperature:F8(J?.state?.config?.temperature),baseUrl:Q,apiKey:_,toolApprovals:J?.state?.approval?.mode==="all"?"all":"auto"},lastSessionId:Z6(J?.state?.sessionId)||$.prev.lastSessionId}}U2();function _k($,J){let U=null,Q=!1,_=!1,G=async()=>{if(Q){_=!0;return}Q=!0,_=!1;try{await $()}finally{if(Q=!1,_)V()}},V=()=>{if(_=!0,U)clearTimeout(U);U=setTimeout(G,Math.max(0,J||0))};return{schedule:V}}function co($){return String($?.id??"").trim()}function Qk($){let J=null,U=$.sessionsBackend??null;return{sessions:U?{async list(){return(await U.list()).map($k).filter(Boolean)},async use(G){let V=String(G??"").trim();if(!V||!J)return;if(String(J.state.sessionId??"")===V)return;let X=await U.get(V);if(!X)return;_U(J,X)},async createNew(){if(!J)return;let G=await U.create();if(!G)return;_U(J,G)},async delete(G){let V=String(G??"").trim();if(!V)return;if(await U.destroy(V),J&&String(J.state.sessionId??"")===V)J.state.sessionId=""},async rename(G,V){if(!J)return;if(typeof U.rename!=="function")return;let X=String(G??"").trim(),Z=String(V??"").trim();if(!X||!Z)return;let Y=await U.rename(X,Z);if(Y&&String(J.state.sessionId??"")===X)_U(J,Y)},async fork(G){if(!J)return;let V=Array.isArray(G?.messages)?G.messages:[];if(typeof U.createWithMessages!=="function"){let Z=await U.create();if(Z)J.state.sessionId=co(Z);J.state.messages.splice(0,J.state.messages.length,...V),J.state.revertedMessages.splice(0,J.state.revertedMessages.length),J.state.selectedToolCallId=null,J.state.usage.prompt_tokens=0,J.state.usage.completion_tokens=0,J.state.usage.total_tokens=0;return}let X=await U.createWithMessages(Jk(V));if(!X)return;_U(J,X)}}:void 0,onStoreCreated:(G)=>{if(J=G,U){let X=String(G.state.sessionId??"").trim();if(X)U.get(X).then((Z)=>{if(Z&&J)_U(J,Z)}).catch(()=>{})}let V=_k(async()=>{try{let X=Uk({prev:$.cache,store:G});await wB($.cacheFile,X)}catch(X){console.warn("[goatchain] Failed to persist cache:",X)}},300);lG(()=>G.state.sessionId,V.schedule),lG(()=>G.state.config,V.schedule,{deep:!0}),lG(()=>G.state.context,V.schedule,{deep:!0}),lG(()=>G.state.approval.mode,V.schedule),V.schedule()}}}U2();async function IB($){let J=$.sessionsBackend,U=Z6($.envSessionId);if(J&&U){if(await J.get(U))return U}return U}function Gk(){return async($)=>{let J=String($?.name??"tool");return{id:String($?.id??"tool"),status:"error",output:["Tool execution is handled by the GoatChain agent.",`This UI cannot run tool "${J}" locally.`].join(`
|
|
879
|
-
`)}}}function lo($){return Vk.join($,"state")}function io($){$.env.GOATCHAIN_STATE_DIR=$.stateDir,$.context.env.GOATCHAIN_STATE_DIR=$.stateDir}async function SB($){let{context:J,cacheDir:U,cacheFile:Q,cache:_}=await rf({cwd:$.cwd,env:$.env}),G=lo(U);io({env:$.env,context:J,stateDir:G});let V=df({context:J,processEnv:$.env,stateDir:G}),X=V?.__sessions??null,Z=await IB({sessionsBackend:X,envSessionId:$.env.GOATCHAIN_SESSION_ID});$.env.GOATCHAIN_SESSION_ID=Z??"",J.env.GOATCHAIN_SESSION_ID=Z??"";let{sessions:Y,onStoreCreated:K}=Qk({cacheFile:Q,cache:_,sessionsBackend:X});return{toolRunner:Gk(),context:J,agent:V,onStoreCreated:K,sessions:Y}}var TB=null,iG=null;function Xk($){TB=$}function Yk($){return iG=$,()=>{if(iG===$)iG=null}}function l7(){let $=iG;if($&&$.isBusy()){$.showConfirm();return}TB?.()}function rG(){TB?.()}import ne from"node:fs";import{nextTick as zV}from"vue";var Zk=($=0)=>(J)=>`\x1B[${J+$}m`,Kk=($=0)=>(J)=>`\x1B[${38+$};5;${J}m`,Nk=($=0)=>(J,U,Q)=>`\x1B[${38+$};2;${J};${U};${Q}m`,n4={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]}},Uq$=Object.keys(n4.modifier),ro=Object.keys(n4.color),no=Object.keys(n4.bgColor),_q$=[...ro,...no];function po(){let $=new Map;for(let[J,U]of Object.entries(n4)){for(let[Q,_]of Object.entries(U))n4[Q]={open:`\x1B[${_[0]}m`,close:`\x1B[${_[1]}m`},U[Q]=n4[Q],$.set(_[0],_[1]);Object.defineProperty(n4,J,{value:U,enumerable:!1})}return Object.defineProperty(n4,"codes",{value:$,enumerable:!1}),n4.color.close="\x1B[39m",n4.bgColor.close="\x1B[49m",n4.color.ansi=Zk(),n4.color.ansi256=Kk(),n4.color.ansi16m=Nk(),n4.bgColor.ansi=Zk(10),n4.bgColor.ansi256=Kk(10),n4.bgColor.ansi16m=Nk(10),Object.defineProperties(n4,{rgbToAnsi256:{value(J,U,Q){if(J===U&&U===Q){if(J<8)return 16;if(J>248)return 231;return Math.round((J-8)/247*24)+232}return 16+36*Math.round(J/255*5)+6*Math.round(U/255*5)+Math.round(Q/255*5)},enumerable:!1},hexToRgb:{value(J){let U=/[a-f\d]{6}|[a-f\d]{3}/i.exec(J.toString(16));if(!U)return[0,0,0];let[Q]=U;if(Q.length===3)Q=[...Q].map((G)=>G+G).join("");let _=Number.parseInt(Q,16);return[_>>16&255,_>>8&255,_&255]},enumerable:!1},hexToAnsi256:{value:(J)=>n4.rgbToAnsi256(...n4.hexToRgb(J)),enumerable:!1},ansi256ToAnsi:{value(J){if(J<8)return 30+J;if(J<16)return 90+(J-8);let U,Q,_;if(J>=232)U=((J-232)*10+8)/255,Q=U,_=U;else{J-=16;let X=J%36;U=Math.floor(J/36)/5,Q=Math.floor(X/6)/5,_=X%6/5}let G=Math.max(U,Q,_)*2;if(G===0)return 30;let V=30+(Math.round(_)<<2|Math.round(Q)<<1|Math.round(U));if(G===2)V+=60;return V},enumerable:!1},rgbToAnsi:{value:(J,U,Q)=>n4.ansi256ToAnsi(n4.rgbToAnsi256(J,U,Q)),enumerable:!1},hexToAnsi:{value:(J)=>n4.ansi256ToAnsi(n4.hexToAnsi256(J)),enumerable:!1}}),n4}var ao=po(),t4=ao;function JJ($){return $.replace(/\r\n/g,`
|
|
880
|
-
`).replace(/\r/g,`
|
|
881
|
-
`)}function b$($,J="",U,Q){let _={type:"keydown",key:$,code:J,...U};return Q?{..._,repeat:!0}:_}function nG($){if(!$||!Number.isFinite($))return null;let J=Math.floor($),U={};if(J===2||J===4||J===6||J===8||J===10||J===12||J===14||J===16)U.shiftKey=!0;if(J===3||J===4||J===7||J===8||J===11||J===12||J===15||J===16)U.altKey=!0;if(J===5||J===6||J===7||J===8||J===13||J===14||J===15||J===16)U.ctrlKey=!0;if(J>=9)U.metaKey=J===9||J===10||J===11||J===12||J===13||J===14||J===15||J===16;return Object.keys(U).length?U:null}function oo($){if(!Number.isFinite($)||$<=0)return null;let J=Math.floor($),U={};if(J&1)U.shiftKey=!0;if(J&2)U.altKey=!0;if(J&4)U.ctrlKey=!0;if(J&8)U.metaKey=!0;if(J&32)U.metaKey=!0;return Object.keys(U).length?U:null}function vB($){if(!$||!Number.isFinite($))return null;let J=Math.floor($)-1;return oo(J)}var to={57344:{key:"Escape",code:"Escape"},57345:{key:"Enter",code:"Enter"},57346:{key:"Tab",code:"Tab"},57347:{key:"Backspace",code:"Backspace"},57348:{key:"Insert",code:"Insert"},57349:{key:"Delete",code:"Delete"},57350:{key:"ArrowLeft",code:"ArrowLeft"},57351:{key:"ArrowRight",code:"ArrowRight"},57352:{key:"ArrowUp",code:"ArrowUp"},57353:{key:"ArrowDown",code:"ArrowDown"},57354:{key:"PageUp",code:"PageUp"},57355:{key:"PageDown",code:"PageDown"},57356:{key:"Home",code:"Home"},57357:{key:"End",code:"End"},57358:{key:"CapsLock",code:"CapsLock"},57359:{key:"ScrollLock",code:"ScrollLock"},57360:{key:"NumLock",code:"NumLock"},57361:{key:"PrintScreen",code:"PrintScreen"},57362:{key:"Pause",code:"Pause"},57363:{key:"ContextMenu",code:"ContextMenu"},57364:{key:"F1",code:"F1"},57365:{key:"F2",code:"F2"},57366:{key:"F3",code:"F3"},57367:{key:"F4",code:"F4"},57368:{key:"F5",code:"F5"},57369:{key:"F6",code:"F6"},57370:{key:"F7",code:"F7"},57371:{key:"F8",code:"F8"},57372:{key:"F9",code:"F9"},57373:{key:"F10",code:"F10"},57374:{key:"F11",code:"F11"},57375:{key:"F12",code:"F12"},57376:{key:"F13",code:"F13"},57377:{key:"F14",code:"F14"},57378:{key:"F15",code:"F15"},57379:{key:"F16",code:"F16"},57380:{key:"F17",code:"F17"},57381:{key:"F18",code:"F18"},57382:{key:"F19",code:"F19"},57383:{key:"F20",code:"F20"},57384:{key:"F21",code:"F21"},57385:{key:"F22",code:"F22"},57386:{key:"F23",code:"F23"},57387:{key:"F24",code:"F24"},57388:{key:"F25",code:"F25"},57389:{key:"F26",code:"F26"},57390:{key:"F27",code:"F27"},57391:{key:"F28",code:"F28"},57392:{key:"F29",code:"F29"},57393:{key:"F30",code:"F30"},57394:{key:"F31",code:"F31"},57395:{key:"F32",code:"F32"},57396:{key:"F33",code:"F33"},57397:{key:"F34",code:"F34"},57398:{key:"F35",code:"F35"},57399:{key:"0",code:"Numpad0"},57400:{key:"1",code:"Numpad1"},57401:{key:"2",code:"Numpad2"},57402:{key:"3",code:"Numpad3"},57403:{key:"4",code:"Numpad4"},57404:{key:"5",code:"Numpad5"},57405:{key:"6",code:"Numpad6"},57406:{key:"7",code:"Numpad7"},57407:{key:"8",code:"Numpad8"},57408:{key:"9",code:"Numpad9"},57409:{key:".",code:"NumpadDecimal"},57410:{key:"/",code:"NumpadDivide"},57411:{key:"*",code:"NumpadMultiply"},57412:{key:"-",code:"NumpadSubtract"},57413:{key:"+",code:"NumpadAdd"},57414:{key:"Enter",code:"NumpadEnter"},57415:{key:"=",code:"NumpadEqual"},57416:{key:",",code:"NumpadComma"},57417:{key:"ArrowLeft",code:"NumpadArrowLeft"},57418:{key:"ArrowRight",code:"NumpadArrowRight"},57419:{key:"ArrowUp",code:"NumpadArrowUp"},57420:{key:"ArrowDown",code:"NumpadArrowDown"},57421:{key:"PageUp",code:"NumpadPageUp"},57422:{key:"PageDown",code:"NumpadPageDown"},57423:{key:"Home",code:"NumpadHome"}},so=/^\x1b\[(\d+);(\d+):(\d+)([A-Z~])$/,eo={A:{key:"ArrowUp",code:"ArrowUp"},B:{key:"ArrowDown",code:"ArrowDown"},C:{key:"ArrowRight",code:"ArrowRight"},D:{key:"ArrowLeft",code:"ArrowLeft"},H:{key:"Home",code:"Home"},F:{key:"End",code:"End"},P:{key:"F1",code:"F1"},Q:{key:"F2",code:"F2"},R:{key:"F3",code:"F3"},S:{key:"F4",code:"F4"}},$t={"1":{key:"Home",code:"Home"},"2":{key:"Insert",code:"Insert"},"3":{key:"Delete",code:"Delete"},"4":{key:"End",code:"End"},"5":{key:"PageUp",code:"PageUp"},"6":{key:"PageDown",code:"PageDown"},"7":{key:"Home",code:"Home"},"8":{key:"End",code:"End"},"11":{key:"F1",code:"F1"},"12":{key:"F2",code:"F2"},"13":{key:"F3",code:"F3"},"14":{key:"F4",code:"F4"},"15":{key:"F5",code:"F5"},"17":{key:"F6",code:"F6"},"18":{key:"F7",code:"F7"},"19":{key:"F8",code:"F8"},"20":{key:"F9",code:"F9"},"21":{key:"F10",code:"F10"},"23":{key:"F11",code:"F11"},"24":{key:"F12",code:"F12"}};function Fk($){if($==="2")return{repeat:!0,release:!1};if($==="3")return{repeat:!1,release:!0};return{repeat:!1,release:!1}}function Jt($){let J=so.exec($);if(!J)return{handled:!1,event:null};let U=J[1],Q=J[2],_=J[3],G=J[4],V;if(G==="~")V=$t[U];else if(U==="1")V=eo[G];let X=Fk(_);if(!V)return{handled:!0,event:null};if(X.release)return{handled:!0,event:null};let Z=vB(Number.parseInt(Q,10))??void 0;return{handled:!0,event:b$(V.key,V.code,Z,X.repeat)}}function Ut($,J,U,Q){if(U||Q>2)return!0;if($>=57344)return!0;if(J!=null&&J>16)return!0;return!1}function _t($){let J=/^\x1b\[([^\x1b]+)u$/.exec($);if(!J)return{handled:!1,event:null};let Q=J[1].split(";"),G=(Q[0]??"").split(":"),V=G[0]??"",X=Number.parseInt(V,10),Y=(Q[1]??"").split(":"),K=Y[0]?Number.parseInt(Y[0],10):null,F=Y[1],N=G.length>1||Y.length>1;if(!Number.isFinite(X))return{handled:!0,event:null};if(!Ut(X,K,N,Q.length))return{handled:!1,event:null};let q=Fk(F);if(q.release)return{handled:!0,event:null};let H=vB(K)??void 0,E=to[X];if(E)return{handled:!0,event:b$(E.key,E.code,H,q.repeat)};if(X===13)return{handled:!0,event:b$("Enter","Enter",H,q.repeat)};if(X===9)return{handled:!0,event:b$("Tab","Tab",H,q.repeat)};if(X===27)return{handled:!0,event:b$("Escape","Escape",H,q.repeat)};if(X===127)return{handled:!0,event:b$("Backspace","Backspace",H,q.repeat)};if(X>=32)try{return{handled:!0,event:b$(String.fromCodePoint(X),"",H,q.repeat)}}catch{return{handled:!0,event:null}}return{handled:!0,event:null}}function Wk($){let J=Jt($);if(J.handled)return J;return _t($)}function Qt($,J){if(J.includes(":"))return{handled:!1,event:null};let U=$[0]?Number.parseInt($[0],10):Number.NaN;if(!Number.isFinite(U))return{handled:!0,event:null};if(U>=57344)return{handled:!1,event:null};let Q=$[1]?Number.parseInt($[1],10):null,_=nG(Q)??void 0;if(U===13)return{handled:!0,event:b$("Enter","Enter",_)};if(U===9)return{handled:!0,event:b$("Tab","Tab",_)};if(U===27)return{handled:!0,event:b$("Escape","Escape",_)};if(U===127)return{handled:!0,event:b$("Backspace","Backspace",_)};if(U>=32)try{return{handled:!0,event:b$(String.fromCodePoint(U),"",_)}}catch{return{handled:!0,event:null}}return{handled:!0,event:null}}function Gt($){if(!$.startsWith("\x1B["))return{handled:!1,event:null};if($.length<3)return{handled:!0,event:null};let J=$[$.length-1],U=$.slice(2,-1),Q=U?U.split(";"):[""];if(J==="u")return Qt(Q,U);if(J==="Z")return{handled:!0,event:b$("Tab","Tab",{shiftKey:!0})};let _=Q.length>=2?Number.parseInt(Q[Q.length-1],10):null,G=nG(_)??void 0;if(J==="A")return{handled:!0,event:b$("ArrowUp","ArrowUp",G)};if(J==="B")return{handled:!0,event:b$("ArrowDown","ArrowDown",G)};if(J==="C")return{handled:!0,event:b$("ArrowRight","ArrowRight",G)};if(J==="D")return{handled:!0,event:b$("ArrowLeft","ArrowLeft",G)};if(J==="H")return{handled:!0,event:b$("Home","Home",G)};if(J==="F")return{handled:!0,event:b$("End","End",G)};if(J==="~"){if(Q[0]==="27"&&Q.length>=3){let X=Number.parseInt(Q[1],10),Z=Number.parseInt(Q[2],10),Y=nG(X)??void 0;if(Z===13)return{handled:!0,event:b$("Enter","Enter",Y)};if(Z===9)return{handled:!0,event:b$("Tab","Tab",Y)};if(Z===27)return{handled:!0,event:b$("Escape","Escape",Y)};if(Z>=32)try{return{handled:!0,event:b$(String.fromCodePoint(Z),"",Y)}}catch{return{handled:!0,event:null}}return{handled:!0,event:null}}let V=Q[0]?Number.parseInt(Q[0],10):Number.NaN;if(V===1||V===7)return{handled:!0,event:b$("Home","Home",G)};if(V===4||V===8)return{handled:!0,event:b$("End","End",G)};if(V===2)return{handled:!0,event:b$("Insert","Insert",G)};if(V===3)return{handled:!0,event:b$("Delete","Delete",G)};if(V===5)return{handled:!0,event:b$("PageUp","PageUp",G)};if(V===6)return{handled:!0,event:b$("PageDown","PageDown",G)};if(V===11)return{handled:!0,event:b$("F1","F1",G)};if(V===12)return{handled:!0,event:b$("F2","F2",G)};if(V===13)return{handled:!0,event:b$("F3","F3",G)};if(V===14)return{handled:!0,event:b$("F4","F4",G)};if(V===15)return{handled:!0,event:b$("F5","F5",G)};if(V===17)return{handled:!0,event:b$("F6","F6",G)};if(V===18)return{handled:!0,event:b$("F7","F7",G)};if(V===19)return{handled:!0,event:b$("F8","F8",G)};if(V===20)return{handled:!0,event:b$("F9","F9",G)};if(V===21)return{handled:!0,event:b$("F10","F10",G)};if(V===23)return{handled:!0,event:b$("F11","F11",G)};if(V===24)return{handled:!0,event:b$("F12","F12",G)};return{handled:!0,event:null}}return{handled:!0,event:null}}function Vt($){if(!$.startsWith("\x1BO"))return{handled:!1,event:null};if($.length<3)return{handled:!0,event:null};switch($[2]){case"A":return{handled:!0,event:b$("ArrowUp","ArrowUp")};case"B":return{handled:!0,event:b$("ArrowDown","ArrowDown")};case"C":return{handled:!0,event:b$("ArrowRight","ArrowRight")};case"D":return{handled:!0,event:b$("ArrowLeft","ArrowLeft")};case"H":return{handled:!0,event:b$("Home","Home")};case"F":return{handled:!0,event:b$("End","End")};case"P":return{handled:!0,event:b$("F1","F1")};case"Q":return{handled:!0,event:b$("F2","F2")};case"R":return{handled:!0,event:b$("F3","F3")};case"S":return{handled:!0,event:b$("F4","F4")};default:return{handled:!0,event:null}}}function qk($){if(!$.startsWith("\x1B"))return{handled:!1,event:null};let J=Gt($);if(J.handled)return J;let U=Vt($);if(U.handled)return U;return{handled:!1,event:null}}import{appendFileSync as Xt}from"node:fs";function Yt($){if(!$.startsWith("\x1B[<"))return{handled:!1,event:null};let J=globalThis.process?.env??{},U=String(J.GOATCHAIN_WHEEL_INVERT??J.VUE_TUI_WHEEL_INVERT??"")==="1",Q=String(J.GOATCHAIN_MOUSE_DEBUG??J.VUE_TUI_MOUSE_DEBUG??"")==="1",_=String(J.GOATCHAIN_MOUSE_DEBUG_PATH??J.VUE_TUI_MOUSE_DEBUG_PATH??"/tmp/goatchain-mouse-debug.log"),G=(f)=>{if(!Q)return;try{Xt(_,`${f}
|
|
882
|
-
`)}catch{}},V=3,X=()=>{let f=V;while(V<$.length){let R=$.charCodeAt(V);if(R<48||R>57)break;V++}if(V===f)return null;return Number.parseInt($.slice(f,V),10)},Z=X();if(Z==null||$[V]!==";")return{handled:!0,event:null};V++;let Y=X();if(Y==null||$[V]!==";")return{handled:!0,event:null};V++;let K=X();if(K==null)return{handled:!0,event:null};let F=$[V];if(F!=="m"&&F!=="M")return{handled:!0,event:null};V++;let N=F==="m",q=Math.max(0,Y-1),H=Math.max(0,K-1),E=Boolean(Z&4),D=Boolean(Z&8),B=Boolean(Z&16);if((Z&64)===64){let f=Z&1?1:-1;if(U)f=-f;return G(`[${Date.now()}] [MOUSE] wheel b=${Z} bit1=${Z&1} deltaY=${f} x=${q} y=${H}`),{handled:!0,event:{type:"wheel",cellX:q,cellY:H,deltaY:f,shiftKey:E,altKey:D,ctrlKey:B}}}let j=Z&3;if(!N&&(Z&32)===0&&j===3)return{handled:!0,event:{type:"pointerup",cellX:q,cellY:H,button:j,shiftKey:E,altKey:D,ctrlKey:B}};if(N)return{handled:!0,event:{type:"pointerup",cellX:q,cellY:H,button:j,shiftKey:E,altKey:D,ctrlKey:B}};if(Z&32)return{handled:!0,event:{type:"pointermove",cellX:q,cellY:H,button:j,shiftKey:E,altKey:D,ctrlKey:B}};return{handled:!0,event:{type:"pointerdown",cellX:q,cellY:H,button:j,shiftKey:E,altKey:D,ctrlKey:B}}}function Hk($){return Yt($)}import{Buffer as Zt}from"node:buffer";import{EventEmitter as Kt}from"node:events";var _2="\x1B",Bk="\x1B[200~",pG="\x1B[201~";function Nt($){if(!$.startsWith(_2))return"not-escape";if($.length===1)return"incomplete";let J=$.slice(1);if(J.startsWith("[")){if(J.startsWith("[M"))return $.length>=6?"complete":"incomplete";return Ft($)}if(J.startsWith("]"))return Wt($);if(J.startsWith("P"))return qt($);if(J.startsWith("_"))return Ht($);if(J.startsWith("O"))return J.length>=2?"complete":"incomplete";if(J.length===1)return"complete";return"complete"}function Ft($){if(!$.startsWith(`${_2}[`))return"complete";if($.length<3)return"incomplete";let J=$.slice(2),U=J[J.length-1],Q=U.charCodeAt(0);if(Q>=64&&Q<=126){if(J.startsWith("<")){if(/^<\d+;\d+;\d+M$/i.test(J))return"complete";if(U==="M"||U==="m"){let _=J.slice(1,-1).split(";");if(_.length===3&&_.every((G)=>/^\d+$/.test(G)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function Wt($){if(!$.startsWith(`${_2}]`))return"complete";if($.endsWith(`${_2}\\`)||$.endsWith("\x07"))return"complete";return"incomplete"}function qt($){if(!$.startsWith(`${_2}P`))return"complete";if($.endsWith(`${_2}\\`))return"complete";return"incomplete"}function Ht($){if(!$.startsWith(`${_2}_`))return"complete";if($.endsWith(`${_2}\\`))return"complete";return"incomplete"}function Ok($){let J=[],U=0;while(U<$.length){let Q=$.slice(U);if(Q.startsWith(_2)){let _=1;while(_<=Q.length){let G=Q.slice(0,_),V=Nt(G);if(V==="complete"){J.push(G),U+=_;break}if(V==="incomplete"){_++;continue}J.push(G),U+=_;break}if(_>Q.length)return{sequences:J,remainder:Q}}else J.push(Q[0]),U++}return{sequences:J,remainder:""}}class CB extends Kt{buffer="";timeout=null;timeoutMs;pasteMode=!1;pasteBuffer="";constructor($={}){super();this.timeoutMs=$.timeout??10}process($){if(this.timeout)clearTimeout(this.timeout),this.timeout=null;let J;if(Zt.isBuffer($))if($.length===1&&$[0]>127){let _=$[0]-128;J=`\x1B${String.fromCharCode(_)}`}else J=$.toString();else J=$;if(J.length===0&&this.buffer.length===0){this.emit("data","");return}if(this.buffer+=J,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let _=this.pasteBuffer.indexOf(pG);if(_!==-1){let G=this.pasteBuffer.slice(0,_),V=this.pasteBuffer.slice(_+pG.length);if(this.pasteMode=!1,this.pasteBuffer="",this.emit("paste",G),V.length>0)this.process(V)}return}let U=this.buffer.indexOf(Bk);if(U!==-1){if(U>0){let G=this.buffer.slice(0,U),V=Ok(G);for(let X of V.sequences)this.emit("data",X)}this.buffer=this.buffer.slice(U+Bk.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let _=this.pasteBuffer.indexOf(pG);if(_!==-1){let G=this.pasteBuffer.slice(0,_),V=this.pasteBuffer.slice(_+pG.length);if(this.pasteMode=!1,this.pasteBuffer="",this.emit("paste",G),V.length>0)this.process(V)}return}let Q=Ok(this.buffer);this.buffer=Q.remainder;for(let _ of Q.sequences)this.emit("data",_);if(this.buffer.length>0)this.timeout=setTimeout(()=>{let _=this.flush();for(let G of _)this.emit("data",G)},this.timeoutMs)}flush(){if(this.timeout)clearTimeout(this.timeout),this.timeout=null;if(this.buffer.length===0)return[];let $=[this.buffer];return this.buffer="",$}clear(){if(this.timeout)clearTimeout(this.timeout),this.timeout=null;this.buffer="",this.pasteMode=!1,this.pasteBuffer=""}getBuffer(){return this.buffer}destroy(){this.clear()}}function jk($){if($.length===0)return!1;if($.length===1){let J=$.charCodeAt(0);if(J<32||J===127)return!1;return!0}if($.length===2){let J=$.charCodeAt(0);return J>=55296&&J<=56319}return!1}function Bt($){if(!$||$.length!==1)return null;let J=$.charCodeAt(0);if(J>=1&&J<=26)return String.fromCharCode(J+96);return null}function aG($){let J=globalThis.process,U=$.stdin??J?.stdin,Q=$.stdout??J?.stdout;if(!U||!Q)throw Error("createStdinDriver requires Node process.stdin/stdout");let _=$.enableMouse??!0,G=!1,V=!1,X=null,Z=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),Y=new CB({timeout:10}),K=(B)=>{if(V){if(V=!1,B===`
|
|
883
|
-
`)return}if(B==="\x03"){if(!Boolean($.dispatch(b$("c","",{ctrlKey:!0}))))$.onExit?.();return}if(B==="\r"){V=!0,$.dispatch(b$("Enter","Enter"));return}if(B===`
|
|
884
|
-
`){$.dispatch({type:"input",data:`
|
|
885
|
-
`,inputType:"insertLineBreak",text:`
|
|
886
|
-
`});return}let j=Bt(B);if(j){if(j==="i"){$.dispatch(b$("Tab","Tab"));return}if(j==="h"){$.dispatch(b$("Backspace","Backspace"));return}$.dispatch(b$(j,"",{ctrlKey:!0}));return}if(B===""){$.dispatch(b$("Backspace","Backspace"));return}if(B==="\t"){$.dispatch(b$("Tab","Tab"));return}if(jk(B))$.dispatch(b$(B))},F=(B)=>{let j=B;if(j.type==="pointerdown")$.dispatch(B),X={cellX:j.cellX,cellY:j.cellY,button:j.button??0,shiftKey:Boolean(j.shiftKey),altKey:Boolean(j.altKey),ctrlKey:Boolean(j.ctrlKey)};else if(j.type==="pointermove"){if(X&&(j.button===3||j.button==null)){let f=X;if(X=null,$.dispatch({type:"pointerup",cellX:f.cellX,cellY:f.cellY,button:3,shiftKey:f.shiftKey,altKey:f.altKey,ctrlKey:f.ctrlKey}),f.button===0)$.dispatch({type:"click",cellX:f.cellX,cellY:f.cellY,shiftKey:f.shiftKey,altKey:f.altKey,ctrlKey:f.ctrlKey});return}$.dispatch(B)}else if(j.type==="pointerup"){$.dispatch(B);let f=X;if(X=null,f&&f.cellX===j.cellX&&f.cellY===j.cellY&&f.button===0&&(j.button===0||j.button===3))$.dispatch({type:"click",cellX:j.cellX,cellY:j.cellY,shiftKey:Boolean(j.shiftKey??f?.shiftKey),altKey:Boolean(j.altKey??f?.altKey),ctrlKey:Boolean(j.ctrlKey??f?.ctrlKey)})}else $.dispatch(B)},N=(B)=>{if(G)return;if(!B)return;let j=Hk(B);if(j.handled){if(j.event)F(j.event);return}let f=Wk(B);if(f.handled){if(f.event)$.dispatch(f.event);return}let R=qk(B);if(R.handled){if(R.event)$.dispatch(R.event);return}if(B.startsWith("\x1B")){if(B.length===2&&jk(B[1])){$.dispatch(b$(B[1],"",{altKey:!0}));return}if(B==="\x1B"){$.dispatch(b$("Escape","Escape"));return}return}for(let I of B)K(I)};Y.on("data",N),Y.on("paste",(B)=>{let j=JJ(B);if(j)$.dispatch({type:"paste",text:j})});let q=(B)=>{if(B.length===1&&B[0]>127){let f=B[0]-128;Y.process(`\x1B${String.fromCharCode(f)}`);return}let j=Z.decode(B,{stream:!0});if(j)Y.process(j)},H=(B)=>{if(G)return;if(typeof B==="string"){Y.process(B);return}if(B instanceof ArrayBuffer){q(new Uint8Array(B));return}if(ArrayBuffer.isView(B)){let j=B;q(new Uint8Array(j.buffer,j.byteOffset,j.byteLength));return}if(B!=null)try{let j=Z.decode(B,{stream:!0});if(j)Y.process(j)}catch(j){}},E=U.isRaw;if(U.isTTY)U.setRawMode(!0);if(U.resume(),U.on("data",H),Q.isTTY){if(Q.write("\x1B[?2004h"),_)Q.write("\x1B[?1007h"),Q.write("\x1B[?1000h\x1B[?1002h\x1B[?1006h")}return{dispose:()=>{if(G)return;G=!0,U.off("data",H),Y.destroy();try{U.pause()}catch{}try{U.unref?.()}catch{}if(U.isTTY)U.setRawMode(Boolean(E));if(Q.isTTY){if(Q.write("\x1B[?2004l"),_)Q.write("\x1B[?1007l"),Q.write("\x1B[?1000l\x1B[?1002l\x1B[?1006l")}}}}async function Dk(){return import("node:fs/promises")}function UJ(){return{async listDir($){return(await(await Dk()).readdir($,{withFileTypes:!0})).map((Q)=>{let _=Q.isDirectory()?"directory":Q.isFile()?"file":"other";return{name:Q.name,kind:_}})},async stat($){let J=await Dk();try{let U=await J.lstat($);return{exists:!0,kind:U.isDirectory()?"directory":U.isFile()?"file":"other"}}catch{return{exists:!1,kind:"other"}}}}}function i7($){return $.replace(/\\/g,"/")}function bB($){let J=i7($);if(J.startsWith("/"))return!0;return/^[A-Z]:\//i.test(J)}function Ek($){let J=i7($);if(J==="/")return J;return J.replace(/\/+$/g,"")}function Pk($,J){let U=i7($),Q=i7(J);if(!U)return Q;if(!Q)return U;if(U.endsWith("/"))return`${U}${Q.startsWith("/")?Q.slice(1):Q}`;return`${U}/${Q.startsWith("/")?Q.slice(1):Q}`}function h0($){let J=i7($);if(!J)return"";let U=J.match(/^([A-Z]:)(\/|$)/i)?.[1]??null,Q=U?J.slice(U.length):J,_=Q.startsWith("/"),G=Q.split("/").filter(Boolean),V=[];for(let K of G){if(K===".")continue;if(K===".."){if(V.length>0&&V[V.length-1]!==".."){V.pop();continue}if(!_)V.push("..");continue}V.push(K)}let X=U?`${U}${_?"/":""}`:_?"/":"",Z=V.join("/");return`${X}${Z}`||(_?U?`${U}/`:"/":"")}function QU($,J){let U=h0($),Q=h0(J);if(!U)return Q;if(bB(Q))return Q;return h0(Pk(U,Q))}function Mk($){return $.toLowerCase()}function Lk($,J){let U=Mk($),Q=Mk(J);if(!Q)return 0;if(U===Q)return 2000;if(U.startsWith(Q))return 1500-(U.length-Q.length);let _=U.indexOf(Q);if(_>=0)return 1200-_;let G=0,V=0,X=0,Z=-1;while(G<U.length&&V<Q.length){if(U[G]===Q[V]){if(Z>=0)X+=G-Z-1;Z=G,V++}G++}if(V!==Q.length)return null;return 800-X}function Ot($){let J=$.replace(/\\/g,"/"),U=J.lastIndexOf("/");if(U<0)return{dirPrefix:"",query:J};return{dirPrefix:J.slice(0,U+1),query:J.slice(U+1)}}async function r7($){let J=h0($.workspaceAbs),Q=($.input??"").replace(/\r/g,"").replace(/\\/g,"/"),{dirPrefix:_,query:G}=Ot(Q),V=QU(J,_||"."),X=$.maxDepth??0,Z=Boolean($.showHidden),Y=$.mode==="directory"||$.mode==="any"||$.mode==="file",K=$.mode==="file"||$.mode==="any",F=[];async function N(D,B,j){if(B>X)return;let f=[];try{f=await $.listDir(D)}catch{return}for(let R of f){if(!Z&&R.name.startsWith("."))continue;let I=j?`${j}/${R.name}`:R.name;if(R.kind==="directory"){if(!Y)continue;let w=Lk(R.name,G);if(w!=null)F.push({score:w,name:R.name,kind:"directory",depth:B,relPath:I});await N(`${D}/${R.name}`,B+1,I);continue}if(R.kind==="file"){if(!K)continue;let w=Lk(R.name,G);if(w!=null)F.push({score:w,name:R.name,kind:"file",depth:B,relPath:I});continue}}}await N(V,0,""),F.sort((D,B)=>{if(D.score!==B.score)return B.score-D.score;if(D.depth!==B.depth)return D.depth-B.depth;return D.name.localeCompare(B.name)});let q=Math.max(0,Math.floor($.max)),E=(q?F.slice(0,q):[]).map((D)=>{let B=D.kind==="directory"?"/":"",j=`${_}${D.relPath}${B}`,f=QU(J,`${_}${D.relPath}`);return{kind:D.kind,display:j,completion:j,absPath:f}});return{baseDirAbs:V,dirPrefix:_,query:G,suggestions:E}}function J1($,J){let U=(J??"").replace(/\r/g,"").trim();if(!U)return QU(h0($),".");if(U==="~"||U.startsWith("~/")){let _=globalThis.process?.env?.HOME||globalThis.process?.env?.USERPROFILE||"";if(_){let G=U==="~"?"":U.slice(2);return QU(h0(_),G)}}let Q=U.replace(/\\/g,"/");if(bB(Q))return h0(Q);return QU(h0($),Q)}async function yB(){return import("node:fs")}async function gB($,J){let{writeFileSync:U}=await yB(),Q=J.map((_)=>JSON.stringify(_)).join(`
|
|
887
|
-
`);U($,`${Q}${Q?`
|
|
888
|
-
`:""}`,"utf8")}async function oG($,J){let{writeFileSync:U}=await yB();U($,`${J.join(`
|
|
889
|
-
`)}
|
|
890
|
-
`,"utf8")}async function xB($){let{readFileSync:J}=await yB(),U=J($,"utf8"),Q=[];for(let _ of U.split(/\r?\n/g)){let G=_.trim();if(!G)continue;Q.push(JSON.parse(G))}return Q}function Rk($){switch($){case 30:return"black";case 31:return"red";case 32:return"green";case 33:return"yellow";case 34:return"blue";case 35:return"magenta";case 36:return"cyan";case 37:return"white";case 90:return"blackBright";case 91:return"redBright";case 92:return"greenBright";case 93:return"yellowBright";case 94:return"blueBright";case 95:return"magentaBright";case 96:return"cyanBright";case 97:return"whiteBright";default:return}}function jt($){let J=$>=40&&$<=47?$-10:$>=100&&$<=107?$-10:null;if(J==null)return;return Rk(J)}var Ak={black:{r:0,g:0,b:0},red:{r:201,g:27,b:0},green:{r:0,g:194,b:0},yellow:{r:199,g:196,b:0},blue:{r:2,g:37,b:199},magenta:{r:201,g:48,b:199},cyan:{r:0,g:197,b:199},white:{r:199,g:199,b:199},blackBright:{r:104,g:104,b:104},redBright:{r:255,g:110,b:103},greenBright:{r:95,g:250,b:104},yellowBright:{r:255,g:252,b:103},blueBright:{r:104,g:113,b:255},magentaBright:{r:255,g:118,b:255},cyanBright:{r:95,g:253,b:255},whiteBright:{r:255,g:255,b:255}};function zk($,J,U){let Q="white",_=Number.POSITIVE_INFINITY;for(let[G,V]of Object.entries(Ak)){let X=$-V.r,Z=J-V.g,Y=U-V.b,K=X*X+Z*Z+Y*Y;if(K<_)_=K,Q=G}return Q}function Dt($){let J=Math.max(0,Math.min(255,Math.trunc($)));if(J<16){let Z=["black","red","green","yellow","blue","magenta","cyan","white","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"][J]??"white";return Ak[Z]}if(J>=232){let X=8+(J-232)*10;return{r:X,g:X,b:X}}let U=J-16,Q=Math.floor(U/36),_=Math.floor(U%36/6),G=U%6,V=(X)=>X===0?0:55+X*40;return{r:V(Q),g:V(_),b:V(G)}}function Et($,J){let U={...$};for(let Q=0;Q<J.length;Q++){let _=J[Q];if(_===0){U={};continue}if(_===1)U={...U,bold:!0};else if(_===2)U={...U,dim:!0};else if(_===3)U={...U,italic:!0};else if(_===4)U={...U,underline:!0};else if(_===7)U={...U,inverse:!0};else if(_===22)U={...U,bold:!1,dim:!1};else if(_===23)U={...U,italic:!1};else if(_===24)U={...U,underline:!1};else if(_===27)U={...U,inverse:!1};else if(_===39)U={...U,fg:void 0};else if(_===49)U={...U,bg:void 0};else if(_>=30&&_<=37||_>=90&&_<=97){let G=Rk(_);U={...U,fg:G??U.fg}}else if(_>=40&&_<=47||_>=100&&_<=107){let G=jt(_);U={...U,bg:G??U.bg}}else if(_===38||_===48){let G=J[Q+1];if(G===5){let V=J[Q+2];if(V!=null){let{r:X,g:Z,b:Y}=Dt(V),K=zk(X,Z,Y);U=_===38?{...U,fg:K}:{...U,bg:K}}Q+=2}else if(G===2){let V=J[Q+2],X=J[Q+3],Z=J[Q+4];if(V!=null&&X!=null&&Z!=null){let Y=zk(V,X,Z);U=_===38?{...U,fg:Y}:{...U,bg:Y}}Q+=4}}}return U}function GU($,J={}){let U=[],Q={...J},_=0;for(let G=0;G<$.length;G++){if($[G]!=="\x1B"||$[G+1]!=="[")continue;let V=G+2;while(V<$.length){let Y=$.charCodeAt(V);if(Y>=48&&Y<=57||Y===59){V++;continue}break}if(V>=$.length||$[V]!=="m")continue;if(G>_)U.push({text:$.slice(_,G),style:Q});let Z=$.slice(G+2,V).split(";").filter(Boolean).map((Y)=>Number.parseInt(Y,10)).filter((Y)=>Number.isFinite(Y));Q=Et(Q,Z.length?Z:[0]),_=V+1,G=V}if(_<$.length)U.push({text:$.slice(_),style:Q});return U}var Pt=[[4352,4447],[9001,9002],[11904,42191],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65280,65376],[65504,65510]];function Mt($){for(let[J,U]of Pt)if($>=J&&$<=U)return!0;return!1}function Lt($){return $>=127744&&$<=129791||$>=127462&&$<=127487}var hB=null;try{hB=new RegExp("\\p{Extended_Pictographic}","u")}catch{hB=null}var uB=null;try{uB=new RegExp("\\p{Emoji_Presentation}","u")}catch{uB=null}var mB=null;try{mB=new RegExp("\\p{Emoji}","u")}catch{mB=null}function u4($){if(!$)return 1;let J=$.codePointAt(0);if(J==null)return 1;let U=$.includes("️");if(Mt(J))return 2;if(Lt(J))return 2;if(uB?.test($))return 2;if($.includes("⃣"))return 2;if(U&&mB?.test($))return 2;if(hB?.test($)){if(J<=65535)return U?2:1;return 2}return 1}var vk=Object.freeze({}),wk=new WeakMap,fk=new WeakMap,kk=new WeakMap,zt=new WeakMap,Rt=new WeakMap,At=128;function dB($){if(!$)return vk;if(Object.isFrozen($))return $;let J=wk.get($);if(J)return J;let U=Object.freeze({...$});return wk.set($,U),U}function Ik($,J){let U=$.get(J);if(U)return U;let Q=new Map;return $.set(J,Q),Q}function tG($,J){if($===" ")return n6(J);let U=dB(J),Q=u4($),_=Q===2?Ik(Rt,U):Ik(zt,U),G=_.get($);if(G)return G;let V={ch:$,width:Q,style:U};if(_.set($,V),_.size>At)_.clear();return V}function n6($){let J=dB($),U=fk.get(J);if(U)return U;let Q=Object.freeze({ch:" ",width:1,style:J});return fk.set(J,Q),Q}function Ck($){let J=dB($),U=kk.get(J);if(U)return U;let Q=Object.freeze({ch:"",width:1,continuation:!0,style:J});return kk.set(J,Q),Q}function bk($,J){let U=Math.max(0,Math.floor($)),Q=Math.max(0,Math.floor(J)),_=n6(),G=Array.from({length:Q},()=>Array.from({length:U},()=>_));return{cols:U,rows:Q,grid:G,gridStart:0,dirtyBits:new Uint8Array(Q),dirtyCount:Q?Q:0,dirtyMin:Q?0:Number.POSITIVE_INFINITY,dirtyMax:Q?Q-1:-1,dirtyAll:Q>0,cursorX:0,cursorY:0,cursorVisible:!0,cursorStyle:vk,scrollback:[],scrollbackLimit:1000,rowPool:[]}}function U1($,J,U){return Math.max(J,Math.min(U,$))}function wt($,J){return($.gridStart+J)%$.rows}function _1($,J){return $.grid[wt($,J)]}function lB($,J,U){return _1($,U)[J]}function yk($){if($.rows<=0)return;$.dirtyAll=!0,$.dirtyCount=$.rows,$.dirtyMin=0,$.dirtyMax=$.rows-1}function W8($,J){if($.dirtyAll)return;if(J<0||J>=$.rows)return;if($.dirtyBits[J])return;if($.dirtyBits[J]=1,$.dirtyCount++,J<$.dirtyMin)$.dirtyMin=J;if(J>$.dirtyMax)$.dirtyMax=J}function ft($,J,U){let Q=n6();for(let _=J;_<U;_++)$[_]=Q}function Sk($,J){if(!$[J]?.continuation)return;$[J]=n6()}function cB($,J){let U=$[J];if(!U)return;if(U.continuation){if(J-1>=0)$[J-1]=n6();$[J]=n6();return}if(U.width===2){if($[J]=n6(),J+1<$.length)$[J+1]=n6()}}function sG($,J,U,Q,_){if(U<0||U>=$.rows)return;if(J<0||J>=$.cols)return;let G=_1($,U);cB(G,J);let V=u4(Q);if(V===2&&J+1>=$.cols){G[J]=n6(),W8($,U);return}if(G[J]=tG(Q,_),V===2&&J+1<$.cols)G[J+1]=Ck(_);W8($,U)}function gk($,J,U,Q,_,G=" ",V){if(Q<=0||_<=0||$.cols===0||$.rows===0)return;let X=U1(Math.floor(J),0,$.cols),Z=U1(Math.floor(U),0,$.rows),Y=U1(Math.floor(J+Q),0,$.cols),K=U1(Math.floor(U+_),0,$.rows);if(Y<=X||K<=Z)return;let F=u4(G);if(F===1){let q=tG(G,V),H=n6();for(let E=Z;E<K;E++){let D=_1($,E);if(D[X]?.continuation)cB(D,X);if(D.fill(q,X,Y),Y<$.cols&&D[Y]?.continuation)D[Y]=H;W8($,E)}return}let N=F===2?void 0:tG(G,V);for(let q=Z;q<K;q++){let H=_1($,q);for(let E=X;E<Y;E++)if(cB(H,E),F===2&&E+1>=$.cols)H[E]=n6();else if(H[E]=N??tG(G,V),F===2&&E+1<$.cols)H[E+1]=Ck(V);W8($,q)}}function xk($,J,U,Q,_){if($.cols===0||$.rows===0)return;if(J==null||U==null||Q==null||_==null){let Y=n6();for(let K=0;K<$.rows;K++){let F=_1($,K);F.length=$.cols;for(let N=0;N<$.cols;N++)F[N]=Y}yk($),$.cursorX=0,$.cursorY=0;return}if(Q<=0||_<=0)return;let G=U1(Math.floor(J),0,$.cols),V=U1(Math.floor(U),0,$.rows),X=U1(Math.floor(J+Q),0,$.cols),Z=U1(Math.floor(U+_),0,$.rows);if(X<=G||Z<=V)return;for(let Y=V;Y<Z;Y++){let K=_1($,Y);if(ft(K,G,X),G-1>=0)Sk(K,G);if(X<$.cols)Sk(K,X);W8($,Y)}}function kt($){return $.rowPool.pop()??null}function Tk($){let J=kt($);if(!J)return Array.from({length:$.cols},()=>n6());J.length=$.cols;let U=n6();for(let Q=0;Q<$.cols;Q++)J[Q]=U;return J}function eG($,J){let U=Math.trunc(J);if(U===0||$.rows===0)return;if(U>0)for(let Q=0;Q<U;Q++){let _=$.gridStart,G=$.grid[_];if($.scrollbackLimit>0){if($.scrollback.push(G),$.scrollback.length>$.scrollbackLimit){let X=$.scrollback.length-$.scrollbackLimit,Z=$.scrollback.splice(0,X);$.rowPool.push(...Z)}}else $.rowPool.push(G);$.gridStart=($.gridStart+1)%$.rows;let V=($.gridStart+$.rows-1)%$.rows;$.grid[V]=Tk($)}else for(let Q=0;Q<-U;Q++){let _=($.gridStart+$.rows-1)%$.rows,G=$.grid[_];$.rowPool.push(G),$.gridStart=($.gridStart-1+$.rows)%$.rows,$.grid[$.gridStart]=Tk($)}yk($),$.cursorY=U1($.cursorY-U,0,Math.max(0,$.rows-1))}function hk($,J,U){let Q=Math.max(0,Math.floor(J)),_=Math.max(0,Math.floor(U));if(Q===$.cols&&_===$.rows)return;let G=n6(),V=Array.from({length:_},()=>Array.from({length:Q},()=>G)),X=Math.min($.rows,_),Z=Math.min($.cols,Q);for(let Y=0;Y<X;Y++){let K=_1($,Y),F=V[Y];for(let N=0;N<Z;N++)F[N]=K[N]}if(Q>0)for(let Y=0;Y<V.length;Y++){let K=V[Y];if(K[Q-1]?.continuation)K[Q-1]=G}for(let Y=0;Y<$.rows;Y++)$.rowPool.push(_1($,Y));$.grid=V,$.gridStart=0,$.cols=Q,$.rows=_,$.dirtyBits=new Uint8Array(_),$.dirtyCount=_?_:0,$.dirtyMin=_?0:Number.POSITIVE_INFINITY,$.dirtyMax=_?_-1:-1,$.dirtyAll=_>0,$.cursorX=U1($.cursorX,0,Math.max(0,Q)),$.cursorY=U1($.cursorY,0,Math.max(0,_-1))}function uk($){let J=Array($.rows);for(let U=0;U<$.rows;U++){let Q=_1($,U);J[U]=Q.map((_)=>_.continuation?" ":_.ch||" ").join("")}return J}class iB{listeners=new Map;on($,J){let U=this.listeners.get($);if(!U)U=new Set,this.listeners.set($,U);return U.add(J),()=>{if(U.delete(J),U.size===0)this.listeners.delete($)}}emit($,J){let U=this.listeners.get($);if(!U)return;for(let Q of U)Q(J)}clear(){this.listeners.clear()}}function It($){return $===`
|
|
891
|
-
`||$==="\r"||$==="\t"}var rB=null;try{rB=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{}function nB($){let J=new iB,U=bk($.cols,$.rows),Q=!1,_=0,G=!1;function V(){if(Q)throw Error("Terminal is disposed")}function X(N,q,H=U.cursorVisible){U.cursorX=Math.max(0,Math.min(U.cols,Math.floor(N))),U.cursorY=Math.max(0,Math.min(U.rows?U.rows-1:0,Math.floor(q))),U.cursorVisible=H,W8(U,U.cursorY)}function Z(N,q,H,E){let D=q,B=H;if(U.cols===0||U.rows===0)return{x:D,y:B};let j=(R)=>{if(It(R)){if(R===`
|
|
892
|
-
`){if(D=0,B+=1,B>=U.rows)eG(U,1),B=U.rows-1}else if(R==="\r")D=0;else if(R==="\t"){let T=Math.min(U.cols,D+(4-D%4));for(;D<T;D++)sG(U,D,B," ",E)}return!0}if(B<0||B>=U.rows)return!1;if(D>=U.cols)D=0,B+=1;if(B>=U.rows)eG(U,1),B=U.rows-1;sG(U,D,B,R,E);let I=R===" "?1:lB(U,D,B).width||1;return D+=I,!0},f=0;for(;f<N.length;f++){if(N.charCodeAt(f)>127)break;if(!j(N[f]))return{x:D,y:B}}if(f<N.length){let R=N.slice(f);if(rB){for(let I of rB.segment(R))if(!j(I.segment))break}else for(let I of R)if(!j(I))break}return{x:D,y:B}}function Y(){if(U.rows===0)return[];if(U.dirtyAll)return null;if(U.dirtyCount===0)return[];let N=Array(U.dirtyCount),q=0,H=Math.max(0,U.dirtyMin),E=Math.min(U.rows-1,U.dirtyMax);for(let D=H;D<=E;D++)if(U.dirtyBits[D]){if(N[q++]=D,q===U.dirtyCount)break}return N.length=q,N}function K(){if(U.rows===0)return[];if(U.dirtyAll)return U.dirtyAll=!1,U.dirtyBits.fill(0),U.dirtyCount=0,U.dirtyMin=Number.POSITIVE_INFINITY,U.dirtyMax=-1,null;if(U.dirtyCount===0)return[];let N=Array(U.dirtyCount),q=0,H=Math.max(0,U.dirtyMin),E=Math.min(U.rows-1,U.dirtyMax);for(let D=H;D<=E;D++)if(U.dirtyBits[D]){if(U.dirtyBits[D]=0,N[q++]=D,q===U.dirtyCount)break}return N.length=q,U.dirtyCount=0,U.dirtyMin=Number.POSITIVE_INFINITY,U.dirtyMax=-1,N}let F={resize(N,q){V();let{cols:H,rows:E}=U;if(hk(U,N,q),U.cols!==H||U.rows!==E)J.emit("resize",{cols:U.cols,rows:U.rows})},clear(N,q,H,E){V(),xk(U,N,q,H,E)},write(N,q){V();let H=q?.x,E=q?.y,D=q?.style;if(H==null||E==null){let B=Z(N,U.cursorX,U.cursorY,D??U.cursorStyle);U.cursorX=B.x,U.cursorY=B.y}else Z(N,H,E,D)},writeAnsi(N,q){V();let H=q?.x,E=q?.y,D=H!=null&&E!=null,B=D?H:U.cursorX,j=D?E:U.cursorY,f=D?{}:U.cursorStyle;for(let R of GU(N,f)){let I=Z(R.text,B,j,R.style);B=I.x,j=I.y,f=R.style}if(!D)U.cursorX=B,U.cursorY=j,U.cursorStyle=f},put(N,q,H,E){V(),sG(U,N,q,H,E)},fill(N,q,H,E,D,B){V(),gk(U,N,q,H,E,D??" ",B)},scroll(N){V(),eG(U,N)},setCursor:X,batch(N){V(),_++;try{return N()}finally{if(_--,_===0&&G)G=!1,F.commit()}},commit(){if(V(),_>0)return G=!0,Y();let N=K();if(N!==null&&N.length===0)return N;return J.emit("commit",{dirtyRows:N}),N},on(N,q){return V(),J.on(N,q)},dispose(){Q=!0,J.clear()},size(){return V(),{cols:U.cols,rows:U.rows}},snapshot(){return V(),{cols:U.cols,rows:U.rows,lines:uk(U)}},getCell(N,q){if(V(),q<0||q>=U.rows||N<0||N>=U.cols)throw RangeError("Cell out of bounds");return lB(U,N,q)},getRow(N){if(V(),N<0||N>=U.rows)throw RangeError("Row out of bounds");return _1(U,N)},setScrollbackLimit(N){if(V(),U.scrollbackLimit=Math.max(0,Math.floor(N)),U.scrollback.length>U.scrollbackLimit)U.scrollback.splice(0,U.scrollback.length-U.scrollbackLimit)},getScrollbackLines(N){V();let q=U.scrollback.map((H)=>H.map((E)=>E.continuation?" ":E.ch||" ").join(""));if(N==null)return q;return q.slice(Math.max(0,q.length-Math.max(0,Math.floor(N))))}};return F}import{defineComponent as Ks,h as $O,provide as KU,ref as JO,shallowReactive as UO,shallowRef as QV}from"vue";import{createRenderer as St}from"vue";function Tt($){let J={type:$,parent:null,children:[],props:{},style:{}};return J.setAttribute=(U,Q)=>{J.props[U]=Q},J.removeAttribute=(U)=>{delete J.props[U]},J}function vt($,J,U){$.parent=J;let Q=J.children;if(!U){Q.push($);return}let _=Q.indexOf(U);if(_<0){Q.push($);return}Q.splice(_,0,$)}function Ct($){let J=$.parent;if(!J)return;let U=J.children,Q=U.indexOf($);if(Q>=0)U.splice(Q,1);$.parent=null}function bt($){return $.parent}function yt($){let J=$.parent;if(!J)return null;let U=J.children.indexOf($);if(U<0)return null;return J.children[U+1]??null}function gt($,J){$.textContent=J,$.children=[]}function xt($){return{type:"text",parent:null,text:$}}function ht($,J){$.text=J}function ut($){return{type:"comment",parent:null,text:$}}function mt($,J,U,Q){if(J==="style"&&Q&&typeof Q==="object"){Object.assign($.style,Q);return}if(J==="class"){$.className=typeof Q==="string"?Q:"";return}$.props[J]=Q}var ct={patchProp:mt,insert:vt,remove:Ct,createElement:Tt,createText:xt,createComment:ut,setText:ht,setElementText:gt,parentNode:bt,nextSibling:yt},dt=St(ct);function mk(...$){return dt.createApp(...$)}function ck(){return{children:[]}}function lt($,J,U){return J>=$.x&&U>=$.y&&J<$.x+$.w&&U<$.y+$.h}function dk($,J){return J.x>=$.x&&J.y>=$.y&&J.x+J.w<=$.x+$.w&&J.y+J.h<=$.y+$.h}function _J($){return Math.max(0,$.w)*Math.max(0,$.h)}function q8($){return $.visible!==!1}function it(){return typeof performance<"u"?performance.now():Date.now()}function pB($){let J=Math.floor($.y),U=Math.ceil($.y+$.h)-1;if(!Number.isFinite(J)||!Number.isFinite(U))return null;if(U<J)return null;return{y0:J,y1:U}}var rt=0;function aB($){let J=new Map,U=new Map,Q=new Map,_=null,G=null,V=$?.record,X=$?.onFocusChange;function Z(O){let M=Q.get(O);if(!M)return;for(let P=M.y0;P<=M.y1;P++){let A=U.get(P);if(!A)continue;if(A.delete(O),A.size===0)U.delete(P)}Q.delete(O)}function Y(O,M){if(!q8(M))return;let P=pB(M.rect);if(!P)return;Q.set(O,P);for(let A=P.y0;A<=P.y1;A++){let k=U.get(A);if(!k)k=new Set,U.set(A,k);k.add(O)}}function K(O,M){if(!q8(M)){Z(O);return}let P=pB(M.rect),A=Q.get(O);if(!P){Z(O);return}if(A&&A.y0===P.y0&&A.y1===P.y1)return;Z(O),Q.set(O,P);for(let k=P.y0;k<=P.y1;k++){let L=U.get(k);if(!L)L=new Set,U.set(k,L);L.add(O)}}function F(O,M){let P=[],A=U.get(M);if(!A)return P;for(let k of A){let L=J.get(k);if(!L)continue;if(!q8(L))continue;if(lt(L.rect,O,M))P.push(L)}return P.sort((k,L)=>_J(L.rect)-_J(k.rect)||k.zIndex-L.zIndex)}function N(O){if(O.length===0)return null;let M=O[0];for(let P of O)if(P.zIndex>M.zIndex)M=P;else if(P.zIndex===M.zIndex&&_J(P.rect)<_J(M.rect))M=P;return M}function q(O,M){if(!M)return[];return[...O.filter((A)=>A.id!==M.id),M]}function H(O){let M=pB(O.rect),P=M?U.get(M.y0):null;if(!P){let L=[];for(let C of J.values()){if(!q8(C))continue;if(dk(C.rect,O.rect))L.push(C)}let v=L.sort((C,b)=>_J(b.rect)-_J(C.rect)||C.zIndex-b.zIndex);return q(v,O)}let A=[];for(let L of P){let v=J.get(L);if(!v)continue;if(!q8(v))continue;if(dk(v.rect,O.rect))A.push(v)}let k=A.sort((L,v)=>_J(v.rect)-_J(L.rect)||L.zIndex-v.zIndex);return q(k,O)}function E(O,M){return{type:O,target:null,currentTarget:null,eventPhase:2,bubbles:!0,cancelable:!0,defaultPrevented:!1,timeStamp:it(),__stopped:!1,stopPropagation(){this.__stopped=!0},preventDefault(){this.defaultPrevented=!0},composedPath(){return[...M].reverse()}}}function D(O,M,P){if(P.currentTarget=M,!M)return;let A=M.handlers[O];if(A)try{A(P)}catch(k){try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let v=E$("fs"),C=new Date().toISOString().split("T")[1].slice(0,-1);v.appendFileSync("/tmp/goatchain-debug.log",`[${C}] [EVENT-MGR] ERROR in handler ${M.id}.${O}: ${k}
|
|
893
|
-
`)}}catch{}}}function B(O,M,P,A){A.target=P;let k=`${O}Capture`;A.eventPhase=1;for(let L of M)if(D(k,L,A),A.__stopped)return;if(P){if(A.eventPhase=2,D(O,P,A),A.__stopped)return}A.eventPhase=3;for(let L=M.length-2;L>=0;L--)if(D(O,M[L],A),A.__stopped)return}function j(O){if(_===O)return;let M=_?J.get(_)??null:null,P=O?J.get(O)??null:null,A=P&&q8(P)?P:null;if(_=A?.id??null,X?.(M?.id??null,_),M){let k=H(M),L=E("blur",k);B("blur",k,M,L)}if(A){let k=H(A),L=E("focus",k);B("focus",k,A,L)}}function f(O,M,P){let A=E(O,M);return Object.assign(A,{clientX:P.clientX??P.cellX,clientY:P.clientY??P.cellY,cellX:P.cellX,cellY:P.cellY,button:P.type==="wheel"?void 0:P.button,buttons:P.type==="wheel"?void 0:P.buttons,ctrlKey:P.ctrlKey,shiftKey:P.shiftKey,altKey:P.altKey,metaKey:P.metaKey,deltaY:P.type==="wheel"?P.deltaY:void 0})}function R(O){let M="";if(O.metaKey)M+="Meta+";if(O.ctrlKey)M+="Ctrl+";if(O.altKey)M+="Alt+";if(O.shiftKey)M+="Shift+";return M+=O.key,M}function I(O,M,P){let A=E(O,M);return Object.assign(A,{key:P.key,code:P.code??"",combo:R(P),ctrlKey:P.ctrlKey,shiftKey:P.shiftKey,altKey:P.altKey,metaKey:P.metaKey,repeat:P.repeat})}function w(O,M,P){let A=E(O,M);return Object.assign(A,{data:P.data,inputType:P.inputType,isComposing:P.isComposing,text:P.text})}function T(O,M,P){let A=F(M.cellX,M.cellY),k=P??N(A),L=k?q(A,k):[],v=f(O,L,M);B(O,L,k,v)}function z(O,M){let P=_?J.get(_)??null:null,A=P?H(P):[],k=I(O,A,M);return B(O,A,P,k),k.defaultPrevented}function S(O,M){let P=_?J.get(_)??null:null,A=P?H(P):[],k=w(O,A,M);return B(O,A,P,k),k.defaultPrevented}return{register(O){let M=O.id??`n${rt++}`,P=O.focusable,A={id:M,rect:O.rect,zIndex:O.zIndex??0,visible:O.visible??!0,focusable:P,selectable:O.selectable??!P,handlers:O.handlers??{}};if(J.has(M))Z(M);return J.set(M,A),Y(M,A),A},update(O,M){let P=J.get(O);if(!P)return;let A=M.visible??P.visible;if(A===!1){if(_===O)j(null);if(G===O)G=null}J.set(O,{...P,...M,rect:M.rect??P.rect,zIndex:M.zIndex??P.zIndex,visible:A,handlers:M.handlers??P.handlers});let k=J.get(O);if(k)K(O,k)},unregister(O){if(G===O)G=null;if(Z(O),J.delete(O),_===O)j(null)},setMetrics(O){},focus(O){j(O)},getFocused(){return _},dispatch(O){if(V?.(O),O.type==="keydown"||O.type==="keyup")return z(O.type,O);if(O.type==="pointerdown"||O.type==="pointermove"||O.type==="pointerup"||O.type==="click"||O.type==="dblclick"||O.type==="contextmenu"||O.type==="wheel"){if(O.type==="pointerdown"){let M=F(O.cellX,O.cellY),P=N(M);if(P?.focusable)j(P.id);return G=P?.id??null,T("pointerdown",O,P),!1}if(O.type==="pointermove"&&G){let M=J.get(G)??null;if(!M)return!1;let P=H(M),A=f("pointermove",P,O);return B("pointermove",P,M,A),A.defaultPrevented}if(O.type==="pointerup"&&G){let M=J.get(G)??null,P=M?H(M):[],A=f("pointerup",P,O);return B("pointerup",P,M,A),G=null,A.defaultPrevented}if(O.type==="pointerup")return T("pointerup",O),G=null,!1;return T(O.type,O),!1}if(O.type==="beforeinput"||O.type==="input"||O.type==="compositionstart"||O.type==="compositionupdate"||O.type==="compositionend"||O.type==="paste")return S(O.type,O);return!1},debugNodes(){return Array.from(J.values()).map((O)=>({id:O.id,rect:O.rect,zIndex:O.zIndex,visible:q8(O),focusable:Boolean(O.focusable)}))},dispose(){U.clear(),Q.clear(),J.clear(),_=null,G=null}}}import{ref as nt,shallowReactive as pt}from"vue";function lk($){let J=nt(Boolean($?.enabled)),U=pt([]),Q=Math.max(10,Math.floor($?.max??400));function _(X){if(!J.value)return;if(U.push(X),U.length>Q)U.splice(0,U.length-Q)}function G(){U.splice(0,U.length)}function V(){return U.slice()}return{enabled:J,records:U,push:_,clear:G,snapshot:V}}function at(){let $=globalThis.performance;if($&&typeof $.now==="function")return $.now();return Date.now()}function ot($){return String($??"").trim()==="1"}function tt($){return String($??"").trim().toLowerCase()==="json"?"json":"text"}function VU($){let J=globalThis.process?.env;if(!ot(J?.GOATCHAIN_PROFILE_TUI))return null;let U=tt(J?.GOATCHAIN_PROFILE_TUI_FORMAT),Q=0,_=0,G=0,V=0,X=0,Z=0,Y=0,K=0,F=0,N=0,q=0,H=0,E=0,D=0,B=0,j=Number(J?.GOATCHAIN_PROFILE_TUI_LOG_EVERY_MS??1000),f=at,R=f();function I(){let T=f(),z=T-R;if(z<=0)return;R=T;let S=_?_*1000/z:0,O=Q?Q*1000/z:0,M=_?X/_:0,P=_?Z/_:0,A=_?Y/_:0,k=F?F*1000/z:0,L=F?N/F:0,v=H?H*1000/z:0,C=F?H/F:0;if(U==="json")console.log(JSON.stringify({tag:"GOATCHAIN_PROFILE_TUI",name:$,elapsedMs:z,rps:S,ips:O,avgMs:M,maxMs:K,avgRows:P,avgNodes:A,full:G,sorted:V,wps:k,avgWriteMs:L,maxWriteMs:q,bps:v,avgBytes:C,writeMode:{stream:E,sync:D,chunked:B}}));else console.log(`[GOATCHAIN_PROFILE_TUI] ${$} rps=${S.toFixed(1)} ips=${O.toFixed(1)} avgMs=${M.toFixed(2)} maxMs=${K.toFixed(2)} avgRows=${P.toFixed(1)} avgNodes=${A.toFixed(1)} full=${G} sorted=${V}`+(F?` wps=${k.toFixed(1)} avgWriteMs=${L.toFixed(2)} maxWriteMs=${q.toFixed(2)} avgBytes=${C.toFixed(0)} bps=${v.toFixed(0)} mode(stream/sync/chunked)=${E}/${D}/${B}`:""));Q=0,_=0,G=0,V=0,X=0,Z=0,Y=0,K=0,F=0,N=0,q=0,H=0,E=0,D=0,B=0}return setInterval(I,Number.isFinite(j)?Math.max(100,j):1000).unref?.(),{now:f,recordInvalidate(){Q++},recordRender(T){if(_++,T.fullRepaint)G++;if(T.sorted)V++;if(X+=T.durationMs,Z+=T.rows,Y+=T.nodes,T.durationMs>K)K=T.durationMs},recordWrite(T){if(F++,N+=T.durationMs,H+=Math.max(0,Math.floor(T.bytes)),T.durationMs>q)q=T.durationMs;if(T.mode==="stream")E++;else if(T.mode==="sync")D++;else B++}}}var $V=Symbol("TerminalContext"),QJ=Symbol("LayoutContext"),n7=Symbol("VisibilityContext"),f0=Symbol("EventZIndex"),JV=Symbol("ImeAnchor");var GJ=Symbol("RenderStack");var p7=!1;function UV($=!1){if(p7=$,p7)try{E$("fs").writeFileSync("/tmp/goatchain-debug.log",`=== GoatChain Debug Log Started at ${new Date().toISOString()} ===
|
|
894
|
-
|
|
895
|
-
`)}catch(J){}return{render:(J)=>ik("[RENDER]",J),stream:(J)=>ik("[STREAM]",J),error:(J,...U)=>{if(!p7)return;let _=`[${new Date().toISOString().split("T")[1].slice(0,-1)}] [ERROR] ${J}`+(U.length?` ${JSON.stringify(U)}`:"");rk(_+`
|
|
896
|
-
`)}}}function ik($,J){if(!p7)return;let U=new Date().toISOString().split("T")[1].slice(0,-1);rk(`[${U}] ${$} ${J}
|
|
897
|
-
`)}function rk($){if(!p7)return;try{E$("fs").appendFileSync("/tmp/goatchain-debug.log",$)}catch{}}function K6(){if(typeof process>"u")return!1;let $=process.env;return $?.GOATCHAIN_DEBUG==="1"||$?.DEBUG==="1"}var XU=0,_V=new Map;function ak($){XU++;try{if(XU===1)_V.clear();return $()}finally{if(XU--,XU===0)_V.clear()}}function e7($){for(let J=0;J<$.length;J++)if($.charCodeAt(J)>127)return!1;return!0}function st($){for(let J of $){let U=J.codePointAt(0);if(U===8205)return!0;if(U>=65024&&U<=65039||U>=917760&&U<=917999)return!0;if(U>=768&&U<=879||U>=6832&&U<=6911||U>=7616&&U<=7679||U>=8400&&U<=8447||U>=65056&&U<=65071)return!0;if(U>=127995&&U<=127999)return!0;if(U>=127462&&U<=127487)return!0}return!1}var oB=null;try{oB=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null}catch{oB=null}function tB($,J){if(!$)return;let U=oB;if(!U||!st($)){for(let Q of $)if(J(Q)===!1)return;return}for(let Q of U.segment($))if(J(Q.segment)===!1)return}function z6($){if(!$)return"";if(!/[\n\r\t]/.test($))return $;return $.replace(/[\n\r\t]/g," ")}function XJ($){if(!$)return"";if(!/[\r\t\x00-\x08\x0B-\x1F\x7F]/.test($))return $;let J=[];J.length=0;for(let U of $){let Q=U.codePointAt(0);if(Q===13)continue;if(Q===9){J.push(" ");continue}if(Q<=31&&Q!==10||Q===127)continue;J.push(U)}return J.join("")}function M$($){if(!$)return 0;if(e7($))return $.length;if(XU>0){let Q=_V.get($);if(Q!=null)return Q}let J=Xs($);if(J!=null)return J;let U=0;if(tB($,(Q)=>{U+=u4(Q)}),XU>0)_V.set($,U);return Ys($,U),U}var a7=new Map,et=256;function I4($){if($=Math.max(0,Math.floor($)),$===0)return"";let J=a7.get($);if(J)return J;let U=" ".repeat($);if(a7.size>=et)a7.clear();return a7.set($,U),U}var o7=new Map,$s=8,Js=256;function YU($,J){if(J=Math.max(0,Math.floor(J)),J===0)return"";if(!$)return"";let U=o7.get($);if(!U){if(o7.size>=$s)o7.clear();U=new Map,o7.set($,U)}let Q=U.get(J);if(Q)return Q;let _=$.repeat(J);if(U.size>=Js)U.clear();return U.set(J,_),_}function m4($,J){if(J=Math.max(0,Math.floor(J)),J<=0)return"";if($&&e7($))return $.slice(0,J);let U=[],Q=0;return tB($,(_)=>{let G=u4(_);if(Q+G>J)return!1;U.push(_),Q+=G;return}),U.length?U.join(""):""}function h6($,J){J=Math.max(0,Math.floor(J));let U=$&&e7($)?$.length:M$($);if(U>=J)return $;return`${$}${I4(J-U)}`}var t7=new Map,Us=32,nk=512;function _s($){let J=t7.get($);if(J)return J;if(t7.size>=Us)t7.clear();return J=new Map,t7.set($,J),J}function sB($,J){if(J=Math.max(0,Math.floor(J)),J===0)return"";if(!$)return I4(J);let U=_s(J),Q=U.get($);if(Q!=null)return Q;let _=z6($);if(_&&e7(_)){let V=_.length>=J?_.slice(0,J):`${_}${I4(J-_.length)}`;if(U.size>=nk)U.clear();return U.set($,V),V}let G=h6(m4(_,J),J);if(U.size>=nk)U.clear();return U.set($,G),G}var s7=new Map,Qs=32,pk=256;function Gs($){let J=s7.get($);if(J)return J;if(s7.size>=Qs)s7.clear();return J=new Map,s7.set($,J),J}var VJ=new Map,Vs=1024;function Xs($){let J=VJ.get($);if(J==null)return null;return VJ.delete($),VJ.set($,J),J}function Ys($,J){if(VJ.set($,J),VJ.size>Vs){let U=VJ.keys().next().value;if(U!=null)VJ.delete(U)}}function eB(){s7.clear(),a7.clear(),o7.clear(),VJ.clear(),t7.clear()}function K0($,J){J=Math.max(1,Math.floor(J));let U=Gs(J);if($&&e7($)){let V=U.get($);if(V)return V;let X=[];for(let Z of $.replace(/\r/g,"").split(`
|
|
898
|
-
`)){if(Z.length===0){X.push("");continue}for(let Y=0;Y<Z.length;Y+=J)X.push(Z.slice(Y,Y+J))}if(U.size>=pk)U.clear();return U.set($,X),X}let Q=U.get($);if(Q)return Q;let _=[];for(let V of $.replace(/\r/g,"").split(`
|
|
899
|
-
`)){let X=[],Z=0;if(tB(V,(Y)=>{let K=u4(Y);if(Z>0&&Z+K>J)_.push(X.join("")),X=[],Z=0;if(X.push(Y),Z+=K,Z>=J)_.push(X.join("")),X=[],Z=0}),X.length||V.length===0)_.push(X.join(""))}let G=_.length?_:[""];if(U.size>=pk)U.clear();return U.set($,G),G}var ZU=UV(K6()),ok=0,Zs=0;function tk($){let J=0,U=new Map,Q=!0,_=!0,G=$.size(),V=G.cols,X=G.rows,Z=Array.from({length:X},(C,b)=>b),Y=[0,X],K=[],F=new Map,N=!0,q=new WeakMap,H=VU("render-manager"),E=new Uint8Array(X),D=0,B=Number.POSITIVE_INFINITY,j=-1,f=[],R=[];$.on("resize",({cols:C,rows:b})=>{V=C,X=b,Q=!0,_=!0,Z=Array.from({length:X},(y,x)=>x),Y[0]=0,Y[1]=X,E=new Uint8Array(X),D=0,B=Number.POSITIVE_INFINITY,j=-1,eB()});let I=Object.freeze({id:`s${ok++}`,parent:null,zIndex:0,order:0});function w(C,b){return Object.freeze({id:`s${ok++}`,parent:C,zIndex:Number.isFinite(b)?b:0,order:++J})}function T(C){if(!C)return{y0:0,y1:0};let b=Math.floor(C.y),y=b+Math.max(0,Math.floor(C.h));return{y0:b,y1:y}}function z(C){if(!C){_=!0;return}let b=Math.floor(C.y),y=b+Math.max(0,Math.floor(C.h)),x=Math.max(0,b),c=Math.min(X,y),s=c-x;if(s>0&&s>=Math.floor(X*0.75)){_=!0;return}for(let F$=x;F$<c;F$++)if(E[F$]===0){if(E[F$]=1,D++,F$<B)B=F$;if(F$>j)j=F$}}function S(C){let b=`r${Zs++}`,y=C.rect??null,{y0:x,y1:c}=T(y),s=Object.freeze({id:b,stack:C.stack,zIndex:C.zIndex??0,order:++J,rect:y,rectY0:x,rectY1:c,paint:C.paint});return U.set(b,s),z(s.rect),N=!0,s}function O(C,b){let y=U.get(C);if(!y)return;if(b.stack&&b.stack!==y.stack||typeof b.zIndex==="number"&&b.zIndex!==y.zIndex)N=!0;let x=b.rect??y.rect,{y0:c,y1:s}=T(x);z(y.rect),z(x);let F$=Object.freeze({...y,stack:b.stack??y.stack,zIndex:b.zIndex??y.zIndex,rect:x,rectY0:c,rectY1:s,paint:b.paint??y.paint});if(U.set(C,F$),!N){let K$=F.get(C);if(K$!=null)K[K$]=F$;else N=!0}}function M(C){let b=U.get(C);if(b)z(b.rect);U.delete(C),N=!0}function P(C){let b=q.get(C);if(b)return b;let y=[],x=C;while(x)y.push({zIndex:x.zIndex,order:x.order,id:x.id}),x=x.parent;return y.reverse(),q.set(C,y),y}function A(C,b){if(C.id===b.id)return 0;let y=P(C.stack),x=P(b.stack),c=Math.min(y.length,x.length);for(let s=0;s<c;s++){let F$=y[s],K$=x[s];if(F$.id===K$.id)continue;if(F$.zIndex!==K$.zIndex)return F$.zIndex-K$.zIndex;return F$.order-K$.order}if(y.length!==x.length)return y.length-x.length;if(C.zIndex!==b.zIndex)return C.zIndex-b.zIndex;return C.order-b.order}function k(C,b,y){if(b<=C)return!1;let x=0,c=y.length;while(x<c){let F$=x+c>>1;if((y[F$]??0)<C)x=F$+1;else c=F$}let s=y[x];return s!=null&&s<b}function L(C,b,y){if(b<=C)return!1;let x=0,c=y.length/2;while(x<c){let V$=x+c>>1;if((y[V$*2]??0)<b)x=V$+1;else c=V$}let s=x-1;if(s<0)return!1;let F$=y[s*2]??0;return(y[s*2+1]??0)>C&&F$<b}function v(){let C=H?.now(),b=globalThis.process?.env;if(b?.GOATCHAIN_DEBUG==="1")ZU.render("[RENDER-MANAGER] render() called");if(!Q&&!_&&D===0){if(b?.GOATCHAIN_DEBUG==="1")ZU.render("[RENDER-MANAGER] render() skipped (no dirty rows)");return}if(b?.GOATCHAIN_DEBUG==="1")ZU.render(`[RENDER-MANAGER] fullDirty=${Q}, allRowsDirty=${_}, dirtyRowCount=${D}`);let y=N;if(N){K=Array.from(U.values()).sort(A),F=new Map;for(let m=0;m<K.length;m++)F.set(K[m].id,m);N=!1}let x=Q,c=D,s=B,F$=j,K$=Z,V$=null,Y$=!1;if(!x&&!_)if(D===0)K$=[];else{if(f.length<D)f=Array(D);K$=f;let m=0,G$=Number.isFinite(B)?B:0,L$=j;for(let P$=G$;P$<=L$;P$++)if(E[P$]===1)K$[m++]=P$;K$.length=m,Y$=!0,R.length=0,V$=R;for(let P$=0;P$<K$.length;P$++){let f$=K$[P$],V4=f$+1;while(P$+1<K$.length&&K$[P$+1]===V4)P$++,V4++;R.push(f$,V4)}}else E.fill(0);if(K$===Z)V$=Y;if(Q=!1,_=!1,D=0,B=Number.POSITIVE_INFINITY,j=-1,K$.length===0){if(b?.GOATCHAIN_DEBUG==="1")ZU.render("[RENDER-MANAGER] render() skipped (no rows to paint)");return}if(b?.GOATCHAIN_DEBUG==="1")ZU.render(`[RENDER-MANAGER] calling terminal.batch() with ${U.size} nodes, ${K$.length} rows`);let u$=x||K$===Z?void 0:K$,_$=!x&&K$!==Z,n=_$&&c<=32,a=(m,G$)=>{if(G$<=m)return!1;if(Number.isFinite(s)&&G$<=s)return!1;if(F$>=0&&m>F$)return!1;if(V$)return L(m,G$,V$);let L$=Math.max(0,m),P$=Math.min(X,G$);for(let f$=L$;f$<P$;f$++)if(E[f$]===1)return!0;return!1};if(ak(()=>$.batch(()=>{if(V$)for(let m=0;m<V$.length;m+=2){let G$=V$[m],L$=V$[m+1];$.clear(0,G$,V,L$-G$)}else for(let m=0;m<K$.length;m++){let G$=K$[m];$.clear(0,G$,V,1)}for(let m of K){if(!m.rect){m.paint(u$);continue}if(_$){if(n){if(!k(m.rectY0,m.rectY1,K$))continue}else if(!a(m.rectY0,m.rectY1))continue}m.paint(u$)}})),Y$)for(let m of K$)E[m]=0;if(H&&C!=null)H.recordRender({durationMs:H.now()-C,rows:K$.length,nodes:K.length,fullRepaint:x||K$===Z,sorted:y});if(b?.GOATCHAIN_DEBUG==="1")ZU.render("[RENDER-MANAGER] terminal.batch() completed")}return{rootStack:I,createStack:w,register:S,update:O,unregister:M,render:v}}var Ns=0;function sk($){if(!$||typeof $!=="object")return!1;let J=Object.getPrototypeOf($);return J===Object.prototype||J===null}function Fs($,J){if($===J)return!0;if(!sk($)||!sk(J))return!1;let U=Object.keys($),Q=Object.keys(J);if(U.length!==Q.length)return!1;for(let _ of U){if(!(_ in J))return!1;if($[_]!==J[_])return!1}return!0}function ek($,J){if($===J)return!0;let U=Object.keys($),Q=Object.keys(J);if(U.length!==Q.length)return!1;for(let _ of U){if(!(_ in J))return!1;if(!Fs($[_],J[_]))return!1}return!0}function _O($){let J=nB({cols:$.cols,rows:$.rows}),U=lk({enabled:Boolean(globalThis.__VT_DEBUG_TRACE__)}),Q=VU("cli-scheduler"),_=aB({record:(A)=>U.push({type:"event",at:Date.now(),event:A}),onFocusChange:(A,k)=>U.push({type:"focus",at:Date.now(),prev:A,next:k})}),G=tk(J),V=J.on("commit",({dirtyRows:A})=>{U.push({type:"commit",at:Date.now(),dirtyRows:A,focusedId:_.getFocused()})}),X=!1,Z=!1,Y=!1,K=!1,F=0,N=0,q=null,H=(()=>{let k=globalThis.process?.env?.GOATCHAIN_TUI_THROTTLE_MS;if(!k)return 0;let L=Number(k);return Number.isFinite(L)&&L>0?L:0})();function E(){if(K)return;X=!1,Z=!0,G.render(),J.commit(),Z=!1,F=Date.now(),N=0}function D(){if(!q)return;clearTimeout(q),q=null}function B(A){let k=Date.now(),L=Math.max(0,A-k);if(L>0){D(),N=A,q=setTimeout(()=>{q=null,E()},L);return}if(D(),N=k,typeof process<"u"&&typeof process.nextTick==="function")process.nextTick(()=>{E()});else if(typeof globalThis.setImmediate==="function")globalThis.setImmediate(()=>{E()});else setTimeout(()=>{E()},0)}function j(){if(K)return;if(Z)return;D(),X=!1,E()}function f(A){if(K)return;if(Z)return;let k=A?.priority??"normal";Q?.recordInvalidate();let L=Date.now(),v=H>0?Math.max(0,F+H-L):0,C=k==="low"?Math.max(v,16):k==="normal"?v:0,b=L+C;if(!X){X=!0,B(b);return}if(!N){B(b);return}if(!q&&N===L)return;if(b<N)B(b)}let R=UO([]),I={mount(A,k){let L=`p${Ns++}`,v={...k},C=UO({id:L,component:A,props:v});R.push(C);let b=!0,y={update(x){if(!b)return;let c={...v,...x};if(ek(v,c))return;v=c,C.props=v,f()},move(x,c){if(!b)return;let s={...v,x,y:c};if(ek(v,s))return;v=s,C.props=v,f()},unmount(){if(!b)return;b=!1;let x=R.findIndex((c)=>c.id===L);if(x>=0)R.splice(x,1);f()}};return f(),y}},w=UO({originX:0,originY:0,clipRect:{x:0,y:0,w:$.cols,h:$.rows}}),T=J.on("resize",({cols:A,rows:k})=>{w.clipRect={x:0,y:0,w:A,h:k},f()}),z={terminal:J,renderer:QV(null),events:QV(_),scheduler:{invalidate:f,flush:E,flushNow:j},runtime:I,observability:{trace:U},defaultStyle:JO($.defaultStyle??{}),render:G},S=QV(null),O=Ks({name:"TerminalAppRoot",setup(){return KU($V,z),KU(QJ,w),KU(n7,JO(!0)),KU(f0,JO(0)),KU(GJ,QV(G.rootStack)),KU(JV,S),()=>{let A=R.map((k)=>$O(k.component,{key:k.id,...k.props}));return $O("div",null,[$O($.component,$.props??{}),...A])}}}),M=mk(O),P=ck();return{app:M,terminal:J,events:_,scheduler:z.scheduler,getImeAnchor(){return S.value},mount(){if(K||Y)return;Y=!0,M.mount(P)},dispose(){if(K)return;if(K=!0,Y)M.unmount();T?.(),V?.(),_.dispose(),J.dispose()}}}var Ws=Object.freeze({black:"#000000",red:"#c91b00",green:"#00c200",yellow:"#c7c400",blue:"#0225c7",magenta:"#c930c7",cyan:"#00c5c7",white:"#c7c7c7",blackBright:"#686868",redBright:"#ff6e67",greenBright:"#5ffa68",yellowBright:"#fffc67",blueBright:"#6871ff",magentaBright:"#ff76ff",cyanBright:"#5ffdff",whiteBright:"#ffffff"});function GV($){let J=$.startsWith("#")?$.slice(1):$;if(J.length!==6)return;let U=Number.parseInt(J.slice(0,2),16),Q=Number.parseInt(J.slice(2,4),16),_=Number.parseInt(J.slice(4,6),16);if(!Number.isFinite(U)||!Number.isFinite(Q)||!Number.isFinite(_))return;return{r:U,g:Q,b:_}}var qs=Object.freeze(Object.fromEntries(Object.entries(Ws).map(([$,J])=>[$,GV(J)])));function QO($){if(!$)return;return qs[$]}var YJ={lastFrameAt:0,lastFrameBytes:0,lastWriteMs:0,writeEmaMs:0,writeMode:"stream",fps:0,bytesPerSec:0},VV=0,GO=0,VO=0;function XO(){return YJ}function $I($){let J=Number($.at);if(!Number.isFinite(J))return;let U=Math.max(0,Math.floor(Number($.bytes)||0)),Q=Math.max(0,Number($.writeMs)||0),_=Math.max(0,Number($.writeEmaMs)||0),G=$.writeMode;if(YJ.lastFrameAt=J,YJ.lastFrameBytes=U,YJ.lastWriteMs=Q,YJ.writeEmaMs=_,YJ.writeMode=G,VV===0)VV=J;GO++,VO+=U;let V=J-VV;if(V>0)YJ.fps=GO*1000/V,YJ.bytesPerSec=VO*1000/V;if(V>=1000)VV=J,GO=0,VO=0}var YO=null;function R6(){if(!YO)YO=UV(K6());return YO}var XV=null;try{let $=globalThis.require?.("node:fs")??globalThis.require?.("fs");if($?.writeSync)XV=(J,U)=>{let Q=Buffer.from(U,"utf8");$.writeSync(J,Q)}}catch{}var Hs="\x1B[?2026h",JI="\x1B[?2026l";function Bs($){let J=String($??"").trim().toLowerCase();if(!J)return null;if(J==="stream")return"stream";if(J==="sync"||J==="writesync")return"sync";if(J==="chunked")return"chunked";return null}function YV($,J){let U=globalThis.process,Q=J?.output??U?.stdout;if(!Q)throw Error("createStdoutRenderer requires a Node stdout-like output");let _=Q,G=J?.clear??!0,V=J?.hideCursor??!0,X=J?.altScreen??Boolean(_.isTTY),Z=J?.defaultBg??"black",Y=J?.trackResize??!0,K=J?.getImeAnchor,F=VU("stdout-renderer");function N(){if(J?.useSyncOutput!=null)return J.useSyncOutput;let Q$=U?.env??{},Z$=Q$.GOATCHAIN_SYNC_OUTPUT;if(Z$!=null){let T$=String(Z$).trim().toLowerCase();return T$==="1"||T$==="true"||T$==="yes"}let k$=String(Q$.TERM??"").toLowerCase(),t$=String(Q$.TERM_PROGRAM??"").toLowerCase(),q4=Q$.TERM_PROGRAM_VERSION;if("GHOSTTY_RESOURCES_DIR"in Q$||t$.includes("apple_terminal")||k$.includes("screen")&&!k$.includes("tmux"))return!1;if(t$.includes("iterm")&&q4&&q(String(q4),"3.5.0")>=0)return!0;return!1}function q(Q$,Z$){let k$=Q$.split(".").map(Number),t$=Z$.split(".").map(Number),q4=Math.max(k$.length,t$.length);for(let _4=0;_4<q4;_4++){let Q4=k$[_4]??0,n$=t$[_4]??0;if(Q4!==n$)return Q4-n$}return 0}let H=N(),E="GHOSTTY_RESOURCES_DIR"in(U?.env??{}),D=U?.env??{},B=Bs(D.GOATCHAIN_TUI_WRITE_MODE??D.VUE_TUI_WRITE_MODE),j=Number(D.GOATCHAIN_TUI_CHUNK_SIZE??D.VUE_TUI_CHUNK_SIZE),f=Number.isFinite(j)?Math.max(512,Math.floor(j)):8192,R=Number(D.GOATCHAIN_TUI_CHUNK_THRESHOLD??D.VUE_TUI_CHUNK_THRESHOLD),I=Number.isFinite(R)?Math.max(1024,Math.floor(R)):65536,w=Number(D.GOATCHAIN_TUI_SYNC_MAX_BYTES??D.VUE_TUI_SYNC_MAX_BYTES),T=Number.isFinite(w)?Math.max(1024,Math.floor(w)):131072,z=E&&U?.env?.GOATCHAIN_DISABLE_CURSOR_POS==="1",S=!1,O=0,M=!1,P=null,A=0,k=!1,L=null,v=0,C=Number.POSITIVE_INFINITY,b=-1,y=!_.isTTY?0:E?24:16;function x(Q$){let Z$=String(Q$??"").trim().toLowerCase();if(!Z$)return null;if(Z$==="truecolor"||Z$==="24bit"||Z$==="rgb")return"truecolor";if(Z$==="ansi256"||Z$==="256"||Z$==="xterm256"||Z$==="xterm-256color")return"ansi256";if(Z$==="ansi16"||Z$==="16")return"ansi16";return null}function c(){let Q$=J?.colorMode??"auto";if(Q$!=="auto")return Q$;let Z$=U?.env??{},k$=x(Z$.GOATCHAIN_COLOR_MODE??Z$.VUE_TUI_COLOR_MODE);if(k$)return k$;if(!_.isTTY)return"truecolor";let t$=String(Z$.COLORTERM??"").toLowerCase();if(t$.includes("truecolor")||t$.includes("24bit"))return"truecolor";if(String(Z$.TERM_PROGRAM??"").toLowerCase().includes("vscode"))return"truecolor";return"truecolor"}let s=c(),F$=new WeakMap;function K$(Q$){let Z$=F$.get(Q$);if(Z$)return Z$;let k$=`${Q$.fg??""}|${Q$.bg??Z}|${Q$.bold?1:0}|${Q$.dim?1:0}|${Q$.italic?1:0}|${Q$.underline?1:0}|${Q$.inverse?1:0}`;return F$.set(Q$,k$),k$}function V$(Q$){return`${Q$.fg??""}|${Q$.bg??Z}|${Q$.bold?1:0}|${Q$.dim?1:0}|${Q$.italic?1:0}|${Q$.underline?1:0}|${Q$.inverse?1:0}`}function Y$(Q$){if(!Q$)return"";if(s==="ansi16")return t4[Q$]?.open??"";let Z$=J?.palette?.[Q$]?GV(J.palette[Q$]):QO(Q$);if(!Z$)return"";if(s==="ansi256")return t4.color?.ansi256?.(n(Z$))??"";return t4.color?.ansi16m?.(Z$.r,Z$.g,Z$.b)??""}function u$(Q$){if(!Q$)return"";if(s==="ansi16"){let k$=`bg${Q$[0].toUpperCase()}${Q$.slice(1)}`;return t4[k$]?.open??""}let Z$=J?.palette?.[Q$]?GV(J.palette[Q$]):QO(Q$);if(!Z$)return"";if(s==="ansi256")return t4.bgColor?.ansi256?.(n(Z$))??"";return t4.bgColor?.ansi16m?.(Z$.r,Z$.g,Z$.b)??""}function _$(Q$){let Z$="";if(Z$+=Y$(Q$.fg),Z$+=u$(Q$.bg??Z),Q$.bold)Z$+=t4.bold.open;if(Q$.dim)Z$+=t4.dim.open;if(Q$.italic)Z$+=t4.italic.open;if(Q$.underline)Z$+=t4.underline.open;if(Q$.inverse)Z$+=t4.inverse.open;return Z$}function n(Q$){let Z$=a(Q$.r),k$=a(Q$.g),t$=a(Q$.b);if(Z$===k$&&k$===t$){if(Z$<8)return 16;if(Z$>248)return 231;return 232+Math.round((Z$-8)/10)}let q4=(p)=>Math.round(p/51),_4=q4(Z$),Q4=q4(k$),n$=q4(t$),T$=16+36*_4+6*Q4+n$,y4=_4*51,p$=Q4*51,e4=n$*51,z$=(Z$-y4)**2+(k$-p$)**2+(t$-e4)**2,g=Math.round((Z$+k$+t$)/3),h=g<8?16:g>248?231:232+Math.round((g-8)/10),q$=h===16?0:h===231?255:8+10*(h-232);return(Z$-q$)**2+(k$-q$)**2+(t$-q$)**2<z$?h:T$}function a(Q$){if(!Number.isFinite(Q$))return 0;return Math.max(0,Math.min(255,Math.round(Q$)))}let m=0,G$=[],L$=[],P$=[],f$=(Q$,Z$)=>{return(Q$.width??1)===2&&Z$.length>1},V4=(Q$)=>{if(G$.length>=Q$)return;let Z$=G$.length;G$.length=Q$,L$.length=Q$;for(let k$=Z$;k$<Q$;k$++)G$[k$]=`\x1B[${k$+1};1H`,L$[k$]=`\x1B[${k$+1};1H\x1B[K`};function s4(Q$){if(!E){if(Q$.length<=f){_.write(Q$);return}for(let Z$=0;Z$<Q$.length;Z$+=f){let k$=Q$.slice(Z$,Z$+f);_.write(k$)}return}if(K6())R6().render(`writeChunked: sync chunked write of ${Q$.length} bytes`);try{if(Q$.length<=f)_.write(Q$);else for(let Z$=0;Z$<Q$.length;Z$+=f){let k$=Q$.slice(Z$,Z$+f);_.write(k$)}if(K6())R6().render("writeChunked: chunked write completed")}catch(Z$){if(K6())R6().error("writeChunked: write error",Z$)}}function U6(Q$){if(K6())R6().render(`doRender() START: dirtyRows=${Q$?.length??"null"}`);if(S)return;M=!1,k=!1,L=null,v=0,C=Number.POSITIVE_INFINITY,b=-1,O=Date.now();let Z$=performance.now(),k$=$.size();V4(Math.max(k$.rows,m));let t$=u$(Z),q4={bg:Z},_4=V$({bg:Z}),Q4=!0,n$=(()=>{if(!Q$||Q$.length===0)return null;let l=[];l.length=Q$.length;let $$=0,e=!0,D$=-1;for(let v$=0;v$<Q$.length;v$++){let A$=Math.floor(Q$[v$]??-1);if(A$<0||A$>=k$.rows)continue;if(A$<=D$)e=!1;D$=A$,l[$$++]=A$}if(l.length=$$,!l.length)return null;if(Q4=e,!e)l.sort((v$,A$)=>v$-A$);return l})(),T$=[];T$.push(!E&&H?Hs:""),T$.push("\x1B[?7l"),T$.push(t4.reset.open,t$);let y4=null,p$={fg:null,bg:Z,bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1},e4=(l)=>{return{fg:l.fg??null,bg:l.bg??Z,bold:Boolean(l.bold),dim:Boolean(l.dim),italic:Boolean(l.italic),underline:Boolean(l.underline),inverse:Boolean(l.inverse)}},z$=(l,$$)=>{if(y4===$$)return;let e=e4(l);if(p$.bold&&!e.bold||p$.dim&&!e.dim||p$.italic&&!e.italic||p$.underline&&!e.underline||p$.inverse&&!e.inverse||p$.fg!=null&&e.fg==null){T$.push(t4.reset.open,_$(l)),y4=$$,p$=e;return}if(p$.fg!==e.fg&&e.fg!=null)T$.push(Y$(e.fg));if(p$.bg!==e.bg)T$.push(u$(e.bg));if(!p$.bold&&e.bold)T$.push(t4.bold.open);if(!p$.dim&&e.dim)T$.push(t4.dim.open);if(!p$.italic&&e.italic)T$.push(t4.italic.open);if(!p$.underline&&e.underline)T$.push(t4.underline.open);if(!p$.inverse&&e.inverse)T$.push(t4.inverse.open);y4=$$,p$=e},g=(l)=>{if(!z)T$.push(G$[l]);let $$=$.getRow(l),e=null,D$=null,v$=P$;v$.length=0;for(let A$=0;A$<$$.length;A$++){let g$=$$[A$];if(g$.continuation)continue;let c$=g$.ch||" ",d$=g$.style,y$=d$===D$&&e!=null?e:K$(d$);if(e==null){if(e=y$,D$=d$,v$.push(c$),f$(g$,c$))v$.push(`\x1B[${l+1};${A$+1+(g$.width??1)}H`);continue}if(y$===e){if(v$.push(c$),f$(g$,c$))v$.push(`\x1B[${l+1};${A$+1+(g$.width??1)}H`);continue}if(y4!==e)z$(D$,e);if(T$.push(v$.join("")),e=y$,D$=d$,v$.length=0,v$.push(c$),f$(g$,c$))v$.push(`\x1B[${l+1};${A$+1+(g$.width??1)}H`)}if(e!=null){if(y4!==e)z$(D$,e);T$.push(v$.join(""))}if(y4!==_4)z$(q4,_4);T$.push("\x1B[K")};if(!n$){if(K6())R6().render(` Full render: ${k$.rows} rows`);for(let l=0;l<k$.rows;l++)g(l)}else{if(K6())R6().render(` Partial render: ${n$.length} dirty rows: [${n$.join(", ")}]`);for(let l of n$)g(l)}if(!n$&&m>k$.rows){let l=m-k$.rows;if(y4!==_4)T$.push(t4.reset.open,t$),y4=_4;for(let $$=0;$$<l;$$++)T$.push(L$[k$.rows+$$])}if(!n$)m=k$.rows;if(K){let l=K();if(l)T$.push(`\x1B[${Math.floor(l.cellY)+1};${Math.floor(l.cellX)+1}H`)}T$.push(t4.reset.open),T$.push("\x1B[?7h"),T$.push(!E&&H?JI:"");let h=T$.join("");if(F)F.recordRender({durationMs:F.now()-Z$,rows:n$?n$.length:k$.rows,nodes:0,fullRepaint:!n$,sorted:Q4});if(K6()){let l=(g$)=>{let c$=0,d$=0;while(!0){if(d$=g$.indexOf("\x1B[0m",d$),d$===-1)return c$;c$++,d$+=4}},$$=(g$)=>{let c$=0;for(let d$=0;d$<g$.length;d$++){if(g$.charCodeAt(d$)!==27)continue;if(g$[d$+1]!=="[")continue;let y$=d$+2,X4=!1;while(y$<g$.length){let W4=g$.charCodeAt(y$);if(W4>=48&&W4<=57){X4=!0,y$++;continue}break}if(!X4||g$[y$]!==";")continue;y$++,X4=!1;while(y$<g$.length){let W4=g$.charCodeAt(y$);if(W4>=48&&W4<=57){X4=!0,y$++;continue}break}if(X4&&g$[y$]==="H")c$++,d$=y$}return c$},e=h.length,D$=$$(h),v$=l(h),A$=(performance.now()-Z$).toFixed(2);R6().render(` Frame built: ${e} bytes, ${D$} cursor sequences, ${v$} resets, ${A$}ms`),R6().render(` Terminal: ${E?"GHOSTTY":"other"}, useSyncOutput: ${H}`)}let q$=performance.now(),p=((l)=>{if(E)return"chunked";if(B)return B;let $$=Boolean(XV&&_.fd===1);if(l>=I||A>=24)return"chunked";if($$&&l<=T)return"sync";return"stream"})(h.length);if(K6())R6().render("Before write()");try{if(p==="chunked"){if(K6())R6().render(` Using chunked write (chunkSize=${f}, threshold=${I}, emaMs=${A.toFixed(2)})`);s4(h)}else if(p==="sync"&&XV&&_.fd===1){if(K6())R6().render(" Using writeSync");try{XV(1,h)}catch{if(K6())R6().render(" writeSync failed, falling back to stream write");_.write(h)}}else{if(K6())R6().render(" Using stream write");_.write(h)}if(K6()){let l=(performance.now()-q$).toFixed(2);R6().render(` Write completed in ${l}ms`)}}catch(l){if(K6())R6().error("Write ERROR:",l);if(!E&&H)try{_.write(`\x1B[?7h${JI}`)}catch{}throw l}{let l=performance.now()-q$;if(A=A===0?l:A*0.85+l*0.15,$I({at:Date.now(),bytes:h.length,writeMs:l,writeEmaMs:A,writeMode:p==="sync"?"sync":p==="chunked"?"chunked":"stream"}),F)F.recordWrite({durationMs:l,bytes:h.length,mode:p==="sync"?"sync":p==="chunked"?"chunked":"stream"})}if(K6()){let l=(performance.now()-Z$).toFixed(2);R6().render(` Total render time: ${l}ms`),R6().render("doRender() END")}}function z4(Q$){if(S)return;if(K6())R6().render(`render() called: dirtyRows=${Q$?.length??"null"}, pending=${M}, elapsed=${Date.now()-O}ms`);let Z$=(_4)=>{if(!L||L.length!==_4)L=new Uint8Array(_4),v=0,C=Number.POSITIVE_INFINITY,b=-1;return L},k$=()=>{if(k)return null;if(!L||v===0)return Q$??null;let _4=[];_4.length=v;let Q4=0,n$=Math.max(0,C),T$=Math.min(L.length-1,b);for(let y4=n$;y4<=T$;y4++)if(L[y4])_4[Q4++]=y4;return _4.length=Q4,Q4?_4:null};if(!Q$||Q$.length===0)k=!0,L=null,v=0,C=Number.POSITIVE_INFINITY,b=-1;else if(!k){let _4=$.size().rows,Q4=Z$(_4);for(let n$=0;n$<Q$.length;n$++){let T$=Math.floor(Q$[n$]??-1);if(T$<0||T$>=_4)continue;if(!Q4[T$]){if(Q4[T$]=1,v++,T$<C)C=T$;if(T$>b)b=T$}}}if(M)return;let q4=Date.now()-O;if(q4>=y){let _4=k$();U6(_4)}else{if(M=!0,P)clearTimeout(P);P=setTimeout(()=>{if(P=null,!S){let _4=k$();U6(_4)}},y-q4)}}if(X&&_.isTTY)_.write("\x1B[?1049h");if(V)_.write("\x1B[?25l");if(G)_.write(`${t4.reset.open}${u$(Z)}\x1B[2J\x1B[H${t4.reset.open}`);let C6=$.on("commit",({dirtyRows:Q$})=>{if(K6())R6().render(`Commit event: dirtyRows=${Q$?.length??"null"}, rows=${Q$?.join(",")??"all"}`);z4(Q$)}),o$=J?.output??U?.stdout,F6=Boolean(Y&&_.isTTY&&typeof o$?.on==="function"),A6=()=>{let Q$=Number(o$?.columns),Z$=Number(o$?.rows);if(!Number.isFinite(Q$)||!Number.isFinite(Z$))return;let k$=$.size();if(Q$===k$.cols&&Z$===k$.rows)return;$.resize(Q$,Z$),z4()};if(F6)try{o$.on("resize",A6),A6()}catch{}z4();function F4(Q$,Z$){if(S)return;_.write(`\x1B[${Math.floor(Z$)+1};${Math.floor(Q$)+1}H`)}function E4(Q$){if(S)return;_.write(Q$?"\x1B[?25h":"\x1B[?25l")}function c4(){if(S)return;if(S=!0,P)clearTimeout(P),P=null;if(k=!1,L=null,v=0,C=Number.POSITIVE_INFINITY,b=-1,C6(),F6&&typeof o$?.off==="function")try{o$.off("resize",A6)}catch{}else if(F6&&typeof o$?.removeListener==="function")try{o$.removeListener("resize",A6)}catch{}if(V)_.write("\x1B[?25h");if(X&&_.isTTY)_.write("\x1B[?1049l")}return{render:z4,dispose:c4,setCursor:F4,showCursor:E4}}import{inject as Os}from"vue";function p4(){let $=Os(QJ,null);if(!$)throw Error("LayoutContext is missing (TerminalProvider/TView)");return $}import{inject as js}from"vue";function NU(){let $=js(GJ,null);if(!$)throw Error("RenderStack is missing");return $}import{computed as Es,onBeforeUnmount as Ps,ref as Ms,watchEffect as Ls}from"vue";import{inject as Ds}from"vue";function L4(){let $=Ds($V,null);if(!$)throw Error("TerminalProvider is missing");return $}function N0($){let{events:J}=L4(),U=Ms(null),Q=Es(()=>$()),_=Ls(()=>{let G=J.value;if(!G)return;let V=Q.value;if(!U.value){let X=G.register({rect:V.rect,zIndex:V.zIndex??0,visible:V.visible,focusable:V.focusable,selectable:V.selectable,handlers:V.handlers??{}});U.value=X.id;return}G.update(U.value,{rect:V.rect,zIndex:V.zIndex??0,visible:V.visible,focusable:V.focusable,selectable:V.selectable,handlers:V.handlers??{}})});return Ps(()=>{_();let G=J.value;if(G&&U.value)G.unregister(U.value)}),{id:U}}import{computed as zs,inject as Rs,provide as As,ref as UI,vShow as ws}from"vue";var ZV="__vueTerminalOnShow",_I=!1;function fs(){if(_I)return;_I=!0;let $=ws,J=$.beforeMount,U=$.updated,Q=$.beforeUnmount,_=(G,V)=>{if(!G||typeof G!=="object")return;let X=G[ZV];X?.(Boolean(V))};if(typeof J==="function")$.beforeMount=(G,V,X)=>{J(G,V,X),_(G,V?.value)};if(typeof U==="function")$.updated=(G,V,X)=>{U(G,V,X),_(G,V?.value)};if(typeof Q==="function")$.beforeUnmount=(G,V,X)=>{Q(G,V,X),_(G,V?.value)}}var ks=Object.freeze({position:"absolute",left:"-9999px",top:"0",width:"0",height:"0",overflow:"hidden"});function p6($){fs();let{scheduler:J}=L4(),U=Rs(n7,UI(!0)),Q=UI(!0),_=zs(()=>U.value&&Q.value);if($?.provide)As(n7,_);let G=(X)=>{Q.value=X,J.invalidate()};return{visible:_,rootProps:{style:ks,onVnodeBeforeMount:(X)=>{let Z=X.el;if(Z&&typeof Z==="object")Z[ZV]=G},onVnodeBeforeUnmount:(X)=>{let Z=X.el;if(Z&&typeof Z==="object"&&Z[ZV]===G)delete Z[ZV]}}}}function F0($,J){let U=Math.max($.x,J.x),Q=Math.max($.y,J.y),_=Math.min($.x+$.w,J.x+J.w),G=Math.min($.y+$.h,J.y+J.h);if(_<=U||G<=Q)return null;return{x:U,y:Q,w:_-U,h:G-Q}}function a6($,J,U){return{x:$.x+J,y:$.y+U,w:$.w,h:$.h}}import{computed as QI,defineComponent as Cs,h as bs,provide as GI,shallowReactive as ys,watchEffect as gs}from"vue";import{computed as Is,onBeforeUnmount as Ss,ref as Ts,watchEffect as vs}from"vue";function o6($){let{scheduler:J,render:U}=L4(),Q=NU(),_=Ts(null),G=Is(()=>$()),V=vs(()=>{let X=G.value;X.deps;let Z=X.stack??Q.value;if(!Z)return;if(!_.value){let Y=U.register({stack:Z,zIndex:X.zIndex,rect:X.rect,paint:X.paint});_.value=Y.id,J.invalidate();return}U.update(_.value,{stack:Z,zIndex:X.zIndex??0,rect:X.rect??null,paint:X.paint}),J.invalidate()});return Ss(()=>{if(V(),_.value)U.unregister(_.value),J.invalidate()}),{id:_}}var ZJ={tl:"┌",tr:"┐",bl:"└",br:"┘",h:"─",v:"│"},xs=-1,hs=1e6,N6=Cs({name:"TBox",props:{x:{type:Number,required:!0},y:{type:Number,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0},zIndex:{type:Number,default:0},border:{type:Boolean,default:!0},title:{type:String,default:""},padding:{type:Number,default:0},scrollX:{type:Number,default:0},scrollY:{type:Number,default:0},style:{type:Object,default:void 0},clear:{type:Boolean,default:!0}},setup($,{slots:J}){let{terminal:U,defaultStyle:Q,render:_}=L4(),G=p4(),V=NU(),{visible:X,rootProps:Z}=p6({provide:!0}),Y=QI(()=>{let H={x:$.x,y:$.y,w:$.w,h:$.h},E=a6(H,G.originX,G.originY);if(!G.clipRect)return E;return F0(E,G.clipRect)??{x:0,y:0,w:0,h:0}}),K=QI(()=>_.createStack(V.value,$.zIndex)),F=ys({originX:0,originY:0,clipRect:null});function N(H,E,D){let B=Math.max(0,Math.floor(H.w)),j=Math.max(0,Math.floor(H.h));if(!$.border||B<2||j<2)return;let f=Math.floor(H.x),R=Math.floor(H.y),I=f+B-1,w=R+j-1,T=Math.max(0,B-2),z=()=>{if(U.write(`${ZJ.tl}${YU(ZJ.h,T)}${ZJ.tr}`,{x:f,y:R,style:E}),$.title){let M=Math.max(0,B-4),P=z6($.title),A=m4(P,M);U.write(` ${A} `,{x:f+1,y:R,style:E})}},S=()=>{U.write(`${ZJ.bl}${YU(ZJ.h,T)}${ZJ.br}`,{x:f,y:w,style:E})},O=(M)=>{U.put(f,M,ZJ.v,E),U.put(I,M,ZJ.v,E)};if(!D){z(),S();for(let M=R+1;M<w;M++)O(M);return}for(let M of D){if(M<R||M>w)continue;if(M===R)z();else if(M===w)S();else O(M)}}function q(H,E,D){if(!$.clear)return;if(!D){U.fill(H.x,H.y,H.w,H.h," ",E);return}let B=Math.floor(H.y),j=B+Math.max(0,Math.floor(H.h));for(let f of D){if(f<B||f>=j)continue;U.fill(H.x,f,H.w,1," ",E)}}return gs(()=>{let H=Y.value,E=$.border?1:0,D=Math.max(0,Math.floor($.padding)),B=Math.max(0,Math.floor((H.w-E*2-1)/2)),j=Math.max(0,Math.floor((H.h-E*2-1)/2)),f=Math.min(D,B,j),R={x:H.x+E+f,y:H.y+E+f,w:Math.max(0,H.w-E*2-f*2),h:Math.max(0,H.h-E*2-f*2)},I=F0(R,H);if(G.clipRect&&I)I=F0(I,G.clipRect);if(!I)I={x:0,y:0,w:0,h:0};F.originX=R.x-Math.floor($.scrollX),F.originY=R.y-Math.floor($.scrollY),F.clipRect=I}),o6(()=>({stack:K.value,zIndex:xs,rect:X.value?Y.value:{x:0,y:0,w:0,h:0},deps:[X.value,Y.value,$.style,$.clear,Q.value],paint:(H)=>{if(!X.value)return;let E=Y.value,D=$.style??Q.value;q(E,D,H??null)}})),o6(()=>({stack:K.value,zIndex:hs,rect:X.value?Y.value:{x:0,y:0,w:0,h:0},deps:[X.value,Y.value,$.border,$.title,$.style,Q.value],paint:(H)=>{if(!X.value)return;let E=Y.value,D=$.style??Q.value;N(E,D,H??null)}})),GI(QJ,F),GI(GJ,K),()=>bs("div",Z,J.default?.())}});import{computed as ZO,defineComponent as us,h as ms}from"vue";function VI($,J){if(J<=0)return"";return $=z6($),m4($,J)}function XI($){return XJ($).split(`
|
|
900
|
-
`)}function cs($){let J=XI($),U=0;for(let Q of J)U=Math.max(U,M$(Q));return U}var t=us({name:"TText",props:{x:{type:Number,required:!0},y:{type:Number,required:!0},zIndex:{type:Number,default:0},value:{type:String,required:!0},w:{type:Number,default:void 0},h:{type:Number,default:void 0},style:{type:Object,default:void 0},clear:{type:Boolean,default:!0},wrap:{type:Boolean,default:!1}},setup($){let{terminal:J,defaultStyle:U}=L4(),Q=p4(),{visible:_,rootProps:G}=p6(),V=ZO(()=>cs($.value)),X=ZO(()=>{let Y=$.w??V.value;if(Y<=0)return[""];if(!$.wrap)return XI($.value).map((F)=>VI(F,Y));let K=XJ($.value);return K0(K,Y).map((F)=>VI(F,Y))}),Z=ZO(()=>{let Y=$.w??V.value,K=$.h??($.wrap?X.value.length||1:X.value.length||1),F={x:$.x,y:$.y,w:Y,h:K},N=a6(F,Q.originX,Q.originY);if(!Q.clipRect)return N;return F0(N,Q.clipRect)??{x:0,y:0,w:0,h:0}});return o6(()=>({zIndex:$.zIndex,rect:_.value?Z.value:{x:0,y:0,w:0,h:0},deps:[_.value,Z.value,$.value,$.w,$.h,$.wrap,$.style,U.value],paint:(Y)=>{if(!_.value)return;let K=Z.value;if(K.w<=0||K.h<=0)return;let F=$.style??U.value,N=$.clear?I4(K.w):"",q=X.value,H=Math.min(q.length,Math.max(0,Math.floor(K.h))),E=(D)=>{let B=D-K.y;if(B<0||B>=K.h)return;if($.clear)J.write(N,{x:K.x,y:D,style:F});if(B<0||B>=H)return;let j=m4(q[B]??"",K.w);J.write(h6(j,K.w),{x:K.x,y:D,style:F})};if(!Y){for(let D=0;D<K.h;D++)E(K.y+D);return}for(let D of Y)E(D)}})),()=>ms("span",G)}});import{computed as $_,defineComponent as ds,h as ls,inject as is,provide as KO,shallowReactive as rs,watchEffect as YI}from"vue";var ns=Object.freeze({x:0,y:0,w:0,h:0}),R4=ds({name:"TView",props:{x:{type:Number,required:!0},y:{type:Number,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0},zIndex:{type:Number,default:0},scrollX:{type:Number,default:0},scrollY:{type:Number,default:0},focusable:{type:Boolean,default:!1},selectable:{type:Boolean,default:void 0},autoFocus:{type:Boolean,default:!1}},emits:["clickCapture","click","dblclickCapture","dblclick","pointerdownCapture","pointerdown","pointerupCapture","pointerup","pointermoveCapture","pointermove","wheelCapture","wheel","keydownCapture","keydown","keyupCapture","keyup","focusCapture","focus","blurCapture","blur"],setup($,{emit:J,slots:U}){let Q=p4(),{render:_,events:G}=L4(),V=NU(),{visible:X,rootProps:Z}=p6({provide:!0}),Y=is(f0,$_(()=>0)),K=$_(()=>(Y.value??0)+($.zIndex??0)),F=$_(()=>a6({x:$.x,y:$.y,w:$.w,h:$.h},Q.originX,Q.originY)),N=$_(()=>{let D=F.value;if(!Q.clipRect)return D;return F0(D,Q.clipRect)??ns}),{id:q}=N0(()=>({rect:N.value,zIndex:K.value,visible:X.value,focusable:$.focusable,selectable:$.selectable,handlers:{clickCapture:(D)=>J("clickCapture",D),click:(D)=>J("click",D),dblclickCapture:(D)=>J("dblclickCapture",D),dblclick:(D)=>J("dblclick",D),pointerdownCapture:(D)=>J("pointerdownCapture",D),pointerdown:(D)=>J("pointerdown",D),pointerupCapture:(D)=>J("pointerupCapture",D),pointerup:(D)=>J("pointerup",D),pointermoveCapture:(D)=>J("pointermoveCapture",D),pointermove:(D)=>J("pointermove",D),wheelCapture:(D)=>J("wheelCapture",D),wheel:(D)=>J("wheel",D),keydownCapture:(D)=>J("keydownCapture",D),keydown:(D)=>J("keydown",D),keyupCapture:(D)=>J("keyupCapture",D),keyup:(D)=>J("keyup",D),focusCapture:(D)=>J("focusCapture",D),focus:(D)=>J("focus",D),blurCapture:(D)=>J("blurCapture",D),blur:(D)=>J("blur",D)}}));YI(()=>{if(!$.autoFocus)return;if(!X.value)return;let D=G.value,B=q.value;if(!D||!B)return;if(D.getFocused()===B)return;D.focus(B)});let H=rs({originX:0,originY:0,clipRect:null}),E=$_(()=>_.createStack(V.value,$.zIndex));return YI(()=>{let D=F.value;H.originX=D.x-Math.floor($.scrollX),H.originY=D.y-Math.floor($.scrollY),H.clipRect=N.value}),KO(QJ,H),KO(GJ,E),KO(f0,K),()=>ls("div",Z,U.default?.())}});import{computed as NO,defineComponent as FO,h as Q2,onBeforeUnmount as ps,onMounted as as,ref as J_,shallowRef as os,watch as KI,watchEffect as ts}from"vue";function KV($,J,U){return Math.max(J,Math.min(U,$))}function ss($){let J=Math.max(0,Math.floor($.cols)),U=Math.max(0,Math.floor($.rows)),Q=Math.max(0,Math.floor($.w)),_=Math.max(0,Math.floor($.h)),G=Math.floor($.offsetX),V=Math.floor($.offsetY),X=Math.max(0,J-Q),Z=Math.max(0,U-_),Y=Math.floor((J-Q)/2),K=Math.floor((U-_)/2),F=0,N=0;switch($.placement){case"top":F=Y,N=0;break;case"bottom":F=Y,N=Z;break;case"left":F=0,N=K;break;case"right":F=X,N=K;break;case"top-left":F=0,N=0;break;case"top-right":F=X,N=0;break;case"bottom-left":F=0,N=Z;break;case"bottom-right":F=X,N=Z;break;case"center":default:F=Y,N=K;break}return F=KV(F+G,0,X),N=KV(N+V,0,Z),{x:F,y:N}}function es($){let J=$.border?1:0,U=Math.max(0,Math.floor($.padding));return{w:Math.max(0,Math.floor($.w)-J*2-U*2),h:Math.max(0,Math.floor($.h)-J*2-U*2)}}var ZI=FO({name:"TDialogSurface",props:{modelValue:{type:Boolean,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0},title:{type:String,default:""},padding:{type:Number,default:1},zIndex:{type:Number,default:1000},style:{type:Object,default:void 0},placement:{type:String,default:"center"},offsetX:{type:Number,default:0},offsetY:{type:Number,default:0},backdrop:{type:Boolean,default:!0},closeOnBackdrop:{type:Boolean,default:!0},closeOnEsc:{type:Boolean,default:!0},closeOnBlur:{type:Boolean,default:!1},content:{type:[Object,Function],required:!0},onRequestClose:{type:Function,required:!0},onDialogFocus:{type:Function,default:void 0},onDialogBlur:{type:Function,default:void 0},onDialogKeydown:{type:Function,default:void 0},dialogNodeId:{type:String,default:void 0},onDialogNodeId:{type:Function,default:void 0}},setup($){let{events:J,scheduler:U}=L4(),Q=p4(),_=NO(()=>Q.clipRect?.w??0),G=NO(()=>Q.clipRect?.h??0),V=!1,X=!1,Z=!1;function Y(){if(V=!1,X)return;X=!0,$.onDialogFocus?.()}function K(){V=!0,queueMicrotask(()=>{if(!V)return;if(!$.modelValue)return;if(!X)return;if(V=!1,X=!1,$.onDialogBlur?.(),$.closeOnBlur)$.onRequestClose()})}let F=NO(()=>ss({cols:_.value,rows:G.value,w:$.w,h:$.h,placement:$.placement,offsetX:$.offsetX,offsetY:$.offsetY}));function N(){if(!$.closeOnBackdrop)return;$.onRequestClose()}function q(D){if($.modelValue&&D?.key==="Tab"&&!D?.defaultPrevented&&!Z){let B=J.value;if(B){Z=!0;try{let{x:j,y:f}=F.value,R=Math.max(0,Math.floor($.w)),I=Math.max(0,Math.floor($.h)),w=$.zIndex+($.backdrop?1:0),T={x:j,y:f,w:R,h:I},z=B.debugNodes(),S=z.filter((P)=>{if(!P.visible||!P.focusable)return!1;let A=P.rect;return A.x>=T.x&&A.y>=T.y&&A.x+A.w<=T.x+T.w&&A.y+A.h<=T.y+T.h}),O=S.find((P)=>P.zIndex===w&&P.rect.w===R&&P.rect.h===I),M;try{M=S.filter((P)=>P.id!==O?.id).sort((P,A)=>P.rect.y-A.rect.y||P.rect.x-A.rect.x||A.zIndex-P.zIndex)}catch{M=S.filter((P)=>P.id!==O?.id)}if(M.length>0){D.preventDefault?.();let P=D.shiftKey?-1:1,A=B.getFocused(),k=A?M.findIndex((C)=>C.id===A):-1,L=k<0?P>0?0:M.length-1:(k+P+M.length)%M.length,v=M[L]?.id;if(v){if(z.find((b)=>b.id===v&&b.visible&&b.focusable))try{B.focus(v),U.invalidate();return}catch(b){console.warn(`[TDialog] Failed to focus node ${v}:`,b)}}}}catch(j){console.error("[TDialog] Error in Tab handling:",j)}finally{setTimeout(()=>{Z=!1},0)}}}if($.onDialogKeydown?.(D),!$.closeOnEsc)return;if(D?.defaultPrevented)return;if(D?.key!=="Escape")return;D.preventDefault?.(),$.onRequestClose()}let H=J_(null),E=!1;return KI(()=>$.modelValue,(D)=>{if(!D){H.value=null;return}if(Z)return;queueMicrotask(()=>{queueMicrotask(()=>{if(Z)return;let B=J.value;if(!B)return;let{x:j,y:f}=F.value,R=Math.max(0,Math.floor($.w)),I=Math.max(0,Math.floor($.h)),w=$.zIndex+($.backdrop?1:0),T={x:j,y:f,w:R,h:I},z=B.debugNodes().filter((P)=>{if(!P.visible||!P.focusable)return!1;let A=P.rect;return A.x>=T.x&&A.y>=T.y&&A.x+A.w<=T.x+T.w&&A.y+A.h<=T.y+T.h}),S=z.find((P)=>P.zIndex===w&&P.rect.w===R&&P.rect.h===I);if(S)H.value=S.id;let O=B.getFocused();if(O){if(z.find((A)=>A.id===O))return}let M;try{M=z.filter((P)=>P.id!==H.value).sort((P,A)=>P.rect.y-A.rect.y||P.rect.x-A.rect.x)}catch{M=z.filter((P)=>P.id!==H.value)}if(M.length>0){E=!0;try{B.focus(M[0].id),U.invalidate()}finally{E=!1}return}if(H.value){E=!0;try{B.focus(H.value),U.invalidate()}finally{E=!1}}})})},{immediate:!0}),()=>{if(!$.modelValue)return null;let D=Math.max(0,Math.floor($.w)),B=Math.max(0,Math.floor($.h)),{x:j,y:f}=F.value,R=Q2(R4,{x:j,y:f,w:D,h:B,zIndex:$.zIndex+($.backdrop?1:0),focusable:!0,autoFocus:!1,onKeydown:q,onClick:(I)=>{I?.stopPropagation?.()},onFocusCapture:Y,onBlurCapture:K},()=>Q2(N6,{x:0,y:0,w:D,h:B,border:!0,title:$.title,padding:$.padding,style:$.style},()=>Q2($.content)));if(!$.backdrop)return R;return Q2(R4,{x:0,y:0,w:_.value,h:G.value,zIndex:$.zIndex,onClick:N},()=>[Q2(N6,{x:0,y:0,w:_.value,h:G.value,border:!1,padding:0,clear:!0}),R])}}}),A4=FO({name:"TDialog",props:{modelValue:{type:Boolean,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0},title:{type:String,default:""},padding:{type:Number,default:1},zIndex:{type:Number,default:1000},style:{type:Object,default:void 0},placement:{type:String,default:"center"},offsetX:{type:Number,default:0},offsetY:{type:Number,default:0},backdrop:{type:Boolean,default:!0},closeOnBackdrop:{type:Boolean,default:!0},closeOnEsc:{type:Boolean,default:!0},closeOnBlur:{type:Boolean,default:!1},teleport:{type:Boolean,default:!1},buttons:{type:Array,default:()=>[]},closeOnConfirm:{type:Boolean,default:!0}},emits:["update:modelValue","close","focus","blur","keydown","confirm"],setup($,{emit:J,slots:U}){let{runtime:Q,events:_,scheduler:G}=L4(),V=J_(!1),X=J_(0),Z=J_(null),Y=J_(null);function K(w,T,z){return T>=w.x&&z>=w.y&&T<w.x+w.w&&z<w.y+w.h}function F(w){return Math.max(0,w.w)*Math.max(0,w.h)}function N(){let w=$.buttons.findIndex((T)=>T.default);return w>=0?w:0}function q(w){let T=$.buttons[w];if(!T)return;if(J("confirm",{...T,index:w}),$.closeOnConfirm)j()}function H(){let w=_.value,T=w?.getFocused()??null;if(Z.value=T,Y.value=null,!w||!T)return;let z=w.debugNodes().find((P)=>P.id===T)??null;if(!z)return;let S=z.rect,O=Math.floor(S.x+Math.max(0,S.w)/2),M=Math.floor(S.y+Math.max(0,S.h)/2);Y.value={x:O,y:M}}function E(){let w=Z.value,T=Y.value;Z.value=null,Y.value=null;let z=()=>{let S=_.value;if(!S)return;if(w){if(S.debugNodes().find((k)=>k.id===w&&k.visible&&k.focusable)){S.focus(w),G.invalidate();return}}if(T){let A=S.debugNodes().filter((k)=>k.visible&&k.focusable&&K(k.rect,T.x,T.y)).sort((k,L)=>L.zIndex-k.zIndex||F(k.rect)-F(L.rect))[0]?.id??null;if(A){S.focus(A),G.invalidate();return}}let M=S.debugNodes().filter((P)=>P.visible&&P.focusable).sort((P,A)=>P.zIndex-A.zIndex||F(A.rect)-F(P.rect))[0]?.id??null;if(M)S.focus(M),G.invalidate()};queueMicrotask(()=>{queueMicrotask(()=>{queueMicrotask(()=>{z()})})})}let D=FO({name:"TDialogContent",setup(){return()=>{let w=U.default?.()??null;if(!$.buttons.length)return w;let T=es({w:$.w,h:$.h,padding:$.padding,border:!0}),z=Math.max(0,T.h-1),S=2,O=$.buttons.map((v)=>`[ ${v.label} ]`),M=O.map((v)=>M$(v)),P=M.reduce((v,C)=>v+C,0)+S*Math.max(0,M.length-1),k=Math.max(0,T.w-P),L=$.buttons.flatMap((v,C)=>{let b=O[C]??`[ ${v.label} ]`,y=M[C]??M$(b),x=C===X.value,c=v.kind==="primary",s=v.kind==="danger",F$={...c?{fg:"greenBright",bold:!0}:s?{fg:"redBright",bold:!0}:{fg:"whiteBright"},...x?{inverse:!0}:{}},K$=[Q2(t,{key:`btn-t-${C}`,x:k,y:z,w:y,value:b,style:F$}),Q2(R4,{key:`btn-v-${C}`,x:k,y:z,w:y,h:1,zIndex:10,onClick:(V$)=>{V$?.stopPropagation?.(),X.value=C,q(C)}})];return k+=y+S,K$});return Q2("div",null,[w,...L])}}}),B=os(null);function j(){V.value=!0,J("update:modelValue",!1),J("close"),E()}function f(){J("focus")}function R(){J("blur")}function I(w){if(J("keydown",w),!$.modelValue)return;if(w?.defaultPrevented)return;if(!$.buttons.length)return;if(w.key==="ArrowLeft"||w.key==="ArrowRight"){w.preventDefault?.();let T=w.key==="ArrowLeft"?-1:1,z=$.buttons.length-1;X.value=KV(X.value+T,0,z);return}if(w.key==="Enter")w.preventDefault?.(),q(X.value)}return KI(()=>$.modelValue,(w,T)=>{if(w&&!T)H();if(w&&!T)X.value=KV(N(),0,Math.max(0,$.buttons.length-1));if(!T||w)return;if(V.value){V.value=!1;return}J("close"),E()},{immediate:!0}),as(()=>{if(!$.teleport)return;B.value=Q.mount(ZI,{modelValue:$.modelValue,w:$.w,h:$.h,title:$.title,padding:$.padding,zIndex:$.zIndex,style:$.style,placement:$.placement,offsetX:$.offsetX,offsetY:$.offsetY,backdrop:$.backdrop,closeOnBackdrop:$.closeOnBackdrop,closeOnEsc:$.closeOnEsc,closeOnBlur:$.closeOnBlur,content:D,onRequestClose:j,onDialogFocus:f,onDialogBlur:R,onDialogKeydown:I})}),ts(()=>{if(!$.teleport)return;let w=B.value;if(!w)return;w.update({modelValue:$.modelValue,w:$.w,h:$.h,title:$.title,padding:$.padding,zIndex:$.zIndex,style:$.style,placement:$.placement,offsetX:$.offsetX,offsetY:$.offsetY,backdrop:$.backdrop,closeOnBackdrop:$.closeOnBackdrop,closeOnEsc:$.closeOnEsc,closeOnBlur:$.closeOnBlur,content:D,onRequestClose:j,onDialogFocus:f,onDialogBlur:R,onDialogKeydown:I})}),ps(()=>{if(B.value?.unmount(),B.value=null,Z.value||Y.value)E()}),()=>{if($.teleport)return null;return Q2(ZI,{modelValue:$.modelValue,w:$.w,h:$.h,title:$.title,padding:$.padding,zIndex:$.zIndex,style:$.style,placement:$.placement,offsetX:$.offsetX,offsetY:$.offsetY,backdrop:$.backdrop,closeOnBackdrop:$.closeOnBackdrop,closeOnEsc:$.closeOnEsc,closeOnBlur:$.closeOnBlur,content:D,onRequestClose:j,onDialogFocus:f,onDialogBlur:R,onDialogKeydown:I})}}});import{computed as O8,defineComponent as Ye,h as Ze,inject as LI,onBeforeUnmount as Ke,ref as t6,watch as zO,watchEffect as Ne}from"vue";function NI($){let J=String($||""),U=Math.max(J.lastIndexOf("/"),J.lastIndexOf("\\"));return(U>=0?J.slice(U+1):J)||J}function $e($){let J=$.lastIndexOf(".");if(J===-1)return"";return $.slice(J+1).toLowerCase()}function Je($){return["png","jpg","jpeg","gif","svg","webp","bmp","ico"].includes($)}function Ue($){return["mp4","webm","ogg","avi","mov","mkv","flv","wmv"].includes($)}function _e($){return["mp3","wav","ogg","flac","m4a","wma"].includes($)}function Qe($){return["pdf","doc","docx","txt","rtf","odt"].includes($)}function Ge($){return["js","ts","jsx","tsx","html","css","scss","less","json","xml","yml","yaml","md","markdown","py","java","cpp","c","go","rb","php"].includes($)}function FI($){if(!$)return"[file]";let J=NI($);return`[${z6(J)}]`}function NV($,J,U){if(U==="directory")return{...$,fg:"blueBright",underline:!0,bold:!0};let Q=NI(J),_=$e(Q);if(Je(_))return{...$,fg:"magentaBright",underline:!0,bold:!0};if(Ue(_))return{...$,fg:"yellowBright",underline:!0,bold:!0};if(_e(_))return{...$,fg:"greenBright",underline:!0,bold:!0};if(Qe(_))return{...$,fg:"blueBright",underline:!0,bold:!0};if(Ge(_))return{...$,fg:"cyanBright",underline:!0,bold:!0};return{...$,fg:"cyanBright",underline:!0}}function U_($,J,U){return Math.max(J,Math.min(U,$))}function Ve($){for(let J=0;J<$.length;J++)if($.charCodeAt(J)>127)return!1;return!0}var G2=M$;function WO($,J){let U=G2($);if(U>=J)return $;return $+I4(J-U)}function FU($,J,U){if(J=Math.max(0,Math.floor(J)),U=Math.max(0,Math.floor(U)),U<=0)return"";if(!$)return"";if(Ve($))return $.slice(J,J+U);let Q="",_=0,G=0;for(let V=0;V<$.length;){if($.charCodeAt(V)<=127){if(_<J){_++,V++;continue}if(G>=U)break;Q+=$[V],G++,V++;continue}let Z=$.codePointAt(V)??0,Y=String.fromCodePoint(Z),K=u4(Y);if(_+K<=J){_+=K,V+=Y.length;continue}if(G+K>U)break;Q+=Y,G+=K,V+=Y.length}return Q}function qO($){let J=[],U=0;for(let Q=0;Q<=$.length;Q++)if(Q===$.length||$[Q]===`
|
|
901
|
-
`)J.push({start:U,end:Q}),U=Q+1;return J.length?J:[{start:0,end:0}]}function WU($,J){return`[... ${(String($?.[J]??"").match(/\n/g)||[]).length+1} lines]`}function qU($,J){let U=String($?.[J]??"");return FI(U)}function WI($,J,U=$.length){let Q=0,_=U_(U,0,$.length);for(let G=0;G<_;G++)if($[G]===J)Q++;return Q}function HU($,J,U=$.length){return WI($,J,U)}function BU($,J,U=$.length){return WI($,J,U)}function qI($,J,U){return HU($,J,U)}function HI($,J,U){return BU($,J,U)}function FV($,J,U,Q,_,G,V){let X=U_(G,0,$.length),Z=U_(V,X,$.length),Y=0,K=0,F=0;for(let N=0;N<Z;){let q=$[N];if(q===J){if(N>=X){let B=WU(Q,K);Y+=M$(B)}K++,N+=1;continue}if(q===U){if(N>=X){let B=qU(_,F);Y+=M$(B)}F++,N+=1;continue}if($.charCodeAt(N)<=127){if(N>=X)Y+=1;N+=1;continue}let E=$.codePointAt(N)??0,D=String.fromCodePoint(E);if(N>=X)Y+=u4(D);N+=D.length}return Y}function Xe($,J,U,Q,_,G){G=Math.max(1,Math.floor(G));let V=[],X=0,Z=0,Y=0,K=0;for(let F=0;F<$.length;){let N=$[F];if(N===`
|
|
902
|
-
`){V.push({start:X,end:F}),F+=1,X=F,Z=0;continue}let q=0,H=0;if(N===J){let E=WU(Q,Y);H=M$(E),q=1,Y++}else if(N===U){let E=qU(_,K);H=M$(E),q=1,K++}else if($.charCodeAt(F)<=127)q=1,H=1;else{let D=$.codePointAt(F)??0,B=String.fromCodePoint(D);q=B.length,H=u4(B)}if(Z>0&&Z+H>G)V.push({start:X,end:F}),X=F,Z=0;if(Z+=H,F+=q,Z>=G)V.push({start:X,end:F}),X=F,Z=0}return V.push({start:X,end:$.length}),V.length?V:[{start:0,end:0}]}function HO($,J,U,Q,_,G,V){if(G=Math.max(1,Math.floor(G)),V=Math.max(1,Math.floor(V)),G>=V)return Xe($,J,U,Q,_,V);let X=[],Z=0,Y=0,K=G,F=!0,N=0,q=0;for(let H=0;H<$.length;){let E=$[H];if(E===`
|
|
903
|
-
`){X.push({start:Z,end:H}),H+=1,Z=H,Y=0,F=!1,K=V;continue}let D=0,B=0;if(E===J){let j=WU(Q,N);B=M$(j),D=1,N++}else if(E===U){let j=qU(_,q);B=M$(j),D=1,q++}else if($.charCodeAt(H)<=127)D=1,B=1;else{let f=$.codePointAt(H)??0,R=String.fromCodePoint(f);D=R.length,B=u4(R)}if(Y>0&&Y+B>K){if(X.push({start:Z,end:H}),Z=H,Y=0,F)F=!1,K=V;continue}if(Y+=B,H+=D,Y>=K){if(X.push({start:Z,end:H}),Z=H,Y=0,F)F=!1,K=V}}return X.push({start:Z,end:$.length}),X.length?X:[{start:0,end:0}]}function BI($,J,U,Q,_,G,V,X){let Z=U_(G,0,$.length),Y=HO($,J,U,Q,_,V,X);for(let F=0;F<Y.length;F++){let N=Y[F];if(Z<=N.end){let q=FV($,J,U,Q,_,N.start,Z);return{line:F,col:q,lines:Y}}}let K=Y[Y.length-1];return{line:Y.length-1,col:FV($,J,U,Q,_,K.start,K.end),lines:Y}}function OI($,J,U,Q,_,G){let V=U_(G,0,$.length),X=qO($);for(let Y=0;Y<X.length;Y++){let K=X[Y];if(V<=K.end){let F=FV($,J,U,Q,_,K.start,V);return{line:Y,col:F,lines:X}}}let Z=X[X.length-1];return{line:X.length-1,col:FV($,J,U,Q,_,Z.start,Z.end),lines:X}}function BO($,J,U,Q,_,G,V,X){let Z=Math.max(0,Math.floor(X)),Y=0,K=HU($,J,G),F=BU($,U,G);for(let N=G;N<V;){let q=$[N];if(q===J){let j=WU(Q,K),f=M$(j);if(Y+f>Z)return{index:N,hit:{kind:"multiline",index:K}};if(Y+=f,Y>=Z)return{index:N+1,hit:null};K++,N+=1;continue}if(q===U){let j=qU(_,F),f=M$(j);if(Y+f>Z)return{index:N,hit:{kind:"mention",index:F}};if(Y+=f,Y>=Z)return{index:N+1,hit:null};F++,N+=1;continue}if($.charCodeAt(N)<=127){if(Y+1>Z)return{index:N,hit:null};if(Y+=1,N+=1,Y>=Z)return{index:N,hit:null};continue}let E=$.codePointAt(N)??0,D=String.fromCodePoint(E),B=u4(D);if(Y+B>Z)return{index:N,hit:null};if(Y+=B,N+=D.length,Y>=Z)return{index:N,hit:null}}return{index:V,hit:null}}function jI($,J,U,Q,_,G,V,X,Z,Y){let K=Math.max(0,Math.floor(Y)),F=K+Math.max(0,Math.floor(Z)),N=0,q=HU($,U,V),H=BU($,Q,V),E="",D=0,B=[];for(let j=V;j<X;){let f=$[j];if(f===`
|
|
904
|
-
`){j+=1;continue}let R="",I=0,w=0,T=!1,z=null,S=0,O;if(f===U)R=WU(_,q),I=M$(R),w=1,z="multiline",S=q,q++,T=!0;else if(f===Q)R=qU(G,H),I=M$(R),w=1,z="mention",S=H,O=String(G?.[H]??""),H++,T=!0;else if($.charCodeAt(j)<=127)R=J[j]??$[j],w=1,I=1;else{let v=$.codePointAt(j)??0,C=String.fromCodePoint(v);R=J.slice(j,j+C.length),w=C.length,I=u4(R)}let M=N,P=N+I;if(P<=K){N=P,j+=w;continue}if(M>=F)break;let A=Math.max(0,K-M),k=Math.min(P,F)-Math.max(M,K);if(k>0){let L=FU(R,A,k);if(!L&&I>1&&A>0&&I<=Z)L=R;if(E+=L,L===R)D+=I;else D+=k;if(T){let v=Math.max(M,K)-K;B.push({startCell:v,label:L,kind:z,index:S,...O?{absPath:O}:{}})}}N=P,j+=w}if(D<Z)E+=I4(Z-D);return{text:E,chips:B}}function DI($,J,U,Q,_,G,V,X,Z,Y,K){let F=Math.max(0,Math.floor(K)),N=F+Math.max(0,Math.floor(Y)),q=0,H=HU($,U,V),E=BU($,Q,V),D=[];for(let B=V;B<X;){let j=$[B];if(j===`
|
|
905
|
-
`){B+=1;continue}let f="",R=0,I=0;if(j===U)f=WU(_,H),R=G2(f),I=1,H++;else if(j===Q)f=qU(G,E),R=G2(f),I=1,E++;else{let M=$.codePointAt(B)??0,P=String.fromCodePoint(M);f=J.slice(B,B+P.length),I=P.length,R=u4(f)}if(B>=Z.end||B+I<=Z.start){q+=R,B+=I;continue}let w=q,T=q+R,z=Math.max(0,F-w),S=Math.min(T,N)-Math.max(w,F);if(T>F&&w<N&&S>0){let M=FU(f,z,S),P=Math.max(w,F)-F;if(M)D.push({startCell:P,text:M})}q=T,B+=I}return D}var u0="",W0="";function OO($,J){return $[J]===u0}function __($,J){return $[J]===W0}function WV($,J=$.length){return HU($,u0,J)}function jO($,J=$.length){return BU($,W0,J)}function qV($,J){return qI($,u0,J)}function OU($,J){return HI($,W0,J)}function DO($,J,U,Q,_){return HO($,u0,W0,J,U,Q,_)}function H8($,J,U,Q,_,G){return BI($,u0,W0,J,U,Q,_,G)}function B8($,J,U,Q){return OI($,u0,W0,J,U,Q)}function EO($,J,U,Q,_,G){return BO($,u0,W0,J,U,Q,_,G)}function PO($,J,U,Q,_){return BO($,u0,W0,J,U,Q.start,Q.end,_)}function EI($,J,U,Q,_,G,V,X){return jI($,J,u0,W0,U,Q,_,G,V,X)}function PI($,J,U,Q,_,G,V,X,Z){return DI($,J,u0,W0,U,Q,_,G,V,X,Z)}function j4($,J,U){return Math.max(J,Math.min(U,$))}function k0($){return $===" "||$==="\t"||$===`
|
|
906
|
-
`||$==="\r"}function KJ($){return/^[\p{L}\p{N}_]$/u.test($)}function MO($,J){let U=j4(J,0,$.length);if(U===0)return 0;while(U>0&&k0($[U-1]))U--;if(U===0)return 0;let Q=KJ($[U-1]);while(U>0){let _=$[U-1];if(k0(_))break;if(KJ(_)!==Q)break;U--}return U}function LO($,J){let U=j4(J,0,$.length);if(U>=$.length)return $.length;while(U<$.length&&k0($[U]))U++;if(U>=$.length)return $.length;let Q=KJ($[U]);while(U<$.length){let _=$[U];if(k0(_))break;if(KJ(_)!==Q)break;U++}return U}function MI($,J){if(!$)return null;let U=j4(J,0,$.length);if(U===$.length)U=$.length-1;if(U<0)return null;let Q=$[U];if(!Q)return null;let _=U,G=U+1;if(k0(Q)){while(_>0&&k0($[_-1]))_--;while(G<$.length&&k0($[G]))G++;return{start:_,end:G}}let V=KJ(Q);while(_>0){let X=$[_-1];if(k0(X))break;if(KJ(X)!==V)break;_--}while(G<$.length){let X=$[G];if(k0(X))break;if(KJ(X)!==V)break;G++}return{start:_,end:G}}function Fe($){if($.ctrlKey||$.metaKey||$.altKey)return!1;return $.key.length===1}function AO($){return qO($)}function RO($,J){let U=j4(J,0,$.length),Q=AO($);for(let G=0;G<Q.length;G++){let V=Q[G];if(U<=V.end){let X=$.slice(V.start,U);return{line:G,col:G2(X),lines:Q}}}let _=Q[Q.length-1];return{line:Q.length-1,col:G2($.slice(_.start,_.end)),lines:Q}}var We=0,J6=Ye({name:"TInput",props:{x:{type:Number,required:!0},y:{type:Number,required:!0},w:{type:Number,required:!0},h:{type:Number,default:1},zIndex:{type:Number,default:0},modelValue:{type:String,required:!0},cursorToEndOnExternalUpdate:{type:Boolean,default:!1},cursorToEndOnFirstFocus:{type:Boolean,default:!1},placeholder:{type:String,default:""},placeholderWhenFocused:{type:Boolean,default:!1},style:{type:Object,default:void 0},autoFocus:{type:Boolean,default:!1},cursorBlink:{type:Boolean,default:!0},cursorShape:{type:String,default:"block"},blinkInterval:{type:Number,default:500},promptSuggestions:{type:Array,default:()=>[]},promptTrigger:{type:String,default:"/"},promptMaxItems:{type:Number,default:6},mentionTrigger:{type:String,default:"@"},mentionWorkspace:{type:String,default:""},mentionMode:{type:String,default:"file"},mentionShowHidden:{type:Boolean,default:!1},mentionSuggestions:{type:Array,default:()=>[]},mentionMaxItems:{type:Number,default:8},collectMentions:{type:Boolean,default:!1},mentions:{type:Array,default:()=>[]},collapseMultiline:{type:Boolean,default:!1},multilineTexts:{type:Array,default:()=>[]},secret:{type:Boolean,default:!1},maskChar:{type:String,default:"•"},plugins:{type:Array,default:()=>[]}},emits:["update:modelValue","input","change","keydown","focus","blur","update:mentions","mentionClick","update:multilineTexts","multilineClick","validationError"],setup($,{emit:J}){let{terminal:U,scheduler:Q,defaultStyle:_,events:G,render:V}=L4(),X=p4(),{visible:Z,rootProps:Y}=p6(),K=LI(JV,null),F=`TInput:${We++}`,N=LI(f0,O8(()=>0)),q=O8(()=>(N.value??0)+($.zIndex??0)),H=1;function E(g){let h=Math.max(0,Math.floor(g.w)),q$=Math.max(0,Math.floor(g.h)),i=j4(1,0,Math.floor(h/2)),p=Math.max(0,h-i*2);return{wAll:h,hAll:q$,padX:i,w:p}}let D=t6(!1),B=t6(0),j=t6(null),f=t6(!1),R=t6(!1),I=t6(0),w=t6(0),T=t6(!1),z=t6(""),S=t6(!1),O=t6(!1),M=t6(!0),P=null,A=t6(null),k=null,L=!1,v=!1,C=!1,b=null,y=450,x=t6(null);function c(){return x.value??$.modelValue}let s=200,F$=[],K$=[],V$=!1;function Y$(g){if(V$)return;let h={value:c(),cursor:B.value};if(h.value===g)return;let q$=F$[F$.length-1];if(q$&&q$.value===h.value&&q$.cursor===h.cursor)return;if(F$.push(h),F$.length>s)F$.splice(0,F$.length-s);K$.length=0}function u$(g){V$=!0;try{t$(g.value,g.cursor)}finally{V$=!1}}function _$(){let g=F$.pop();if(!g)return;let h={value:c(),cursor:B.value};K$.push(h),u$(g)}function n(){let g=K$.pop();if(!g)return;let h={value:c(),cursor:B.value};F$.push(h),u$(g)}let a=O8(()=>Math.max(1,Math.floor($.h))>1),m=O8(()=>{let g={x:$.x,y:$.y,w:$.w,h:Math.max(1,Math.floor($.h))};return a6(g,X.originX,X.originY)});zO(()=>$.modelValue,(g,h)=>{let q$=x.value!=null;if(x.value=null,!q$)F$.length=0,K$.length=0;let i=g.length;if(!q$&&$.cursorToEndOnExternalUpdate&&!T.value)B.value=i,j.value=null;else if(B.value=j4(B.value,0,i),j.value!=null)j.value=j4(j.value,0,i);if(T.value&&g!==h)S.value=!0,T.value=!1,z.value="";let p=WV(g),l=$.multilineTexts??[];if(l.length>p)J("update:multilineTexts",l.slice(0,p));Z$(),Q.invalidate()});let G$=[];function L$(g){G$.push(g)}let P$=[];function f$(g){P$.push(g)}let V4=t6(null);function s4(g){V4.value=g}function U6(g){return String($.maskChar||"•").repeat(Math.max(0,g.length))}function z4(){if(P!=null)clearInterval(P),P=null;M.value=!0}function C6(){if(z4(),!$.cursorBlink)return;let g=Math.max(120,Math.floor($.blinkInterval));P=globalThis.setInterval(()=>{M.value=!M.value,Q.invalidate()},g)}let o$=O8(()=>{let g={x:$.x,y:$.y,w:$.w,h:Math.max(1,Math.floor($.h))},h=a6(g,X.originX,X.originY);if(!X.clipRect)return h;return F0(h,X.clipRect)??{x:0,y:0,w:0,h:0}}),F6=O8(()=>{if(j.value==null||j.value===B.value)return null;let g=Math.min(j.value,B.value),h=Math.max(j.value,B.value);return{start:g,end:h}});function A6(){let g=c(),h=MI(g,B.value);if(!h)return;j.value=h.start,B.value=h.end,Z$(),Q.invalidate()}function F4(){let g=c();j.value=0,B.value=g.length,Z$(),Q.invalidate()}let E4=O8(()=>{if(c())return!1;if(!$.placeholder)return!1;if(D.value&&T.value&&z.value)return!1;return!D.value||$.placeholderWhenFocused}),c4=typeof document<"u";function Q$(g){let h=j4(B.value,0,g.length);if(T.value&&z.value){let q$=`${g.slice(0,h)}${z.value}${g.slice(h)}`,i=c4?j4(h+z.value.length,0,q$.length):h;return{text:q$,cursor:i}}return{text:g,cursor:h}}function Z$(){let g=o$.value,{hAll:h,w:q$}=E(g),i=Math.max(1,q$),p=Math.max(1,h),l=c(),$$=Q$(l),e=a.value,D$=i,{line:v$,col:A$,lines:g$}=e?H8($$.text,$.multilineTexts,$.mentions,$$.cursor,D$,i):B8($$.text,$.multilineTexts,$.mentions,$$.cursor);if(e)I.value=0;else if(i<=0)I.value=0;else{let d$=v$===0?D$:i;if(A$<I.value)I.value=A$;else if(A$>I.value+d$-1)I.value=Math.max(0,A$-(d$-1))}let c$=Math.max(0,g$.length-p);if(w.value=j4(w.value,0,c$),v$<w.value)w.value=v$;else if(v$>w.value+p-1)w.value=j4(v$-(p-1),0,c$)}function k$(g,h,q$=!1,i){let p=o$.value,{w:l,padX:$$}=E(p),e=Math.max(1,l),D$=j4(g-(p.x+$$),0,Math.max(0,l-1)),v$=j4(h-p.y,0,Math.max(0,p.h-1)),A$=c(),g$=a.value,c$=D$,d$=e,y$=0,X4=null;if(g$){let W4=DO(A$,$.multilineTexts,$.mentions,d$,e),_6=j4(w.value+v$,0,W4.length-1),i$=c$,l$=PO(A$,$.multilineTexts,$.mentions,W4[_6],i$);y$=l$.index,X4=l$.hit}else{let W4=AO(A$),_6=j4(w.value+v$,0,W4.length-1),i$=I.value+c$,l$=W4[_6],Y4=EO(A$,$.multilineTexts,$.mentions,l$.start,l$.end,i$);y$=Y4.index,X4=Y4.hit}if(X4){if(B.value=y$,j.value=null,Z$(),X4.kind==="multiline")J("multilineClick",X4.index);else{let W4=String($.mentions?.[X4.index]??"");if(W4)J("mentionClick",W4,i)}i?.preventDefault?.(),Q.invalidate();return}if(!q$)j.value=null;else if(j.value==null)j.value=B.value;B.value=y$,A.value=g$?H8(A$,$.multilineTexts,$.mentions,B.value,d$,e).col:B8(A$,$.multilineTexts,$.mentions,B.value).col,Z$()}function t$(g,h,q$=!1){let i=j4(h,0,g.length);if(B.value=i,j.value=null,T.value=!1,z.value="",x.value=g,a.value){let{w:p}=E(o$.value),l=Math.max(1,p),$$=l;A.value=H8(g,$.multilineTexts,$.mentions,i,$$,l).col}else A.value=B8(g,$.multilineTexts,$.mentions,i).col;if(Z$(),J("update:modelValue",g),J("input",g),q$)J("change",g);Q.invalidate()}function q4(g,h){let q$=B.value,i=c();if(h){if(j.value==null)j.value=q$}else j.value=null;if(B.value=j4(g,0,i.length),a.value){let{w:p}=E(o$.value),l=Math.max(1,p),$$=l;A.value=H8(i,$.multilineTexts,$.mentions,B.value,$$,l).col}else A.value=B8(i,$.multilineTexts,$.mentions,B.value).col;Z$(),Q.invalidate()}zO([()=>o$.value.w,()=>o$.value.h,()=>a.value],()=>{Z$(),Q.invalidate()}),zO([()=>$.mentions,()=>$.multilineTexts],()=>{Z$(),Q.invalidate()});function _4(g){let h=F6.value;if(!h)return{value:g,cursor:B.value,deleted:!1};let q$=WV(g,h.start),i=WV(g,h.end);if(i>q$){let e=$.multilineTexts??[],D$=[...e.slice(0,q$),...e.slice(i)];J("update:multilineTexts",D$)}let p=jO(g,h.start),l=jO(g,h.end);if(l>p){let e=$.mentions??[],D$=[...e.slice(0,p),...e.slice(l)];J("update:mentions",D$)}return{value:g.slice(0,h.start)+g.slice(h.end),cursor:h.start,deleted:!0}}function Q4(g){let h=g||"";if(!h)return;let q$=c(),i=F6.value;for(let g$ of P$){try{h=g$({text:h,value:q$,cursor:B.value,selection:i})}catch{}if(!h)return}let p=c(),{value:l,cursor:$$,deleted:e}=_4(p),D$=e?l:p,v$=e?$$:B.value,A$=D$.slice(0,v$)+h+D$.slice(v$);Y$(A$),t$(A$,v$+h.length)}for(let g of $.plugins??[])try{g.install({getProps:()=>({zIndex:$.zIndex,style:$.style,promptSuggestions:$.promptSuggestions,promptTrigger:$.promptTrigger,promptMaxItems:$.promptMaxItems,mentionTrigger:$.mentionTrigger,mentionWorkspace:$.mentionWorkspace,mentionMode:$.mentionMode,mentionShowHidden:$.mentionShowHidden,mentionSuggestions:$.mentionSuggestions,mentionMaxItems:$.mentionMaxItems,collectMentions:$.collectMentions,mentions:$.mentions}),emit:J,terminal:U,scheduler:Q,defaultStyle:_,render:V,visible:Z,rawAbsRect:m,eventZ:q,focused:D,cursor:B,getValue:c,insertText:Q4,pushUndoSnapshot:Y$,applyEdit:(h,q$)=>t$(h,q$),registerKeydownInterceptor:L$,registerTextFilter:f$,registerChipStyleProvider:s4,mentionToken:W0})}catch{}function n$(g){let h=c(),{value:q$,cursor:i,deleted:p}=_4(h),l=p?q$:h,$$=p?i:B.value,e=qV(l,$$),D$=$.multilineTexts??[],v$=[...D$.slice(0,e),g,...D$.slice(e)];J("update:multilineTexts",v$);let A$=`${l.slice(0,$$)}${u0}${l.slice($$)}`;t$(A$,$$+1)}function T$(g,h){let q$=Math.max(0,Math.floor(h)),i=0;for(let p=0;p<g.length;p++){if(g[p]!==W0)continue;if(i===q$)return{value:g.slice(0,p)+g.slice(p+1),removedCharIndex:p};i++}return{value:g,removedCharIndex:null}}function y4(g){let h=String(g||"").trim();if(!h)return;if(!$.collectMentions){let y$=$.mentionTrigger||"@";Q4(`${y$}${h} `);return}let q$=c(),{value:i,cursor:p,deleted:l}=_4(q$),$$=l?i:q$,e=l?p:B.value,v$=[...$.mentions??[]],A$=v$.indexOf(h);if(A$>=0){let y$=T$($$,A$);if(y$.removedCharIndex!=null&&y$.removedCharIndex<e)e=Math.max(0,e-1);$$=y$.value,v$.splice(A$,1)}let g$=OU($$,e);v$.splice(g$,0,h),J("update:mentions",v$);let c$=$$.slice(e);if(c$.startsWith(" "))c$=c$.slice(1);let d$=`${$$.slice(0,e)}${W0} ${c$}`;Y$(d$),t$(d$,e+2)}function p$(g){if(typeof g.text==="string")return g.text;if(typeof g.data==="string"&&g.data)return g.data;let h=g.nativeEvent,q$=h?.clipboardData;if(q$?.getData){let p=q$.getData("text/plain")||q$.getData("text");if(typeof p==="string"&&p)return p}let i=h?.target;if(i&&typeof i.value==="string"&&i.value)return i.value;return""}function e4(g){if(T.value){J("keydown",g);return}for(let i$ of G$)if(i$(g)){J("keydown",g);return}if(J("keydown",g),g.defaultPrevented)return;let h=c(),q$=Boolean(g.shiftKey),i=Boolean(g.altKey||g.ctrlKey&&!g.metaKey&&!g.altKey),p=Boolean(g.metaKey),l=Boolean(g.metaKey||g.ctrlKey&&!g.altKey),$$=typeof globalThis.window>"u"&&typeof globalThis.process<"u",e=Boolean((g.metaKey||g.ctrlKey)&&!g.altKey),D$=g.key==="c"||g.key==="C",v$=g.key==="x"||g.key==="X",A$=g.key==="a"||g.key==="A",g$=g.key==="e"||g.key==="E",c$=g.key==="z"||g.key==="Z",d$=g.key==="y"||g.key==="Y",y$=F6.value;if(e&&c$){if(g.preventDefault(),g.stopPropagation(),g.shiftKey)n();else _$();return}if(e&&d$){g.preventDefault(),g.stopPropagation(),n();return}if($$&&g.ctrlKey&&!g.metaKey&&!g.altKey&&(A$||g$)){g.preventDefault();let{line:i$,lines:l$}=RO(h,B.value),Y4=A$?l$[i$].start:l$[i$].end;q4(Y4,q$);return}if($$&&g.altKey&&!g.ctrlKey&&!g.metaKey){let i$=g.key==="b"||g.key==="B",l$=g.key==="f"||g.key==="F";if(i$||l$){g.preventDefault();let Y4=i$?MO(h,B.value):LO(h,B.value);q4(Y4,q$);return}}let X4=(i$)=>{let Y4="";for(let a$=0;a$<i$.length;a$+=3){let $4=i$[a$]??0,x$=i$[a$+1]??0,r$=i$[a$+2]??0,D4=$4<<16|x$<<8|r$;Y4+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[D4>>18&63]??"",Y4+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[D4>>12&63]??"",Y4+=a$+1<i$.length?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[D4>>6&63]??"":"=",Y4+=a$+2<i$.length?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[D4&63]??"":"="}return Y4},W4=(i$)=>{if(typeof TextEncoder<"u")return X4(new TextEncoder().encode(i$));let l$=unescape(encodeURIComponent(i$)),Y4=new Uint8Array(l$.length);for(let a$=0;a$<l$.length;a$++)Y4[a$]=l$.charCodeAt(a$);return X4(Y4)},_6=async(i$)=>{if(!i$)return!1;let l$=globalThis.navigator;if(l$?.clipboard?.writeText)try{return await l$.clipboard.writeText(i$),!0}catch{}let Y4=globalThis.process;if(Y4?.stdout?.write&&Y4?.stdout?.isTTY)try{let $4=W4(i$);return Y4.stdout.write(`\x1B]52;c;${$4}\x07`),!0}catch{}let a$=globalThis.document;if(!a$?.createElement||!a$?.body?.appendChild||typeof a$.execCommand!=="function")return!1;try{let $4=a$.activeElement,x$=a$.createElement("textarea");x$.value=i$,x$.setAttribute("readonly","true"),x$.setAttribute("aria-hidden","true"),x$.style.position="fixed",x$.style.left="-9999px",x$.style.top="-9999px",x$.style.opacity="0",a$.body.appendChild(x$),x$.focus(),x$.select(),x$.setSelectionRange(0,x$.value.length);let r$=Boolean(a$.execCommand("copy"));x$.remove();try{$4?.focus?.({preventScroll:!0})}catch{$4?.focus?.()}return r$}catch{return!1}};if(e&&A$){g.preventDefault(),g.stopPropagation(),j.value=0,B.value=h.length,Z$(),Q.invalidate();return}if(e&&(D$||v$)&&y$){g.preventDefault(),g.stopPropagation();let i$=h.slice(y$.start,y$.end);if(_6(i$).then((l$)=>{if(!$$)return;let Y4=globalThis.__VT_SHOW_COPY_TOAST__;if(typeof Y4==="function")Y4(l$?"Copied":"Copy failed")}).catch(()=>{if(!$$)return;let l$=globalThis.__VT_SHOW_COPY_TOAST__;if(typeof l$==="function")l$("Copy failed")}),v$){let l$=h.slice(0,y$.start)+h.slice(y$.end);Y$(l$),t$(l$,y$.start)}return}if(g.key==="ArrowLeft"){g.preventDefault();let i$=p?0:i?MO(h,B.value):B.value-1;q4(i$,q$);return}if(g.key==="ArrowRight"){g.preventDefault();let i$=p?h.length:i?LO(h,B.value):B.value+1;q4(i$,q$);return}if(g.key==="ArrowUp"||g.key==="ArrowDown"){g.preventDefault();let i$=a.value,{w:l$}=E(o$.value),Y4=Math.max(1,l$),a$=Y4,{line:$4,col:x$,lines:r$}=i$?H8(h,$.multilineTexts,$.mentions,B.value,a$,Y4):B8(h,$.multilineTexts,$.mentions,B.value),D4=g.key==="ArrowUp"?$4-1:$4+1;if(D4<0){let b6=r$[$4].start;q4(b6,q$);return}if(D4>=r$.length){let b6=r$[$4].end;q4(b6,q$);return}let w4=D4,d4=A.value??x$,$6=i$?PO(h,$.multilineTexts,$.mentions,r$[w4],d4).index:EO(h,$.multilineTexts,$.mentions,r$[w4].start,r$[w4].end,d4).index;q4($6,q$),A.value=d4;return}if(g.key==="Home"){if(g.preventDefault(),l)q4(0,q$);else{let{line:i$,lines:l$}=RO(h,B.value),Y4=l$[i$].start;q4(Y4,q$)}return}if(g.key==="End"){if(g.preventDefault(),l)q4(h.length,q$);else{let{line:i$,lines:l$}=RO(h,B.value),Y4=l$[i$].end;q4(Y4,q$)}return}if(g.key==="Backspace"){let i$=$.mentions??[];if(!h&&B.value<=0&&i$.length>0){g.preventDefault(),J("update:mentions",i$.slice(0,-1)),Q.invalidate();return}g.preventDefault();let{value:l$,cursor:Y4,deleted:a$}=_4(h);if(a$){Y$(l$),t$(l$,Y4);return}if(B.value<=0)return;if(B.value>=2&&h[B.value-1]===" "&&__(h,B.value-2)){let x$=OU(h,B.value-2),r$=$.mentions??[];if(x$>=0&&x$<r$.length){let w4=[...r$.slice(0,x$),...r$.slice(x$+1)];J("update:mentions",w4)}let D4=h.slice(0,B.value-2)+h.slice(B.value);Y$(D4),t$(D4,B.value-2);return}if(__(h,B.value-1)){let x$=OU(h,B.value-1),r$=$.mentions??[];if(x$>=0&&x$<r$.length){let w4=[...r$.slice(0,x$),...r$.slice(x$+1)];J("update:mentions",w4)}let D4=h.slice(0,B.value-1)+h.slice(B.value);Y$(D4),t$(D4,B.value-1);return}if(OO(h,B.value-1)){let x$=qV(h,B.value-1),r$=$.multilineTexts??[];if(x$>=0&&x$<r$.length){let D4=[...r$.slice(0,x$),...r$.slice(x$+1)];J("update:multilineTexts",D4)}}let $4=h.slice(0,B.value-1)+h.slice(B.value);Y$($4),t$($4,B.value-1);return}if(g.key==="Delete"){g.preventDefault();let{value:i$,cursor:l$,deleted:Y4}=_4(h);if(Y4){Y$(i$),t$(i$,l$);return}if(B.value>=h.length)return;if(__(h,B.value)&&h[B.value+1]===" "){let $4=OU(h,B.value),x$=$.mentions??[];if($4>=0&&$4<x$.length){let D4=[...x$.slice(0,$4),...x$.slice($4+1)];J("update:mentions",D4)}let r$=h.slice(0,B.value)+h.slice(B.value+2);Y$(r$),t$(r$,B.value);return}if(__(h,B.value)){let $4=OU(h,B.value),x$=$.mentions??[];if($4>=0&&$4<x$.length){let D4=[...x$.slice(0,$4),...x$.slice($4+1)];J("update:mentions",D4)}let r$=h.slice(0,B.value)+h.slice(B.value+1);Y$(r$),t$(r$,B.value);return}if(OO(h,B.value)){let $4=qV(h,B.value),x$=$.multilineTexts??[];if($4>=0&&$4<x$.length){let r$=[...x$.slice(0,$4),...x$.slice($4+1)];J("update:multilineTexts",r$)}}let a$=h.slice(0,B.value)+h.slice(B.value+1);Y$(a$),t$(a$,B.value);return}if(g.key==="Enter"){if(g.preventDefault(),g.shiftKey)Q4(`
|
|
907
|
-
`);else J("change",h);return}if(g.key==="Escape"){g.preventDefault(),D.value=!1,j.value=null,J("blur"),Q.invalidate();return}if(Fe(g))g.preventDefault(),Q4(g.key)}let{id:z$}=N0(()=>({rect:o$.value,zIndex:q.value,visible:Z.value,focusable:!0,handlers:{pointerdown:(g)=>{if(g.button!==0)return;k={cellX:g.cellX,cellY:g.cellY},L=Boolean(g.shiftKey),v=!1,C=!1},pointermove:(g)=>{if(!k)return;let h=k.cellX!==g.cellX||k.cellY!==g.cellY;if(!v&&!h)return;if(!v){if(v=!0,C=!0,L){k$(g.cellX,g.cellY,!0,g),Q.invalidate();return}if(k$(k.cellX,k.cellY,!1,g),g.defaultPrevented)return;j.value=B.value}k$(g.cellX,g.cellY,!0,g),Q.invalidate()},pointerup:()=>{if(v)C=!0;k=null,L=!1,v=!1},beforeinput:(g)=>{if(S.value)return;if(g.isComposing||g.inputType==="insertCompositionText")T.value=!0,z.value=p$(g),Z$(),Q.invalidate()},click:(g)=>{if(C){C=!1;return}let h=typeof g.timeStamp==="number"?g.timeStamp:Date.now(),q$=Boolean(b&&b.cellX===g.cellX&&b.cellY===g.cellY),i=Boolean(b&&h-b.time<=y),p=q$&&i?b.count+1:1,l=p===2,$$=p>=3;b={time:h,cellX:g.cellX,cellY:g.cellY,count:p},D.value=!0,R.value=!0;let e=G.value;if(e&&z$.value)e.focus(z$.value);J("focus");let D$=!l&&!$$&&Boolean(g.shiftKey);if(k$(g.cellX,g.cellY,D$,g),g.defaultPrevented)return;if($$){F4(),b=null;return}if(l)A6();Q.invalidate()},paste:(g)=>{g.preventDefault();let h=JJ(p$(g)),i=XJ(h)||h,p=h.trim(),l=$.mentionTrigger||"@";if(p.startsWith(l)&&!/[\s\r\n]/.test(p)&&(p.slice(l.length).includes("/")||p.slice(l.length).includes("\\"))&&$.collectMentions){let e=p.slice(l.length).trim(),D$=$.mentionWorkspace?J1($.mentionWorkspace,e):e;if(D$)y4(D$);return}if($.collapseMultiline){if((i.match(/\n/g)||[]).length+1>=2){n$(i);return}}Q4(h)},compositionstart:(g)=>{S.value=!1,T.value=!0,z.value=p$(g),Z$(),Q.invalidate()},compositionupdate:(g)=>{if(S.value)return;T.value=!0,z.value=p$(g),Z$(),Q.invalidate()},compositionend:(g)=>{if(S.value)return;let h=p$(g)||z.value;if(T.value=!1,z.value="",S.value=!1,h)Q4(h);O.value=!0,queueMicrotask(()=>{O.value=!1}),Q.invalidate()},input:(g)=>{if(O.value)return;if(S.value)return;if(g.isComposing){T.value=!0,z.value=p$(g),Z$(),Q.invalidate();return}if(T.value){let q$=p$(g)||z.value;if(T.value=!1,z.value="",q$)Q4(q$);Q.invalidate();return}let h=p$(g);if(h)Q4(h)},focus:()=>{D.value=!0,J("focus");let g=c().length,h=$.cursorToEndOnFirstFocus&&!f.value&&!R.value;if(R.value=!1,h)B.value=g,j.value=null;f.value=!0,B.value=j4(B.value,0,g),Z$(),C6(),Q.invalidate()},blur:()=>{if(D.value=!1,j.value=null,S.value=!1,T.value=!1,z.value="",K?.value?.ownerId===F)K.value=null;z4(),J("blur"),Q.invalidate()},keydown:e4}}));return Ne(()=>{if(!$.autoFocus)return;if(!Z.value)return;let g=G.value,h=z$.value;if(!g||!h)return;if(g.getFocused()===h)return;g.focus(h)}),o6(()=>({zIndex:$.zIndex,rect:Z.value?o$.value:{x:0,y:0,w:0,h:0},deps:[Z.value,o$.value,$.w,$.h,$.zIndex,$.modelValue,$.mentions,$.multilineTexts,$.placeholder,$.placeholderWhenFocused,$.style,$.autoFocus,$.cursorBlink,$.cursorShape,$.blinkInterval,D.value,B.value,j.value,I.value,w.value,T.value,z.value,M.value,_.value,V4.value?.version.value??0],paint:()=>{if(!Z.value)return;let g=o$.value;if(g.w<=0||g.h<=0)return;let h=$.style??_.value,q$=E4.value,i=q$?0:I.value,p=q$?0:w.value,l=a.value&&!q$,$$=c(),e=Q$($$),D$=q$?D.value&&$.placeholderWhenFocused?` ${$.placeholder}`:$.placeholder:e.text,v$=$.secret&&!q$?U6(D$):D$,A$=q$?{...h,fg:"white"}:h,{wAll:g$,padX:c$,w:d$}=E(g),y$=g.x+c$,X4=Math.max(1,d$),W4=X4,_6=l?DO(v$,$.multilineTexts,$.mentions,W4,X4):AO(v$);for(let l$=0;l$<g.h;l$++){let Y4=p+l$,a$=_6[Y4],$4=X4,x$=a$?EI(D$,v$,$.multilineTexts,$.mentions,a$.start,a$.end,$4,l?0:i):{text:I4($4),chips:[]},r$=x$.text;if(U.write(I4(g$),{x:g.x,y:g.y+l$,style:A$}),d$<=0)continue;let D4=y$;if(U.write(r$,{x:D4,y:g.y+l$,style:A$}),x$.chips.length>0)for(let w4 of x$.chips){let d4;if(w4.kind==="multiline")d4={...h,fg:"cyan",dim:!0};else{let $6=String(w4.absPath??"");d4=V4.value?.getStyle(h,{kind:"mention",absPath:$6})??NV(h,$6)}U.write(w4.label,{x:D4+w4.startCell,y:g.y+l$,style:d4})}}let i$=F6.value;if(i$&&!q$)for(let a$=0;a$<g.h;a$++){let $4=p+a$,x$=_6[$4];if(!x$)continue;let r$=X4,D4=y$,w4=g.y+a$,d4=l?0:i,$6=PI(e.text,v$,$.multilineTexts,$.mentions,x$.start,x$.end,i$,r$,d4);for(let b6 of $6){if(!b6.text)continue;U.write(b6.text,{x:D4+b6.startCell,y:w4,style:{...h,fg:"black",bg:"blueBright"}})}}if(D.value&&M.value&&!(F6.value&&!q$)){let l$=X4,Y4=l$,a$=q$?"":e.text,$4=$.secret&&!q$?U6(a$):a$,x$=l?H8($4,$.multilineTexts,$.mentions,e.cursor,Y4,l$):B8($4,$.multilineTexts,$.mentions,e.cursor),r$=x$.col-i,D4=x$.line-p;if(K&&D.value){let w4=j4(r$,0,Math.max(0,X4-1)),d4=j4(D4,0,Math.max(0,g.h-1));K.value={cellX:g.x+c$+w4,cellY:g.y+d4,ownerId:F}}if(r$>=0&&r$<X4&&D4>=0&&D4<g.h){let w4=g.y+D4,d4=y$+r$,$6=null;try{if($6=U.getCell(d4,w4),$6.continuation&&d4>0)d4-=1,$6=U.getCell(d4,w4)}catch{$6=null}let b6=h.fg??_.value.fg??"whiteBright",k8=h.bg??_.value.bg??"black",b0=$6?.style??h,B0={...b0,fg:b0.fg??b6,bg:b0.bg??k8},Z1=$6&&!$6.continuation?$6.ch||" ":" ";if($.cursorShape==="underline")U.put(d4,w4,Z1,{...B0,underline:!0});else if($.cursorShape==="bar")if(Z1===" ")U.put(d4,w4,"│",{...B0,fg:B0.fg??b6});else U.put(d4,w4,Z1,{...B0,inverse:!0});else U.put(d4,w4,Z1,{...B0,inverse:!0})}}}})),Ke(()=>{z4()}),()=>Ze("span",Y)}});import{watchEffect as De}from"vue";import{computed as jU,ref as HV,watch as zI,watchEffect as RI}from"vue";function qe($,J){let U=$.trim().toLowerCase(),Q=J.toLowerCase();if(!U)return 0;if(Q===U)return 1e4;let _=0;if(Q.startsWith(U))_+=1000;let G=0,V=0;for(let X=0;X<Q.length&&G<U.length;X++)if(Q[X]===U[G])G++,V++,_+=10+V*5;else V=0;if(G<U.length)return null;return _+=Math.max(0,40-Q.length),_}function AI($,J,U){if($===J||$===U)return!0;if(k0($))return!0;return/[,;:!?,。!?、()[\]{}<>]/.test($)}function He($,J,U,Q,_){if(!U||$[J]!==U)return!1;if(J<=0)return!0;let G=$[J-1];return AI(G,Q,_)||!/\w/.test(G)}function Be($){return/^[\w./~\\:-]$/.test($)}function Oe($,J,U){if(!U)return null;let Q=j4(J,0,$.length),_=$.lastIndexOf(`
|
|
908
|
-
`,Math.max(0,Q-1))+1;if($.slice(_,_+U.length)!==U)return null;let G=$.length;for(let Y=_;Y<$.length;Y++)if(k0($[Y])){G=Y;break}if(Q<_||Q>G)return null;let V=$.slice(_,G),X=V.slice(U.length),Z=`${_}:${V}`;return{tokenStart:_,tokenEnd:G,tokenText:V,query:X,key:Z}}function je($,J,U,Q,_){if(!U)return null;let G=j4(J,0,$.length),V=-1;for(let q=G-1;q>=0;q--){let H=$[q];if(He($,q,U,Q,_)){V=q;break}if(AI(H,Q,_))break}if(V<0)return null;let X=V+U.length,Z=$[X];if(Z==='"'||Z==="'"){let q=Z;X+=1;while(X<$.length&&$[X]!==q)X++;if(X<$.length&&$[X]===q)X++}else while(X<$.length&&Be($[X]))X++;if(G<V||G>X)return null;let Y=$.slice(V,X),K=j4(G,V+U.length,X),F=$.slice(V+U.length,K),N=`${V}:${Y}`;return{tokenStart:V,tokenEnd:X,tokenText:Y,query:F,key:N}}function wI($){let{props:J,focused:U,cursor:Q,getValue:_,rawAbsRect:G,terminal:V,scheduler:X,multilineToken:Z,mentionToken:Y}=$,K=HV(0),F=HV(null),N=HV(0),q=new Map,H=0;RI(()=>{let T=(J.mentions??[]).map((M)=>String(M??"")).filter(Boolean);if(!(typeof globalThis.window>"u"&&typeof globalThis.process<"u")){q.clear(),N.value++;return}let S=++H,O=UJ();Promise.allSettled(T.map(async(M)=>{let P=await O.stat(M);return{absPath:M,kind:P.kind}})).then((M)=>{if(S!==H)return;q.clear();for(let P of M){if(P.status!=="fulfilled")continue;q.set(P.value.absPath,P.value.kind)}N.value++,X.invalidate()}).catch(()=>{if(S!==H)return;q.clear(),N.value++,X.invalidate()})});let E=jU(()=>{if(!U.value)return null;if(!J.promptSuggestions?.length)return null;return Oe(_(),Q.value,J.promptTrigger||"/")}),D=jU(()=>{if(!U.value)return null;let T=J.mentionSuggestions?.length>0,z=Boolean(J.mentionWorkspace);if(!T&&!z)return null;return je(_(),Q.value,J.mentionTrigger||"@",Z,Y)}),B=jU(()=>D.value??E.value);zI(()=>B.value?.key??null,(T,z)=>{if(z&&T!==z)F.value=null});let j=HV([]),f=0;RI(()=>{let T=D.value,z=J.mentionWorkspace;if(!T||!z)return;J.mentionMode,J.mentionShowHidden,J.mentionMaxItems;let S=++f,O=UJ(),M=Math.max(0,Math.floor(J.mentionMaxItems));r7({workspaceAbs:z,input:T.query,mode:J.mentionMode,max:M,showHidden:J.mentionShowHidden,listDir:O.listDir,maxDepth:3}).then((P)=>{if(S!==f)return;j.value=P.suggestions.map((A)=>({value:`${J.mentionTrigger}${A.completion}`,insert:`${J.mentionTrigger}${A.completion} `,detail:A.kind})),X.invalidate()}).catch(()=>{if(S!==f)return;j.value=[],X.invalidate()})});let R=jU(()=>{let T=B.value;if(!T)return[];let z=J.mentionTrigger||"@",S=J.promptTrigger||"/",O=T.tokenText.startsWith(z),M=O?z:S,P=Math.max(0,Math.floor(O?J.mentionMaxItems:J.promptMaxItems)),A=O?J.mentionWorkspace?j.value:J.mentionSuggestions??[]:J.promptSuggestions??[],k=T.query.trim(),L=[];for(let v=0;v<A.length;v++){let C=A[v],b=C.value||"";if(!b.startsWith(M))continue;if(O&&J.mentionWorkspace){L.push({item:C,score:0,order:v});continue}if(!k){L.push({item:C,score:0,order:v});continue}let y=[b.slice(M.length),C.label??"",C.detail??"",...C.keywords??[]].join(" "),x=qe(k,y);if(x!=null)L.push({item:C,score:x,order:v})}if(!k||O&&J.mentionWorkspace)return L.slice(0,P);return L.sort((v,C)=>C.score-v.score||v.order-C.order),L.slice(0,P)});zI(()=>R.value.length,(T)=>{K.value=j4(K.value,0,Math.max(0,T-1))});let I=jU(()=>{let T=B.value;if(!T)return!1;if(F.value&&F.value===T.key)return!1;return!0}),w=jU(()=>{let T=G.value,z=V.size(),S={x:0,y:0,w:z.cols,h:z.rows},O=Math.max(1,R.value.length||1),M=j4(2+O,3,Math.max(3,Math.floor(S.h))),P=j4(Math.floor(T.w),10,Math.max(10,Math.floor(S.w))),A=Math.floor(T.y)-M,k=Math.floor(T.y)+Math.floor(T.h),L=A>=Math.floor(S.y),v=k+M<=Math.floor(S.y)+Math.floor(S.h),b=j4(L?A:v?k:A,Math.floor(S.y),Math.floor(S.y)+Math.floor(S.h)-M);return{x:j4(Math.floor(T.x),Math.floor(S.x),Math.floor(S.x)+Math.floor(S.w)-P),y:b,w:P,h:M}});return{promptActive:K,promptSuppressedKey:F,mentionKindByPath:q,mentionKindVersion:N,promptContext:E,mentionContext:D,activeContext:B,promptMatches:R,promptVisible:I,promptRect:w}}function Ee($,J,U=$.length){let Q=0,_=j4(U,0,$.length);for(let G=0;G<_;G++)if($[G]===J)Q++;return Q}function Pe($,J,U){return Ee($,J,U)}function DU(){return{name:"promptMention",install:($)=>{let J=()=>$.getProps(),U=$.render.createStack($.render.rootStack,1e4),Q=new WeakMap,_=wI({props:{promptSuggestions:J().promptSuggestions,promptTrigger:J().promptTrigger,promptMaxItems:J().promptMaxItems,mentionTrigger:J().mentionTrigger,mentionWorkspace:J().mentionWorkspace,mentionMode:J().mentionMode,mentionShowHidden:J().mentionShowHidden,mentionSuggestions:J().mentionSuggestions,mentionMaxItems:J().mentionMaxItems,mentions:J().mentions},focused:$.focused,cursor:$.cursor,getValue:$.getValue,rawAbsRect:$.rawAbsRect,terminal:$.terminal,scheduler:$.scheduler,multilineToken:"",mentionToken:$.mentionToken});$.registerChipStyleProvider({getStyle:(Z,Y)=>{if(Y.kind!=="mention")return null;let K=String(Y.absPath??"");if(!K)return null;let F=_.mentionKindByPath.get(K);return NV(Z,K,F)},version:_.mentionKindVersion});function G(Z,Y,K){let F=String(Z||"").trim();if(!F)return;let N=$.getValue(),q=j4(Y,0,N.length),H=j4(K,q,N.length),D=[...J().mentions??[]],B=N.slice(0,q),j=N.slice(H),f=j.match(/^[\s\u200B]*\]+/u);if(f){j=j.slice(f[0].length);let z=B.length-1;while(z>=0&&/[\s\u200B]/u.test(B[z]))z--;if(z>=0&&B[z]==="[")B=B.slice(0,z)+B.slice(z+1)}let R=Pe(N,$.mentionToken,q);D.splice(R,0,F),$.emit("update:mentions",D);let I=j;if(I.startsWith(" "))I=I.slice(1);let w=`${B}${$.mentionToken} ${I}`,T=B.length+2;$.pushUndoSnapshot(w),$.applyEdit(w,T)}function V(Z){let Y=_.activeContext.value;if(!Y)return;let K=_.promptMatches.value,F=K[j4(Z,0,Math.max(0,K.length-1))];if(!F)return;let N=F.item,q=J().mentionTrigger||"@";if(Y.tokenText.startsWith(q)){if(!J().collectMentions){let w=N.insert??(N.value.endsWith(" ")?N.value:`${N.value} `),T=$.getValue().slice(0,Y.tokenStart),z=$.getValue().slice(Y.tokenEnd);if(w.endsWith(" ")&&z.startsWith(" "))z=z.slice(1);let S=`${T}${w}${z}`,O=Y.tokenStart+w.length;_.promptSuppressedKey.value=null,$.pushUndoSnapshot(S),$.applyEdit(S,O);return}let R=String(N.value||"").startsWith(q)?String(N.value).slice(q.length):String(N.value),I=J().mentionWorkspace?J1(J().mentionWorkspace,R):R;if(!I){_.promptSuppressedKey.value=null;return}G(I,Y.tokenStart,Y.tokenEnd),_.promptSuppressedKey.value=null,$.scheduler.invalidate();return}if(typeof N.onSelect==="function"){if(N.onSelect({value:N.value,query:Y.query})!==!1){_.promptSuppressedKey.value=Y.key,$.scheduler.invalidate();return}}let E=N.insert??(N.value.endsWith(" ")?N.value:`${N.value} `),D=$.getValue().slice(0,Y.tokenStart),B=$.getValue().slice(Y.tokenEnd);if(E.endsWith(" ")&&B.startsWith(" "))B=B.slice(1);let j=`${D}${E}${B}`,f=Y.tokenStart+E.length;_.promptSuppressedKey.value=null,$.pushUndoSnapshot(j),$.applyEdit(j,f)}function X(Z){if(!_.promptVisible.value)return!1;let Y=_.promptMatches.value.length;if(Z.key==="ArrowDown"){if(Z.preventDefault(),Y<=0)_.promptActive.value=0;else if(_.promptActive.value>=Y-1)_.promptActive.value=0;else _.promptActive.value=j4(_.promptActive.value+1,0,Y-1);return $.scheduler.invalidate(),!0}if(Z.key==="ArrowUp"){if(Z.preventDefault(),Y<=0)_.promptActive.value=0;else if(_.promptActive.value<=0)_.promptActive.value=Y-1;else _.promptActive.value=j4(_.promptActive.value-1,0,Y-1);return $.scheduler.invalidate(),!0}if(Z.key==="Tab"||Z.key==="Enter"&&!Z.shiftKey){if(Y===0)return!1;return Z.preventDefault(),V(_.promptActive.value),!0}if(Z.key==="Escape")return Z.preventDefault(),_.promptSuppressedKey.value=_.activeContext.value?.key??null,$.scheduler.invalidate(),!0;return!1}$.registerKeydownInterceptor(X),o6(()=>({zIndex:J().zIndex+5,stack:U,rect:$.visible.value&&_.promptVisible.value?_.promptRect.value:{x:0,y:0,w:0,h:0},deps:[$.visible.value,_.promptVisible.value,_.promptRect.value,_.promptMatches.value,_.promptActive.value,J().style,J().zIndex,$.defaultStyle.value,_.mentionKindVersion.value],paint:()=>{if(!$.visible.value||!_.promptVisible.value)return;let Z=_.promptRect.value;if(Z.w<3||Z.h<3)return;let Y=J().style??$.defaultStyle.value,K=Y&&typeof Y==="object"?Y:null,F=K?Q.get(K):null;if(!F){let R={...Y,dim:!0},I={...Y},w={...Y,bg:"yellow",fg:"black"},T={...Y,dim:!0},z={...Y,bg:"yellow",fg:"black",dim:!0},S={...Y,dim:!0};if(F={borderStyle:R,itemStyle:I,selectedStyle:w,detailStyle:T,selectedDetailStyle:z,emptyStyle:S},K)Q.set(K,F)}let N=Math.floor(Z.x),q=Math.floor(Z.y),H=Math.max(0,Math.floor(Z.w)),E=Math.max(0,Math.floor(Z.h)),D=Math.max(0,H-2),B=F.borderStyle;$.terminal.write(`┌${YU("─",D)}┐`,{x:N,y:q,style:B}),$.terminal.write(`└${YU("─",D)}┘`,{x:N,y:q+E-1,style:B});let j=_.promptMatches.value,f=Math.max(0,E-2);for(let R=0;R<f;R++){let I=q+1+R;if($.terminal.put(N,I,"│",B),$.terminal.put(N+H-1,I,"│",B),R>=j.length){$.terminal.write(I4(D),{x:N+1,y:I,style:B});continue}let w=j[R],T=R===_.promptActive.value,z=z6(w.item.value),S=w.item.detail?z6(w.item.detail):"",O=G2(z),M=S?G2(S):0,P=2,A=D-O-P;if(S&&A>=4){let k=T?F.selectedStyle:F.itemStyle;$.terminal.write(z,{x:N+1,y:I,style:k});let L=D-O-Math.min(M,A),v=T?F.selectedStyle:F.itemStyle;$.terminal.write(I4(L),{x:N+1+O,y:I,style:v});let C=FU(S,0,A),b=T?F.selectedDetailStyle:F.detailStyle;$.terminal.write(C,{x:N+1+O+L,y:I,style:b})}else{let k=WO(FU(z,0,D),D),L=T?F.selectedStyle:F.itemStyle;$.terminal.write(k,{x:N+1,y:I,style:L})}}if(j.length===0&&f>0){let R=q+1;$.terminal.put(N,R,"│",B),$.terminal.put(N+H-1,R,"│",B);let I=WO(FU("(no matches)",0,D),D);$.terminal.write(I,{x:N+1,y:R,style:F.emptyStyle})}}})),N0(()=>({rect:_.promptVisible.value?_.promptRect.value:{x:0,y:0,w:0,h:0},zIndex:$.eventZ.value+1e4,visible:$.visible.value&&_.promptVisible.value,focusable:!1,handlers:{click:(Z)=>{let Y=_.promptRect.value,K=Z.cellY-Y.y;if(K<=0||K>=Y.h-1)return;let F=K-1;_.promptActive.value=j4(F,0,Math.max(0,_.promptMatches.value.length-1)),V(_.promptActive.value)}}})),De(()=>{J().mentions,_.mentionKindVersion.value})}}}function Me($,J){let U=$.selection?$.selection.start:$.cursor,Q=$.selection?$.selection.end:$.cursor;return $.value.slice(0,U)+J+$.value.slice(Q)}function Le($,J){if("filter"in $)return $.filter(J);if("replace"in $)return J.text.replace($.replace.from,$.replace.to);if("allowChars"in $){let U="";for(let Q of J.text)if($.allowChars.test(Q))U+=Q;return U}if("denyChars"in $)return J.text.replace($.denyChars,"");if("allow"in $){let U=Me(J,J.text);return $.allow.test(U)?J.text:""}return J.text}function BV($){let J=$.name??"restrictText",U=$.rules??[];return{name:J,install(Q){Q.registerTextFilter((_)=>{let{text:G,text:V}=_;for(let X of U)if(V=Le(X,{..._,text:V}),!V){if(G)Q.emit("validationError",{plugin:J,kind:"reject",originalText:G,acceptedText:"",value:_.value,cursor:_.cursor,selection:_.selection});return""}if(G&&V!==G)Q.emit("validationError",{plugin:J,kind:"filter",originalText:G,acceptedText:V,value:_.value,cursor:_.cursor,selection:_.selection});return V})}}}function ze($,J,U){return Math.max(J,Math.min(U,$))}function Re($){let J=Math.abs($);return J>0&&J<=3&&Number.isInteger($)}function Ae($){if(Math.abs($)<=3&&Number.isInteger($))return $;return $/100}function we($,J){let U=$-J;if(!Number.isFinite(U)||U<=0||U>120)return 1;return 1+(1-U/120)*1.5}function Q_(){return{accumulator:0,lastAt:0,lastEdgeDir:0,lastEdgeAt:0}}function G_($,J,U,Q,_=Date.now()){if(!Number.isFinite(J)||J===0||Q<=0){if(Q<=0)$.accumulator=0,$.lastEdgeDir=0,$.lastEdgeAt=0;return{nextTop:U,dir:0,lines:0}}let G=$.lastAt?_-$.lastAt:1/0,V=Re(J);if(V&&G!==1/0&&G>=0&&G<6)return{nextTop:U,dir:0,lines:0};let X=V?1:$.lastAt?we(_,$.lastAt):1;$.lastAt=_,$.accumulator+=Ae(J)*X;let Z=Math.trunc($.accumulator);if(Z===0)return{nextTop:U,dir:0,lines:0};$.accumulator-=Z;let Y=Z>0?1:-1,K=U<=0,F=U>=Q;if(Y<0&&K||Y>0&&F)return $.lastEdgeDir=Y,$.lastEdgeAt=_,$.accumulator=0,{nextTop:U,dir:0,lines:0};if($.lastEdgeDir!==0&&_-$.lastEdgeAt<120&&Y===-$.lastEdgeDir&&(K||F))return{nextTop:U,dir:0,lines:0};let N=U+Z,q=ze(N,0,Q);if(q===U)return $.accumulator=0,{nextTop:U,dir:0,lines:0};if(q!==N)$.accumulator=0;return $.lastEdgeDir=0,{nextTop:q,dir:q>U?1:-1,lines:q-U}}import{computed as EU,defineComponent as fe,h as ke,inject as Ie,watchEffect as Se}from"vue";var V2={tl:"┌",tr:"┐",bl:"└",br:"┘",h:"─",v:"│"},OV=fe({name:"TMultilineModal",props:{visible:{type:Boolean,required:!0},content:{type:String,required:!0},title:{type:String,default:"Multiline Text"},style:{type:Object,default:void 0},zIndex:{type:Number,default:1000}},emits:["close"],setup($,{emit:J}){let{terminal:U,scheduler:Q,defaultStyle:_,events:G}=L4(),V=p4(),{visible:X,rootProps:Z}=p6(),Y=Ie(f0,EU(()=>0)),K=EU(()=>(Y.value??0)+($.zIndex??0)),F=EU(()=>X.value&&$.visible),N=EU(()=>{let j=U.size(),f=j.cols,R=j.rows,I=Math.floor(f*0.8),w=Math.floor(R*0.7),T=Math.floor((f-I)/2),z=Math.floor((R-w)/2);return a6({x:T,y:z,w:I,h:w},V.originX,V.originY)}),q=EU(()=>{return XJ(String($.content||"")).split(`
|
|
909
|
-
`)}),H=EU(()=>0);function E(j){if(j.preventDefault(),j.stopPropagation(),j.key==="Escape")J("close"),Q.invalidate()}let D=N0(()=>({rect:F.value?{x:0,y:0,w:U.size().cols,h:U.size().rows}:{x:0,y:0,w:0,h:0},zIndex:K.value,visible:F.value,focusable:!0,handlers:{click:(j)=>{j.preventDefault(),j.stopPropagation(),J("close"),Q.invalidate()},keydown:E}})),B=N0(()=>({rect:F.value?N.value:{x:0,y:0,w:0,h:0},zIndex:K.value+1,visible:F.value,focusable:!0,handlers:{click:(j)=>{j.preventDefault(),j.stopPropagation();let f=G.value,R=B.id.value;if(f&&R)f.focus(R)},keydown:E}}));return Se(()=>{if(!F.value)return;let j=G.value,f=B.id.value||D.id.value;if(!j||!f)return;j.focus(f)}),o6(()=>({zIndex:$.zIndex,rect:F.value?{x:0,y:0,w:U.size().cols,h:U.size().rows}:{x:0,y:0,w:0,h:0},deps:[F.value,N.value,$.content,$.title,$.style,_.value],paint:()=>{if(!F.value)return;let j=U.size(),f=$.style??_.value,R={...f,bg:"black",dim:!0},I=I4(j.cols);for(let V$=0;V$<j.rows;V$++)U.write(I,{x:0,y:V$,style:R});let w=N.value,T=f.fg??_.value.fg??"whiteBright",z=f.bg??_.value.bg??"black",S={...f,fg:"white"},O={...f,fg:T,bg:z},M={...f,dim:!0};U.put(w.x,w.y,V2.tl,S),U.put(w.x+w.w-1,w.y,V2.tr,S),U.put(w.x,w.y+w.h-1,V2.bl,S),U.put(w.x+w.w-1,w.y+w.h-1,V2.br,S);let P=Math.max(0,w.w-2),A=` ${z6($.title)} `,k=Math.min(A.length,P),L=w.x+1;U.write(A.slice(0,k),{x:L,y:w.y,style:S});let v=P-k;if(v>0)U.write(V2.h.repeat(v),{x:L+k,y:w.y,style:S});let C=" Press ESC to close ",b=Math.min(C.length,P),y=w.x+Math.floor((w.w-b)/2),x=y-w.x-1,c=P-x-b;if(x>0)U.write(V2.h.repeat(x),{x:w.x+1,y:w.y+w.h-1,style:S});if(U.write(C,{x:y,y:w.y+w.h-1,style:M}),c>0)U.write(V2.h.repeat(c),{x:y+b,y:w.y+w.h-1,style:S});for(let V$=1;V$<w.h-1;V$++)U.put(w.x,w.y+V$,V2.v,S),U.put(w.x+w.w-1,w.y+V$,V2.v,S);let s=Math.max(0,w.h-2),F$=q.value,K$=H.value;for(let V$=0;V$<s;V$++){let Y$=K$+V$,u$=F$[Y$]??"",_$=m4(u$,P),n=h6(_$,P);U.write(n,{x:w.x+1,y:w.y+1+V$,style:O})}}})),()=>ke("span",Z)}});import{computed as V_,defineComponent as Te,h as fI,inject as ve,ref as jV,watch as Ce,watchEffect as be}from"vue";function PU($,J,U){return Math.max(J,Math.min(U,$))}function kI($){return Boolean($.ctrlKey||$.metaKey)}var DV=Te({name:"TPathPicker",props:{x:{type:Number,required:!0},y:{type:Number,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0},zIndex:{type:Number,default:0},workspace:{type:String,required:!0},mode:{type:String,default:"any"},modelValue:{type:String,required:!0},placeholder:{type:String,default:""},style:{type:Object,default:void 0},autoFocus:{type:Boolean,default:!1},showHidden:{type:Boolean,default:!1},maxSuggestions:{type:Number,default:50},provider:{type:Object,default:void 0}},emits:["update:modelValue","select","invalid","keydown","focus","blur"],setup($,{emit:J}){let{terminal:U,scheduler:Q,defaultStyle:_}=L4(),G=p4(),{visible:V,rootProps:X}=p6(),Z=ve(f0,V_(()=>0)),Y=V_(()=>(Z.value??0)+($.zIndex??0)),K=V_(()=>$.provider??UJ()),F=jV([]),N=jV(0),q=jV(0),H=jV(null),E=1,D=V_(()=>Math.max(0,Math.floor($.h)-1)),B=V_(()=>{let P={x:$.x,y:$.y+1,w:$.w,h:D.value},A=a6(P,G.originX,G.originY);if(!G.clipRect)return A;return F0(A,G.clipRect)??{x:0,y:0,w:0,h:0}});function j(){let P=Math.max(0,D.value);if(P<=0){q.value=0;return}let A=Math.max(0,F.value.length-P);if(q.value=PU(q.value,0,A),N.value<q.value)q.value=N.value;else if(N.value>=q.value+P)q.value=PU(N.value-(P-1),0,A)}Ce([()=>N.value,()=>F.value.length,()=>D.value],()=>{j()});async function f(){let P=Math.max(0,Math.floor($.maxSuggestions)),A=await r7({workspaceAbs:$.workspace,input:$.modelValue,mode:$.mode,max:P,showHidden:$.showHidden,listDir:K.value.listDir});F.value=A.suggestions,N.value=PU(N.value,0,Math.max(0,F.value.length-1)),j(),Q.invalidate()}let R=0;be(()=>{if(!V.value)return;$.workspace,$.mode,$.showHidden,$.modelValue,D.value,H.value=null;let P=++R;f().catch((A)=>{if(P!==R)return;F.value=[],H.value=A instanceof Error?A.message:String(A),Q.invalidate()})});function I(P){let A=P.replace(/\r/g,"").replace(/\n/g," ");J("update:modelValue",A)}function w(P){let A=F.value.length;if(A<=0)return;let k=PU(N.value+P,0,A-1);if(k!==N.value)N.value=k,j(),Q.invalidate()}function T(){let P=F.value[N.value];if(!P)return;I(P.completion)}async function z(P){let A=await K.value.stat(P);if(!A.exists){H.value="Not found",J("invalid",{reason:"not_found",absPath:P}),Q.invalidate();return}if($.mode==="file"&&A.kind==="directory"){let k=h0(P),L=h0($.workspace),v=k===L?"":k.startsWith(`${L}/`)?k.slice(L.length+1):k;I(v?`${v}/`:""),H.value=null,Q.invalidate();return}if($.mode==="file"&&A.kind!=="file"){H.value="Not a file",J("invalid",{reason:"not_file",absPath:P}),Q.invalidate();return}if($.mode==="directory"&&A.kind!=="directory"){H.value="Not a directory",J("invalid",{reason:"not_directory",absPath:P}),Q.invalidate();return}J("select",Ek(P))}async function S(){let P=J1($.workspace,$.modelValue),A=await K.value.stat(P);if(A.exists){if($.mode==="file"&&A.kind==="directory"){let L=$.modelValue.replace(/\r/g,"").replace(/\\/g,"/"),v=L.endsWith("/")?L:`${L}/`;I(v),H.value=null,Q.invalidate();return}await z(P);return}let k=F.value[N.value];if(k){if($.mode==="file"&&k.kind==="directory"){I(k.completion),H.value=null,Q.invalidate();return}await z(k.absPath);return}H.value="Not found",J("invalid",{reason:"not_found",absPath:P}),Q.invalidate()}function O(P){if(J("keydown",P),P.key==="Tab"){P.preventDefault(),T();return}if(P.key==="ArrowUp"){P.preventDefault(),w(-1);return}if(P.key==="ArrowDown"){P.preventDefault(),w(1);return}if(kI(P)&&(P.key==="p"||P.key==="P")){P.preventDefault(),w(-1);return}if(kI(P)&&(P.key==="n"||P.key==="N"))P.preventDefault(),w(1)}let M=Q_();return N0(()=>({rect:B.value,zIndex:Y.value,visible:V.value,focusable:!1,handlers:{click:(P)=>{let A=B.value,k=q.value+(P.cellY-A.y);if(k>=0&&k<F.value.length)N.value=k,j(),Q.invalidate()},dblclick:async(P)=>{let A=B.value,k=q.value+(P.cellY-A.y),L=F.value[k];if(!L)return;if($.mode==="file"&&L.kind==="directory"){I(L.completion),H.value=null,Q.invalidate();return}await z(L.absPath)},wheel:(P)=>{let A=P.deltaY??0;if(!A)return;let k=Math.max(0,D.value),L=Math.max(0,F.value.length-k),{nextTop:v,dir:C}=G_(M,A,q.value,L);if(!C||v===q.value)return;q.value=v;let b=v,y=v+k-1;if(N.value<b||N.value>y){let x=C>0?y:b;N.value=PU(x,0,Math.max(0,F.value.length-1))}Q.invalidate()}}})),o6(()=>({zIndex:$.zIndex,rect:V.value?B.value:{x:0,y:0,w:0,h:0},deps:[V.value,B.value,$.w,D.value,$.style,_.value,F.value,N.value,q.value,H.value],paint:()=>{if(!V.value)return;let P=B.value;if(P.w<=0||P.h<=0)return;let A=$.style??_.value,k=PU(q.value,0,Math.max(0,F.value.length-P.h));for(let L=0;L<P.h;L++){let v=k+L,C=F.value[v],b=C?z6(C.display):"",y=h6(m4(b,P.w),P.w),x=v===N.value?{...A,inverse:!0}:A;U.write(y,{x:P.x,y:P.y+L,style:x})}if(F.value.length===0&&P.h>0){let L=H.value?`(${z6(H.value)})`:"(no matches)";U.write(h6(m4(L,P.w),P.w),{x:P.x,y:P.y,style:{...A,dim:!0}})}}})),()=>fI("span",X,[fI(J6,{x:$.x,y:$.y,w:$.w,h:1,zIndex:$.zIndex,modelValue:$.modelValue,"onUpdate:modelValue":(P)=>I(P),cursorToEndOnExternalUpdate:!0,placeholder:$.placeholder,style:$.style,autoFocus:$.autoFocus,onKeydown:(P)=>O(P),onChange:()=>void S(),onFocus:()=>J("focus"),onBlur:()=>J("blur")})])}});import{computed as wO,defineComponent as ye,h as ge,inject as xe,ref as II,watchEffect as SI}from"vue";function X2($,J,U){return Math.max(J,Math.min(U,$))}var q0=ye({name:"TSelect",props:{x:{type:Number,required:!0},y:{type:Number,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0},zIndex:{type:Number,default:0},options:{type:Array,required:!0},modelValue:{type:[Number,Array],default:0},multiple:{type:Boolean,default:!1},multipleEmit:{type:String,default:"value"},style:{type:Object,default:void 0},highlightStyle:{type:Object,default:void 0},autoFocus:{type:Boolean,default:!1},closeOnBlur:{type:Boolean,default:!1}},emits:["update:modelValue","change","confirm","close","focus","blur","keydown"],setup($,{emit:J}){let{terminal:U,scheduler:Q,defaultStyle:_,events:G}=L4(),V=p4(),{visible:X,rootProps:Z}=p6(),Y=xe(f0,wO(()=>0)),K=wO(()=>(Y.value??0)+($.zIndex??0)),F=II(!1),N=(()=>{let O=Math.max(0,$.options.length-1);if(!$.multiple){let A=typeof $.modelValue==="number"?$.modelValue:0;return X2(A,0,O)}let P=(Array.isArray($.modelValue)?$.modelValue:[])[0]??0;return X2(P,0,O)})(),q=II(N),H=wO(()=>{let O={x:$.x,y:$.y,w:$.w,h:$.h},M=a6(O,V.originX,V.originY);if(!V.clipRect)return M;return F0(M,V.clipRect)??{x:0,y:0,w:0,h:0}});SI(()=>{let O=Math.max(0,$.options.length-1);if(!$.multiple){let M=typeof $.modelValue==="number"?$.modelValue:0;q.value=X2(M,0,O);return}q.value=X2(q.value,0,O)});function E(O){return typeof O==="string"?O:O.label}function D(O){return typeof O==="string"?void 0:O.detail}function B(O){let M=X2(O,0,Math.max(0,$.options.length-1));q.value=M,J("update:modelValue",M);let P=$.options[M];J("change",P?E(P):null)}function j(){if(!$.multiple)return[];let O=Math.max(0,$.options.length-1),M=Array.isArray($.modelValue)?$.modelValue:[],P=new Set;for(let A of M){if(typeof A!=="number"||!Number.isFinite(A))continue;P.add(X2(Math.trunc(A),0,O))}return[...P].sort((A,k)=>A-k)}function f(O){let M=O.map((P)=>$.options[P]).filter(Boolean).map((P)=>E(P));return{indices:O,values:M}}function R(O,M){let P=f(M);if($.multipleEmit==="index"){J(O,P.indices);return}if($.multipleEmit==="both"){J(O,P);return}J(O,P.values)}function I(O){let M=X2(O,0,Math.max(0,$.options.length-1));q.value=M;let P=new Set(j());if(P.has(M))P.delete(M);else P.add(M);let A=[...P].sort((k,L)=>k-L);J("update:modelValue",A),R("change",A)}function w(){let O=j();R("confirm",O)}function T(O){if($.multiple)I(O);else B(O)}function z(O){if(J("keydown",O),O.defaultPrevented)return;let M=Math.max(0,$.options.length-1);if(O.key==="ArrowUp"||O.code==="ArrowUp"){if(O.preventDefault(),M<=0)q.value=0;else if(q.value<=0)q.value=M;else q.value=X2(q.value-1,0,M);if(!$.multiple)J("update:modelValue",q.value);Q.invalidate();return}if(O.key==="ArrowDown"||O.code==="ArrowDown"){if(O.preventDefault(),M<=0)q.value=0;else if(q.value>=M)q.value=0;else q.value=X2(q.value+1,0,M);if(!$.multiple)J("update:modelValue",q.value);Q.invalidate();return}if($.multiple&&(O.code==="Space"||O.key===" "||O.key==="Spacebar")){O.preventDefault(),I(q.value);return}if(O.key==="Enter"){if($.multiple){O.preventDefault(),w();return}T(q.value);return}if(O.key==="Escape")O.preventDefault(),J("close")}let{id:S}=N0(()=>({rect:H.value,zIndex:K.value,visible:X.value,focusable:!0,handlers:{click:(O)=>{let M=H.value,P=O.cellY-M.y;if(P>=0&&P<$.options.length)T(P);else J("close")},focus:()=>{F.value=!0,J("focus"),Q.invalidate()},blur:()=>{if(F.value=!1,J("blur"),$.closeOnBlur)J("close");Q.invalidate()},keydown:z}}));return SI(()=>{if(!$.autoFocus)return;if(!X.value)return;let O=G.value,M=S.value;if(!O||!M)return;if(O.getFocused()===M)return;O.focus(M)}),o6(()=>({zIndex:$.zIndex,rect:X.value?H.value:{x:0,y:0,w:0,h:0},deps:[X.value,H.value,$.w,$.h,$.options,$.modelValue,$.multiple,$.multipleEmit,$.style,$.highlightStyle,F.value,q.value,_.value],paint:(O)=>{if(!X.value)return;let M=H.value;if(M.w<=0||M.h<=0)return;let P=$.style??_.value,A=$.highlightStyle??{...P,bg:"yellow",fg:"black"},k={...P,dim:!0},L={...A,dim:!0},v=$.multiple?new Set(j()):null,C=(s)=>{let F$=$.options[s];if(!F$){U.write(I4(M.w),{x:M.x,y:M.y+s,style:P});return}let K$=s===q.value,V$=$.multiple?v.has(s):K$,Y$=$.multiple?F.value&&K$:K$,u$=$.multiple?V$?"[x] ":"[ ] ":"",_$=z6(E(F$)),n=D(F$),a=n?z6(n):"",m=`${u$}${_$}`,G$=M$(m),L$=1,P$=Math.max(0,M.w-G$-L$);if(a&&P$>=4){let f$=Y$?A:P;U.write(m,{x:M.x,y:M.y+s,style:f$});let V4=m4(a,P$),s4=M$(V4),U6=Math.max(0,M.w-G$-s4),z4=Y$?A:P;U.write(I4(U6),{x:M.x+G$,y:M.y+s,style:z4});let C6=Y$?L:k;U.write(V4,{x:M.x+G$+U6,y:M.y+s,style:C6})}else{let f$=sB(m,M.w),V4=Y$?A:P;U.write(f$,{x:M.x,y:M.y+s,style:V4})}};if(!O){for(let s=0;s<M.h;s++)C(s);return}let b=Math.floor(M.y),y=b+Math.max(0,Math.floor(M.h));if(y<=b)return;let x=0,c=O.length;while(x<c){let s=x+c>>1;if((O[s]??0)<b)x=s+1;else c=s}for(let s=x;s<O.length;s++){let F$=Math.floor(O[s]??-1);if(F$<b)continue;if(F$>=y)break;let K$=F$-b;if(K$>=0&&K$<M.h)C(K$)}}})),()=>ge("span",Z)}});import{computed as he,inject as TI}from"vue";var MU=Symbol("TerminalRouter"),EV=Symbol("TerminalRoute");function LU(){let $=TI(MU,null);if(!$)throw Error("TerminalRouter is missing");return $}function PV(){let $=TI(EV,null);if(!$)throw Error("TerminalRoute is missing");return he(()=>$.value)}import{ref as ue}from"vue";function vI($,J){let U=typeof $==="string"?{name:$}:$,Q=J.get(U.name);return{name:U.name,params:U.params,meta:Q?.meta}}function X_($){return typeof $==="string"||typeof $==="object"&&$!=null&&"name"in $}function MV($){let J=new Map($.routes.map((F)=>[F.name,F])),U=ue(vI($.initialRoute,J)),Q=[U.value],_=0,G=[],V=[],X=[];async function Z(F,N,q){for(let H of F){let E=await H(N,q);if(E===!1)return!1;if(X_(E))return E}return!0}async function Y(F,N){let q=U.value,H=vI(F,J),E=J.get(q.name)??null,D=J.get(H.name)??null,B=await Z(G,H,q);if(B===!1)return;if(X_(B))return Y(B,N);let j=await Z(V,H,q);if(j===!1)return;if(X_(j))return Y(j,N);if(E?.onLeave)await E.onLeave(H,q);if(U.value=H,N==="replace")Q[_]=H;else if(N==="push")Q.splice(_+1),Q.push(H),_=Q.length-1;if(D?.onEnter)await D.onEnter(H,q);for(let f of X)f(H,q)}let K={currentRoute:U,async push(F){await Y(F,"push")},async replace(F){await Y(F,"replace")},async back(){if(_<=0)return;let F=U.value,N=Q[_-1],q=J.get(F.name)??null,H=J.get(N.name)??null,E=await Z(G,N,F);if(E===!1)return;if(X_(E))return Y(E,"push");let D=await Z(V,N,F);if(D===!1)return;if(X_(D))return Y(D,"push");if(q?.onLeave)await q.onLeave(N,F);if(_-=1,U.value=N,H?.onEnter)await H.onEnter(N,F);for(let B of X)B(N,F)},beforeEach(F){return G.push(F),()=>{let N=G.indexOf(F);if(N>=0)G.splice(N,1)}},beforeResolve(F){return V.push(F),()=>{let N=V.indexOf(F);if(N>=0)V.splice(N,1)}},afterEach(F){return X.push(F),()=>{let N=X.indexOf(F);if(N>=0)X.splice(N,1)}},install(F){F.provide(MU,K),F.provide(EV,U)}};return K}function CI($,J){let U=$.currentRoute.value;return J.find((_)=>_.name===U.name)?.component??null}import{computed as me,defineComponent as ce,h as de,inject as le,ref as ie,watch as re}from"vue";var LV=ce({name:"TRouterView",props:{routes:{type:Array,required:!0},forceRemount:{type:Boolean,default:!0}},setup($){let J=le(MU,null);if(!J)throw Error("TerminalRouter is missing (did you forget to app.use(router)?)");let U=ie(0);re(()=>J.currentRoute.value,()=>{if($.forceRemount)U.value++},{deep:!0});let Q=me(()=>CI(J,$.routes));return()=>{let _=Q.value;return _?de(_,{key:$.forceRemount?U.value:void 0}):null}}});function fO(){return typeof performance<"u"?performance.now():Date.now()}async function kO($){await new Promise((J)=>setTimeout(J,$))}var bI=null;function j8($){if(bI?.GOATCHAIN_DEBUG==="1")try{let J=new Date().toISOString().split("T")[1].slice(0,-1);ne.appendFileSync("/tmp/goatchain-debug.log",`[${J}] [GHOSTTY-KEEPALIVE] ${$}
|
|
910
|
-
`)}catch{}}function pe($){let J=_O({cols:$.cols,rows:$.rows,component:$.component,props:$.props,defaultStyle:$.defaultStyle});return $.install?.(J.app),J.mount(),{app:J.app,terminal:J.terminal,events:J.events,scheduler:J.scheduler,getImeAnchor:J.getImeAnchor,dispose:J.dispose}}async function ae($,J,U){let Q=null;for(let _ of U){let G=typeof _?.time==="number"?_.time:null;if(G!=null&&Q!=null){let V=Math.max(0,G-Q);await kO(Math.min(V,5000))}if(G!=null)Q=G;$.dispatch(_),await zV(),J.flush()}}async function yI($){bI=$.proc.env,j8("runTerminalUi() called");let J=pe({cols:$.cols,rows:$.rows,component:$.component,props:$.props,install:$.install,defaultStyle:$.defaultStyle}),U=()=>YV(J.terminal,{output:$.proc.stdout,altScreen:$.altScreen,palette:$.palette,trackResize:!$.sizeLocked,hideCursor:!0,defaultBg:$.defaultBg,getImeAnchor:J.getImeAnchor}),Q=U(),_=[],G=fO(),V=(z)=>{let S=z.time==null?{...z,time:fO()-G}:z;return _.push(S),J.events.dispatch(S)};J.scheduler.flush();let X=null,Z=()=>{let z=$.proc?.stdin;if(!z||typeof z.listeners!=="function"||typeof z.removeAllListeners!=="function")return;if(!(typeof globalThis.Bun<"u"))return;try{let O=z.listeners("data")??[],M=z.listeners("readable")??[];if(O.length>0||M.length>0)j8(`Taking over stdin: removing listeners (data=${O.length}, readable=${M.length})`),z.removeAllListeners("data"),z.removeAllListeners("readable")}catch{}},Y="GHOSTTY_RESOURCES_DIR"in($.proc.env??{});j8(`BEFORE exit setup - Ghostty detection: ${Y}`);let K=null,F=null,N=!1,q=!1,H=()=>{if(K)clearInterval(K),K=null},E=()=>{if(N)return;N=!0;let z=J.scheduler.invalidate;J.scheduler.invalidate=()=>{q=!0,z()}},D=()=>{if(!Y||K)return;E(),K=setInterval(()=>{if(q)J.scheduler.flush(),q=!1},100)},B=()=>{if(F)return;let z=typeof $.proc.exitCode==="number"?$.proc.exitCode:0;F=setTimeout(()=>{try{$.proc.exit(z)}catch{}},1500),F.unref?.()},j=()=>{if(H(),X)X.dispose(),X=null;if(Q)Q.dispose(),Q=null},f=!1,R=()=>{if(j(),!f)J.dispose(),f=!0};Xk(()=>{(async()=>{if($.proc.exitCode==null)$.proc.exitCode=0;let z=$.snapshotPath?J.terminal.snapshot().lines:null;if(R(),$.recordPath)await gB($.recordPath,_);if($.snapshotPath&&z)await oG($.snapshotPath,z);B()})()}),$.proc.on("exit",()=>{R()}),$.proc.on("beforeExit",()=>{R()});let w=()=>{j();try{$.proc.removeListener("SIGTSTP",w)}catch{}try{$.proc.kill($.proc.pid,"SIGTSTP")}catch{}},T=()=>{try{let z=typeof $.proc.listeners==="function"?$.proc.listeners("SIGTSTP"):[];if(Array.isArray(z)&&z.includes(w))return}catch{}$.proc.on("SIGTSTP",w)};if(T(),$.proc.on("SIGCONT",()=>{if(T(),!Q)Q=U();if(!X&&!$.replayPath)Z(),X=aG({stdin:$.proc.stdin,stdout:$.proc.stdout,dispatch:V,enableMouse:$.enableMouse,onExit:()=>l7()}),D();J.scheduler.invalidate(),J.scheduler.flush()}),$.replayPath){await zV(),await zV(),J.scheduler.flush();let z=await xB($.replayPath);if(await ae(J.events,J.scheduler,z),await kO(800),await zV(),J.scheduler.flush(),$.snapshotPath)await oG($.snapshotPath,J.terminal.snapshot().lines);R();return}if(Z(),X=aG({stdin:$.proc.stdin,stdout:$.proc.stdout,dispatch:V,enableMouse:$.enableMouse,onExit:()=>l7()}),Y)j8("Starting keep-alive interval (100ms)"),D(),j8("Keep-alive interval created successfully");if($.proc.on("SIGINT",()=>l7()),$.proc.on("SIGTERM",()=>l7()),Y)j8("Entering ghostty keep-alive loop (waiting forever)"),await new Promise(()=>{}),j8("Keep-alive loop exited (this should never happen)")}var xV=U4(AT(),1);import{spawn as c6$}from"node:child_process";import{existsSync as d6$,readFileSync as l6$}from"node:fs";import iO from"node:path";import{fileURLToPath as i6$}from"node:url";var Y2="goatchain-cli",r6$="upgrade-toast.json",n6$="upgrade-check.log",fT=process.env.GOATCHAIN_DEBUG_LOG||"./goatchain-debug.log",p6$=`https://registry.npmjs.org/${Y2}`,a6$=5000;async function o6$(){try{let $=new AbortController,J=setTimeout(()=>$.abort(),a6$),U=await fetch(p6$,{signal:$.signal,headers:{Accept:"application/json"}});if(clearTimeout(J),!U.ok)throw Error(`npm registry returned ${U.status}`);let _=(await U.json())["dist-tags"]?.latest;if(!_||typeof _!=="string")throw Error("No latest version found in registry response");return _}catch($){if($ instanceof Error&&$.name==="AbortError")throw Error("npm registry request timed out");throw $}}async function kT(){if(await $0("start",{disableAutoUpdate:process.env.GOATCHAIN_DISABLE_AUTOUPDATE==="1",autoUpdate:process.env.GOATCHAIN_AUTOUPDATE!=="0",cwd:$0$(),argv:J0$(),debugLogPath:fT}),process.env.GOATCHAIN_DISABLE_AUTOUPDATE==="1")return await $0("skip-disabled"),null;let $=U0$();if(!$?.version)return await $0("skip-missing-version"),null;let J=$.version,U=$.source==="injected";try{let Q=await o6$();if(await $0("check-result",{current:J,latest:Q,hasInjectedVersion:U}),!Q)return await $0("error",{message:"Failed to fetch latest version"}),null;if(xV.default.valid(J)&&xV.default.valid(Q)){if(xV.default.gte(J,Q))return await $0("no-update",{current:J,latest:Q}),null;if(process.env.GOATCHAIN_AUTOUPDATE!=="0"&&U)return await $0("update-available",{current:J,latest:Q,autoUpdate:!0}),t6$(Q),`Update available: ${Y2}@${Q} (current: ${J}). Installing in background. Restart terminal after it finishes.`;return await $0("update-available",{current:J,latest:Q,autoUpdate:!1}),`Update available: ${Y2}@${Q} (current: ${J})`}if(J===Q)return await $0("no-update",{current:J,latest:Q}),null;return await $0("update-available",{current:J,latest:Q,autoUpdate:!1}),`Update available: ${Y2}@${Q} (current: ${J})`}catch(Q){return await $0("error",{message:Q instanceof Error?Q.message:String(Q)}),null}}function t6$($){try{$0("autoupdate-start",{version:$});let J=c6$("npm",["install","-g",`${Y2}@${$}`],{stdio:"ignore",detached:!0});J.unref();let U=!1,Q=(_)=>{if(U)return;U=!0,$0("autoupdate-finish",{version:$,message:_}),wT(_)};J.on("close",(_)=>{if(_===0)Q(`Update installed: ${Y2}@${$}. Restart terminal to use the new version.`);else Q(`Auto-update failed. Run: npm install -g ${Y2}`)}),J.on("error",()=>{$0("autoupdate-error",{version:$,reason:"process-error"}),Q(`Auto-update failed. Run: npm install -g ${Y2}`)})}catch{$0("autoupdate-error",{version:$,reason:"spawn-throw"}),wT(`Auto-update failed. Run: npm install -g ${Y2}`)}}function wT($){let J=globalThis?.__GOATCHAIN_UPGRADE_TOAST__;if(typeof J==="function")try{J($);return}catch{}s6$($)}async function s6$($){try{let{getGoatChainUserDir:J}=await Promise.resolve().then(() => (U2(),fB)),[{mkdir:U,writeFile:Q},_]=await Promise.all([import("node:fs/promises"),import("node:path")]),G=await J(process.env);await U(G,{recursive:!0});let V=_.join(G,r6$),X=JSON.stringify({message:$,createdAt:Date.now()});await Q(V,X,"utf8")}catch{}}async function $0($,J){try{let{getGoatChainUserDir:U}=await Promise.resolve().then(() => (U2(),fB)),[{mkdir:Q,appendFile:_},G]=await Promise.all([import("node:fs/promises"),import("node:path")]),V=await U(process.env);await Q(V,{recursive:!0});let X=G.join(V,n6$),Z={ts:new Date().toISOString(),event:$,...J};await _(X,`${JSON.stringify(Z)}
|
|
911
|
-
`,{encoding:"utf8",mode:384}),await e6$(Z)}catch{}}async function e6$($){try{let{appendFile:J}=await import("node:fs/promises"),Q=`[${String($.ts??new Date().toISOString())}] upgrade_check ${JSON.stringify($)}
|
|
912
|
-
`;await J(fT,Q,{encoding:"utf8"})}catch{}}function $0$(){try{return process.cwd()}catch{return}}function J0$(){try{return process.argv}catch{return}}function U0$(){let $="0.0.5-beta.9".trim();if($)return{version:$,source:"injected"};let J=_0$();if(J)return{version:J,source:"package"};return null}function _0$(){try{let $=iO.dirname(i6$(import.meta.url));for(let J=0;J<6;J++){let U=iO.join($,"package.json");if(d6$(U)){let _=l6$(U,"utf8"),G=JSON.parse(_),V=typeof G?.version==="string"?G.version.trim():"";if(V)return V}let Q=iO.dirname($);if(Q===$)break;$=Q}}catch{}return null}import{computed as k6,defineComponent as g1$,h as BJ,inject as x1$,nextTick as h1$,onBeforeUnmount as KC,provide as u1$,ref as C0,watch as A8}from"vue";var E8=Symbol("GoatChainBridge");var IT=["user","assistant","tool"];var ST=["status","thinking","markdown","tool_call","tool_output","tool_result","approve","todo","plan","llm_meta"];var RU=[...IT,...ST];var hV=["black","red","green","yellow","blue","magenta","cyan","white","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"];function rO($,J){let U={};for(let Q of RU)U[Q]={fg:$,bg:J};return U}var TT=Object.freeze({goatchain:{...rO("white","black"),user:{fg:"whiteBright",bg:"blackBright"},assistant:{fg:"white",bg:"black"},tool:{fg:"white",bg:"black"},markdown:{fg:"white",bg:"black"},status:{fg:"white",bg:"black"},thinking:{fg:"blueBright",bg:"black"},tool_call:{fg:"white",bg:"black"},tool_output:{fg:"white",bg:"black"},tool_result:{fg:"white",bg:"black"},approve:{fg:"white",bg:"black"},todo:{fg:"whiteBright",bg:"black"},plan:{fg:"whiteBright",bg:"black"}},mono:{...rO("white","black"),user:{fg:"white",bg:"black"},assistant:{fg:"white",bg:"black"},tool:{fg:"white",bg:"black"},thinking:{fg:"white",bg:"black"}},contrast:{...rO("whiteBright","black"),user:{fg:"whiteBright",bg:"blackBright"},assistant:{fg:"whiteBright",bg:"black"},tool:{fg:"whiteBright",bg:"black"},thinking:{fg:"blueBright",bg:"black"},tool_call:{fg:"yellowBright",bg:"black"},tool_output:{fg:"cyanBright",bg:"black"},tool_result:{fg:"cyanBright",bg:"black"},todo:{fg:"greenBright",bg:"black"},plan:{fg:"magentaBright",bg:"black"}}});function k1($,J){let U=TT[$.preset]??TT.goatchain,Q=U[J]??U.assistant??{fg:"white",bg:"black"},_=$.overrides?.[J]??{};return{...Q,..._}}import nO from"node:fs";function Q0$($){let U="";for(let Q=0;Q<$.length;Q++){if($[Q]!=="\x1B"||$[Q+1]!=="["){U+=$[Q];continue}let _=Q+2;while(_<$.length){let G=$.charCodeAt(_);if(G>=48&&G<=57||G===59){_++;continue}break}if(_<$.length&&$[_]==="m"){Q=_;continue}U+=$[Q]}return U}function vT($){$=Q0$($);let J="";for(let U of $){let Q=U.codePointAt(0);if(Q<=31&&Q!==10&&Q!==9||Q===127||Q>=128&&Q<=159)continue;J+=U}return J}var uV=null;try{uV=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null}catch{uV=null}function CT($,J){if(!$)return;if(uV){for(let Q of uV.segment($))J(Q);return}let U=0;while(U<$.length){let Q=$.codePointAt(U)??0,_=String.fromCodePoint(Q);J({segment:_,index:U}),U+=_.length}}function AU($){let J=0;return CT($,(U)=>{J+=u4(U.segment)}),J}function mV($,J){if(J=Math.max(0,Math.floor(J)),J<=0)return{chunk:"",rest:$};let U=0,Q=0,_=[];CT($,(G)=>{_.push({segment:G.segment,index:G.index})});for(let G=0;G<_.length;G++){let{segment:V,index:X}=_[G],Z=X+V.length,Y=u4(V);if(U+Y>J)break;if(U+=Y,Q=Z,U>=J)break}return{chunk:$.slice(0,Q),rest:$.slice(Q)}}function B_($,J){return mV($,J).chunk}function bT($,J){J=Math.max(0,Math.floor(J));let U=AU($);if(U>=J)return B_($,J);return`${$}${" ".repeat(J-U)}`}function yT($,J){if(J=Math.max(1,Math.floor(J)),!$)return[""];let U=[],Q=$;while(!0){let{chunk:_,rest:G}=mV(Q,J);if(U.push(_),!G)break;Q=G}return U}var P8=new Map,G0$=100,V0$=60000;function X0$($,J){let U=0,Q=`${$}|${J}`;for(let _=0;_<Q.length;_++){let G=Q.charCodeAt(_);U=(U<<5)-U+G,U=U&U}return U.toString(36)}function Y0$(){let $=Date.now();for(let[J,U]of P8.entries())if($-U.timestamp>V0$)P8.delete(J)}if(typeof setInterval<"u")setInterval(Y0$,1e4);function cV($){let J=(Z)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let K=new Date().toISOString().split("T")[1].slice(0,-1);nO.appendFileSync("/tmp/goatchain-debug.log",`[${K}] [PARSE-INLINE] ${Z}
|
|
913
|
-
`)}}catch{}},U=[],Q="",_=0;J(`START: text length=${$.length}`);function G(){if(!Q)return;U.push({kind:"text",text:Q}),Q=""}let V=0,X=$.length*10+1000;while(_<$.length){if(V++,V>X){J(`ERROR: Infinite loop detected! i=${_}, text.length=${$.length}, iterations=${V}`);break}if(V%100===0)J(` Progress: i=${_}/${$.length}, iterations=${V}`);let Z=$[_];if(Z==="`"){let Y=$.indexOf("`",_+1);if(Y>_+1){G(),U.push({kind:"code",text:$.slice(_+1,Y)}),_=Y+1;continue}}if(Z==="*"&&$[_+1]==="*"){let Y=$.indexOf("**",_+2);if(Y>_+2){G(),U.push({kind:"bold",text:$.slice(_+2,Y)}),_=Y+2;continue}}Q+=Z,_++}return G(),J(`END: ${U.length} spans, iterations=${V}`),U}function dV($,J){let U=(F)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let q=new Date().toISOString().split("T")[1].slice(0,-1);nO.appendFileSync("/tmp/goatchain-debug.log",`[${q}] [WRAP-SPANS] ${F}
|
|
914
|
-
`)}}catch{}};if(J<=0)return[[{kind:"text",text:""}]];U(`START: spans=${$.length}, width=${J}`);function Q(F){let N=[],q=/\s+/g,H=0;for(let E=q.exec(F.text);E;E=q.exec(F.text)){if(E.index>H)N.push({kind:F.kind,text:F.text.slice(H,E.index)});N.push({kind:F.kind,text:E[0]}),H=E.index+E[0].length}if(H<F.text.length)N.push({kind:F.kind,text:F.text.slice(H)});return N}let _=[],G=[],V=0;function X(F){if(!F.text)return 0;if(/^\s+$/.test(F.text))return F.text.length;return AU(F.text)}function Z(F){let N=G[G.length-1];if(N&&N.kind===F.kind){N.text+=F.text;return}G.push({...F})}function Y(){_.push(G),G=[],V=0}let K=0;for(let F of $){K++;let N=Q(F),q=0;for(let H of N){if(q++,!H.text)continue;if(/^\s+$/.test(H.text)&&V===0)continue;let E=X(H);if(E<=J-V){Z(H),V+=E;continue}if(!/^\s+$/.test(H.text)&&V>0&&E<=J){Y(),Z(H),V+=E;continue}let D=H.text,B=0,j=H.text.length*10+100;while(D){if(B++,B>j){U(`ERROR: Infinite loop in chunking! span=${K}, token=${q}, iterations=${B}, remaining="${D.slice(0,50)}", col=${V}, width=${J}`);break}let f=J-V;if(f<=0){Y();continue}if(/^\s+$/.test(D)){Y(),D="";continue}let R=mV(D,f),I=R.chunk;if(D=R.rest,Z({kind:H.kind,text:I}),V+=AU(I),V>=J)Y()}}}if(G.length===0)return _.length?_:[[{kind:"text",text:""}]];return _.push(G),U(`END: ${_.length} lines`),_}function gT($,J){let U=(w)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let z=new Date().toISOString().split("T")[1].slice(0,-1);nO.appendFileSync("/tmp/goatchain-debug.log",`[${z}] [MARKDOWN-PARSE] ${w}
|
|
915
|
-
`)}}catch{}},Q=Date.now();U(`START: markdown length=${$.length}, width=${J}`);let _=X0$($,J),G=P8.get(_);if(G)return U(`CACHE HIT: returning ${G.lines.length} cached lines`),G.timestamp=Date.now(),G.lines;U("CACHE MISS: parsing markdown");let V=vT($).split(`
|
|
916
|
-
`);U(`After sanitize: ${V.length} lines`);let X=[],Z=!1,Y="",K=0,F=2,N=!0,q=!0,H=/[┌┐└┘│─├┤┬┴┼╭╮╯╰]/;function E(w){return Math.max(0,Math.floor(w))}function D(w,T){if(T<=0)return"";return bT(w,T)}function B(w,T){if(T=E(T),T<=0)return"";if(T===1)return"┌";let z=Math.max(0,T-2),O=` ${(w||"code").trim()} `;if(z===0)return"┌┐";let M=B_(O,z),P="─".repeat(Math.max(0,z-AU(M)));return`┌${M}${P}┐`.slice(0,T)}function j(w){if(w=E(w),w<=0)return"";if(w===1)return"└";return`└${"─".repeat(Math.max(0,w-2))}┘`.slice(0,w)}function f(w,T,z){if(z=E(z),z<=0)return"";if(z<4)return B_(w,z);let S=Math.max(0,z-2),M=S<6||!T?"":`${T} │ `;return`│${D(`${M}${w}`,S)}│`.slice(0,z)}let R=0;for(let w of V){if(R%100===0)U(`Processing line #${R}/${V.length}`);let T=w.replace(/\r/g,"");if(T.startsWith("```")){if(!Z){Z=!0,Y=T.slice(3).trim(),K=0,F=2,N=!0,q=!0;let C=0,b=!1;for(let y=R+1;y<V.length;y++){let x=V[y].replace(/\r/g,"");if(x.startsWith("```"))break;if(C++,!b&&H.test(x))b=!0}if(F=Math.max(2,String(Math.max(0,C)).length),b)N=!1,q=!1;X.push({kind:"code",spans:[{kind:"text",text:B(Y||"code",J)}]})}else Z=!1,X.push({kind:"code",spans:[{kind:"text",text:j(J)}]});R++;continue}if(Z){K+=1;let C=String(K).padStart(F," "),b=Math.max(0,E(J)-2),x=!q||b<6?0:F+3,c=Math.max(1,b-x),s=N?yT(T,c):[B_(T,c)];for(let[F$,K$]of s.entries()){let V$=!q?"":F$===0?C:" ".repeat(F);X.push({kind:"code",spans:[{kind:"text",text:f(K$,V$,J)}]})}R++;continue}if(/^#{1,6}\s+/.test(T)){let C=T.replace(/^#{1,6}\s+/,""),b=cV(C);for(let y of dV(b,J))X.push({kind:"heading",spans:y});R++;continue}if(T.startsWith("> ")){let C=T.slice(2),b=cV(C);for(let y of dV(b,Math.max(1,J-2)))X.push({kind:"quote",spans:[{kind:"text",text:"│ "},...y]});R++;continue}let z=0;while(z<T.length&&T[z]===" ")z++;let S=(C)=>T[C]===" "||T[C]==="\t",O=(C)=>{let b=C;while(b<T.length&&S(b))b++;return b},M=!1,P="",A="",k=0,L=T[z];if(L==="-"||L==="*"||L==="+"){let C=z+1;if(S(C)){let b=O(C);if(b<T.length)M=!0,k=Math.floor(z/2),P="•",A=T.slice(b)}}if(!M){let C=z;while(C<T.length){let b=T.charCodeAt(C);if(b<48||b>57)break;C++}if(C>z&&T[C]==="."&&S(C+1)){let b=O(C+1);if(b<T.length)M=!0,k=Math.floor(z/2),P=`${T.slice(z,C)}.`,A=T.slice(b)}}if(M){let b=`${" ".repeat(k*2)}${P} `,y=AU(b),x=" ".repeat(y),c=cV(A),s=dV(c,Math.max(1,J-y));for(let[F$,K$]of s.entries())X.push({kind:"list",spans:[{kind:"text",text:F$===0?b:x},...K$]});R++;continue}if(!T.trim()){X.push({kind:"text",spans:[{kind:"text",text:""}]}),R++;continue}let v=cV(T);for(let C of dV(v,J))X.push({kind:"text",spans:C});R++}if(U(`After parsing: ${X.length} output lines`),P8.size>=G0$){let w=null,T=Date.now();for(let[z,S]of P8.entries())if(S.timestamp<T)T=S.timestamp,w=z;if(w)P8.delete(w)}P8.set(_,{hash:_,lines:X,timestamp:Date.now()});let I=Date.now()-Q;return U(`END: total ${I}ms, ${X.length} lines`),X}function xT(){return{type:"none"}}function hT($){return{type:"selectToolCall",callId:$}}function uT(){return{type:"openApproval"}}function mT($){return{type:"openFile",absPath:$}}function pO($,J,U){return{type:"toggleItem",messageId:$,part:J,itemId:U}}function lV($,J,U){return{type:"toggleCollapse",messageId:$,part:J,partIndex:U}}function J0($){return{type:"toggleBashOutput",toolCallId:$}}var iV=null;try{iV=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null}catch{iV=null}function cT($,J){if(!$)return;if(iV){for(let Q of iV.segment($))J(Q);return}let U=0;while(U<$.length){let Q=$.codePointAt(U)??0,_=String.fromCodePoint(Q);J({segment:_,index:U}),U+=_.length}}function dT($){let J=/\[?@((?:\/|\.\.?\/)[^\s[\](){}'"`,;:!?]+)\]*/g,U=[],Q="",_=0,G;G=J.exec($);while(G!==null){let V=G[0],X=G[1],Z=G.index;Q+=$.slice(_,Z);let Y=X.replace(/[\])'"`,;:!?]+$/,"").replace(/[.-]+$/,""),F=`[${Y.split("/").pop()||Y}]`,N=Q.length;Q+=F;let q=Q.length;U.push({start:N,end:q,absPath:Y}),_=Z+V.length,G=J.exec($)}return Q+=$.slice(_),{displayText:Q,segments:U}}function O_($,J){J=Math.max(1,Math.floor(J));let U=[],Q=0,_=[],G=0,V=(Z)=>{U.push({text:_.join(""),start:Q,end:Z}),_=[],G=0},X=[];cT($,(Z)=>{X.push({segment:Z.segment,index:Z.index})});for(let Z=0;Z<X.length;Z++){let{segment:Y,index:K}=X[Z],F=K+Y.length;if(Y===`
|
|
917
|
-
`){V(K),Q=F;continue}let N=u4(Y);if(G+N>J){if(G===0){_=[Y],G=N,V(F),Q=F;continue}V(K),Q=K,Z--;continue}_.push(Y),G+=N}return U.push({text:_.join(""),start:Q,end:$.length}),U}function lT($,J){let U=Math.max(0,Math.floor(J));if(!U)return{text:"",truncated:$.length>0};let Q=[],_=0,G=0,V=[];cT($,(X)=>{V.push({segment:X.segment,index:X.index})});for(let X=0;X<V.length;X++){let{segment:Z,index:Y}=V[X],K=Y+Z.length,F=u4(Z);if(_+F>U)break;Q.push(Z),_+=F,G=K}return{text:Q.join(""),truncated:G<$.length}}var aO=2000,oO=5000000;function tO($,J){let U=new TextEncoder().encode($).length,Q=new TextEncoder().encode(J).length;if(U>oO||Q>oO)return[{type:"context",content:`[Diff too large: ${Math.max(U,Q).toLocaleString()} bytes. Size limit: ${oO.toLocaleString()} bytes]`}];let _=$.replace(/\r/g,"").split(`
|
|
918
|
-
`),G=J.replace(/\r/g,"").split(`
|
|
919
|
-
`),V=_.length,X=G.length;if(V>aO||X>aO)return[{type:"context",content:`[Diff too large: ${Math.max(V,X).toLocaleString()} lines. Line limit: ${aO.toLocaleString()} lines]`}];let Z=Array.from({length:V+1},()=>Array(X+1).fill(0));for(let H=1;H<=V;H++)for(let E=1;E<=X;E++)if(_[H-1]===G[E-1])Z[H][E]=Z[H-1][E-1]+1;else Z[H][E]=Math.max(Z[H-1][E],Z[H][E-1]);let Y=[],K=V,F=X,N=1,q=1;while(K>0||F>0)if(K>0&&F>0&&_[K-1]===G[F-1])Y.unshift({type:"context",lineNumber:q,content:G[F-1]}),K--,F--,N++,q++;else if(F>0&&(K===0||Z[K][F-1]>=Z[K-1][F]))Y.unshift({type:"added",lineNumber:q,content:G[F-1]}),F--,q++;else if(K>0&&(F===0||Z[K][F-1]<Z[K-1][F]))Y.unshift({type:"removed",lineNumber:N,content:_[K-1]}),K--,N++;return Y}function iT($,J){let U=tO($,J),Q=0,_=0;for(let G of U)if(G.type==="added")Q++;else if(G.type==="removed")_++;return{added:Q,removed:_}}function rT($,J,U){if(!J&&!U)return!1;let Q=iT(J,U),_=[];if(Q.removed>0)_.push(`-${Q.removed}`);if(Q.added>0)_.push(`+${Q.added}`);if(_.length>0){let G={...$.detailStyle,bold:!0},V=_.join(" ");return $.pushLine(` diff: ${V}`,G),!0}return!1}function nT($,J,U){if(!J&&!U)return;let Q=tO(J,U),_=$.maxLines??24,V=Z0$(Q,3,_),X={...$.detailStyle,fg:"yellowBright"},Z={...$.detailStyle,fg:"red"},Y={...$.detailStyle,fg:"green"};for(let K of V){let F=K.type==="removed"?"- ":K.type==="added"?"+ ":" ",N=K.type==="removed"?Z:K.type==="added"?Y:X;$.pushLine(` ${F}${K.content}`,N)}}function Z0$($,J,U){let Q=[],_=0;for(let G=0;G<$.length;G++){let V=$[G];if(V.type==="context"){let X=G>0?$[G-1]:null,Z=G<$.length-1?$[G+1]:null,Y=X?.type!=="context"||Z?.type!=="context";if(Y||_<J)if(Q.push(V),Y)_=0;else _++;else if(_===J)Q.push({type:"context",content:"…"}),_++}else Q.push(V),_=0;if(Q.length>=U){Q.push({type:"context",content:"… (more lines truncated)"});break}}return Q}function pT($){return $<=31&&$!==9&&$!==10}function aT($){return $>=128&&$<=159}function I0($){let J=String($??""),U="";for(let Q=0;Q<J.length;){let _=J.codePointAt(Q)??0,G=_>65535?2:1;if(_===27||pT(_)||_===127||aT(_)){Q+=G;continue}U+=String.fromCodePoint(_),Q+=G}return U}function sO($){let J=String($??""),U="";for(let Q=0;Q<J.length;){if(J[Q]==="\x1B"){let V=J[Q+1];if(V==="["){let X=Q+2;while(X<J.length){let Z=J.charCodeAt(X);if(Z>=48&&Z<=57||Z===59){X++;continue}break}if(X<J.length&&J[X]==="m"){U+=J.slice(Q,X+1),Q=X+1;continue}X=Q+2;while(X<J.length){let Z=J.charCodeAt(X);if(X++,Z>=64&&Z<=126)break}Q=X;continue}if(V==="]"){let X=Q+2;while(X<J.length){if(J.charCodeAt(X)===7){X++;break}if(J[X]==="\x1B"&&J[X+1]==="\\"){X+=2;break}X++}Q=X;continue}if(Q+=1,Q<J.length)Q+=1;continue}let _=J.codePointAt(Q)??0,G=_>65535?2:1;if(pT(_)||_===127||aT(_)){Q+=G;continue}U+=String.fromCodePoint(_),Q+=G}return U}var T0=" ";function S0($,J,U){let Q=k1($,J);return{fg:Q.fg,bg:Q.bg,...U??{}}}function oT($,J){return{pushLine:(G,V,X)=>{$.push({text:` ${G}`,style:V,segments:[],action:X})},pushLineWithSegments:(G,V,X,Z)=>{$.push({text:` ${G}`,style:V,segments:X,action:Z})},pushSpans:(G,V)=>{let X=J,Z=[];for(let K of G){let F=K.kind==="bold"?{...V??{},bold:!0}:K.kind==="code"?{...V??{},fg:"yellowBright"}:V,N=M$(K.text);if(K.kind!=="text")Z.push({x:X,w:N,text:K.text,style:F});X+=N}let Y=G.map((K)=>K.text).join("");$.push({text:` ${Y}`,style:V,segments:Z.map((K)=>({...K,x:K.x}))})}}}function tT($){let J=[],{pushLine:U}=oT(J,$.contentIndent),Q=S0($.theme,"user",{fg:k1($.theme,"user").fg??"whiteBright"}),_=$.message.content.replace(/\r/g,""),G=Math.max(1,$.width-$.contentIndent),V=dT(_),X=V.displayText,Z=V.segments,Y=($.message.focusFiles??[]).map((K)=>String(K??"")).filter(Boolean);if(Y.length>0){let K="",F=[];for(let H of Y){let D=`[${H.split(/[/\\]/).filter(Boolean).pop()??H}]`,B=K.length?" ":"",j=K.length+B.length;K+=`${B}${D}`;let f=K.length;F.push({start:j,end:f,absPath:H})}let N=X.startsWith(`
|
|
920
|
-
`)?"":X?" ":"",q=K.length+N.length;X=`${K}${N}${X}`,Z=[...F,...Z.map((H)=>({...H,start:H.start+q,end:H.end+q}))]}for(let K of O_(X,G)){let{text:F,start:N,end:q}=K,H=[];for(let E of Z)if(E.end>N&&E.start<q){let D=Math.max(N,E.start),B=Math.min(q,E.end),j=X.slice(D,B),f=X.slice(N,D),R=$.contentIndent+M$(f);H.push({x:R,w:M$(j),text:j,style:{fg:"cyanBright",bold:!0},action:mT(E.absPath)})}if(H.length>0)J.push({text:` ${F}`,style:Q,segments:H});else U(F,Q)}return J}function K0$($,J){if($.selectedToolCallId!==J)return;let Q=$.toolNameById.get(J);if(Q&&String(Q).toLowerCase()==="bash")return;let G=String($.toolOutputById.get(J)??"").replace(/\r/g,"");if(!G.trim())return;let V=S0($.theme,"tool_output",{dim:!0});$.pushLine("↳ output",V);let X=G.split(`
|
|
921
|
-
`),Z=10,Y=$.expandedBashOutputs.has(J),K=Y?Number.POSITIVE_INFINITY:Z,F=Math.max(0,X.length-K);for(let q of X.slice(F))$.pushLine(I0(q),V);let N=X.length>Z;if(N&&!Y){let q={...V,fg:"cyan"},H=X.length-Z;$.pushLine(`... (${H} more lines)`,q,J0(J))}else if(N&&Y){let q={...V,fg:"cyan"};$.pushLine("... (collapse)",q,J0(J))}}function wU($){let J=String($??""),U=J.match(/^( +)(?=\d+\|)/);if(!U)return{text:J,removedCells:0};let Q=U[1].length;return{text:J.slice(Q),removedCells:Q}}function sT($,J){let U=Math.max(0,Math.floor(J));if(!U)return $.slice();let Q=U,_=[];for(let G of $){if(!G||!G.text)continue;if(!Q){_.push(G);continue}let V=String(G.text),X=0;while(X<V.length&&Q>0&&V[X]===" ")X++,Q--;let Z=V.slice(X);if(Z)_.push({...G,text:Z})}return _}function eT($){let J=String($??"").trim();if(!J)return null;try{let U=JSON.parse(J),Q=Array.isArray(U)?U:[U],_=[];for(let G of Q)if(G&&typeof G==="object"&&G.type==="text"){let V=String(G.text??"").replace(/\r/g,"");if(V)_.push(...V.split(`
|
|
922
|
-
`))}return _.length>0?_:null}catch{return null}}function N0$($,J){if($.selectedToolCallId!==J)return;let Q=$.toolResultById.get(J);if(!Q)return;let _=$.toolNameById.get(J),G=_&&String(_).toLowerCase()==="bash",V=String(_??"").toLowerCase(),X=S0($.theme,"tool_result",{dim:!0});if(Q.status!=="success")$.pushLine(`✗ ${Q.status}`,X);if(G)return;if(V==="askuserquestion")return;let Z=V&&V!=="read"?Q.outputAnsi:void 0,Y=typeof Z==="string"&&Z.trim().length>0,K=10,F=$.expandedBashOutputs.has(J),N=F?Number.POSITIVE_INFINITY:K,q=eT(Q.output),H=String(Q.output??"").replace(/\r/g,"").split(`
|
|
923
|
-
`),E=q?.length??H.length,D=Math.min(E,N),B=Y?String(Z??"").replace(/\r/g,"").split(`
|
|
924
|
-
`):null,j=M$(T0);if(q){for(let I of q.slice(0,D)){let w=wU(I);$.pushLine(`${T0}${I0(w.text)}`,X)}let R=q.length>K;if(R&&!F){let I={...X,fg:"cyan"},w=q.length-K;$.pushLine(`... (${w} more lines)`,I,J0(J))}else if(R&&F){let I={...X,fg:"cyan"};$.pushLine("... (collapse)",I,J0(J))}return}for(let R=0;R<D;R++){let I=H[R]??"";if(Y&&B&&R<B.length){let T=sO(B[R]??"");if(T===""){$.pushLine(T0,X);continue}let z=GU(T,{}),S=z.map((L)=>L.text).join(""),O=wU(S),M=I0(O.text),P=O.removedCells>0?sT(z,O.removedCells):z,A=$.contentIndent+j,k=[];for(let L of P){let v=I0(L.text),C=M$(v);if(C>0&&Object.keys(L.style??{}).length>0)k.push({x:A,w:C,text:v,style:L.style});A+=C}$.pushLineWithSegments(`${T0}${M}`,X,k);continue}if(I===""){$.pushLine(T0,X);continue}let w=wU(I);$.pushLine(`${T0}${I0(w.text)}`,X)}let f=E>K;if(f&&!F){let R={...X,fg:"cyan"},I=E-K;$.pushLine(`... (${I} more lines)`,R,J0(J))}else if(f&&F){let R={...X,fg:"cyan"};$.pushLine("... (collapse)",R,J0(J))}}var F0$={status($,J){},thinking($,J){let U=J.collapsed?"▸":"▾",_={...S0($.theme,"thinking"),bold:!0},V=S0($.theme,"assistant");if($.pushLine(`${U} ${J.title}`,_,lV($.messageId,J.type,$.partIndex)),J.collapsed)return $.pushLine("");let X=String(J.content??"").replace(/\r/g,"").trim();if(!X)return $.pushLine("");let Z=" ",Y=M$(Z),K=Math.max(10,$.width-$.contentIndent-Y),F=X.split(`
|
|
925
|
-
`);$.pushLine("");for(let N of F){let q=O_(N,K);if(q.length===0){$.pushLine(Z,V);continue}for(let H of q)$.pushLine(`${Z}${H.text}`,V)}$.pushLine("")},markdown($,J){let U=(Y)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let F=E$("node:fs"),N=new Date().toISOString().split("T")[1].slice(0,-1);F.appendFileSync("/tmp/goatchain-debug.log",`[${N}] [RENDER-MARKDOWN] ${Y}
|
|
926
|
-
`)}}catch{}},Q=J.markdown,_=$.width-$.contentIndent,G=Date.now();U(`START: markdown length=${Q.length}, width=${_}`);let V=S0($.theme,"markdown"),X=gT(Q,_);U(`markdownToLines returned: ${X.length} lines in ${Date.now()-G}ms`);let Z=0;for(let Y of X){if(Z%100===0)U(` Processing line #${Z}/${X.length}`);let K=Y.kind==="heading"?{...V,bold:!0}:Y.kind==="quote"?{...V,dim:!0}:Y.kind==="code"?{...V,fg:"yellowBright"}:V;$.pushSpans(Y.spans,K),Z++}U(`END: processed ${X.length} lines in ${Date.now()-G}ms`)},tool_call($,J){if($.partIndex!==void 0&&$.partIndex>0){if($.parts[$.partIndex-1]?.type==="markdown")$.pushLine("")}let U=$.selectedToolCallId===J.call.id,Q=U?"▾":"▸",_=S0($.theme,"tool_call"),G=$.toolResultById.get(J.call.id),V=(()=>{if(G?.status==="success")return"green";if(G?.status==="error")return"red";return"whiteBright"})(),X="●",Z=U?{..._,bold:!0,fg:"white"}:{..._,dim:!0,fg:"white"},Y={..._,fg:V},K=J.call.arguments,N=((R)=>R!=null&&typeof R==="object"&&!Array.isArray(R))(K)?K:null,q=(()=>{let R=String(J.call.name??"").toLowerCase();if(R==="bash"&&N){let I=typeof N.description==="string"?String(N.description).trim():"";if(I)return` ${I}`}else if(R==="read"&&N){let I=typeof N.file_path==="string"?String(N.file_path).trim():"";if(I){let{limit:w,offset:T}=N,z=[];if(typeof T==="number"&&T>0)z.push(`offset ${T}`);if(typeof w==="number"&&w>0)z.push(`limit ${w}`);if(z.length>0)return` ${I} (${z.join(", ")})`;return` ${I}`}}else if(R==="write"){let I=typeof N?.file_path==="string"?String(N.file_path).trim():"";if(I)return` ${I}`;let w=J.call.argumentsText?.match(/"file_path":\s*"([^"]+)"/);if(w)return` ${w[1]}`}else if(R==="glob"&&N){let I=typeof N.pattern==="string"?String(N.pattern).trim():"";if(I){try{let T=JSON.parse(G?.output||"[]")[0].text.match(/Found\s(\d+)\s+files/);if(T){let z=T[1];return` ${I} (${z} matches)`}}catch{}return` ${I}`}}else if(R==="grep"&&N){let I=typeof N.pattern==="string"?String(N.pattern).trim():"";if(I)return` ${I}`}else if(R==="askuserquestion"&&N){let I=Array.isArray(N.questions)?N.questions:[];if(I.length>0&&I[0]?.header){let w=String(I[0].header).trim();if(w)return` [${w}]`}}else if(R==="edit"&&N){if(N.file_path)return` ${N.file_path}`;let I=J.call.argumentsText?.match(/"file_path": "([^:"]+)"/);if(I)return` ${I[1]}`}else if(R==="todoplan"&&N){let I=N.todos;if(Array.isArray(I)&&I.length>0)return` (${I.length} todos)`}return""})(),H=`${Q} `,E=M$(` ${H}`),D=M$(`${X} ${J.call.name}`),B=Math.max(0,$.width-E-D),j=(()=>{if(!q||B<=0)return"";let R=lT(q.trim(),B);if(!R.truncated)return q;return` ${R.text}…`})(),f=`${X} ${J.call.name}${j}`;if($.pushLineWithSegments(`${H}${f}`,U?{..._,bold:!0}:{..._,dim:!0},[{x:E,w:1,text:X,style:Y},{x:E+2,w:M$(J.call.name),text:J.call.name,style:Z}],hT(J.call.id)),$.pushLine(""),U){let R={..._,dim:!0},I=Math.max(10,$.width-$.contentIndent-2),w=String(J.call.name??"").toLowerCase();if(w==="bash"){let T=typeof N?.command==="string"?String(N.command).trim():"",z=$.toolResultById.get(J.call.id),S=$.toolOutputById.get(J.call.id)?.trim();try{S=z?.output?JSON.parse(z?.output)[0].text.trim():$.toolOutputById.get(J.call.id)?.trim()}catch{}if(T){let O={..._,bold:!0};$.pushLine(" in:",O);let M={...R,fg:"yellowBright"},P=T.replace(/\r/g,"").split(`
|
|
927
|
-
`),A=!0;for(let k of P){let L=A?" $ ":" | ",v=Math.max(5,I-M$(L)+2),C=O_(k,v);if(C.length===0){$.pushLine(` ${L.trim()}`,M),A=!1;continue}for(let b of C){let y=A?" $ ":" | ";$.pushLine(` ${y.trim()}${b.text}`,M),A=!1}}}if(S){let O=$.expandedBashOutputs.has(J.call.id),M=10,P=O?Number.POSITIVE_INFINITY:10,A=S.replace(/\r/g,"").split(`
|
|
928
|
-
`),k=A.length>10,L={..._,bold:!0};$.pushLine(" out:",L);for(let v of A.slice(0,P))$.pushLine(` ${v}`,R);if(k&&!O){let v={...R,fg:"cyan"},C=A.length-10;$.pushLine(` ... (${C} more lines)`,v,J0(J.call.id))}else if(k&&O){let v={...R,fg:"cyan"};$.pushLine(" ... (collapse)",v,J0(J.call.id))}}}else{let T=new Set;if(w==="read")T.add("file_path"),T.add("limit"),T.add("offset");else if(w==="glob")T.add("pattern");else if(w==="grep")T.add("pattern");else if(w==="askuserquestion")T.add("questions");else if(w==="write")T.add("file_path");else if(w==="edit")T.add("edit");let z=!1;if(w==="askuserquestion"&&N){let O=Array.isArray(N.questions)?N.questions:[];if(O.length>0){let M={..._,fg:"white"},P={..._,fg:"white"},A={..._,fg:"blackBright"};for(let k=0;k<O.length;k++){let L=O[k];if(L?.question){if($.pushLine(`${T0}Q${k+1}: ${L.question}`,{...M,bold:!0}),Array.isArray(L.options))for(let v=0;v<L.options.length;v++){let C=L.options[v],b=C?.label??"",y=C?.description??"",c=`${v+1}. `;if($.pushLine(`${T0}${T0}${c}${b}`,P),y)$.pushLine(`${T0}${T0}${T0}${y}`,A)}}}}z=!0}else if(w==="edit"&&N){let O=typeof N.new_string==="string"?N.new_string:"",M=typeof N.old_string==="string"?N.old_string:"";rT({pushLine:$.pushLine,detailStyle:_},M,O),nT({pushLine:$.pushLine,detailStyle:R,width:$.width,maxLines:24},M,O),z=!0}else if(w==="todoplan"&&N)z=!0;let S=(O,M)=>{let P=typeof M==="string"?M:JSON.stringify(M);if(!P||!String(P).trim())return;let A=`${T0}${O}: ${String(P)}`;for(let k of O_(A,I))$.pushLine(`${k.text}`,R)};if(!z&&N&&Object.keys(N).length>0){for(let O of["command","description","pattern","query","file_path"]){if(T.has(O))continue;let M=N[O];if(M!=null)S(O,M);T.add(O)}for(let[O,M]of Object.entries(N)){if(T.has(O))continue;if(M==null)continue;S(O,M)}}}K0$($,J.call.id),N0$($,J.call.id)}},tool_output($,J){if($.selectedToolCallId!==J.toolCallId)return;if($.toolNameById.has(J.toolCallId))return;if(String(J.toolName??"").toLowerCase()==="bash")return;let _=String(J.output??"").replace(/\r/g,"");if(!_.trim())return;let G=S0($.theme,"tool_output",{dim:!0});$.pushLine("↳ output",G);let V=_.split(`
|
|
929
|
-
`),X=10,Z=$.expandedBashOutputs.has(J.toolCallId),Y=Z?Number.POSITIVE_INFINITY:X,K=Math.max(0,V.length-Y);for(let N of V.slice(K))$.pushLine(N,G);let F=V.length>X;if(F&&!Z){let N={...G,fg:"cyan"},q=V.length-X;$.pushLine(`... (${q} more lines)`,N,J0(J.toolCallId))}else if(F&&Z){let N={...G,fg:"cyan"};$.pushLine("... (collapse)",N,J0(J.toolCallId))}},tool_result($,J){if($.selectedToolCallId!==J.result.id)return;if($.toolNameById.has(J.result.id))return;let Q=$.toolNameById.get(J.result.id),_=Q&&String(Q).toLowerCase()==="bash",G=S0($.theme,"tool_result",{dim:!0});if(J.result.status!=="success")$.pushLine(`✗ ${J.result.status}`,G);if(_)return;if(String(Q).toLowerCase()==="askuserquestion"){let R=J.result.output;if(R&&R.trim()){try{let w;try{w=JSON.parse(R)}catch{if(typeof R==="object")w=R;else{let S=R.match(/\{[\s\S]*\}/);if(S)w=JSON.parse(S[0])}}let T={...G,fg:"cyan",bold:!0},z={...G,fg:"white"};if(w&&typeof w==="object"&&!Array.isArray(w)){let S=w.answers;if(S&&Object.keys(S).length>0){$.pushLine(" User responses:",T);let O=0;for(let[M,P]of Object.entries(S)){O++;let A=Array.isArray(P)?P.join(", "):String(P);$.pushLine(` Q${O}: ${A}`,z)}return}}else if(Array.isArray(w)){w.map((S)=>{let O=S.text.split(`
|
|
930
|
-
`).filter(Boolean),M=null;for(let P=O.length-1;P>0;P--){let k=O[P].match(/Answer:\s*(.*)/);if(k){M=k[1];let L={...G,fg:"cyan",bold:!0},v={...G,fg:"white"};$.pushLine(" User responses:",L),$.pushLine(` ${M}`,v);return}}});return}}catch(w){console.debug("Failed to parse AskUserQuestion output:",w)}let I=R.split(`
|
|
931
|
-
`);for(let w of I)if(w.trim())$.pushLine(` ${I0(w)}`,G)}return}let V=String($.toolNameById.get(J.result.id)??"").toLowerCase(),X=V&&V!=="read"?J.result.outputAnsi:void 0,Z=typeof X==="string"&&X.trim().length>0,Y=10,K=$.expandedBashOutputs.has(J.result.id),F=K?Number.POSITIVE_INFINITY:Y,N=eT(J.result.output),q=String(J.result.output??"").replace(/\r/g,"").split(`
|
|
932
|
-
`),H=N?.length??q.length,E=Math.min(H,F),D=Z?String(X??"").replace(/\r/g,"").split(`
|
|
933
|
-
`):null,B=" ",j=M$(B);if(N){for(let I of N.slice(0,E))$.pushLine(`${B}${I0(wU(I).text)}`,G);let R=N.length>Y;if(R&&!K){let I={...G,fg:"cyan"},w=N.length-Y;$.pushLine(` ... (${w} more lines)`,I,J0(J.result.id))}else if(R&&K){let I={...G,fg:"cyan"};$.pushLine(" ... (collapse)",I,J0(J.result.id))}return}for(let R=0;R<E;R++){let I=q[R]??"";if(Z&&D&&R<D.length){let w=sO(D[R]??"");if(w===""){$.pushLine(B,G);continue}let T=GU(w,{}),z=T.map((k)=>k.text).join(""),S=wU(z),O=I0(S.text),M=S.removedCells>0?sT(T,S.removedCells):T,P=$.contentIndent+j,A=[];for(let k of M){let L=I0(k.text),v=M$(L);if(v>0&&Object.keys(k.style??{}).length>0)A.push({x:P,w:v,text:L,style:k.style});P+=v}$.pushLineWithSegments(`${B}${O}`,G,A);continue}if(I===""){$.pushLine(B,G);continue}$.pushLine(`${B}${I0(wU(I).text)}`,G)}let f=H>Y;if(f&&!K){let R={...G,fg:"cyan"},I=H-Y;$.pushLine(` ... (${I} more lines)`,R,J0(J.result.id))}else if(f&&K){let R={...G,fg:"cyan"};$.pushLine(" ... (collapse)",R,J0(J.result.id))}},approve($,J){let U=J.request.status;if(U==="approved"&&$.toolResultById.has(J.request.toolCallId))return;let Q=U==="pending"?"!":U==="approved"?"✓":"✗",_=S0($.theme,"approve"),G={..._,dim:!0};if($.pushLine(`${Q} ${J.request.tool} — ${J.request.permission}`,U==="pending"?{..._,bold:!0}:G,U==="pending"?uT():xT()),U==="pending")$.pushLine(` ${J.request.reason}`,G)},todo($,J){let U=J.collapsed?"▸":"▾",Q=S0($.theme,"todo"),_={...Q,dim:!0};if($.pushLine(`${U} ${J.title}`,{...Q,bold:!0},lV($.messageId,J.type)),!J.collapsed)for(let G of J.items){let V=G.done?"☑":"☐";$.pushLine(` ${V} ${G.text}`,_,pO($.messageId,J.type,G.id))}},plan($,J){let U=J.collapsed?"▸":"▾",Q=S0($.theme,"plan"),_={...Q,dim:!0};if($.pushLine(`${U} ${J.title}`,{...Q,bold:!0},lV($.messageId,J.type)),!J.collapsed)for(let G of J.items){let V=G.done?"☑":"☐";$.pushLine(` ${V} ${G.text}`,_,pO($.messageId,J.type,G.id))}},llm_meta($,J){let U=S0($.theme,"assistant",{dim:!0}),Q=Math.max(0,Math.floor(J.durationMs)),_=Q<1e4?(Q/1000).toFixed(2):(Q/1000).toFixed(1),G=String(J.modelId??"").trim();$.pushLine(`⏱ ${_}s${G?` · ${G}`:""}`,U)}};function $v($){let J=(N)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let H=E$("node:fs"),E=new Date().toISOString().split("T")[1].slice(0,-1);H.appendFileSync("/tmp/goatchain-debug.log",`[${E}] [RENDER-ASSIST] ${N}
|
|
934
|
-
`)}}catch{}},U=Date.now();J(`START: parts=${$.message.parts.length}, width=${$.width}`);let Q=[],{pushLine:_,pushLineWithSegments:G,pushSpans:V}=oT(Q,$.contentIndent),X=new Map,Z=new Map,Y=new Map;for(let N of $.message.parts){if(N.type==="tool_result")X.set(N.result.id,N.result);if(N.type==="tool_output")Z.set(N.toolCallId,N.output);if(N.type==="tool_call")Y.set(N.call.id,N.call.name)}let K={messageId:$.message.id,width:$.width,contentIndent:$.contentIndent,selectedToolCallId:$.selectedToolCallId,expandedBashOutputs:$.expandedBashOutputs,toolResultById:X,toolOutputById:Z,toolNameById:Y,pushLine:_,pushLineWithSegments:G,pushSpans:V,theme:$.theme,parts:$.message.parts};J(`Starting to render ${$.message.parts.length} parts`);for(let N=0;N<$.message.parts.length;N++){let q=Date.now(),H=$.message.parts[N];J(` Part #${N}: type=${H.type}`);let E=F0$[H.type],D={...K,partIndex:N};J(` Part #${N}: calling renderer for type=${H.type}`),E(D,H);let B=Date.now()-q;J(` Part #${N}: done in ${B}ms, output lines=${Q.length}`)}let F=Date.now()-U;return J(`END: total ${F}ms, ${Q.length} lines`),Q}function W0$($){return Array.from($).sort().join(",")}function q0$($){let J=$?.preset??"goatchain",U=$?.overrides??{},Q=Object.keys(U).sort();if(Q.length===0)return String(J);let _=Q.map((G)=>{let V=U[G]??{};return`${G}:${String(V.fg??"")},${String(V.bg??"")}`});return`${J}|${_.join("|")}`}function rV($){if($.role==="user"){let U=String($.content??""),Q=$?.focusFiles?.length??0;return`u:${U.length}:${Q}`}if($.role==="assistant"){let U=$.parts??[],Q=`a:${U.length}`;for(let _ of U){let G=String(_?.type??"");if(G==="status")Q+=`|s:${String(_?.text??"").length}`;else if(G==="thinking")Q+=`|th:${String(_?.title??"").length}:${_?.collapsed?1:0}:${String(_?.content??"").length}`;else if(G==="markdown")Q+=`|m:${String(_?.markdown??"").length}`;else if(G==="tool_call"){let V=_?.call??{},X=V?.argumentsText,Z=typeof X==="string"?X.length:(()=>{try{return JSON.stringify(V?.arguments??{}).length}catch{return 0}})();Q+=`|tc:${String(V?.id??"")}:${Z}`}else if(G==="tool_output")Q+=`|to:${String(_?.toolCallId??"")}:${String(_?.toolName??"").length}:${String(_?.output??"").length}`;else if(G==="tool_result"){let V=_?.result??{};Q+=`|tr:${String(V?.id??"")}:${String(V?.status??"")}:${String(V?.output??"").length}:${String(V?.outputAnsi??"").length}`}else if(G==="approve"){let V=_?.request??{};Q+=`|ap:${String(V?.id??"")}:${String(V?.status??"")}`}else if(G==="todo"||G==="plan"){let V=_?.items??[],X=0;for(let Z of V)if(Z?.done)X++;Q+=`|${G}:${String(_?.title??"").length}:${_?.collapsed?1:0}:${V.length}:${X}`}else Q+=`|${G}`}return Q}let J=$?.result??{};return`t:${String(J?.id??"")}:${String(J?.status??"")}:${String(J?.output??"").length}`}function eO($,J,U,Q,_){let G=(Z)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let K=E$("fs"),F=new Date().toISOString().split("T")[1].slice(0,-1);K.appendFileSync("/tmp/goatchain-debug.log",`[${F}] [RENDER-BLOCK] ${Z}
|
|
935
|
-
`)}}catch{}},V=2;if(G(`START: role=${$.role}, width=${J}`),$.role==="user"){G("Rendering user message");let Z=tT({message:$,width:J,contentIndent:2,theme:_});return G(`User message: ${Z.length} lines`),{role:$.role,messageId:$.id,lines:Z}}if($.role==="tool")return G("Tool message: skipped"),null;G("Rendering assistant message");let X=$v({message:$,width:J,contentIndent:2,selectedToolCallId:U,expandedBashOutputs:Q,theme:_});return G(`Assistant message: ${X.length} lines`),{role:$.role,messageId:$.id,lines:X}}function $j($,J,U){let Q=(D)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let j=E$("fs"),f=new Date().toISOString().split("T")[1].slice(0,-1);j.appendFileSync("/tmp/goatchain-debug.log",`[${f}] [DECORATE] ${D}
|
|
936
|
-
`)}}catch{}};Q(`START: role=${$.role}, lines=${$.lines.length}, isFirst=${U}`);let _=Date.now(),G=[],V=k1(J,"assistant"),X=k1(J,"user"),Z=V.bg??"black",Y=X.bg??"blackBright",K=Z;if(!U)Q(" Adding spacer line"),G.push({text:"",style:{bg:K},segments:[],hasBackground:!1});let F=$.role==="user",q={fg:"blueBright",bg:F?Y:Z};if(F)Q(" Adding user top padding"),G.push({text:"┃",style:{bg:Y},segments:[{x:0,w:1,text:"┃",style:q}],hasBackground:!0,messageId:$.messageId});Q(` Processing ${$.lines.length} block lines`);let H=0;for(let D of $.lines){if(F){let B=[{x:0,w:1,text:"┃",style:q},...D.segments.map((j)=>({...j,x:j.x+1,style:{...j.style??{},bg:Y}}))];G.push({text:`┃${D.text}`,style:{...D.style,bg:Y},segments:B,action:D.action,hasBackground:!0,messageId:$.messageId})}else{let B=D.style?.bg??Z;G.push({text:D.text,style:{...D.style,bg:B},segments:D.segments.map((j)=>({...j,style:{...j.style??{},bg:B}})),action:D.action,hasBackground:!1,messageId:$.messageId})}if(H++,H%100===0)Q(` Processed ${H}/${$.lines.length} lines`)}if(F)Q(" Adding user bottom padding"),G.push({text:"┃",style:{bg:Y},segments:[{x:0,w:1,text:"┃",style:q}],hasBackground:!0,messageId:$.messageId});let E=Date.now()-_;return Q(`END: ${G.length} output lines in ${E}ms`),G}function Jv(){let $=-1,J=null,U="",Q="",_=-1,G=[],V=new Map,X=[],Z=new Map,Y=[],K=new Map,F=new Map;function N(){X=G.slice(),Z=new Map(V)}function q(D,B){for(let j=0;j<D.length;j++){let f=D[j]?.action;if(f?.type==="selectToolCall")V.set(f.callId,B+j)}}function H(D){G=[],V=new Map,Y.length=0,K.clear(),F.clear();let B=Math.max(0,D.width),j=0;for(let f of D.messages){let R=eO(f,B,D.selectedToolCallId,D.expandedBashOutputs,D.theme);if(!R)continue;let I=rV(f),w=$j(R,D.theme,j===0);j++;let T=G.length;G.push(...w);let z=G.length;Y.push(R.messageId),K.set(R.messageId,{start:T,end:z}),F.set(R.messageId,I),q(w,T)}}function E(D,B,j,f){let R=B.id,I=K.get(R);if(!I)return;let{start:w,end:T}=I,z=T-w,S=eO(B,f.width,f.selectedToolCallId,f.expandedBashOutputs,f.theme);if(!S)return;let O=$j(S,f.theme,D===0);G.splice(w,z,...O);let M=O.length-z,P=w+O.length;if(K.set(R,{start:w,end:P}),F.set(R,j),M!==0)for(let k=D+1;k<Y.length;k++){let L=Y[k],v=K.get(L);if(!v)continue;K.set(L,{start:v.start+M,end:v.end+M})}let A=new Map;for(let[k,L]of V.entries()){if(L<w){A.set(k,L);continue}if(L>=T){A.set(k,L+M);continue}}V=A,q(O,w)}return(D)=>{let B=Math.max(0,D.width),j=D.selectedToolCallId??null,f=W0$(D.expandedBashOutputs),R=q0$(D.theme),I=!1;try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let M=E$("fs"),P=new Date().toISOString().split("T")[1].slice(0,-1);M.appendFileSync("/tmp/goatchain-debug.log",`[${P}] [LAYOUT-MODEL] buildChatLayoutModel START: messages=${D.messages.length}
|
|
937
|
-
`)}}catch{}if(B!==$||j!==J||f!==U||R!==Q)return H(D),$=B,J=j,U=f,Q=R,I=!0,N(),{lines:X,toolLineById:Z};let T=[];for(let O of D.messages){if(O.role==="tool")continue;T.push(O)}if(T.length<Y.length)return H(D),I=!0,N(),{lines:X,toolLineById:Z};for(let O=0;O<Y.length;O++)if(T[O]?.id!==Y[O])return H(D),I=!0,N(),{lines:X,toolLineById:Z};for(let O=Y.length;O<T.length;O++){let M=T[O],P=eO(M,B,j,D.expandedBashOutputs,D.theme);if(!P)continue;let A=rV(M),k=$j(P,D.theme,O===0),L=G.length;G.push(...k);let v=G.length;Y.push(P.messageId),K.set(P.messageId,{start:L,end:v}),F.set(P.messageId,A),q(k,L),I=!0}if(typeof D.dirtySeq==="number"&&D.dirtySeq!==_){_=D.dirtySeq;let O=String(D.dirtyMessageId??"").trim();if(O){let M=Y.indexOf(O),P=M>=0?T[M]:null;if(P){let A=rV(P),k=F.get(O);if(A!==k)E(M,P,A,{width:B,selectedToolCallId:j,expandedBashOutputs:D.expandedBashOutputs,theme:D.theme}),I=!0}}}let z=5,S=Math.max(0,T.length-z);for(let O=S;O<T.length;O++){let M=T[O],P=M.id,A=rV(M),k=F.get(P);if(A!==k)E(O,M,A,{width:B,selectedToolCallId:j,expandedBashOutputs:D.expandedBashOutputs,theme:D.theme}),I=!0}if(I)N();try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let M=E$("fs"),P=new Date().toISOString().split("T")[1].slice(0,-1);M.appendFileSync("/tmp/goatchain-debug.log",`[${P}] [LAYOUT-MODEL] buildChatLayoutModel END: changed=${I}, lines=${X.length}
|
|
938
|
-
`)}}catch{}return{lines:X,toolLineById:Z}}}import{defineComponent as H0$,h as d0,inject as B0$,onMounted as O0$,ref as j0$}from"vue";var H0=Symbol("GoatChainChatPageContext");var nV={fg:"whiteBright",bg:"black"},j_={fg:"white",dim:!0,bg:"blackBright"},Uv={fg:"whiteBright",bg:"blackBright"},_v={fg:"whiteBright",bg:"blackBright"},NJ={fg:"white",dim:!0,bg:"black"};async function D0$($){if(!$||$.includes("\x00"))return;try{let{spawn:J}=await import("node:child_process"),U=globalThis.process,Q=String(U?.platform||"");J(Q==="darwin"?"open":Q==="win32"?"explorer.exe":"xdg-open",[$],{shell:!1,detached:!0,stdio:"ignore"}).unref()}catch{}}var Qv=H0$({name:"GoatChainChatBottomPanel",setup(){let $=B0$(H0);if(!$)throw Error("GoatChainChatBottomPanel missing ChatPageContext");let J=$,{events:U,scheduler:Q}=L4(),_=j0$(!1);function G(){_.value=!1;let V=U.value;if(!V||typeof V.debugNodes!=="function"||typeof V.focus!=="function")return;let X=Math.floor(J.inputX.value),Z=Math.floor(J.panelTopY.value),Y=Math.floor(J.inputInnerW.value),K=Math.floor(J.inputLines.value),F=(V.debugNodes?.()??[]).filter((B)=>B?.visible&&B?.focusable),N=F.find((B)=>{let j=B?.rect;return j&&j.x===X&&j.y===Z&&j.w===Y&&j.h===K});if(N?.id){V.focus(N.id),_.value=!0,Q.invalidate();return}let q=X+Math.floor(Math.max(0,Y-1)/2),H=Z+Math.floor(Math.max(0,K-1)/2),E=F.filter((B)=>{let j=B?.rect;return j&&q>=j.x&&H>=j.y&&q<j.x+j.w&&H<j.y+j.h});E.sort((B,j)=>{let f=B?.zIndex??0,R=j?.zIndex??0;if(R!==f)return R-f;let I=B?.rect??{w:0,h:0},w=j?.rect??{w:0,h:0};return I.w*I.h-w.w*w.h});let D=E[0];if(D?.id)V.focus(D.id),_.value=!0,Q.invalidate()}return O0$(()=>{setTimeout(()=>{G()})}),()=>{let V=J.panelW.value-2,X=J.panelH.value,Z=`╭${"─".repeat(Math.max(0,V))}╮`,Y=`╰${"─".repeat(Math.max(0,V))}╯`,K=Array.from({length:X},()=>"│").join(`
|
|
939
|
-
`),F=Array.from({length:X},()=>"│").join(`
|
|
940
|
-
`),N=[d0(t,{key:"panel-top-border",x:J.panelX.value,y:J.panelTopY.value-1,w:J.panelW.value,value:Z,style:j_,zIndex:-20}),d0(t,{key:"panel-fill",x:J.panelX.value+1,y:J.panelTopY.value,w:Math.max(0,J.panelW.value-2),h:J.panelH.value,value:"",style:Uv,zIndex:-20}),d0(t,{key:"panel-left-border",x:J.panelX.value,y:J.panelTopY.value,w:1,h:X,value:K,style:j_,zIndex:-19}),d0(t,{key:"panel-right-border",x:J.panelX.value+J.panelW.value-1,y:J.panelTopY.value,w:1,h:X,value:F,style:j_,zIndex:-19}),d0(t,{key:"panel-bottom-border",x:J.panelX.value,y:J.panelTopY.value+J.panelH.value,w:J.panelW.value,value:Y,style:j_,zIndex:-20}),d0(R4,{key:"panel-hit",x:J.panelX.value,y:J.panelTopY.value-1,w:J.panelW.value,h:J.panelH.value+2,zIndex:10,focusable:!1,onPointerdownCapture:()=>{J.focusMode.value="input",J.focusBrowserTextarea(),G(),Q.invalidate()}}),d0(J6,{key:"chat-input",x:J.inputX.value,y:J.panelTopY.value,w:J.inputInnerW.value,h:J.inputLines.value,modelValue:J.input.value,"onUpdate:modelValue":(z)=>J.input.value=z,cursorToEndOnExternalUpdate:!0,autoFocus:J.focusMode.value==="input"&&!_.value&&!J.showCommands.value&&!J.showTheme.value&&!J.showSessions.value&&!J.showMessageActions.value&&!J.showRedoConfirm.value&&!J.showConfig.value&&!J.showToolApprovals.value&&!J.showApproval.value&&!J.showAskUser.value&&!J.showPathPicker.value&&!J.showExitConfirm.value,cursorShape:"bar",cursorBlink:!1,placeholder:"Ask anything... (newline: Shift+Enter or Ctrl+J)",placeholderWhenFocused:!0,style:_v,plugins:[DU()],promptSuggestions:J.promptSuggestions,mentionWorkspace:J.nodeLike?J.pickerWorkspace.value:"",mentionMode:"any",collectMentions:!0,mentions:J.focusFiles.value,"onUpdate:mentions":(z)=>J.focusFiles.value=[...z],onMentionClick:(z,S)=>{if(!J.nodeLike)return;if(S?.metaKey||S?.ctrlKey)D0$(z)},onChange:(z)=>J.send(z),onKeydown:J.onInputKeydown,onFocus:()=>{_.value=!0,J.focusMode.value="input"},onBlur:()=>_.value=!1,zIndex:11})],q=J.panelTopY.value+J.inputLines.value+J.modelRowGap.value,H=J.ctxPctChip.value,E=J.modelInfo.value.build,D=J.modelInfo.value.label,B=M$(H),j=M$(E),f=M$(D),R=2,I=B+2+j+1+f,w=J.inputX.value+Math.max(0,J.inputInnerW.value-I),T=Math.max(0,w-J.inputX.value-1);if(T>0){let z=J.modeLabel.value,S=` ${z.toUpperCase()} `,O=z==="plan"?"magentaBright":"greenBright",M=Math.min(T,M$(S));N.push(d0(t,{key:"panel-mode",x:J.inputX.value,y:q,w:M,value:S,style:{fg:"black",bg:O,bold:!0},zIndex:-18}));let P=J.inputX.value+M+1,A=Math.max(0,T-M-1);if(J.assistantStatusDisplay.value&&A>0)N.push(d0(t,{key:"panel-status",x:P,y:q,w:A,value:J.assistantStatusDisplay.value,style:J.assistantStatusStyle.value,zIndex:-18}))}return N.push(d0(t,{key:"ctx-pct",x:w,y:q,value:H,style:{fg:"white",dim:!0,bg:"blackBright"},zIndex:-18})),N.push(d0(t,{key:"model-chip",x:w+B+2,y:q,value:E,style:{fg:"blueBright",bold:!0,bg:"blackBright"},zIndex:-18})),N.push(d0(t,{key:"model-label",x:w+B+2+j+1,y:q,w:Math.max(0,J.inputX.value+J.inputInnerW.value-(w+B+2+j+1)),value:D,style:{fg:"white",dim:!0,bg:"blackBright"},zIndex:-18})),N}}});import{defineComponent as E0$,h as fU,inject as P0$}from"vue";var Gv=E0$({name:"GoatChainChatFooter",setup(){let $=P0$(H0);if(!$)throw Error("GoatChainChatFooter missing ChatPageContext");let J=$;return()=>{let U=Math.max(0,J.rows.value-J.footerH),Q="drag to select",_=J.isLoading.value?[fU(t,{key:"footer-dots",x:2,y:U,value:J.loadingDots.value,style:{fg:"whiteBright",bg:"black"},zIndex:21}),fU(t,{key:"footer-esc",x:2+J.loadingDots.value.length+2,y:U,value:"esc",style:{fg:"blackBright",bg:"black"},zIndex:21}),fU(t,{key:"footer-interrupt",x:2+J.loadingDots.value.length+2+4,y:U,value:"interrupt",style:{fg:"white",dim:!0,bg:"black"},zIndex:21})]:[fU(t,{key:"footer-left-hint",x:2,y:U,value:"drag to select",style:NJ,zIndex:21})];return[J.rows.value>0?fU(t,{key:"footer-bg",x:0,y:U,w:J.cols.value,value:"",style:nV,zIndex:20}):null,..._,fU(t,{key:"footer-right",x:Math.max(0,J.contentW.value-2-M$(J.footerRight.value)),y:U,value:J.footerRight.value,style:NJ,zIndex:21})]}}});import{defineComponent as M0$,h as D_,inject as L0$}from"vue";function pV($,J){J=Math.max(0,Math.floor(J));let U=String($??"").replace(/\s+/g," ").trim();if(!U||J<=0)return"";if(M$(U)<=J)return U;if(J<=1)return m4(U,J);return`${m4(U,J-1)}…`}var Vv=M0$({name:"GoatChainChatHeader",setup(){let $=L0$(H0);if(!$)throw Error("GoatChainChatHeader missing ChatPageContext");let J=$;return()=>{let U=J.headerStatsDisplay.value,Q=M$(U),_=Math.max(0,J.contentW.value-2-Q),G=J.store.state.context?.env??{},V=String(G.GOATCHAIN_VERSION||G.VUE_TERMINAL_VERSION||"").trim(),X=String(J.pickerWorkspace.value??"").trim(),Z=[V?`v${V}`:"",X].filter(Boolean).join(" · "),Y=Math.max(0,J.contentW.value-4),K=12,F=2,N=Z?Math.max(0,Y-12-2):0,q=Z?pV(Z,N):"",H=q?M$(q):0,E=q?Math.max(0,J.contentW.value-2-H):0,D=2,B=H?Math.max(0,Y-H-2):Y,j=pV(J.sessionHeaderTitle.value,B),f=2,R=2,I=Math.max(0,_-2-2),w=[D_(t,{key:"page-title",x:2,y:0,w:Y,value:"GoatChain",style:NJ}),D_(t,{key:"session-title",x:2,y:1,w:B,value:j,style:{fg:"blueBright",bold:!0,bg:"black"}})];if(q)w.push(D_(t,{key:"header-meta",x:E,y:1,value:q,style:NJ}));if(w.push(D_(t,{key:"header-stats",x:_,y:2,value:U,style:NJ})),I>0)w.push(D_(t,{key:"header-summary",x:2,y:2,w:I,value:pV(J.sessionHeaderSummary.value,I),style:NJ}));return w}}});import{computed as z0$,defineComponent as _j,h as Z2,inject as R0$}from"vue";var Jj=null;try{Jj=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null}catch{Jj=null}function Xv($,J){if(!$)return;let U=0,Q=Jj;if(!Q){for(let _ of $){let G=_.length>0?u4(_):0,V=J(_,U,U+G);if(U+=G,V===!1)return}return}for(let _ of Q.segment($)){let G=_.segment,V=u4(G),X=J(G,U,U+V);if(U+=V,X===!1)return}}function Uj($,J,U){if(J=Math.max(0,Math.floor(J)),U=Math.max(0,Math.floor(U)),U<=J)return{startCol:J,endCol:U};let Q=J,_=U;return Xv($,(G,V,X)=>{if(J>V&&J<X)Q=V;if(U>V&&U<X)_=X;if(V>U&&V>J)return!1;return}),{startCol:Q,endCol:_}}function E_($,J,U){if(J=Math.max(0,Math.floor(J)),U=Math.max(0,Math.floor(U)),U<=J)return"";let Q=Uj($,J,U),_=Q.startCol,G=Q.endCol;if(G<=_)return"";let V="";return Xv($,(X,Z,Y)=>{if(Y<=_)return;if(Z>=G)return!1;V+=X;return}),V}function Yv($,J,U){if(!J||!U)return"";let Q=Math.min(J.row,U.row),_=Math.max(J.row,U.row),G=J.row<U.row?J.col:J.row>U.row?U.col:Math.min(J.col,U.col),V=J.row<U.row?U.col:J.row>U.row?J.col:Math.max(J.col,U.col),X=[];for(let Z=Q;Z<=_&&Z<$.length;Z++){let Y=$[Z]?.text??"";if(Q===_)X.push(E_(Y,G,V));else if(Z===Q)X.push(E_(Y,G,Number.MAX_SAFE_INTEGER));else if(Z===_)X.push(E_(Y,0,V));else X.push(Y)}return X.join(`
|
|
941
|
-
`).trim()}function A0$($,J){if(!Boolean($&&J&&($.row!==J.row||$.col!==J.col)))return{active:!1,startRow:-1,endRow:-1,startCol:0,endCol:0};let Q=Math.min($.row,J.row),_=Math.max($.row,J.row),G=$.row<J.row?$.col:$.row>J.row?J.col:Math.min($.col,J.col),V=$.row<J.row?J.col:$.row>J.row?$.col:Math.max($.col,J.col);return{active:!0,startRow:Q,endRow:_,startCol:G,endCol:V}}var Zv=_j({name:"GoatChainChatMessages",setup(){let $=R0$(H0);if(!$)throw Error("GoatChainChatMessages missing ChatPageContext");let J=$,U=z0$(()=>A0$(J.messageSelectStart.value,J.messageSelectEnd.value)),Q=new Map,_=new WeakMap;function G(Y,K){if(!Y){let H=Q.get(K);if(H)return H;let E={bg:K};return Q.set(K,E),E}if(Y.bg===K)return Y;let F=_.get(Y);if(!F)F=new Map,_.set(Y,F);let N=F.get(K);if(N)return N;let q={...Y,bg:K};return F.set(K,q),q}function V(Y,K){let F=Math.max(0,J.mainW.value-4),N=J.scrollTop.value+K,q=Y.style?.bg??(Y.hasBackground?"blackBright":"black"),E=Boolean(Y.hasBackground&&Y.messageId&&J.hoveredUserMessageId.value===Y.messageId)?"black":q,D=U.value,B=D.active&&N>=D.startRow&&N<=D.endRow,j=0,f=0;if(B)if(D.startRow===D.endRow)j=D.startCol,f=D.endCol;else if(N===D.startRow)j=D.startCol,f=F;else if(N===D.endRow)j=0,f=D.endCol;else j=0,f=F;let R=Y.segments.length,I=B&&f>j,w=Boolean(Y.action),T=(I?1:0)+(w?1:0),z=[Z2(t,{key:`r${K}_bg`,x:0,y:K,w:F,value:I4(F),style:{bg:E},zIndex:0}),Z2(t,{key:`r${K}_base`,x:0,y:K,w:F,value:Y.text,style:G(Y.style,E),zIndex:1})];z.length=2+R*2+T;let S=2;for(let O=0;O<R;O++){let M=Y.segments[O];if(z[S++]=Z2(t,{key:`r${K}_s${M.x}`,x:M.x,y:K,w:Math.max(0,Math.min(F-M.x,M.w)),value:M.text,style:G(M.style,E),zIndex:2}),M.action?.type==="openFile")z[S++]=Z2(R4,{key:`r${K}_s${M.x}_hit`,x:M.x,y:K,w:Math.max(0,Math.min(F-M.x,M.w)),h:1,zIndex:11,focusable:!1,onClick:async(P)=>{if(!J.nodeLike)return;let A=M.action.absPath;if(P?.metaKey||P?.ctrlKey)try{if(!A||A.includes("\x00"))return;let{spawn:k}=await import("node:child_process"),L=globalThis.process,v=String(L?.platform||"");k(v==="darwin"?"open":v==="win32"?"explorer.exe":"xdg-open",[A],{shell:!1,detached:!0,stdio:"ignore"}).unref()}catch{}}})}if(I){let O=Uj(Y.text,j,f),M=Math.max(0,Math.min(F,O.startCol)),P=Math.max(0,Math.min(F,O.endCol)),A=Math.min(P-M,F-M);if(A>0){let k=h6(E_(Y.text,M,M+A),A);z[S++]=Z2(t,{key:`r${K}_sel`,x:M,y:K,w:A,value:k,style:{fg:"whiteBright",bg:"blueBright"},zIndex:3})}}if(!w)return z.length=S,z;return z[S++]=Z2(R4,{key:`r${K}_hit`,x:0,y:K,w:F,h:1,zIndex:10,focusable:!0,onFocusCapture:()=>J.focusMode.value="messages",onKeydown:J.onSelectionKeydown,onClick:()=>J.onLineClick(Y.action)}),z.length=S,z}let X=_j({name:"GoatChainUserMessageBlock",props:{startRow:{type:Number,required:!0},lines:{type:Array,required:!0}},setup(Y){return()=>{let K=[];for(let F=0;F<Y.lines.length;F++){let N=V(Y.lines[F],Y.startRow+F);for(let q=0;q<N.length;q++)K.push(N[q])}return K}}}),Z=_j({name:"GoatChainAssistantMessageBlock",props:{startRow:{type:Number,required:!0},lines:{type:Array,required:!0}},setup(Y){return()=>{let K=[];for(let F=0;F<Y.lines.length;F++){let N=V(Y.lines[F],Y.startRow+F);for(let q=0;q<N.length;q++)K.push(N[q])}return K}}});return()=>Z2(R4,{x:2,y:J.mainY,w:Math.max(0,J.mainW.value-4),h:J.mainH.value,zIndex:1,selectable:!0,focusable:!0,onFocusCapture:()=>J.focusMode.value="messages",onWheel:J.onWheel,onKeydown:J.onSelectionKeydown,onClickCapture:J.onMessageClick,onPointerdownCapture:J.onMessagePointerDown,onPointermoveCapture:J.onMessagePointerMove,onPointerupCapture:J.onMessagePointerUp,onContextmenuCapture:J.onMessageContextMenu},()=>{let Y=J.messageRoleById.value,K=J.visibleLines.value,F=K.length,N=Math.max(1,Math.floor(F/5)),q=[];q.length=N;let H=0;for(let B=0;B<F;B++){let j=K[B],f=String(j?.messageId??"").trim();if(!f){q[H++]={kind:"spacer",startRow:B,lines:[j]};continue}let R=Y.get(f)==="user"?"user":"assistant",I=q[H-1];if(I&&I.kind!=="spacer"&&I.messageId===f){I.lines.push(j);continue}q[H++]={kind:R,messageId:f,startRow:B,lines:[j]}}q.length=H;let E=[];E.length=H;let D=0;for(let B=0;B<H;B++){let j=q[B];if(j.kind==="spacer")E[D++]=V(j.lines[0],j.startRow)[0];else if(j.kind==="user")E[D++]=Z2(X,{key:`u_${j.startRow}`,startRow:j.startRow,lines:j.lines});else E[D++]=Z2(Z,{key:`a_${j.startRow}`,startRow:j.startRow,lines:j.lines})}return E.length=D,E})}});import{defineComponent as W1$,inject as q1$}from"vue";import{h as jv}from"vue";import{defineComponent as w0$,h as I1,ref as Nv,watch as f0$}from"vue";function Kv($){return Math.max(1,Math.ceil($.length/4))}function kU($){try{return JSON.stringify($)}catch{return'"[unserializable]"'}}function G1($){return $.replace(/\r/g,"").trimEnd()}function IU($,J,U){return Math.max(J,Math.min(U,$))}function Fv($){let J=G1($),U=J.search(/\s(?:Args|Command|Description):\s/i);if(U<=0)return J;return J.slice(0,U).trimEnd()}function k0$($){let Q=Math.max(0,Math.floor($)),_=(V,X,Z)=>{return[V,X,Z].map((F)=>M$(`[ ${F} ]`)).reduce((F,N)=>F+N,0)+2*Math.max(0,2)},G=[{approve:"Approve",always:"Always approve",deny:"Deny"},{approve:"Approve",always:"Always",deny:"Deny"},{approve:"OK",always:"Always",deny:"No"},{approve:"Y",always:"All",deny:"N"}];for(let V of G)if(_(V.approve,V.always,V.deny)<=Q)return V;return G[G.length-1]}function Wv($){if(!$)return null;let J=$.arguments,U=typeof J?.command==="string"?J.command:void 0,Q=typeof J?.description==="string"?J.description:void 0;if(!U&&!Q)return null;return{command:U,description:Q}}function qv($){if(!$||typeof $!=="object"||Array.isArray($))return null;let J=$,U=typeof J.command==="string"?J.command:void 0,Q=typeof J.description==="string"?J.description:void 0;if(!U&&!Q)return null;return{command:U,description:Q}}var Hv=w0$({name:"GoatChainApprovalDialog",props:{modelValue:{type:Boolean,required:!0},request:{type:Object,required:!0},call:{type:Object,required:!1,default:null},w:{type:Number,required:!0},h:{type:Number,required:!0}},emits:{"update:modelValue":($)=>!0,approve:()=>!0,alwaysApprove:()=>!0,deny:()=>!0},setup($,{emit:J}){let Q=Nv(0),_=Nv(null);return f0$([()=>$.modelValue,()=>$.request.id],([G,V])=>{if(!G)return;if(_.value!==V)Q.value=0;_.value=V},{immediate:!0}),()=>{if(!$.modelValue)return null;let G=Math.max(0,$.w-4),V=k0$(G),X=()=>{let Z=$.request,Y=Z.args,K=Wv($.call)??qv(Y),F=Math.max(0,$.w-4),N=Math.max(0,$.h-4),q=1,H=Math.max(0,N-1),E=2;if(H-E>=4)E+=1;let D=Fv(Z.reason),B=K0(D,Math.max(1,F)),j=Math.max(0,H-E),f=K?(K.description?2:0)+(K.command?4:0):0,R=(j>=2?1:0)+(j>=2+f?f:0),I=IU(Math.max(1,j-R),1,Math.max(1,j)),w=Math.max(0,B.length-I);return{reasonH:I,maxOffset:w}};return I1(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(Z)=>J("update:modelValue",Z),onKeydownCapture:(Z)=>{if(Z?.key==="Enter")Z.__goatchainApprovalDialogHandled=!0;if(typeof Z?.key==="string"&&Z.key.length===1&&!Z.ctrlKey&&!Z.metaKey&&!Z.altKey)Z.preventDefault?.(),Z.stopPropagation?.()},onKeydown:(Z)=>{let{reasonH:Y,maxOffset:K}=X();if(K<=0)return;let F=Q.value,N=F;if(Z?.key==="ArrowUp")N=F-1;else if(Z?.key==="ArrowDown")N=F+1;else if(Z?.key==="PageUp")N=F-Math.max(1,Y);else if(Z?.key==="PageDown")N=F+Math.max(1,Y);else if(Z?.key==="Home")N=0;else if(Z?.key==="End")N=K;else return;Z.preventDefault?.(),Z.stopPropagation?.(),Q.value=IU(N,0,K)},w:$.w,h:$.h,title:"Approve Tool Permission",placement:"center",backdrop:!1,padding:1,style:{fg:"yellowBright",bg:"black"},closeOnConfirm:!1,buttons:[{label:V.approve,value:"approve",kind:"primary",default:!0},{label:V.always,value:"alwaysApprove",kind:"danger"},{label:V.deny,value:"deny"}],onConfirm:(Z)=>{if(Z?.value==="approve")J("approve");else if(Z?.value==="alwaysApprove")J("alwaysApprove");else if(Z?.value==="deny")J("deny")},onClose:()=>J("update:modelValue",!1)},()=>{let Z=$.request,Y=Z.args,K=Wv($.call)??qv(Y),F=Math.max(0,$.w-4),N=Math.max(0,$.h-4),q=1,H=Math.max(0,N-1),E=[I1(t,{x:0,y:0,w:F,h:N,value:"",style:{bg:"black"}}),I1(t,{x:0,y:0,w:F,value:`Tool: ${Z.tool}`,style:{fg:"whiteBright",bold:!0,bg:"black"}}),I1(t,{x:0,y:1,w:F,value:`Permission: ${Z.permission}`,style:{fg:"cyanBright",bg:"black"}})],D=2;if(H-D>=4)D+=1;if(D<H){let B=Math.max(1,H-D),j=Fv(Z.reason),f=K0(j,Math.max(1,F)),R=Math.max(0,H-D),I=K?(K.description?2:0)+(K.command?4:0):0,w=(R>=2?1:0)+(R>=2+I?I:0),T=IU(Math.max(1,R-w),1,B),z=Math.max(0,f.length-T),S=IU(Q.value,0,z),O=f.slice(S,S+T).join(`
|
|
942
|
-
`);if(E.push(I1(t,{x:0,y:D,w:F,h:T,value:O,style:{fg:"white",dim:!0,bg:"black"}})),F>0&&T>0){if(S>0)E.push(I1(t,{x:F-1,y:D,w:1,value:"↑",style:{fg:"whiteBright",dim:!0,bg:"black"}}));if(S+T<f.length)E.push(I1(t,{x:F-1,y:D+T-1,w:1,value:"↓",style:{fg:"whiteBright",dim:!0,bg:"black"}}))}D+=T}if(K&&D<H){if(K.description&&D<H){let B=Math.max(1,H-D),j=IU(2,1,B);E.push(I1(t,{x:0,y:D,w:F,h:j,wrap:!0,value:`Description: ${G1(K.description)}`,style:{fg:"white",dim:!0,bg:"black"}})),D+=j}if(K.command&&D<H){if(E.push(I1(t,{x:0,y:D,w:F,value:"Command:",style:{fg:"yellowBright",bg:"blackBright",bold:!0}})),D+=1,D<H){let B=Math.max(1,H-D),j=IU(3,1,B);E.push(I1(t,{x:0,y:D,w:F,h:j,wrap:!0,value:G1(K.command),style:{fg:"whiteBright",bg:"blackBright"}})),D+=j}}}return E})}}});import{computed as I0$,defineComponent as S0$,h as v0,ref as M8,watch as Bv}from"vue";function L8($,J,U){return Math.max(J,Math.min(U,$))}var Ov=S0$({name:"GoatChainAskUserDialog",props:{modelValue:{type:Boolean,required:!0},toolCallId:{type:String,required:!0},questions:{type:Array,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0}},emits:{"update:modelValue":($)=>!0,submit:($)=>!0,cancel:()=>!0},setup($,{emit:J}){let U=M8(0),Q=M8(0),_=M8({}),G=M8({}),V=M8({}),X=M8({}),Z=M8({});Bv(()=>[$.toolCallId,$.questions.length],()=>{U.value=0,Q.value=0;let N={},q={},H={},E={},D={};for(let B=0;B<$.questions.length;B++){let j=String(B);N[j]=0,q[j]=[],H[j]="",E[j]=0,D[j]="select"}_.value=N,G.value=q,V.value=H,X.value=E,Z.value=D},{immediate:!0});let Y=I0$(()=>{let N={};for(let q=0;q<$.questions.length;q++){let H=String(q),E=$.questions[q],j=[...(E.options||[]).map((f)=>f.label),"Other"];if(E.multiSelect){let f=G.value[H]??[],R=f.map((z)=>j[z]).filter((z)=>Boolean(z)&&z!=="Other"),I=V.value[H]?.trim(),w=j.length-1;if(f.includes(w)&&I)R.push(I);N[H]=R.length>0?R:[]}else{let f=_.value[H]??0,R=j[f]??"";if(R==="Other")N[H]=V.value[H]||"";else N[H]=R}}return N});function K(){J("submit",{...Y.value}),J("update:modelValue",!1)}function F(){J("cancel"),J("update:modelValue",!1)}return Bv(()=>$.modelValue,(N,q)=>{if(!N||q)return;Q.value=1},{immediate:!0}),()=>{if(!$.modelValue)return null;let N=Math.max(0,$.w-4),q=Math.max(0,$.h-5),H={fg:"whiteBright",bg:"black"},E={fg:"whiteBright",bold:!0},D={fg:"white",dim:!0},B=L8(U.value,0,Math.max(0,$.questions.length-1)),j=$.questions[B],f=j?.multiSelect??!1,R=String(B);if(!j)return v0(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(L)=>J("update:modelValue",L),w:$.w,h:$.h,title:"No Questions",placement:"center",padding:1,style:{fg:"cyanBright",bg:"black"},buttons:[{label:"Close",value:"close",kind:"primary",default:!0}],onConfirm:()=>F(),onClose:()=>F()},()=>[v0(t,{x:0,y:0,w:N,value:"No questions to answer.",style:D})]);let I=j.options||[],w=I.map((L)=>({label:L.label,detail:L.description}));w.push({label:"Other",detail:"Provide a custom answer"});let z=[...I.map((L)=>L.label),"Other"],S=z.length-1,O=f?(G.value[R]??[]).includes(S):(_.value[R]??0)===S,M=B>=$.questions.length-1,P=B<=0,A=[{label:"Prev",value:"prev"},M?{label:"Submit",value:"submit",kind:"primary",default:!0}:{label:"Next",value:"next",kind:"primary",default:!0},{label:"Cancel",value:"cancel"}],k=(L)=>{if(L==="submit")K();else if(L==="next")U.value=Math.min(U.value+1,$.questions.length-1);else if(L==="prev"){if(!P)U.value=Math.max(U.value-1,0)}else F()};return v0(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(L)=>J("update:modelValue",L),onKeydownCapture:(L)=>{if(L?.key==="Enter"&&O){let v=(V.value[R]??"").trim(),C=Number(L?.target?.rect?.h??0);if(!v&&C>1){L.preventDefault?.(),L.stopPropagation?.(),Z.value={...Z.value,[R]:"input"};let b=X.value[R]??0;X.value={...X.value,[R]:b+1};return}}if(L?.key==="Escape")L.preventDefault?.(),L.stopPropagation?.(),F()},w:$.w,h:$.h,title:`Question ${B+1}/${$.questions.length}: ${j.header||"Question"}`,placement:"center",backdrop:!1,padding:1,style:{fg:"cyanBright",bg:"black"},buttons:A,closeOnConfirm:!1,onKeydown:(L)=>{if(f&&L?.key==="Enter"&&L.defaultPrevented){L.preventDefault?.(),L.stopPropagation?.();let v=L8(Q.value,0,Math.max(0,A.length-1)),C=A[v];k(String(C?.value??""))}if((L?.key==="ArrowLeft"||L?.key==="ArrowRight")&&!L.defaultPrevented){let v=L.key==="ArrowLeft"?-1:1;Q.value=L8(Q.value+v,0,Math.max(0,A.length-1))}},onConfirm:(L)=>{if(typeof L?.index==="number")Q.value=L8(L.index,0,Math.max(0,A.length-1));k(String(L?.value??""))},onClose:()=>F()},()=>{let L=0,v=[];if(O&&Z.value[R]==="buttons"){let C=Math.max(0,N-1),b=Math.max(0,q-1);v.push(v0(R4,{x:C,y:b,w:1,h:1,zIndex:-1,focusable:!0,autoFocus:!0,onKeydown:(y)=>{if(y?.key==="ArrowDown"){y.preventDefault?.(),y.stopPropagation?.();return}if(y?.key!=="ArrowUp")return;y.preventDefault?.(),y.stopPropagation?.(),Z.value={...Z.value,[R]:"input"}}}))}if(v.push(v0(t,{x:0,y:L++,w:N,wrap:!0,value:j.question||"",style:E})),L++,f){v.push(v0(t,{x:0,y:L++,w:N,value:"[Multi-select] Space to toggle, Enter to confirm",style:{fg:"yellow"}})),L++;let C=G.value[R]??[],b=Math.min(z.length,Math.max(3,q-L-2));if(b>0&&L<q-2){if(v.push(v0(q0,{x:0,y:L,w:N,h:b,multiple:!0,options:w,modelValue:C,"onUpdate:modelValue":(y)=>{if(!Array.isArray(y))return;G.value={...G.value,[R]:y};let x=y.includes(S);Z.value={...Z.value,[R]:x?"input":"select"}},onFocus:()=>{Z.value={...Z.value,[R]:"select"}},autoFocus:Z.value[R]==="select",style:H,highlightStyle:{fg:"whiteBright",bg:"blueBright",bold:!0}})),L+=b+1,O&&L<q-1)v.push(v0(t,{x:0,y:L++,w:N,value:"Custom answer:",style:D})),v.push(v0(J6,{key:`custom-input:${R}:${X.value[R]??0}`,x:0,y:L,w:N,modelValue:V.value[R]||"","onUpdate:modelValue":(y)=>{V.value={...V.value,[R]:y}},onFocus:()=>{Z.value={...Z.value,[R]:"input"}},onKeydown:(y)=>{if(y?.key==="ArrowDown"){y.preventDefault?.(),y.stopPropagation?.(),Z.value={...Z.value,[R]:"buttons"};return}if(y?.key==="Enter"&&!y?.shiftKey){y.preventDefault?.(),y.stopPropagation?.();let x=L8(Q.value,0,Math.max(0,A.length-1)),c=A[x];k(String(c?.value??""));return}if(y?.key!=="ArrowUp")return;y.preventDefault?.(),y.stopPropagation?.(),Z.value={...Z.value,[R]:"select"}},autoFocus:Z.value[R]==="input",placeholder:"Type your answer...",style:{fg:"whiteBright",bg:"blackBright"}}))}}else{v.push(v0(t,{x:0,y:L++,w:N,value:"[Single-select] Use arrows, Enter to confirm",style:{fg:"yellow"}})),L++;let C=_.value[R]??0,b=Math.min(z.length,Math.max(3,q-L-2));if(v.push(v0(q0,{x:0,y:L,w:N,h:b,options:w,modelValue:C,"onUpdate:modelValue":(y)=>{_.value={..._.value,[R]:y},Z.value={...Z.value,[R]:y===S?"input":"select"}},onFocus:()=>{Z.value={...Z.value,[R]:"select"}},autoFocus:Z.value[R]==="select",style:H,highlightStyle:{fg:"whiteBright",bg:"blueBright",bold:!0}})),L+=b+1,O&&L<q-1)v.push(v0(t,{x:0,y:L++,w:N,value:"Custom answer:",style:D})),v.push(v0(J6,{key:`custom-input:${R}:${X.value[R]??0}`,x:0,y:L,w:N,modelValue:V.value[R]||"","onUpdate:modelValue":(y)=>{V.value={...V.value,[R]:y}},onFocus:()=>{Z.value={...Z.value,[R]:"input"}},onKeydown:(y)=>{if(y?.key==="ArrowDown"){y.preventDefault?.(),y.stopPropagation?.(),Z.value={...Z.value,[R]:"buttons"};return}if(y?.key==="Enter"&&!y?.shiftKey){y.preventDefault?.(),y.stopPropagation?.();let s=L8(Q.value,0,Math.max(0,A.length-1)),F$=A[s];k(String(F$?.value??""));return}if(y?.key!=="ArrowUp")return;y.preventDefault?.(),y.stopPropagation?.();let x=_.value[R]??0,c=L8(x-1,0,S);_.value={..._.value,[R]:c},Z.value={...Z.value,[R]:"select"}},autoFocus:Z.value[R]==="input",placeholder:"Type your answer...",style:{fg:"whiteBright",bg:"blackBright"}}))}return v})}}});function T0$($,J){let U=String(J??"").trim();if(!U)return null;for(let Q of $.store.state.messages){if(Q.role!=="assistant")continue;for(let _ of Q.parts)if(_.type==="tool_call"&&_.call.id===U)return _.call}return null}function Dv($){return[$.showApproval.value&&$.activeApproval.value?jv(Hv,{modelValue:$.showApproval.value,"onUpdate:modelValue":(J)=>$.showApproval.value=J,request:$.activeApproval.value,call:T0$($,$.activeApproval.value.toolCallId),w:$.approvalW.value,h:$.approvalH.value,onApprove:()=>void $.store.approve(),onAlwaysApprove:()=>{$.applyToolApprovals("all"),$.store.approve()},onDeny:()=>void $.store.deny()}):null,$.showAskUser.value&&$.activeAskUser.value?jv(Ov,{modelValue:$.showAskUser.value,"onUpdate:modelValue":(J)=>$.showAskUser.value=J,toolCallId:String($.activeAskUser.value.toolCallId??""),questions:$.activeAskUser.value.questions??[],w:$.askUserW.value,h:$.askUserH.value,onSubmit:(J)=>void $.store.submitAskUserAnswers(J),onCancel:()=>$.store.cancelAskUser()}):null]}import{h as y0$}from"vue";import{computed as aV,defineComponent as v0$,ref as C0$,watch as b0$}from"vue";function Ev($,J){let U=$.toLowerCase(),Q=J.toLowerCase().trim();if(!Q)return 0;if(U===Q)return 1e4;if(U.startsWith(Q))return 5000-U.length;let _=U.indexOf(Q);if(_>=0)return 2000-_;let G=0,V=0,X=0;for(let Z=0;Z<U.length&&G<Q.length;Z++)if(U[Z]===Q[G])G++,X++,V+=10+X*5;else X=0;if(G<Q.length)return null;return V}function FJ($,J,U){return Math.max(J,Math.min(U,$))}function Pv($,J){let U=J.trim(),Q=[];for(let _=0;_<$.length;_++){let G=$[_],V=(G.keywords??[]).filter(Boolean).join(" "),X=`${G.label} ${G.detail??""} ${V}`.trim(),Z=Ev(X,U);if(Z==null)continue;Q.push({idx:_,opt:G,score:Z})}return Q.sort((_,G)=>G.score-_.score||_.idx-G.idx),Q}function Mv($,J){let U=$.findIndex((Q)=>Q.idx===J);return U>=0?U:0}import{h as V1}from"vue";function Lv($){if(!$.modelValue)return null;let J=Math.max(0,Math.floor($.cols)),U=Math.max(0,Math.floor($.rows)),Q=J<=0?0:FJ(Math.floor(J*0.78),Math.min(44,J),J),_=U<=0?0:FJ(12,10,Math.max(10,Math.min(18,U))),G=Math.max(0,Math.floor(($.cols-Q)/2)),V=FJ(Math.floor($.rows*0.25),1,Math.max(1,$.rows-_-1)),X=Math.max(0,Q-2),Z=Math.max(0,_-2),Y=Math.max(0,X-2),K=Math.max(0,Z-2),F=$.filtered,N=1,q=2,H=Math.max(q,K-1),E=Math.max(q,H-2),D=FJ(F.length,1,Math.max(1,E-q)),B=Math.max(1,D),j=Math.max(0,F.length-B),f=FJ($.selectedFilteredIndex-Math.floor(B/2),0,j),R=F.slice(f,f+B),I=F[$.selectedFilteredIndex]?.opt,w=I?.detail?String(I.detail):"",T=w?K0(w,Math.max(1,Y)).slice(0,2):[],z=()=>{$.onUpdateModelValue(!1),$.onClose()},S=(M)=>{if(!F.length)return;let P=F.length-1,A=$.selectedFilteredIndex+M;if(A<0)A=P;else if(A>P)A=0;let k=F[A]?.idx;if(k!=null)$.onUpdateSelectedIndex(k)},O=()=>{let M=F[$.selectedFilteredIndex];$.onSelect(M?.opt?.label??null)};return V1(R4,{x:0,y:0,w:$.cols,h:$.rows,zIndex:100,focusable:!0,onClick:z,onKeydownCapture:(M)=>{if(M?.key==="Escape")M?.preventDefault?.(),M?.stopPropagation?.(),z()}},()=>V1(N6,{x:G,y:V,w:Q,h:_,border:!0,title:$.title,padding:1,style:{fg:"blueBright",bg:"black"},zIndex:110},()=>[V1(t,{x:0,y:0,w:Y,h:K,value:"",style:{bg:"black"}}),V1(J6,{x:0,y:0,w:Y,modelValue:$.query,"onUpdate:modelValue":(M)=>$.setQuery(M),placeholder:"Search…",placeholderWhenFocused:!0,autoFocus:!0,style:{fg:"whiteBright",bg:"blackBright"},onKeydown:(M)=>{if(M?.key==="ArrowDown")M.preventDefault?.(),S(1);else if(M?.key==="ArrowUp")M.preventDefault?.(),S(-1);else if(M?.key==="Enter")M.preventDefault?.(),O()}}),Y>0?V1(t,{x:0,y:N,w:Y,value:"─".repeat(Y),style:{fg:"white",dim:!0,bg:"black"}}):null,F.length?V1(q0,{x:0,y:q,w:Y,h:D,options:R.map((M)=>({label:M.opt.label})),modelValue:FJ($.selectedFilteredIndex-f,0,Math.max(0,R.length-1)),"onUpdate:modelValue":(M)=>{let P=R[FJ(M,0,Math.max(0,R.length-1))];if(P)$.onUpdateSelectedIndex(P.idx)},style:{fg:"whiteBright",bg:"black"},highlightStyle:{fg:"black",bg:"blueBright",bold:!0},autoFocus:!1,closeOnBlur:!1,onChange:(M)=>$.onSelect(M),onClose:z}):V1(t,{x:0,y:q,w:Y,h:D,value:"No matches",style:{fg:"white",dim:!0,bg:"blackBright"}}),T.length?T.map((M,P)=>V1(t,{key:`detail-${P}`,x:0,y:E+P,w:Y,value:M,style:{fg:"white",dim:!0,bg:"black"}})):V1(t,{x:0,y:E,w:Y,h:2,value:"",style:{bg:"black"}}),V1(t,{x:0,y:H,w:Y,value:"Type to filter • Enter: open • Esc: close",style:{fg:"white",dim:!0,bg:"black"}}),Y>0?V1(t,{x:Math.max(0,Y-1),y:H,w:1,value:" ",style:{bg:"black"}}):null]))}var oV=v0$({name:"GoatChainCommandPalette",props:{modelValue:{type:Boolean,required:!0},title:{type:String,default:"Commands"},initialQuery:{type:String,default:""},options:{type:Array,required:!0},selectedIndex:{type:Number,required:!0}},emits:{"update:modelValue":($)=>!0,"update:selectedIndex":($)=>!0,select:($)=>!0,close:()=>!0},setup($,{emit:J}){let U=p4(),Q=aV(()=>U.clipRect?.w??0),_=aV(()=>U.clipRect?.h??0),G=C0$("");b0$(()=>[$.modelValue,$.initialQuery],([Y])=>{if(Y)G.value=String($.initialQuery??"")});function V(){J("close")}let X=aV(()=>Pv($.options,G.value)),Z=aV(()=>Mv(X.value,$.selectedIndex));return()=>{return Lv({modelValue:$.modelValue,title:$.title,cols:Q.value,rows:_.value,query:G.value,setQuery:(Y)=>G.value=Y,filtered:X.value,selectedFilteredIndex:Z.value,onUpdateModelValue:(Y)=>J("update:modelValue",Y),onUpdateSelectedIndex:(Y)=>J("update:selectedIndex",Y),onSelect:(Y)=>J("select",Y),onClose:V})}}});function zv($){return[y0$(oV,{modelValue:$.showCommands.value,"onUpdate:modelValue":(J)=>$.showCommands.value=J,title:"Commands",options:$.commandOptions.value,selectedIndex:$.commandIndex.value,"onUpdate:selectedIndex":(J)=>$.commandIndex.value=J,onSelect:(J)=>$.onCommandSelect(J),onClose:$.closeCommandPalette})]}import{h as x0$}from"vue";import{defineComponent as g0$,h as Qj}from"vue";var Rv=g0$({name:"GoatChainExitSessionDialog",props:{modelValue:{type:Boolean,required:!0}},emits:{"update:modelValue":($)=>!0,exit:()=>!0},setup($,{emit:J}){return()=>{if(!$.modelValue)return null;return Qj(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(U)=>J("update:modelValue",U),onKeydownCapture:(U)=>{if(U?.key==="Escape"){U.preventDefault?.(),U.stopPropagation?.(),J("update:modelValue",!1);return}if(typeof U?.key==="string"&&U.key.length===1&&!U.ctrlKey&&!U.metaKey&&!U.altKey)U.preventDefault?.(),U.stopPropagation?.()},w:54,h:10,title:"Exit Session",placement:"center",backdrop:!1,padding:1,style:{fg:"yellowBright",bg:"black"},buttons:[{label:"Cancel",value:"cancel"},{label:"Exit",value:"exit",kind:"primary",default:!0}],onConfirm:(U)=>{if(U?.value==="exit")J("exit");J("update:modelValue",!1)},onClose:()=>J("update:modelValue",!1)},()=>[Qj(t,{x:0,y:0,w:50,wrap:!0,value:"Exit the current session and return to Home?",style:{fg:"whiteBright",bg:"black"}}),Qj(t,{x:0,y:2,w:50,wrap:!0,value:"Next message will start a new session.",style:{fg:"white",dim:!0,bg:"black"}})])}}});function Av($){return[x0$(Rv,{modelValue:$.showExitConfirm.value,"onUpdate:modelValue":(J)=>$.showExitConfirm.value=J,onExit:async()=>{$.showExitConfirm.value=!1,await $.exitSessionToHome()}})]}import{h as z8}from"vue";import{defineComponent as h0$,h as tV}from"vue";var wv=h0$({name:"GoatChainMessageActionsDialog",props:{modelValue:{type:Boolean,required:!0},selectedIndex:{type:Number,required:!0}},emits:{"update:modelValue":($)=>!0,"update:selectedIndex":($)=>!0,action:($)=>!0},setup($,{emit:J}){let U=["Revert undo messages and file changes","Copy message text to clipboard","Fork create a new session"];function Q(V){return V===0?"revert":V===1?"copy":"fork"}function _(){J("update:modelValue",!1),J("update:selectedIndex",0)}function G(V){if(V.defaultPrevented)return;if(V.key==="ArrowUp")V.preventDefault?.(),V.stopPropagation?.(),J("update:selectedIndex",Math.max(0,$.selectedIndex-1));else if(V.key==="ArrowDown")V.preventDefault?.(),V.stopPropagation?.(),J("update:selectedIndex",Math.min(2,$.selectedIndex+1));else if(V.key==="Enter")V.preventDefault?.(),V.stopPropagation?.(),J("action",Q($.selectedIndex));else if(V.key==="Escape")V.preventDefault?.(),V.stopPropagation?.(),_()}return()=>{if(!$.modelValue)return null;return tV(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(V)=>{if(J("update:modelValue",V),!V)J("update:selectedIndex",0)},onKeydownCapture:(V)=>{if(typeof V?.key==="string"&&V.key.length===1&&!V.ctrlKey&&!V.metaKey&&!V.altKey)V.preventDefault?.(),V.stopPropagation?.()},w:48,h:7,title:"Message Actions",placement:"center",backdrop:!1,padding:1,style:{fg:"blueBright",bg:"black"},onClose:_},()=>tV(R4,{x:0,y:0,w:44,h:3,focusable:!0,autoFocus:!0,onKeydownCapture:G},()=>U.flatMap((V,X)=>{let Z=$.selectedIndex===X,Y=Z?{fg:"white",bg:"black",bold:!0}:{fg:"whiteBright",dim:!0,bg:"black"},K=Z?"▸ ":" ";return[tV(t,{key:`action-t-${X}`,x:0,y:X,w:44,value:`${K}${V}`,style:Y}),tV(R4,{key:`action-v-${X}`,x:0,y:X,w:44,h:1,onClick:(F)=>{F?.stopPropagation?.(),J("update:selectedIndex",X),J("action",Q(X))}})]})))}}});import{defineComponent as u0$,h as fv}from"vue";var kv=u0$({name:"GoatChainRedoConfirmDialog",props:{modelValue:{type:Boolean,required:!0}},emits:{"update:modelValue":($)=>!0,confirm:()=>!0,cancel:()=>!0},setup($,{emit:J}){function U(){J("update:modelValue",!1),J("cancel")}return()=>{if(!$.modelValue)return null;return fv(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(Q)=>J("update:modelValue",Q),onKeydownCapture:(Q)=>{if(typeof Q?.key==="string"&&Q.key.length===1&&!Q.ctrlKey&&!Q.metaKey&&!Q.altKey)Q.preventDefault?.(),Q.stopPropagation?.()},w:52,h:8,title:"Confirm Redo",placement:"center",backdrop:!1,padding:1,style:{fg:"whiteBright",bg:"black"},buttons:[{label:"Cancel",value:"cancel"},{label:"Confirm",value:"confirm",kind:"primary",default:!0}],onConfirm:(Q)=>{if(Q?.value==="confirm")J("confirm"),J("update:modelValue",!1);else U()},onClose:U},()=>[fv(t,{x:0,y:1,w:48,value:"Are you sure you want to restore the reverted messages?",style:{fg:"white"}})])}}});function Iv($){let J=[];if($.store.hasRevertedMessages.value){let _=$.mainY+$.mainH.value,G=Math.max(0,$.mainW.value-4),V=Array.from({length:2},()=>"┃").join(`
|
|
943
|
-
`),X=4,Z=Math.max(0,G-3);J.push(z8(t,{key:"revert-banner-bg",x:2,y:_,w:G,h:2,value:"",style:{bg:"black"},zIndex:50}),z8(t,{key:"revert-banner-bar",x:2,y:_,w:1,h:2,value:V,style:{fg:"blueBright",bg:"black"},zIndex:51}),z8(t,{key:"revert-banner-text",x:4,y:_,w:Z,value:`${$.store.revertedMessageCount.value} message${$.store.revertedMessageCount.value>1?"s":""} reverted`,style:{fg:"yellowBright",bg:"black"},zIndex:52}),z8(t,{key:"revert-banner-hint",x:4,y:_+1,w:Z,value:"click or ctrl+r or /redo to restore",style:{fg:"white",dim:!0,bg:"black",bold:!0},zIndex:52}),z8(R4,{key:"revert-banner-hit",x:2,y:_,w:G,h:2,zIndex:60,focusable:!0,onClick:()=>{$.confirmRestore(),$.focusBrowserTextarea()}}))}return J.push(z8(wv,{modelValue:$.showMessageActions.value,"onUpdate:modelValue":(U)=>{if($.showMessageActions.value=U,!U)$.messageActionsTargetId.value=null,$.messageActionsIndex.value=0},selectedIndex:$.messageActionsIndex.value,"onUpdate:selectedIndex":(U)=>$.messageActionsIndex.value=U,onAction:(U)=>{if(U==="revert")$.handleRevertMessage();else if(U==="copy")$.handleCopyMessage();else $.handleForkSession()}}),z8(kv,{modelValue:$.showRedoConfirm.value,"onUpdate:modelValue":(U)=>$.showRedoConfirm.value=U,onConfirm:$.confirmRestore,onCancel:$.cancelRestore})),J}import{h as d0$}from"vue";import{defineComponent as m0$,h as Gj,watch as c0$}from"vue";var sV=m0$({name:"GoatChainPathPickerDialog",props:{modelValue:{type:Boolean,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0},title:{type:String,required:!0},workspace:{type:String,required:!0},mode:{type:String,required:!0},query:{type:String,required:!0},placeholder:{type:String,required:!0}},emits:{"update:modelValue":($)=>!0,"update:query":($)=>!0,invalid:($)=>!0,select:($)=>!0,close:()=>!0},setup($,{emit:J}){let U=UJ(),Q=!1;function _(){Q=!1}function G(X){let Z=X?.key;if(Z==="ArrowUp"||Z==="ArrowDown"){Q=!0;return}if((X?.ctrlKey||X?.metaKey)&&!X?.altKey&&(Z==="p"||Z==="P"||Z==="n"||Z==="N"))Q=!0}let V={listDir:U.listDir,stat:async(X)=>{if(Q){let Z=J1($.workspace,$.query);if(X===Z)return Q=!1,{exists:!1,kind:"other"}}return U.stat(X)}};return c0$(()=>$.modelValue,(X)=>{if(!X)_()}),()=>{if(!$.modelValue)return null;let X=Math.max(0,$.w-2),Z=Math.max(0,$.h-2);return Gj(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(Y)=>J("update:modelValue",Y),w:$.w,h:$.h,title:$.title,placement:"center",backdrop:!1,padding:1,style:{fg:"blueBright",bg:"black"},onClose:()=>{_(),J("update:modelValue",!1),J("close")}},()=>[Gj(t,{x:0,y:0,w:X,value:"↑/↓ select • Tab complete • Enter confirm • Esc close",style:{fg:"white",dim:!0}}),Gj(DV,{x:0,y:2,w:X,h:Math.max(0,Z-3),workspace:$.workspace,mode:$.mode,provider:V,modelValue:$.query,"onUpdate:modelValue":(Y)=>{_(),J("update:query",Y)},placeholder:$.placeholder,autoFocus:!0,style:{fg:"blueBright",bg:"black"},onKeydown:(Y)=>{if(G(Y),Y?.key!=="Escape")return;Y?.preventDefault?.(),_(),J("update:modelValue",!1),J("close")},onInvalid:(Y)=>{_(),J("invalid",String(Y?.reason??"invalid"))},onSelect:(Y)=>{_(),J("select",Y)}})])}}});function Sv($){return[d0$(sV,{modelValue:$.showPathPicker.value,"onUpdate:modelValue":(J)=>$.showPathPicker.value=J,w:$.pickerW.value,h:$.pickerH.value,title:$.pathPickerTitle.value,workspace:$.pickerWorkspace.value,mode:$.pathPickerMode.value,query:$.pathPickerQuery.value,"onUpdate:query":(J)=>$.pathPickerQuery.value=J,placeholder:$.pathPickerPlaceholder.value,onInvalid:(J)=>$.pathPickerError.value=J,onSelect:(J)=>{if($.pathPickerError.value=null,$.showPathPicker.value=!1,$.pathPickerQuery.value="",$.pathPickerMode.value==="directory")$.setContextCwd(J);else if(!$.focusFiles.value.includes(J))$.focusFiles.value=[...$.focusFiles.value,J]},onClose:()=>{$.showPathPicker.value=!1,$.pathPickerQuery.value="",$.pathPickerError.value=null}})]}import{h as n0$}from"vue";import{defineComponent as l0$,h as Vj,ref as i0$,watch as r0$}from"vue";var Tv=l0$({name:"GoatChainRenameSessionDialog",props:{modelValue:{type:Boolean,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0},initialValue:{type:String,default:""}},emits:{"update:modelValue":($)=>!0,submit:($)=>!0,cancel:()=>!0},setup($,{emit:J}){let U=i0$(String($.initialValue??""));r0$(()=>$.modelValue,(V,X)=>{if(!V||X)return;U.value=String($.initialValue??"")},{immediate:!0});function Q(){J("update:modelValue",!1)}function _(){J("cancel"),Q()}function G(){let V=String(U.value??"").trim();J("submit",V),Q()}return()=>{if(!$.modelValue)return null;let V=Math.max(0,$.w-4);return Vj(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(X)=>J("update:modelValue",X),w:$.w,h:$.h,title:"Rename session",placement:"center",padding:1,backdrop:!1,closeOnBackdrop:!1,style:{fg:"blueBright",bg:"black"},buttons:[{label:"Save",value:"save",kind:"primary",default:!0},{label:"Cancel",value:"cancel"}],closeOnConfirm:!1,onConfirm:(X)=>{if(X?.value==="save")G();else _()},onClose:_,onKeydownCapture:(X)=>{if(X?.key==="Enter")X.preventDefault?.(),G()}},()=>[Vj(t,{x:0,y:0,w:V,value:"Session name",style:{fg:"white",dim:!0,bg:"black"}}),Vj(J6,{x:0,y:1,w:V,modelValue:U.value,"onUpdate:modelValue":(X)=>U.value=X,onKeydown:(X)=>{if(X?.key==="Escape")X.preventDefault?.(),_()},placeholder:"e.g. Planning notes",placeholderWhenFocused:!0,autoFocus:!0,cursorToEndOnFirstFocus:!0,style:{fg:"whiteBright",bg:"blackBright"}})])}}});function vv($){if(!$.showRenameSession.value)return[];return[n0$(Tv,{key:"rename-session",modelValue:$.showRenameSession.value,"onUpdate:modelValue":(J)=>$.showRenameSession.value=J,w:$.renameSessionW.value,h:$.renameSessionH.value,initialValue:$.renameSessionInitialValue.value,onSubmit:(J)=>$.applyRenameSession(J),onCancel:()=>$.cancelRenameSession()})]}import{h as gv}from"vue";import{defineComponent as J1$,ref as U1$,watch as _1$}from"vue";function WJ($,J,U){return Math.max(J,Math.min(U,$))}function p0$($,J=Date.now()){if(!Number.isFinite($))return"";let U=Number($)-Number(J);if(!Number.isFinite(U))return"";let Q=Math.abs(U);if(Q<60000)return"now";if(Q<3600000)return`${Math.max(1,Math.floor(Q/60000))} min`;if(Q<86400000)return`${Math.max(1,Math.floor(Q/3600000))} hr`;return`${Math.max(1,Math.floor(Q/86400000))} d`}function a0$($,J){J=Math.max(0,Math.floor(J));let U=String($??"").replace(/\s+/g," ").trim();if(!U||J<=0)return"";if(M$(U)<=J)return U;if(J<=1)return m4(U,J);return`${m4(U,J-1)}…`}function o0$($,J){J=Math.max(0,Math.floor(J));let U=String($??"").replace(/\s+/g," ").trim();if(!U||J<=0)return"";if(M$(U)<=J)return U;if(J<=1)return m4(U,J);let Q=J-1,_=Q,G=[];for(let V=U.length;V>0&&_>0;){let X=V-1,Z=U.charCodeAt(X);if(Z>=56320&&Z<=57343&&X-1>=0){let F=U.charCodeAt(X-1);if(F>=55296&&F<=56319)X-=1}let Y=U.slice(X,V),K=M$(Y);if(K>_)break;G.push(Y),_-=K,V=X}if(G.length===0)return`…${m4(U,Q)}`;return G.reverse(),`…${G.join("")}`}function t0$($,J=3){let U=String($??"").trim();if(!U)return"";let _=U.replace(/[\\/]+/g,"/").split("/").filter(Boolean);if(_.length===0)return U.startsWith("/")?"/":U;let G=/^[A-Za-z]:$/.test(_[0])?_[0]:"",V=G?_.slice(1):_,X=V.slice(-Math.max(1,Math.floor(J))),Z=V.length>X.length;if(G){if(Z)return`${G}/…/${X.join("/")}`;return`${G}/${X.join("/")}`}if(Z)return`…/${X.join("/")}`;return X.join("/")}function s0$($){return $.title||$.summary||"New session"}function Cv($,J){return p0$($.updatedAt,J)}function e0$($){return t0$($.cwd,3)}function $1$($){if($<34)return{cwdW:0,summaryW:$,colGap:2};let _=Math.max(0,$-34),G=14+Math.floor(_*0.6),V=Math.max(0,$-2-G);return{cwdW:G,summaryW:V,colGap:2}}function bv($){let J=Math.floor($.w??78),U=Math.floor($.h??20),Q=Math.max(0,J-4),_=Math.max(0,U-4),G=Math.max(0,_-1),V=2,X=1,Z=Array.isArray($.sessions)?$.sessions:[],Y=Z.length,K=WJ(Y,1,Math.max(1,G-2-1)),F=WJ($.selectedIndex,0,Math.max(0,Y-1)),N=Date.now(),q=Math.max(0,...Z.map((M)=>M$(Cv(M,N)))),H=1,E=Math.max(0,Q-1-q),{cwdW:D,summaryW:B,colGap:j}=$1$(E),f=Math.max(1,K),R=Math.max(0,Y-f),I=WJ(F-Math.floor(f/2),0,R),T=Z.slice(I,I+f).map((M)=>{let P=[];if(D>0){let A=e0$(M)||"—",k=h6(o0$(A,D),D);P.push(k)}if(B>0){let A=s0$(M),k=h6(a0$(A,B),B);P.push(k)}return{label:P.filter(Boolean).join(" ".repeat(j)).trimEnd(),detail:Cv(M,N)}}),z=WJ(F-I,0,Math.max(0,T.length-1)),S=`Sessions (${Y})`,O=$.loading?"Loading…":$.deleteArmed?"Confirm delete: press Delete again":Y?`${Y} sessions • Arrow keys to navigate • Enter selects${Y>f?` • Showing ${I+1}-${Math.min(Y,I+f)}`:""}`:"No saved sessions yet";return{w:J,h:U,innerW:Q,listY:2,listH:K,offset:I,windowSize:f,totalSessions:Y,selectedIndex:F,selectedOptionIndex:z,title:S,headerText:O,options:T}}import{h as Xj}from"vue";function yv($){if(!$.modelValue)return null;return Xj(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(J)=>$.onUpdateModelValue(J),onKeydownCapture:(J)=>$.onKeydownCapture(J),w:$.vm.w,h:$.vm.h,title:$.vm.title,placement:"center",backdrop:!1,padding:1,style:{fg:"blueBright",bg:"black"},closeOnConfirm:!1,buttons:[{label:"Open",value:"open",kind:"primary",default:!$.deleteArmed},{label:"New",value:"new"},{label:$.deleteArmed?"Delete (confirm)":"Delete",value:"delete",kind:"danger",default:$.deleteArmed},{label:"Refresh",value:"refresh"},{label:"Close",value:"close"}],onConfirm:(J)=>$.onConfirm(J),onClose:()=>$.onClose()},()=>[Xj(t,{x:0,y:0,w:$.vm.innerW,value:$.vm.headerText,style:{fg:"white",dim:!0,bg:"black"}}),Xj(q0,{x:0,y:$.vm.listY,w:$.vm.innerW,h:$.vm.listH,options:$.vm.options,modelValue:$.vm.selectedOptionIndex,"onUpdate:modelValue":(J)=>{let U=WJ($.vm.offset+J,0,Math.max(0,$.vm.totalSessions-1));$.onUpdateSelectedIndex(U)},onKeydownCapture:$.onKeydownCapture,onChange:(J)=>{if(!J)return;$.onOpen()},autoFocus:!0,style:{fg:"whiteBright",bg:"black"},highlightStyle:{fg:"whiteBright",bg:"blueBright",bold:!0},zIndex:1002})])}var eV=J1$({name:"GoatChainSessionsDialog",props:{modelValue:{type:Boolean,required:!0},loading:{type:Boolean,default:!1},deleteArmed:{type:Boolean,default:!1},sessions:{type:Array,required:!0},selectedIndex:{type:Number,required:!0}},emits:{"update:modelValue":($)=>!0,"update:selectedIndex":($)=>!0,open:()=>!0,new:()=>!0,delete:()=>!0,refresh:()=>!0},setup($,{emit:J}){let U=["open","new","delete","refresh","close"],Q=U1$(0),_="__goatchainSessionsDialogHandled";function G(){return $.deleteArmed?U.indexOf("delete"):U.indexOf("open")}function V(Y){let K=U.length-1;Q.value=WJ(Q.value+Y,0,K)}function X(){let Y=U[Q.value]??"open";if(Y==="open")J("open");else if(Y==="new")J("new");else if(Y==="delete")J("delete");else if(Y==="refresh")J("refresh");else J("update:modelValue",!1)}function Z(Y){if(!$.modelValue)return;if(!Y||typeof Y!=="object")return;if(Y.__goatchainSessionsDialogHandled)return;if(Y.key==="ArrowLeft"||Y.key==="ArrowRight"){Y.__goatchainSessionsDialogHandled=!0;let K=Y.key==="ArrowLeft"?-1:1;V(K);return}if(Y.key==="Enter")Y.__goatchainSessionsDialogHandled=!0,Y.preventDefault?.(),Y.stopPropagation?.(),X()}return _1$(()=>$.modelValue,(Y,K)=>{if(Y&&!K)Q.value=G()},{immediate:!0}),()=>{let Y=bv({modelValue:$.modelValue,loading:$.loading,deleteArmed:$.deleteArmed,sessions:$.sessions,selectedIndex:$.selectedIndex});return yv({modelValue:$.modelValue,deleteArmed:$.deleteArmed,vm:Y,onUpdateModelValue:(K)=>J("update:modelValue",K),onUpdateSelectedIndex:(K)=>J("update:selectedIndex",K),onOpen:()=>J("open"),onNew:()=>J("new"),onDelete:()=>J("delete"),onRefresh:()=>J("refresh"),onKeydownCapture:(K)=>{if(K?.key==="Escape"){K.preventDefault?.(),K.stopPropagation?.(),J("update:modelValue",!1);return}if(typeof K?.key==="string"&&K.key.length===1&&!K.ctrlKey&&!K.metaKey&&!K.altKey)K.preventDefault?.(),K.stopPropagation?.();Z(K)},onConfirm:(K)=>{let F=String(K?.value??""),N=U.indexOf(F);if(N>=0)Q.value=N;if(F==="open")J("open");else if(F==="new")J("new");else if(F==="delete")J("delete");else if(F==="refresh")J("refresh");else J("update:modelValue",!1)},onClose:()=>J("update:modelValue",!1)})}}});import{defineComponent as Q1$,h as $X}from"vue";var JX=Q1$({name:"GoatChainSwitchSessionDialog",props:{modelValue:{type:Boolean,required:!0},title:{type:String,default:"Switch Session"},targetLabel:{type:String,default:""},reason:{type:String,default:""}},emits:{"update:modelValue":($)=>!0,confirm:()=>!0},setup($,{emit:J}){return()=>{if(!$.modelValue)return null;let U=String($.targetLabel??"").trim(),Q=String($.reason??"").trim();return $X(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(_)=>J("update:modelValue",_),onKeydownCapture:(_)=>{if(_?.key==="Escape"){_.preventDefault?.(),_.stopPropagation?.(),J("update:modelValue",!1);return}if(typeof _?.key==="string"&&_.key.length===1&&!_.ctrlKey&&!_.metaKey&&!_.altKey)_.preventDefault?.(),_.stopPropagation?.()},w:64,h:12,title:String($.title??"Switch Session"),placement:"center",backdrop:!1,padding:1,style:{fg:"yellowBright",bg:"black"},buttons:[{label:"Cancel",value:"cancel"},{label:"Switch & Interrupt",value:"confirm",kind:"primary",default:!0}],onConfirm:(_)=>{if(_?.value==="confirm")J("confirm");J("update:modelValue",!1)},onClose:()=>J("update:modelValue",!1)},()=>[$X(t,{x:0,y:0,w:60,wrap:!0,value:U?`Switch to ${U}?`:"Switch sessions now?",style:{fg:"whiteBright",bg:"blackBright"}}),$X(t,{x:0,y:2,w:60,wrap:!0,value:"This will interrupt the current response/flow in the active session.",style:{fg:"white",dim:!0,bg:"blackBright"}}),Q?$X(t,{x:0,y:4,w:60,wrap:!0,value:`Reason: ${Q}`,style:{fg:"white",dim:!0,bg:"blackBright"}}):null])}}});function xv($){return[gv(eV,{modelValue:$.showSessions.value,"onUpdate:modelValue":(J)=>{if($.showSessions.value=J,!J)$.sessionsDeleteArmed.value=!1},loading:$.sessionsLoading.value,deleteArmed:$.sessionsDeleteArmed.value,sessions:$.sessionsList.value,selectedIndex:$.sessionsIndex.value,"onUpdate:selectedIndex":(J)=>{$.sessionsIndex.value=J,$.sessionsDeleteArmed.value=!1},onOpen:async()=>{await $.openSelectedSession()},onNew:async()=>{await $.createNewSession({after:async()=>$.router.push("home")})},onDelete:async()=>{let J=$.sessionsApi,U=$.sessionsList.value[$.sessionsIndex.value];if(!J||!U)return;let Q=$.sessionsIndex.value;if(!$.sessionsDeleteArmed.value){$.sessionsDeleteArmed.value=!0,$.showCopyToast("Press Delete again to confirm.");return}$.sessionsDeleteArmed.value=!1,await J.delete(U.id),await $.refreshSessions({preferIndex:Q})},onRefresh:async()=>{$.sessionsDeleteArmed.value=!1,await $.refreshSessions()}}),gv(JX,{modelValue:$.showSwitchConfirm.value,"onUpdate:modelValue":(J)=>{if($.showSwitchConfirm.value=J,!J)$.cancelSwitch()},title:$.switchConfirmTitle.value,targetLabel:$.switchConfirmTargetLabel.value,reason:$.switchConfirmReason.value,onConfirm:()=>void $.confirmSwitch()})]}import{h as Kj}from"vue";import{defineComponent as V1$}from"vue";import{h as U0}from"vue";function G1$($,J,U){return Math.max(J,Math.min(U,$))}function hv($,J){if(!$.modelValue)return null;let U=Math.max(44,Math.floor($.w)),Q=Math.max(18,Math.floor($.h)),_=Math.max(0,U-4),G=Math.max(0,Q-4),V=Math.max(0,G-1),X={fg:"white",dim:!0},Z={fg:"white",bg:"black",dim:!0},Y={fg:"whiteBright",bg:"blackBright"},K=0,F=4,N=3,q=5,H=V>=F*q+1?F:N,E=Math.max(1,H-2),D=V>=H*q+1,B=D?U0(t,{x:0,y:0,w:_,value:"Tab/Shift+Tab switch field • Enter Apply • Esc Cancel",style:X}):null,j=H===N?1:2,f=G1$(Math.floor(_*0.28),16,Math.max(16,_-(16+j))),R=Math.max(0,_-f-j),I=D?1+K:0,w=I;I+=H+K;let T=I;I+=H+K;let z=I;I+=H+K;let S=1,M=Boolean($.apiKeyMasked)&&I+S+H*2<=V,P=I;if(M)I+=S;let A=I;I+=H+K;let k=I,L=Math.min(H,Math.max(1,V-k)),v=Math.max(1,L-2);return U0(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(C)=>J.updateModelValue(C),onKeydownCapture:(C)=>{if(C?.key==="Escape"){C.preventDefault?.(),C.stopPropagation?.(),J.cancel(),J.updateModelValue(!1);return}if(C?.key==="Enter")C.preventDefault?.(),C.stopPropagation?.(),J.apply()},w:U,h:Q,title:"Settings",placement:"center",backdrop:Boolean($.backdrop),closeOnBackdrop:!1,padding:1,style:{fg:"blueBright",bg:"black"},buttons:[{label:"Apply",value:"apply",kind:"primary",default:!0},{label:"Cancel",value:"cancel"}],onConfirm:(C)=>{if(C?.value==="apply")J.apply();else J.cancel()},onClose:()=>J.cancel()},()=>[B,U0(N6,{x:0,y:w,w:_,h:H,border:!0,title:"Model",padding:0,style:Z,clear:!0},()=>U0(J6,{x:0,y:0,w:Math.max(0,_-2),h:E,modelValue:$.modelId,"onUpdate:modelValue":(C)=>J.updateModelId(C),placeholder:"deepseek-v3.1",cursorToEndOnFirstFocus:!0,cursorToEndOnExternalUpdate:!0,style:Y,zIndex:1002,autoFocus:!0})),U0(N6,{x:0,y:T,w:f,h:H,border:!0,title:"Context Window",padding:0,style:Z,clear:!0},()=>U0(J6,{x:0,y:0,w:Math.max(0,f-2),h:E,modelValue:$.contextWindow,"onUpdate:modelValue":(C)=>J.updateContextWindow(C),placeholder:"128000",cursorToEndOnFirstFocus:!0,cursorToEndOnExternalUpdate:!0,style:Y,zIndex:1002})),U0(N6,{x:f+j,y:T,w:R,h:H,border:!0,title:"Temperature",padding:0,style:Z,clear:!0},()=>U0(J6,{x:0,y:0,w:Math.max(0,R-2),h:E,modelValue:$.temperature,"onUpdate:modelValue":(C)=>J.updateTemperature(C),placeholder:"0.7",cursorToEndOnFirstFocus:!0,cursorToEndOnExternalUpdate:!0,style:Y,zIndex:1002,plugins:[BV({name:"temperatureNumeric",rules:[{allowChars:/[0-9.]/},{allow:/^\d*\.?\d*$/}]})],onValidationError:(C)=>{if(C?.plugin!=="temperatureNumeric")return;let b=globalThis.__VT_SHOW_COPY_TOAST__;if(typeof b==="function")b('Temperature: only numbers and "."')}})),U0(N6,{x:0,y:z,w:_,h:H,border:!0,title:"Base URL (OpenAI-compatible)",padding:0,style:Z,clear:!0},()=>U0(J6,{x:0,y:0,w:Math.max(0,_-2),h:E,modelValue:$.baseUrl,"onUpdate:modelValue":(C)=>J.updateBaseUrl(C),placeholder:"https://api.openai.com/v1",cursorToEndOnFirstFocus:!0,cursorToEndOnExternalUpdate:!0,style:Y,zIndex:1002})),M?U0(t,{x:0,y:P,w:_,value:$.apiKeyMasked?`Current: ${$.apiKeyMasked}`:"Current: (not set)",style:X}):null,U0(N6,{x:0,y:A,w:_,h:H,border:!0,title:"API Key",padding:0,style:Z,clear:!0},()=>U0(J6,{x:0,y:0,w:Math.max(0,_-2),h:E,modelValue:$.apiKeyDraft,"onUpdate:modelValue":(C)=>J.updateApiKeyDraft(C),placeholder:"Paste a new key to update (leave empty to keep)",secret:!0,cursorToEndOnFirstFocus:!0,cursorToEndOnExternalUpdate:!0,style:Y,zIndex:1002})),U0(N6,{x:0,y:k,w:_,h:L,border:!0,title:"Interleaved Thinking",padding:0,style:Z,clear:!0},()=>U0(J6,{x:0,y:0,w:Math.max(0,_-2),h:v,modelValue:$.interleavedThinking?"1":"0","onUpdate:modelValue":(C)=>J.updateInterleavedThinking(C.trim()==="1"),placeholder:"0 or 1",cursorToEndOnFirstFocus:!0,cursorToEndOnExternalUpdate:!0,style:Y,zIndex:1002}))])}var UX=V1$({name:"GoatChainConfigDialog",props:{modelValue:{type:Boolean,required:!0},w:{type:Number,default:74},h:{type:Number,default:24},backdrop:{type:Boolean,default:!1},modelId:{type:String,required:!0},contextWindow:{type:String,required:!0},temperature:{type:String,required:!0},interleavedThinking:{type:Boolean,required:!0},baseUrl:{type:String,required:!0},apiKeyDraft:{type:String,required:!0},apiKeyMasked:{type:String,required:!0}},emits:{"update:modelValue":($)=>!0,"update:modelId":($)=>!0,"update:contextWindow":($)=>!0,"update:temperature":($)=>!0,"update:interleavedThinking":($)=>!0,"update:baseUrl":($)=>!0,"update:apiKeyDraft":($)=>!0,apply:()=>!0,cancel:()=>!0},setup($,{emit:J}){return()=>{return hv({modelValue:$.modelValue,w:$.w,h:$.h,backdrop:$.backdrop,modelId:$.modelId,contextWindow:$.contextWindow,temperature:$.temperature,interleavedThinking:$.interleavedThinking,baseUrl:$.baseUrl,apiKeyDraft:$.apiKeyDraft,apiKeyMasked:$.apiKeyMasked},{updateModelValue:(U)=>J("update:modelValue",U),updateModelId:(U)=>J("update:modelId",U),updateContextWindow:(U)=>J("update:contextWindow",U),updateTemperature:(U)=>J("update:temperature",U),updateInterleavedThinking:(U)=>J("update:interleavedThinking",U),updateBaseUrl:(U)=>J("update:baseUrl",U),updateApiKeyDraft:(U)=>J("update:apiKeyDraft",U),apply:()=>J("apply"),cancel:()=>J("cancel")})}}});import{computed as Yj,defineComponent as X1$,h as l0,ref as Zj,watch as Y1$}from"vue";var _X=["goatchain","mono","contrast"],uv=["inherit",...hV];function mv($,J,U){return Math.max(J,Math.min(U,$))}function cv($){if(!$)return 0;let J=hV.indexOf($);return J>=0?J+1:0}function QX($){if($<=0)return;return hV[$-1]}var dv=X1$({name:"GoatChainThemeDialog",props:{modelValue:{type:Boolean,required:!0},preset:{type:String,required:!0},overrides:{type:Object,required:!0}},emits:{"update:modelValue":($)=>!0,"update:preset":($)=>!0,setOverride:($,J)=>!0,resetOverrides:()=>!0},setup($,{emit:J}){let U=Zj(0),Q=Zj(0),_=Zj(0),G=Yj(()=>{return RU[mv(U.value,0,RU.length-1)]});Y1$([()=>$.modelValue,G,()=>$.overrides],()=>{if(!$.modelValue)return;let K=$.overrides[G.value];Q.value=cv(K?.fg),_.value=cv(K?.bg)},{immediate:!0});function V(K){Q.value=K;let F=QX(K),N=QX(_.value);J("setOverride",G.value,!F&&!N?null:{fg:F,bg:N})}function X(K){_.value=K;let F=QX(Q.value),N=QX(K);J("setOverride",G.value,!F&&!N?null:{fg:F,bg:N})}let Z=Yj(()=>{let K={preset:$.preset,overrides:$.overrides};return k1(K,G.value)}),Y=Yj(()=>{let K=_X.indexOf($.preset);return K>=0?K:0});return()=>{if(!$.modelValue)return null;let K={fg:"black",bg:"blueBright",bold:!0},F={fg:"whiteBright",bg:"blackBright"},N={fg:"whiteBright",bold:!0},q={fg:"white",dim:!0};return l0(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(H)=>J("update:modelValue",H),onKeydownCapture:(H)=>{if(H?.key==="Escape"){H.preventDefault?.(),H.stopPropagation?.(),J("update:modelValue",!1);return}if(typeof H?.key==="string"&&H.key.length===1&&!H.ctrlKey&&!H.metaKey&&!H.altKey)H.preventDefault?.(),H.stopPropagation?.()},w:64,h:19,title:"Theme",placement:"center",backdrop:!1,padding:1,style:{fg:"blueBright",bg:"black"},buttons:[{label:"Reset Overrides",value:"reset"},{label:"Close",value:"close",kind:"primary",default:!0}],onConfirm:(H)=>{if(H?.value==="reset")J("resetOverrides");J("update:modelValue",!1)},onClose:()=>J("update:modelValue",!1)},()=>[l0(t,{x:0,y:0,w:60,value:"Preset",style:N}),l0(q0,{x:0,y:1,w:60,h:3,options:[..._X],modelValue:Y.value,"onUpdate:modelValue":(H)=>{let E=_X[mv(H,0,_X.length-1)]??"goatchain";J("update:preset",E)},autoFocus:!0,style:F,highlightStyle:K}),l0(t,{x:0,y:5,w:24,value:"Message Type",style:N}),l0(q0,{x:0,y:6,w:24,h:4,options:[...RU],modelValue:U.value,"onUpdate:modelValue":(H)=>U.value=H,style:F,highlightStyle:K}),l0(t,{x:28,y:5,w:10,value:"fg",style:N}),l0(t,{x:46,y:5,w:10,value:"bg",style:N}),l0(q0,{x:28,y:6,w:16,h:4,options:[...uv],modelValue:Q.value,"onUpdate:modelValue":(H)=>V(H),style:F,highlightStyle:K}),l0(q0,{x:46,y:6,w:16,h:4,options:[...uv],modelValue:_.value,"onUpdate:modelValue":(H)=>X(H),style:F,highlightStyle:K}),l0(t,{x:0,y:11,w:60,value:"Preview",style:N}),l0(t,{x:0,y:12,w:60,value:` ${G.value} `,style:{fg:Z.value.fg??"whiteBright",bg:Z.value.bg??"black"}}),l0(t,{x:0,y:14,w:60,value:'Tip: set fg/bg to "inherit" to use preset.',style:q})])}}});import{defineComponent as Z1$,h as P_,ref as K1$,watch as N1$}from"vue";function F1$($,J){let Q=Math.max(20,Math.floor(J/1));return Math.max(1,Math.ceil($.length/Q))}var GX=Z1$({name:"GoatChainToolApprovalsDialog",props:{modelValue:{type:Boolean,required:!0},mode:{type:String,required:!0},w:{type:Number,required:!0},h:{type:Number,required:!0}},emits:{"update:modelValue":($)=>!0,select:($)=>!0},setup($,{emit:J}){function U(G,V,X){return Math.max(V,Math.min(X,G))}let Q=K1$(0);function _(G){return G==="all"?1:0}return N1$([()=>$.modelValue,()=>$.mode],([G])=>{if(!G)return;Q.value=_($.mode)},{immediate:!0}),()=>{if(!$.modelValue)return null;let G=Math.max(0,$.w-4),V={fg:"black",bg:"blueBright",bold:!0},X={fg:"whiteBright",dim:!0,bg:"black"},Z={fg:"white",dim:!0,bg:"blackBright"},Y=[{label:"Use Auto",value:"auto"},{label:"Use All",value:"all"},{label:"Close",value:"close"}],K=U(Q.value,0,Y.length-1),F=Y[K]?.value??"auto",N=F==="auto"?"AUTO":F==="all"?"ALL":"CLOSE",q=F==="auto"?"Auto-approve low-risk tools. Prompt before high-risk tools (e.g. network/shell/write).":F==="all"?"Auto-approve everything. No approval prompts (fastest, least safe).":"Close this dialog without changing the current setting.",H=0,E=H+2,B=F1$(q,G),j=E+1,f=2,R=j+B+1,I=R+f,w=Math.max($.h,I+4);return P_(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(T)=>J("update:modelValue",T),onKeydownCapture:(T)=>{if(T?.key==="Escape"){T.preventDefault?.(),T.stopPropagation?.(),J("update:modelValue",!1);return}if(typeof T?.key==="string"&&T.key.length===1&&!T.ctrlKey&&!T.metaKey&&!T.altKey)T.preventDefault?.(),T.stopPropagation?.()},onKeydown:(T)=>{if(T?.key!=="ArrowLeft"&&T?.key!=="ArrowRight")return;let z=T.key==="ArrowLeft"?-1:1;Q.value=U(Q.value+z,0,Y.length-1)},w:$.w,h:w,title:"Tool Approvals",placement:"center",backdrop:!1,padding:1,style:{fg:"blueBright",bg:"black"},buttons:[{label:"Use Auto",value:"auto",kind:$.mode==="auto"?"primary":void 0,default:$.mode==="auto"},{label:"Use All",value:"all",kind:$.mode==="all"?"primary":void 0,default:$.mode==="all"},{label:"Close",value:"close"}],onConfirm:(T)=>{if(T?.value==="auto")J("select","auto");else if(T?.value==="all")J("select","all");J("update:modelValue",!1)},onClose:()=>J("update:modelValue",!1)},()=>[P_(t,{x:0,y:H,w:G,value:`Current: ${$.mode}`,style:{fg:"white",dim:!0,bg:"blackBright"}}),P_(t,{x:0,y:E,w:G,value:N,style:V}),P_(t,{x:0,y:j,w:G,h:B,wrap:!0,value:q,style:Z}),P_(t,{x:0,y:R,w:G,h:2,wrap:!0,value:"Tip: use ←/→ to move between buttons, Enter to confirm, Esc to close.",style:X})])}}});function lv($){return[Kj(dv,{modelValue:$.showTheme.value,"onUpdate:modelValue":(J)=>$.showTheme.value=J,preset:$.store.state.ui.theme.preset,"onUpdate:preset":(J)=>$.store.setThemePreset(J),overrides:$.store.state.ui.theme.overrides,onSetOverride:(J,U)=>$.store.setMessageTypeThemeOverride(J,U),onResetOverrides:()=>$.store.resetThemeOverrides()}),Kj(UX,{modelValue:$.showConfig.value,"onUpdate:modelValue":(J)=>$.showConfig.value=J,w:$.configW.value,h:$.configH.value,modelId:$.modelId.value,"onUpdate:modelId":(J)=>$.modelId.value=J,contextWindow:$.contextWindow.value,"onUpdate:contextWindow":(J)=>$.contextWindow.value=J,temperature:$.temperature.value,"onUpdate:temperature":(J)=>$.temperature.value=J,interleavedThinking:$.interleavedThinking.value,"onUpdate:interleavedThinking":(J)=>$.interleavedThinking.value=J,baseUrl:$.baseUrl.value,"onUpdate:baseUrl":(J)=>$.baseUrl.value=J,apiKeyDraft:$.apiKeyDraft.value,"onUpdate:apiKeyDraft":(J)=>$.apiKeyDraft.value=J,apiKeyMasked:$.apiKeyMasked.value,onApply:$.applyConfig,onCancel:$.closeConfig}),Kj(GX,{modelValue:$.showToolApprovals.value,"onUpdate:modelValue":(J)=>$.showToolApprovals.value=J,mode:String($.store.state.approval.mode??"auto"),w:$.toolApprovalsW.value,h:$.toolApprovalsH.value,onSelect:(J)=>{$.applyToolApprovals(J),$.showToolApprovals.value=!1}})]}import{h as VX}from"vue";function XX($){if(!$.visible.value)return[];let J=String($.text.value??"").trim();if(!J)return[];let U=typeof $.cols==="number"?$.cols:$.cols.value,Q=/\bfail(ed)?\b/i.test(J)||/\berror\b/i.test(J),G=J==="Copied"?"Copied to clipboard":J,V="blackBright",X="whiteBright",Z=Q?"redBright":"cyanBright",Y=1,K=3,F=1,N=Math.max(0,Math.floor(U??0)),q=Math.max(22,Math.min(56,N-4)),H=Math.min(28,q),E=M$(G)+Y*2+K*2,D=Math.min(Math.max(E,H),q),B=Math.max(1,D-Y*2-K*2),j=m4(G,B),f=M$(j),R=Math.max(0,Math.floor((B-f)/2)),I=h6(`${I4(R)}${j}`,B),w=1+F*2,T=Math.max(2,N-D-2),z=1;return[VX(t,{key:"copy-toast-bg",x:T,y:z,w:D,h:w,value:I4(D),style:{bg:V},zIndex:220}),VX(t,{key:"copy-toast-accent-left",x:T,y:z,w:Y,h:w,value:I4(Y),style:{bg:Z},zIndex:221}),VX(t,{key:"copy-toast-accent-right",x:T+D-Y,y:z,w:Y,h:w,value:I4(Y),style:{bg:Z},zIndex:221}),VX(t,{key:"copy-toast-text",x:T+Y+K,y:z+F,w:B,h:1,value:I,style:{fg:X,bg:V,bold:!0},zIndex:222})]}function iv($){return XX({visible:$.copyToastVisible,text:$.copyToastText,cols:$.cols})}import{h as YX}from"vue";function ZX($){let J=[],U=$.notification;if(!U?.visible)return J;let Q=String(U.message??"").trim();if(!Q)return J;let _=Q.startsWith("Update available")?"update":Q.startsWith("Update installed")||Q.startsWith("No updates")?"ok":Q.startsWith("Auto-update failed")||Q.startsWith("Update check failed")?"error":"info",G=_==="update"?"[UPDATE]":_==="ok"?"[OK]":_==="error"?"[ERROR]":"[INFO]",V=_==="update"?{bg:"blue",fg:"whiteBright",accentBg:"cyanBright"}:_==="ok"?{bg:"green",fg:"whiteBright",accentBg:"greenBright"}:_==="error"?{bg:"red",fg:"whiteBright",accentBg:"redBright"}:{bg:"blackBright",fg:"white",accentBg:"blueBright"},X=2,Z=2,Y=1,K=`${G} ${Q}`,F=Math.max(0,Math.floor($.cols??0)),N=Math.max(30,F-4),q=Math.min(64,N),H=M$(K)+X+Z*2,E=Math.min(Math.max(H,q),N),D=Math.max(1,E-X-Z*2),B=3,j=[...K0(K,D)];if(j.length>B){j=j.slice(0,B);let w=B-1;if(D>1)j[w]=`${m4(j[w],D-1)}…`;else j[w]="…"}let f=Math.max(1,j.length)+Y*2,R=Math.max(2,F-E-2),I=1;return J.push(YX(t,{key:"upgrade-toast-bg",x:R,y:I,w:E,h:f,value:I4(E),style:{bg:V.bg},zIndex:200}),YX(t,{key:"upgrade-toast-accent",x:R,y:I,w:X,h:f,value:I4(X),style:{bg:V.accentBg},zIndex:201}),YX(t,{key:"upgrade-toast-text",x:R+X+Z,y:I+Y,w:D,h:j.length,value:j.join(`
|
|
944
|
-
`),style:{fg:V.fg,bg:V.bg,bold:!0},zIndex:202})),J.push(YX(R4,{key:"upgrade-toast-hit",x:R,y:I,w:E,h:f,zIndex:210,focusable:!0,onClick:()=>{$.onDismiss?.(),$.onFocus?.()}})),J}function rv($){return ZX({notification:$.store.upgradeNotification.value,cols:$.cols.value,onDismiss:()=>{$.store.dismissUpgradeNotification(),$.focusBrowserTextarea()}})}var nv=W1$({name:"GoatChainChatOverlays",setup(){let $=q1$(H0);if(!$)throw Error("GoatChainChatOverlays missing ChatPageContext");let J=$;return()=>[...zv(J),...Sv(J),...xv(J),...lv(J),...vv(J),...Dv(J),...Iv(J),...Av(J),...iv(J),...rv(J)]}});import{computed as M_,defineComponent as H1$,h as R8,inject as B1$,onBeforeUnmount as O1$,ref as Nj}from"vue";function j1$($){if(!Number.isFinite($)||$<=0)return"0 B/s";if($<1024)return`${$.toFixed(0)} B/s`;if($<1048576)return`${($/1024).toFixed(1)} KB/s`;return`${($/1048576).toFixed(1)} MB/s`}var pv=H1$({name:"GoatChainDebugPerfPanel",setup(){let $=B1$(H0);if(!$)throw Error("GoatChainDebugPerfPanel missing ChatPageContext");let J=$,{scheduler:U,defaultStyle:Q}=L4(),_=M_(()=>J.nodeLike&&Boolean(J.store.state?.ui?.debugPerfPanel)),G=XO(),V=Nj(""),X=Nj(""),Z=Nj(""),Y=setInterval(()=>{if(!_.value)return;try{let E=Number(G.fps)||0,D=Number(G.writeEmaMs)||0,B=Number(G.bytesPerSec)||0;Z.value=`cells ${J.cols.value}x${J.rows.value}`,X.value=`fps ${E.toFixed(1)} write ${D.toFixed(1)}ms ${j1$(B)}`}catch{Z.value="",X.value=""}try{let E=globalThis?.process?.memoryUsage?.(),D=Number(E?.rss??0),B=Number(E?.heapUsed??0);V.value=`mem rss=${(D/1048576).toFixed(1)}MB heap=${(B/1048576).toFixed(1)}MB`}catch{V.value=""}U?.invalidate?.()},500);Y.unref?.(),O1$(()=>clearInterval(Y));let K=M_(()=>Math.min(48,Math.max(28,J.cols.value-4))),F=M_(()=>Math.max(0,J.cols.value-K.value-1)),N=M_(()=>1),q=M_(()=>{let E=String(J.store.state.sessionId??"").trim(),D=J.store.state.context?.env??{},B=String(D.GOATCHAIN_STATE_DIR??globalThis?.process?.env?.GOATCHAIN_STATE_DIR??"").trim();if(!E||!B)return"";try{return E$("node:path").join(B,E)}catch{return""}});async function H(E){if(!J.nodeLike)return;if(!E?.metaKey&&!E?.ctrlKey)return;let D=q.value;if(!D||D.includes("\x00"))return;try{let{spawn:B}=await import("node:child_process"),j=globalThis.process,f=String(j?.platform||"");B(f==="darwin"?"open":f==="win32"?"explorer.exe":"xdg-open",[D],{shell:!1,detached:!0,stdio:"ignore"}).unref()}catch{}}return()=>{if(!_.value)return null;let E=K.value,D=F.value,B=N.value,j=Z.value,f=X.value,R=q.value,I=R?`ctrl+click: ${R}`:"ctrl+click: (no session dir)",w={...Q.value,dim:!0};return R8(R4,{x:D,y:B,w:E,h:6,zIndex:50,focusable:!1},()=>[R8(N6,{x:0,y:0,w:E,h:6,border:!0,title:"Debug",padding:0,style:{fg:"yellowBright"}}),R8(t,{x:1,y:1,w:E-2,value:j,style:w}),R8(t,{x:1,y:2,w:E-2,value:f,style:w}),R8(t,{x:1,y:3,w:E-2,value:V.value,style:w}),R8(t,{x:1,y:4,w:E-2,value:I,style:{...w,fg:R?"cyanBright":"white"}}),R8(R4,{x:1,y:4,w:E-2,h:1,focusable:!1,onClick:H})])}}});import{appendFileSync as D1$}from"node:fs";import{computed as f6,ref as av,watch as ov}from"vue";function O4($,J,U){return Math.max(J,Math.min(U,$))}var E1$="";function P1$($){let J=String($||"");if(!J)return"[file]";return`[${J.split(/[/\\]/).filter(Boolean).pop()??J}]`}function Fj($,J,U=[]){if(J<=0)return 1;let Q=0,_="";for(let G of String($)){if(G===E1$){_+=P1$(U[Q]??""),Q++;continue}_+=G}return K0(_,J).length||1}function tv($){let J=f6(()=>Math.max(0,$.cols.value??0)),U=f6(()=>Math.max(0,$.rows.value??0)),Q=f6(()=>Math.max(0,J.value)),_=3,G=1,V=4,X=1,Z=2,Y=4,K=1,F=2,N=2,q=f6(()=>{return Math.max(1,Math.max(0,Q.value-4)-4-2)}),H=f6(()=>Fj($.input.value,q.value,$.mentions.value)),E=f6(()=>{return O4(H.value+1,2,4)}),D=f6(()=>H.value+1>4?1:0),B=f6(()=>$.hasRevertedMessages.value?3:1),j=f6(()=>E.value+D.value+1),f=f6(()=>j.value+2),R=f6(()=>Math.max(0,U.value-4-f.value-2-B.value)),I=4,w=f6(()=>4+R.value+B.value+1),T=f6(()=>Math.max(0,Q.value-4)),z=f6(()=>2),S=f6(()=>z.value+1+1),O=f6(()=>Math.max(1,T.value-4-2));return{contentW:J,contentH:U,mainW:Q,mainH:R,mainY:4,panelW:T,panelX:z,panelTopY:w,panelH:j,inputX:S,inputInnerW:O,inputLines:E,modelRowGap:D,inputWrapWidth:q,footerH:2,contentPadX:1}}function sv($){let J=av(0),U=av(!0),Q=f6(()=>Math.max(0,$.lines.value.length-$.mainH.value));ov([()=>$.lines.value.length,()=>$.mainH.value],()=>{if(U.value)J.value=Q.value;else J.value=O4(J.value,0,Q.value)},{immediate:!0});let _=f6(()=>{return $.lines.value.slice(J.value,J.value+$.mainH.value)}),G="GHOSTTY_RESOURCES_DIR"in globalThis.process?.env||!1,V=Q_(),X=0,Z=0,Y=0,K=String(globalThis.process?.env?.GOATCHAIN_SCROLL_DEBUG??"")==="1",F=String(globalThis.process?.env?.GOATCHAIN_SCROLL_DEBUG_PATH??"/tmp/goatchain-scroll-debug.log");function N(H){if(!K)return;try{D1$(F,`${H}
|
|
945
|
-
`)}catch{}}ov(Q,(H,E)=>{N(`[${Date.now()}] [CHAT_SCROLL] maxScroll ${E} -> ${H} stick=${U.value?1:0} top=${J.value}`)});function q(H){let E=H.deltaY??0;if(!E)return;let D=Date.now();if(G&&Number.isInteger(E)&&Math.abs(E)===1&&X!==0){let R=E>0?1:-1,I=D-Z;if(R===-X&&I>=0&&I<160){if(Y+=1,Y<2){N(`[${D}] [CHAT_SCROLL] wheel suppressed dy=${E} dt=${I} top=${J.value} lastAppliedDir=${X}`),H.preventDefault?.();return}V.accumulator=0,N(`[${D}] [CHAT_SCROLL] wheel reversal confirmed dy=${E} dt=${I} top=${J.value} lastAppliedDir=${X}`)}else Y=0}else Y=0;let{nextTop:B,dir:j,lines:f}=G_(V,E,J.value,Q.value,D);if(N(`[${D}] [CHAT_SCROLL] wheel dy=${E} top=${J.value} max=${Q.value} stick=${U.value?1:0} -> next=${B} dir=${j} lines=${f} ghostty=${G?1:0}`),!j||B===J.value){H.preventDefault?.();return}if(j<0&&U.value)U.value=!1;if(J.value=O4(B,0,Q.value),X=j,Z=D,j>0&&J.value===Q.value&&!U.value)U.value=!0}return{scrollTop:J,stickToBottom:U,maxScroll:Q,visibleLines:_,onWheel:q}}import{computed as X1,ref as TU,watch as KX}from"vue";function Wj($){let J=$.permission,U=String($.riskLevel??"").trim().toLowerCase();if(J==="require_action")return!0;if(!U)return!0;return U==="high"||U==="critical"}function SU($,J){return $==="all"||$==="auto"&&!Wj(J)}function ev($,J){if($==="all")return!0;return J==="require_action"}function $C($){let J=TU(!1),U=TU(0),Q=TU(!1),_=TU(!1),G=TU(!1),V=TU(!1),X=X1(()=>$.store.state.approval.active),Z=X1(()=>{let I=Math.min(86,Math.max(1,$.contentW.value)),w=Math.min(46,I),T=Math.floor($.contentW.value*0.5);return O4(T,w,I)}),Y=X1(()=>O4(11,9,Math.max(9,$.rows.value-6))),K=X1(()=>$.store.state.paused?.kind==="ask_user"?$.store.state.paused:null),F=X1(()=>O4(Math.floor($.contentW.value*0.62),40,90)),N=X1(()=>O4(18,14,Math.max(14,$.rows.value-4))),q=X1(()=>O4(Math.floor($.contentW.value*0.78),56,84)),H=X1(()=>O4(24,18,Math.max(18,$.rows.value-4))),E=X1(()=>O4(Math.floor($.contentW.value*0.62),46,86)),D=X1(()=>O4(14,11,Math.max(11,$.rows.value-6)));function B(I){if(String($.store.state.approval.mode??"auto")==="all")return!1;return Wj(I)}KX(()=>X.value?.id??null,()=>{let I=X.value;if(I&&I.status==="pending"&&B(I))_.value=!0;else _.value=!1},{immediate:!0}),KX(()=>$.store.state.approval.mode,()=>{let I=X.value;if(!I||I.status!=="pending"||!B(I))_.value=!1}),KX(()=>K.value?.toolCallId??null,(I)=>{G.value=Boolean(I)});let j=X1(()=>J.value||Q.value||$.showSessions.value||$.showSwitchConfirm.value||$.showMessageActions.value||$.showRedoConfirm.value||$.showConfig.value||$.showToolApprovals.value||$.showRenameSession.value||_.value||$.showPathPicker.value||G.value||V.value);KX(j,(I)=>{if(!I)$.focusMode.value="input"});function f(){J.value=!0,U.value=0}function R(){J.value=!1}return{showCommands:J,commandIndex:U,showTheme:Q,showApproval:_,showAskUser:G,showExitConfirm:V,activeApproval:X,approvalW:Z,approvalH:Y,activeAskUser:K,askUserW:F,askUserH:N,configW:q,configH:H,toolApprovalsW:E,toolApprovalsH:D,anyDialogOpen:j,openCommandPalette:f,closeCommandPalette:R}}function JC($){function J(Y){let K=Y.trim();return K===""||K==="/"}function U(Y){let K=Y?.currentTarget?.id;if(typeof K==="string"&&K)$.events.value?.focus?.(K)}function Q(){return $.focusMode.value==="messages"}function _(Y,K){let F=Boolean(K?.allowAlt),N=Boolean((Y.metaKey||Y.ctrlKey)&&!Y.altKey),q=Boolean(Y.altKey&&!Y.metaKey&&!Y.ctrlKey);if(!(Y.key==="c"||Y.key==="C"))return!1;if(!$.hasMessageSelection.value)return!1;if(!N&&!(F&&q))return!1;let D=$.getSelectedMessageText();if(!D)return!1;return Y.stopPropagation?.(),Y.preventDefault?.(),$.copyTextToClipboard(D).then((B)=>$.showCopyToast(B?"Copied":"Copy failed")).catch(()=>$.showCopyToast("Copy failed")),!0}function G(Y){if($.anyDialogOpen.value)return;if(_(Y,{allowAlt:!1}),Y.key==="ArrowUp"){Y.preventDefault?.(),$.moveToolSelection(-1),U(Y);return}if(Y.key==="ArrowDown"){Y.preventDefault?.(),$.moveToolSelection(1),U(Y);return}if(Y.key==="Enter"){if(!$.selectedToolCallId.value)return;Y.preventDefault?.(),$.runSelected().finally(()=>U(Y))}}function V(Y){if($.showExitConfirm.value){if(Y.key==="Escape"){Y.preventDefault?.(),$.showExitConfirm.value=!1;return}if(Y.key==="Enter"){Y.preventDefault?.(),$.showExitConfirm.value=!1,$.exitSessionToHome();return}if(typeof Y?.key==="string"&&Y.key.length===1&&!Y.ctrlKey&&!Y.metaKey&&!Y.altKey){Y.preventDefault?.(),Y.stopPropagation?.();return}}if($.showApproval.value&&Y.key==="Enter"){Y.preventDefault?.(),Y.stopPropagation?.(),$.store.approve();return}if(Y.defaultPrevented)return;if((Y.ctrlKey||Y.metaKey)&&(Y.key==="p"||Y.key==="P")){Y.preventDefault?.(),$.openCommandPalette();return}if(Y.key==="Tab"&&!Y.metaKey&&!Y.ctrlKey&&!Y.altKey){Y.preventDefault?.(),$.cycleUiMode(Y.shiftKey?-1:1);return}if((Y.ctrlKey||Y.metaKey)&&(Y.key==="k"||Y.key==="K")){Y.preventDefault?.(),$.openConfig();return}if(!$.anyDialogOpen.value&&Y.key==="Enter"){if(!$.selectedToolCallId.value)return;if($.input.value.trim())return;Y.preventDefault?.(),$.runSelected();return}if(Y.defaultPrevented)return;let K=Fj($.input.value,$.inputWrapWidth.value,$.mentions?.value??[]);if(Y.key==="ArrowUp"){if(K>1)return;if($.history.value.length===0)return;Y.preventDefault?.(),$.historyIndex.value=O4($.historyIndex.value-1,0,$.history.value.length-1),$.input.value=$.history.value[$.historyIndex.value]??"";return}if(Y.key==="ArrowDown"){if(K>1)return;if($.history.value.length===0)return;if(Y.preventDefault?.(),$.historyIndex.value>=$.history.value.length-1){$.historyIndex.value=$.history.value.length,$.input.value="";return}$.historyIndex.value=O4($.historyIndex.value+1,0,$.history.value.length-1),$.input.value=$.history.value[$.historyIndex.value]??""}if(Y.key==="Escape"&&J($.input.value)){if(Y.preventDefault?.(),$.isLoading.value){$.store.interrupt();return}$.showExitConfirm.value=!0}}function X(Y){if(_(Y,{allowAlt:$.nodeLike}))return;if($.showApproval.value&&Y.key==="Enter"){if(Y?.__goatchainApprovalDialogHandled)return;if(Y.defaultPrevented)return;Y.stopPropagation?.(),Y.preventDefault?.(),$.store.approve();return}if($.showExitConfirm.value&&Y.key==="Enter"){Y.stopPropagation?.(),Y.preventDefault?.(),$.showExitConfirm.value=!1,$.exitSessionToHome();return}if(Y.defaultPrevented)return;if(!$.anyDialogOpen.value){if((Y.ctrlKey||Y.metaKey)&&!Y.altKey&&(Y.key==="k"||Y.key==="K")){Y.stopPropagation?.(),Y.preventDefault?.(),$.openConfig();return}if((Y.ctrlKey||Y.metaKey)&&!Y.altKey&&(Y.key==="p"||Y.key==="P")){Y.stopPropagation?.(),Y.preventDefault?.(),$.openCommandPalette();return}if(Y.key==="Tab"&&!Y.metaKey&&!Y.ctrlKey&&!Y.altKey){Y.stopPropagation?.(),Y.preventDefault?.(),$.cycleUiMode(Y.shiftKey?-1:1);return}}if((Y.ctrlKey||Y.metaKey)&&!Y.altKey&&(Y.key==="r"||Y.key==="R")){if($.store.hasRevertedMessages.value){Y.stopPropagation?.(),Y.preventDefault?.(),$.showRedoConfirm.value=!0;return}}if(Y.key!=="Escape")return;if(Y.stopPropagation?.(),Y.preventDefault?.(),$.showRedoConfirm.value)$.showRedoConfirm.value=!1;else if($.showCommands.value)$.closeCommandPalette();else if($.showTheme.value)$.showTheme.value=!1;else if($.showSessions.value)$.showSessions.value=!1;else if($.showMessageActions.value)$.showMessageActions.value=!1;else if($.showConfig.value)$.closeConfig();else if($.showToolApprovals.value)$.showToolApprovals.value=!1;else if($.showApproval.value)$.showApproval.value=!1;else if($.showAskUser.value)$.showAskUser.value=!1;else if($.showPathPicker.value)$.closePathPicker();else if($.showExitConfirm.value)$.showExitConfirm.value=!1;else if($.isLoading.value)$.store.interrupt();else if($.hasMessageSelection.value)$.clearMessageSelection();else $.showExitConfirm.value=!0}function Z(Y){if($.anyDialogOpen.value)return;if(Y.key==="Tab"&&!Y.metaKey&&!Y.ctrlKey&&!Y.altKey){Y.stopPropagation?.(),Y.preventDefault?.(),$.cycleUiMode(Y.shiftKey?-1:1);return}if(!Q())return;if(Y.key==="ArrowUp"){Y.stopPropagation?.(),Y.preventDefault?.(),$.moveToolSelection(-1);return}if(Y.key==="ArrowDown"){Y.stopPropagation?.(),Y.preventDefault?.(),$.moveToolSelection(1);return}if(Y.key==="Enter"&&$.selectedToolCallId.value&&!$.input.value.trim())Y.stopPropagation?.(),Y.preventDefault?.(),$.runSelected()}return{onInputKeydown:V,onSelectionKeydown:G,onGlobalKeydown:X,onGlobalKeydownCapture:Z}}function UC($){if($.role==="user")return String($.content??"");if($.role==="tool")return String($.result.output??"");return $.parts.map((J)=>{if(J.type==="markdown")return String(J.markdown??"");if(J.type==="thinking")return String(J.content??"");if(J.type==="status")return String(J.text??"");return""}).filter(Boolean).join(`
|
|
946
|
-
`)}function M1$($){if($.role!=="assistant")return $;let J=$.parts.filter((U)=>U.type!=="status"&&U.type!=="thinking"&&U.type!=="tool_output");return{...$,parts:J}}function _C($,J){let U=$.findIndex((Q)=>Q.id===J);if(U<0)return null;return $.slice(0,U).map(M1$)}async function QC($){let J=$.sessionsApi;if(J&&typeof J.fork==="function"){await J.fork({messages:$.seed});return}if($.sessionsApi){await $.sessionsApi.createNew(),$.store.state.messages.splice(0,$.store.state.messages.length,...$.seed),$.store.state.revertedMessages.splice(0,$.store.state.revertedMessages.length),$.store.state.selectedToolCallId=null;return}$.store.state.sessionId="",$.store.state.messages.splice(0,$.store.state.messages.length,...$.seed),$.store.state.revertedMessages.splice(0,$.store.state.revertedMessages.length),$.store.state.selectedToolCallId=null,$.store.state.usage.prompt_tokens=0,$.store.state.usage.completion_tokens=0,$.store.state.usage.total_tokens=0}import{computed as L1$,shallowRef as qj,triggerRef as z1$}from"vue";function GC($){let J=qj(null),U=qj(null),Q=qj(!1),_={x:0,y:0},G=globalThis.requestAnimationFrame??((S)=>setTimeout(()=>S(Date.now()),16)),V=globalThis.cancelAnimationFrame??clearTimeout,X=null,Z=0,Y=0,K=L1$(()=>{let S=J.value,O=U.value;return Boolean(S&&O&&(S.row!==O.row||S.col!==O.col))});function F(S,O){let M=U.value;if(!M){U.value={row:S,col:O};return}if(M.row===S&&M.col===O)return;M.row=S,M.col=O,z1$(U)}function N(){return Yv($.lines.value,J.value,U.value)}function q(){let S=globalThis.getSelection?.();return typeof S?.toString==="function"?String(S.toString()):""}function H(){if($.nodeLike)return;try{globalThis.document?.querySelector?.("[data-vt-host] textarea")?.focus?.()}catch{}}function E(){if(J.value=null,U.value=null,Q.value=!1,$.hoveredUserMessageId)$.hoveredUserMessageId.value=null}function D(S){if($.focusMode.value="messages",H(),!$.nodeLike&&!S?.altKey)return;let O=(S.cellY??0)-$.mainY,M=(S.cellX??0)-2,P=$.scrollTop.value+O;J.value={row:P,col:Math.max(0,M)},U.value={row:P,col:Math.max(0,M)},Q.value=!0}function B(S){if(!Q.value){let A=(S.cellY??0)-$.mainY,k=$.scrollTop.value+A,L=$.lines.value[k],v=String(L?.messageId??"").trim();if(v&&$.hoveredUserMessageId){if($.store.state.messages.find((b)=>b.id===v)?.role==="user"){if($.hoveredUserMessageId.value!==v)$.hoveredUserMessageId.value=v}else if($.hoveredUserMessageId.value)$.hoveredUserMessageId.value=null}else if($.hoveredUserMessageId?.value)$.hoveredUserMessageId.value=null;return}let O=(S.cellY??0)-$.mainY,M=(S.cellX??0)-2;_.y=O,_.x=M;let P=$.scrollTop.value+O;F(P,Math.max(0,M)),w()}function j(S){if(!Q.value)return;if(Q.value=!1,I(),$.hoveredUserMessageId)$.hoveredUserMessageId.value=null;let O=J.value,M=U.value,P=O&&M&&(O.row!==M.row||Math.abs(O.col-M.col)>1);if(!$.nodeLike)return;if(P)return;if(!P&&O){if(S.target&&S.currentTarget&&S.target!==S.currentTarget)return;let A=$.lines.value[O.row];if(!A?.messageId)return;if($.store.state.messages.find((L)=>L.id===A.messageId)?.role!=="user")return;$.messageActionsTargetId.value=A.messageId,$.showMessageActions.value=!0}}function f(S){if($.nodeLike)return;if(H(),$.focusMode.value="messages",q().trim())return;if(!S?.shiftKey)return;if(S.target&&S.currentTarget&&S.target!==S.currentTarget)return;let O=(S.cellY??0)-$.mainY,M=$.scrollTop.value+O,P=$.lines.value[M];if(!P?.messageId)return;if($.store.state.messages.find((k)=>k.id===P.messageId)?.role!=="user")return;$.messageActionsTargetId.value=P.messageId,$.showMessageActions.value=!0}function R(S){if(q().trim())return;S.preventDefault?.();let O=(S.cellY??0)-$.mainY,M=$.scrollTop.value+O,P=$.lines.value[M];if(!P?.messageId)return;if($.store.state.messages.find((k)=>k.id===P.messageId)?.role!=="user")return;$.messageActionsTargetId.value=P.messageId,$.showMessageActions.value=!0}function I(){if(X!=null)V(X),X=null;Z=0,Y=0}function w(){if(!Q.value){I();return}let S=Math.max(1,$.mainH.value),O=Math.max(0,$.lines.value.length-S),M=_.y,P=Math.max(0,M-(S-1)),A=Math.max(0,-M),k=P>0&&$.scrollTop.value<O,L=A>0&&$.scrollTop.value>0;if(!k&&!L){I();return}if(X==null)Z=0,Y=0,X=G(z)}function T(S){let O=Math.min(10,Math.max(0,S));return Math.min(80,8+O*12+O*O*2)}function z(S){if(X=null,!Q.value)return;let O=Math.max(1,$.mainH.value),M=Math.max(0,$.lines.value.length-O),P=_.y,A=Math.max(0,P-(O-1)),k=Math.max(0,-P),L=0,v=0;if(A>0&&$.scrollTop.value<M)L=1,v=A;else if(k>0&&$.scrollTop.value>0)L=-1,v=k;else{I();return}let C=Z?Math.max(0,S-Z):16;Z=S;let b=T(v);Y+=L*b*(C/1000);let y=Y>0?Math.floor(Y):Math.ceil(Y);if(y!==0){Y-=y;let x=Math.max(0,Math.min(M,$.scrollTop.value+y));if(x!==$.scrollTop.value){$.scrollTop.value=x;let c=$.scrollTop.value+_.y;F(c,Math.max(0,_.x))}}w()}return{messageSelectStart:J,messageSelectEnd:U,isSelecting:Q,hasMessageSelection:K,focusBrowserTextarea:H,getSelectedMessageText:N,getNativeSelectionText:q,clearMessageSelection:E,onMessageClick:f,onMessagePointerDown:D,onMessagePointerMove:B,onMessagePointerUp:j,onMessageContextMenu:R}}import{computed as Y1,onBeforeUnmount as R1$,ref as A1$,watch as w1$}from"vue";function VC($){let J=Y1(()=>{let f=$.store.state.messages.length,R=Math.max(0,Number($.store.state.usage.prompt_tokens)||0),I=Math.max(0,Number($.store.state.usage.completion_tokens)||0),w=R+I,T=`${f.toLocaleString()} msgs · ${w.toLocaleString()} tok`;return $.copyToastVisible.value&&$.copyToastText.value?`${T} ${$.copyToastText.value}`:T});function U(f){if(f>=88)return"●";if(f>=63)return"◕";if(f>=38)return"◑";if(f>=13)return"◔";return"○"}let Q=Y1(()=>{let f=Math.max(0,Number($.store.state.usage.prompt_tokens)||0),R=Math.max(0,Number($.store.state.usage.completion_tokens)||0),I=f+R,w=Math.max(1,Number($.store.state.config.context_window)||128000),T=O4(Math.round(I/w*100),0,100);return`${U(T)} ${T}%`}),_=Y1(()=>{return{build:"■",label:String($.store.state.config.model??"model")}}),G=Y1(()=>$.uiMode.value),V=-1,X=-1,Z=Y1(()=>{let f=$.store.state.messages,R=f.length;if(R!==X){if(X=R,V>=R)V=-1}let I=V>=0?f[V]:void 0;if(!I||I.role!=="assistant"){V=-1;for(let z=f.length-1;z>=0;z--){let S=f[z];if(S&&S.role==="assistant"){V=z,I=S;break}}}if(!I||I.role!=="assistant")return"";let w=I.parts.find((z)=>z.type==="status"),T=String(w?.text??"").trim();return!T||T==="Done."?"":T}),Y=Y1(()=>{return{fg:k1($.store.state.ui.theme,"status").fg??"white",bg:"blackBright",dim:!0}}),K=Y1(()=>Boolean($.store.state.runningToolCallId)||Boolean($.store.state.runningAgentRound)),F=A1$(0),N=10,q=3,H=null,E=Y1(()=>{if(K.value)return!0;return/^thinking\b/i.test(Z.value)});w1$(E,(f)=>{if(f&&!H)H=setInterval(()=>{F.value=(F.value+1)%N},100);else if(!f&&H)clearInterval(H),H=null,F.value=0},{immediate:!0}),R1$(()=>{if(H)clearInterval(H);H=null});let D=Y1(()=>{let f=Z.value;if(!f)return"";return f}),B=Y1(()=>{let f=[];for(let R=0;R<N;R++){let I=(R-F.value+N)%N;f.push(I>=N-q?"■":"·")}return f.join("")}),j=Y1(()=>"Ctrl+K: config Tab: mode Ctrl+P: commands");return{headerStatsDisplay:J,ctxPctChip:Q,modelInfo:_,modeLabel:G,assistantStatusDisplay:D,assistantStatusStyle:Y,isLoading:K,loadingDots:B,footerRight:j}}function qJ(){if(typeof globalThis.window<"u")return!1;let $=globalThis.process;return!!$&&typeof $?.versions?.node==="string"&&typeof $?.cwd==="function"}function XC(){try{let $=globalThis.process;return(typeof $?.cwd==="function"?String($.cwd()):"")||"/"}catch{return"/"}}async function NX($){let J=String($??"");if(!J)return!1;let U=globalThis.navigator;if(U?.clipboard?.writeText)try{return await U.clipboard.writeText(J),!0}catch{}if(qJ())try{let G=globalThis.process,V=String(G?.platform||""),{spawn:X}=await import("node:child_process"),Z=(Y,K)=>new Promise((F)=>{try{let N=X(Y,K,{stdio:["pipe","ignore","ignore"],windowsHide:!0});N.on("error",()=>F(!1)),N.on("close",(q)=>F(q===0)),N.stdin?.write(J,"utf8"),N.stdin?.end()}catch{F(!1)}});if(V==="darwin"){if(await Z("pbcopy",[]))return!0}else if(V==="win32"){if(await Z("cmd",["/c","clip"]))return!0}else{if(await Z("wl-copy",[]))return!0;if(await Z("xclip",["-selection","clipboard"]))return!0;if(await Z("xsel",["--clipboard","--input"]))return!0}}catch{}let Q=globalThis.process;if(Q?.stdout?.write&&Q?.stdout?.isTTY)try{let G=qJ()?(await import("node:buffer")).Buffer.from(J,"utf-8").toString("base64"):btoa(unescape(encodeURIComponent(J)));return Q.stdout.write(`\x1B]52;c;${G}\x07`),!0}catch{}let _=globalThis.document;if(!_?.createElement||!_?.body?.appendChild||typeof _.execCommand!=="function")return!1;try{let G=_.activeElement,V=_.createElement("textarea");V.value=J,V.setAttribute("readonly","true"),V.setAttribute("aria-hidden","true"),V.style.position="fixed",V.style.left="-9999px",V.style.top="-9999px",V.style.opacity="0",_.body.appendChild(V),V.focus(),V.select(),V.setSelectionRange(0,V.value.length);let X=Boolean(_.execCommand("copy"));V.remove();try{G?.focus?.({preventScroll:!0})}catch{G?.focus?.()}return X}catch{return!1}}function FX($){let J=String($??"").trim();if(!J.startsWith("/"))return{kind:"none"};if(J==="/approvals"||J==="/approval")return{kind:"approvals"};if(J.startsWith("/approvals ")||J.startsWith("/approval "))return{kind:"approvals_invalid_args"};if(J==="/settings"||J==="/config")return{kind:"settings"};if(J==="/sessions")return{kind:"sessions"};if(J==="/codexoath")return{kind:"codexoath"};if(J==="/new")return{kind:"new"};if(J==="/redo")return{kind:"redo"};if(J==="/rename")return{kind:"rename_invalid_args"};if(J.startsWith("/rename ")){let U=J.slice(8).trim();if(!U)return{kind:"rename_invalid_args"};return{kind:"rename",title:U}}return{kind:"none"}}function WX($){return[{label:"Sessions",detail:"Pick or create a session (/sessions)",run:$.openSessionsDialog},{label:"New Session",detail:"Start a new session (/new)",run:$.createNewSession},{label:"Settings",detail:"Model + API (/settings, Ctrl+K)",run:$.openConfig},{label:"Tool Approvals",detail:"Configure approvals (/approvals)",run:$.openToolApprovals}]}import{computed as L_,ref as qX}from"vue";function HX($){let J=qX(!1),U=qX("directory"),Q=qX(""),_=qX(null),G=L_(()=>{let N=String($.store.state.context?.cwd??".");if(!$.nodeLike)return N;return J1(XC(),N)}),V=L_(()=>U.value==="directory"?"Select Workspace":"Select File"),X=L_(()=>U.value==="directory"?"Type a path (../ etc). Tab to complete. Enter selects a directory.":"Type a path (../ etc). Tab to complete. Enter selects a file."),Z=L_(()=>O4(Math.min(72,Math.max(32,Math.floor($.cols.value*0.72))),32,Math.max(32,$.cols.value-4))),Y=L_(()=>O4(Math.min(18,Math.max(8,Math.floor($.rows.value*0.55))),8,Math.max(8,$.rows.value-6)));function K(N,q=""){if(!$.nodeLike){_.value="node-only";return}J.value=!0,U.value=N,Q.value=String(q??""),_.value=null}function F(){J.value=!1,Q.value="",_.value=null}return{showPathPicker:J,pathPickerMode:U,pathPickerQuery:Q,pathPickerError:_,pickerWorkspace:G,pickerW:Z,pickerH:Y,pathPickerTitle:V,pathPickerPlaceholder:X,openPathPicker:K,closePathPicker:F}}import{appendFileSync as f1$}from"node:fs";function k1$(){let $=globalThis.process;return Boolean($&&typeof $?.versions?.node==="string")}function I1$(){if(!k1$())return!1;let $=globalThis.process?.env??{},J=String($.GOATCHAIN_DEBUG??"").trim().toLowerCase();return J==="1"||J==="true"||J==="yes"||J==="on"}function S1$(){let $=globalThis.process?.env??{};return String($.GOATCHAIN_DEBUG_LOG??"").trim()||"./goatchain-debug.log"}function b4($,J){if(!I1$())return;let U=String($??"").trim()||"event",_=`[${new Date().toISOString()}] ${U}`;if(J!==void 0)try{_+=` ${JSON.stringify(J)}`}catch{}_+=`
|
|
947
|
-
`;try{f1$(S1$(),_)}catch{}}import{ref as S1,watch as T1$}from"vue";function BX($){let J=S1(!1),U=S1(!1),Q=S1("Switch Session"),_=S1(""),G=S1(""),V=S1(!1),X=S1(!1),Z=S1([]),Y=S1(0),K=S1(null);function F(){let I=$.store.state;if(I.runningAgentRound)return"Agent is still responding";if(I.paused?.kind==="ask_user")return"Awaiting AskUser answers";if(I.paused?.kind==="tool_approval")return"Awaiting tool approval";if(I.approval?.active?.status==="pending")return"Pending approval";return""}function N(){let I=$.store.state;if(I.runningAgentRound)return!0;if(I.paused)return!0;return Boolean(I.approval?.active&&I.approval.active.status==="pending")}async function q(I){if(!$.sessionsApi){$.showToast?.("Sessions are only available in Node/CLI mode."),b4("session_switch_unavailable",{title:I.title,target:I.targetLabel});return}if(!N()){b4("session_switch",{title:I.title,target:I.targetLabel,busy:!1}),await I.run(),U.value=!1,K.value=null,Q.value="Switch Session",_.value="",G.value="",J.value=!1,X.value=!1;return}K.value={run:I.run},Q.value=I.title,_.value=I.targetLabel,G.value=F(),U.value=!0,b4("session_switch_prompt",{title:I.title,target:I.targetLabel,reason:G.value})}async function H(I={}){let w=$.sessionsApi;if(!w){Z.value=[],Y.value=0;return}V.value=!0;try{let T=await w.list();Z.value=T.slice().sort((O,M)=>Number(M?.updatedAt??0)-Number(O?.updatedAt??0));let z=Math.max(0,Z.value.length-1),S=-1;if(I.preferId)S=Z.value.findIndex((O)=>O.id===I.preferId);if(S<0&&typeof I.preferIndex==="number")S=O4(I.preferIndex,0,z);if(S<0){let O=String($.store.state.sessionId??"");S=Z.value.findIndex((M)=>M.id===O)}Y.value=S>=0?S:0}catch{Z.value=[],Y.value=0}finally{V.value=!1}}async function E(){if(!$.sessionsApi){$.showToast?.("Sessions are only available in Node/CLI mode.");return}X.value=!1,J.value=!0,await H()}async function D(I){let w=$.sessionsApi,T=Z.value[Y.value];if(!w||!T)return;await q({title:"Switch Session",targetLabel:String(T.title||T.id),run:async()=>{let z=String($.store.state.sessionId??"");await w.use(T.id),b4("session_switch_run",{from:z,to:String(T.id),kind:"use"}),await I?.after?.()}})}async function B(I){let w=$.sessionsApi;if(!w){$.showToast?.("Sessions are only available in Node/CLI mode.");return}await q({title:"New Session",targetLabel:"a new session",run:async()=>{let T=String($.store.state.sessionId??"");await w.createNew(),b4("session_switch_run",{from:T,to:String($.store.state.sessionId??""),kind:"new"}),await I?.after?.()}})}async function j(){let I=K.value;if(!I)return;U.value=!1,K.value=null,$.store.interrupt(),b4("session_switch_confirm",{title:Q.value,target:_.value,reason:G.value}),await I.run(),J.value=!1,X.value=!1,Q.value="Switch Session",_.value="",G.value=""}function f(){U.value=!1,K.value=null,b4("session_switch_cancel",{title:Q.value,target:_.value,reason:G.value}),Q.value="Switch Session",_.value="",G.value=""}return T1$([J,()=>String($.store.state.sessionId??"").trim()],([I,w])=>{if(!I)return;if(!$.sessionsApi||!w)return;H({preferId:w})}),{showSessions:J,showSwitchConfirm:U,switchConfirmTitle:Q,switchConfirmTargetLabel:_,switchConfirmReason:G,sessionsLoading:V,sessionsDeleteArmed:X,sessionsList:Z,sessionsIndex:Y,refreshSessions:H,openSessionsDialog:E,openSelectedSession:D,createNewSession:B,confirmSwitch:j,cancelSwitch:f}}import{computed as v1$,ref as HJ}from"vue";function YC($){let J=String($??"").trim();if(!J)return"";return`***${J.slice(-4)||"****"}`}function OX($){let J=HJ(!1),U=HJ(!1),Q=HJ(""),_=HJ(""),G=HJ(""),V=HJ(!1),X=HJ(""),Z=HJ(""),Y=v1$(()=>{let D=$.store.state.context?.env??{};return YC(D.OPENAI_API_KEY)});function K(){return $.store.state.paused?.kind==="tool_approval"||$.store.state.approval.active?.status==="pending"}function F(){Q.value="",_.value="",G.value="",V.value=!1,X.value="",Z.value="",J.value=!0,queueMicrotask(()=>{Q.value=String($.store.state.config.model??"").trim()||"deepseek-v3.1",_.value=String($.store.state.config.context_window??128000),G.value=String($.store.state.config.temperature??""),V.value=Boolean($.store.state.config.interleaved_thinking??!1);let D=$.store.state.context?.env??{};X.value=String(D.GOATCHAIN_OPENAI_BASE_URL||D.OPENAI_BASE_URL||""),Z.value=""})}function N(){J.value=!1}function q(){if($.guardPendingApprovals!==!1&&K()){$.showToast("Resolve the pending approval before changing settings.");return}let D=Q.value.trim();if(D)$.store.state.config.model=D;$.store.state.config.context_window=O4(Number.parseInt(_.value||"0",10)||$.store.state.config.context_window,1000,2000000);let B=Number.parseFloat(G.value);$.store.state.config.temperature=Number.isFinite(B)?B:$.store.state.config.temperature,$.store.state.config.interleaved_thinking=V.value,$.store.setEnvVar("GOATCHAIN_MODEL",$.store.state.config.model),$.store.setEnvVar("GOATCHAIN_CONTEXT_WINDOW",String($.store.state.config.context_window)),$.store.setEnvVar("GOATCHAIN_TEMPERATURE",String($.store.state.config.temperature??"")),$.store.setEnvVar("GOATCHAIN_INTERLEAVED_THINKING",V.value?"1":"0"),$.store.setEnvVar("GOATCHAIN_OPENAI_BASE_URL",X.value.trim()||void 0);let j=Z.value.trim();if(j)$.store.setEnvVar("OPENAI_API_KEY",j);if($.nodeLike){let f=globalThis.process;if(f?.env){f.env.GOATCHAIN_MODEL=$.store.state.config.model,f.env.GOATCHAIN_CONTEXT_WINDOW=String($.store.state.config.context_window),f.env.GOATCHAIN_TEMPERATURE=String($.store.state.config.temperature??""),f.env.GOATCHAIN_INTERLEAVED_THINKING=V.value?"1":"0";let R=X.value.trim();if(R)f.env.GOATCHAIN_OPENAI_BASE_URL=R;else delete f.env.GOATCHAIN_OPENAI_BASE_URL;if(j)f.env.OPENAI_API_KEY=j}}Z.value="",N()}function H(){if(K()){$.showToast("Resolve the pending approval before changing settings.");return}U.value=!0}function E(D){if($.store.state.approval.mode=D,$.store.setEnvVar("GOATCHAIN_TOOL_APPROVALS",D),$.nodeLike){let B=globalThis.process;if(B?.env)B.env.GOATCHAIN_TOOL_APPROVALS=D}$.showToast(`Tool approvals: ${D}`)}return{showConfig:J,showToolApprovals:U,modelId:Q,contextWindow:_,temperature:G,interleavedThinking:V,baseUrl:X,apiKeyDraft:Z,apiKeyMasked:Y,openConfig:F,closeConfig:N,applyConfig:q,openToolApprovals:H,applyToolApprovals:E}}U2();function jX($){let J=$.store.state.context?.env??{},U=(V)=>{if(typeof $.store.showUpgradeNotification==="function")$.store.showUpgradeNotification(V);else $.showToast(V)};if($.nodeLike)globalThis.__GOATCHAIN_UPGRADE_TOAST__=U;let Q=String(J.GOATCHAIN_STARTUP_UPGRADE_TOAST??"").trim();if(Q){if(U(Q),$.store.setEnvVar("GOATCHAIN_STARTUP_UPGRADE_TOAST",void 0),$.nodeLike){let V=globalThis.process;if(V?.env)delete V.env.GOATCHAIN_STARTUP_UPGRADE_TOAST}}if($.nodeLike)C1$(J,U);let _=String(J.GOATCHAIN_STARTUP_TOAST??"").trim();if(!_)return;if($.showToast(_),$.store.setEnvVar("GOATCHAIN_STARTUP_TOAST",void 0),!$.nodeLike)return;let G=globalThis.process;if(G?.env)delete G.env.GOATCHAIN_STARTUP_TOAST}async function C1$($,J){try{let[{readFile:U,unlink:Q},_]=await Promise.all([import("node:fs/promises"),import("node:path")]),G=await cG($),V=_.join(G,"upgrade-toast.json"),X=await U(V,"utf8"),Z=JSON.parse(X),Y=String(Z?.message??"").trim();if(await Q(V),Y)J(Y)}catch{}}import{onBeforeUnmount as b1$,ref as ZC}from"vue";function DX($=1200){let J=ZC(!1),U=ZC(""),Q=null,_=(G)=>{if(U.value=String(G??""),J.value=!0,Q)clearTimeout(Q);Q=setTimeout(()=>{J.value=!1,Q=null},Math.max(0,$))};return b1$(()=>{if(Q)clearTimeout(Q);Q=null}),{visible:J,text:U,show:_}}function y1$($,J=120){let U=I0(String($??"")).replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();if(!U)return"";let Q=Math.max(0,Math.floor(J));if(Q>0&&U.length>Q)return`${U.slice(0,Math.max(0,Q-1))}…`;return U}function z_($,J){let U=globalThis.process,Q=J?.stdout??U?.stdout;if(!Q||typeof Q.write!=="function")return;if(!J?.force&&!Q.isTTY)return;let _=y1$($,J?.maxLen??120);if(!_)return;let G="\x1B";Q.write(`${G}]0;${_}${G}\\`)}var Hj=g1$({name:"GoatChainChatPage",setup(){let $=qJ(),J=LU(),U=PV(),Q=p4(),{events:_,scheduler:G}=L4(),V=x1$(E8,null);if(!V)throw Error("GoatChainBridge is missing (did you forget to wrap with <GoatChainProvider />?)");let{store:X,sessions:Z}=V,Y=k6(()=>Q.clipRect?.w??0),K=k6(()=>Q.clipRect?.h??0),F=C0(""),N=k6(()=>{let N$=[];for(let C$ of X.state.messages){if(!C$||C$.role!=="user")continue;let Z4=String(C$.content??""),f4=JJ(Z4).trim();if(!f4)continue;N$.push(f4)}return N$}),q=C0(N.value.length),H=C0([]),E=C0("input"),D=C0(X.getMode?.()??"agent");function B(N$=1){let C$=["plan","agent"],Z4=D.value,a4=(C$.indexOf(Z4)+N$+C$.length)%C$.length,j6=C$[a4]??"agent";D.value=j6,X.setMode?.(j6)}let j=tv({cols:Y,rows:K,input:F,mentions:H,hasRevertedMessages:X.hasRevertedMessages}),{contentW:f,mainW:R,mainH:I,mainY:w,panelW:T,panelX:z,panelTopY:S,panelH:O,inputX:M,inputInnerW:P,inputLines:A,modelRowGap:k,inputWrapWidth:L,footerH:v}=j,C=DX(1200),b=C.visible,y=C.text,x=(N$)=>{C.show(N$),G.invalidate()};if($){let N$=globalThis,C$=N$.__VT_SHOW_COPY_TOAST__,Z4=(f4)=>x(f4);N$.__VT_SHOW_COPY_TOAST__=Z4,KC(()=>{if(N$.__VT_SHOW_COPY_TOAST__===Z4)if(C$)N$.__VT_SHOW_COPY_TOAST__=C$;else delete N$.__VT_SHOW_COPY_TOAST__})}let c=VC({store:X,uiMode:D,copyToastVisible:b,copyToastText:y}),{headerStatsDisplay:s,ctxPctChip:F$,modelInfo:K$,modeLabel:V$,assistantStatusDisplay:Y$,assistantStatusStyle:u$,isLoading:_$,loadingDots:n,footerRight:a}=c,m=OX({store:X,nodeLike:$,showToast:x}),{showConfig:G$,showToolApprovals:L$,modelId:P$,contextWindow:f$,temperature:V4,interleavedThinking:s4,baseUrl:U6,apiKeyDraft:z4,apiKeyMasked:C6,openConfig:o$,closeConfig:F6,applyConfig:A6,openToolApprovals:F4,applyToolApprovals:E4}=m,c4=BX({store:X,sessionsApi:Z,showToast:x}),{showSessions:Q$,showSwitchConfirm:Z$,switchConfirmTitle:k$,switchConfirmTargetLabel:t$,switchConfirmReason:q4,openSelectedSession:_4,createNewSession:Q4,confirmSwitch:n$,cancelSwitch:T$,sessionsLoading:y4,sessionsDeleteArmed:p$,sessionsList:e4,sessionsIndex:z$,refreshSessions:g,openSessionsDialog:h}=c4,q$=HX({store:X,cols:Y,rows:K,nodeLike:$}),{showPathPicker:i,pathPickerMode:p,pathPickerQuery:l,pathPickerError:$$,pickerWorkspace:e,pickerW:D$,pickerH:v$,pathPickerTitle:A$,pathPickerPlaceholder:g$,closePathPicker:c$}=q$;jX({store:X,nodeLike:$,showToast:x});let d$=[{value:"/new",detail:"Start a new session",onSelect:()=>{Q4({after:async()=>J.push("home")}),F.value=""}},{value:"/sessions",detail:"List/pick sessions",onSelect:()=>{h(),F.value=""}},{value:"/settings",detail:"Configure model + API",onSelect:()=>{o$(),F.value=""}},{value:"/approvals",detail:"Configure tool approvals (auto/all)",onSelect:()=>Rj("/approvals")},{value:"/rename",detail:"Rename current session",insert:"",onSelect:()=>{return K2(),!1}}],y$=C0(!1),X4=C0(0),W4=C0(!1),_6=C0(null),i$=C0(null),l$=C0(!1),Y4=$C({store:X,rows:K,contentW:f,focusMode:E,showSessions:Q$,showSwitchConfirm:Z$,showConfig:G$,showToolApprovals:L$,showPathPicker:i,showMessageActions:y$,showRedoConfirm:W4,showRenameSession:l$}),{showCommands:a$,commandIndex:$4,showTheme:x$,showApproval:r$,showAskUser:D4,showExitConfirm:w4,activeApproval:d4,approvalW:$6,approvalH:b6,activeAskUser:k8,askUserW:b0,askUserH:B0,configW:Z1,configH:jJ,toolApprovalsW:RX,toolApprovalsH:bU,anyDialogOpen:yU,openCommandPalette:AX,closeCommandPalette:DJ}=Y4;A8(H,(N$)=>{X.setFocusFiles(N$)});let K1=k6(()=>String(X.state.sessionId??"").trim());A8(K1,(N$)=>{if(!Z||!N$)return;g({preferId:N$})},{immediate:!0}),A8(()=>[K1.value,N.value.length],([N$,C$],Z4)=>{let[f4,a4]=Z4??[void 0,0];if(N$!==f4){q.value=C$;return}if(C$!==a4&&q.value>=a4)q.value=C$;else if(q.value>C$)q.value=C$},{immediate:!0});let I8=k6(()=>{let N$=K1.value;if(!N$)return null;return e4.value.find((C$)=>C$.id===N$)??null}),R_=k6(()=>{return`# ${K1.value||"new"}`}),wX=k6(()=>{return String(I8.value?.title??"").trim()||""}),gU=k6(()=>O4(Math.floor(f.value*0.62),44,86)),EJ=k6(()=>9);function K2(){let N$=K1.value;if(!Z||typeof Z.rename!=="function"){x("Rename is only available in Node/CLI mode.");return}if(!N$){x("No active session to rename.");return}l$.value=!0}function xU(){if(l$.value=!1,String(F.value??"").trim().startsWith("/rename"))F.value="";E.value="input"}function A_(N$){let C$=K1.value;if(!Z||typeof Z.rename!=="function"){x("Rename is only available in Node/CLI mode.");return}if(!C$){x("No active session to rename.");return}let Z4=String(N$??"").trim();if(!Z4){x("Session name cannot be empty.");return}(async()=>{await Z.rename(C$,Z4),await g({preferId:C$}),x(`Renamed session to: ${Z4}`)})()}let S8=k6(()=>{let N$=String(I8.value?.title??"").trim();if(N$)return N$;let C$=String(I8.value?.summary??"").trim();if(C$)return C$;let Z4=X.state.messages.find((a4)=>a4.role==="user");return String(Z4?.content??"").trim()||"New session"});if($){let N$=globalThis.process,C$=String(N$?.env?.GOATCHAIN_TERM_TITLE_BASE??"goatchain").trim()||"goatchain",Z4=(f4)=>{let a4=String(f4??"").trim();z_(a4?`${C$} ${a4}`:C$)};A8(S8,(f4)=>Z4(f4),{immediate:!0}),KC(()=>z_(C$))}let v1=k6(()=>[...WX({openSessionsDialog:()=>void h(),createNewSession:()=>void Q4(),openConfig:o$,openToolApprovals:F4}),{label:"Theme",detail:"Message colors",run:()=>x$.value=!0}]),C1=k6(()=>v1.value.map((N$)=>({label:N$.label,detail:N$.detail})));function fX(N$){if(DJ(),!N$)return;v1.value.find((Z4)=>Z4.label===N$)?.run()}let kX=Jv(),PJ=C0(null),T8=C0(0),IX=k6(()=>{let N$=Math.max(0,R.value-4);return kX({messages:X.state.messages,width:N$,selectedToolCallId:X.state.selectedToolCallId,expandedBashOutputs:X.state.expandedBashOutputs,theme:X.state.ui.theme,dirtyMessageId:PJ.value,dirtySeq:T8.value})}),MJ={get value(){return IX.value}},w_=-1,v8=new Map,SX=k6(()=>{let N$=X.state.messages.length;if(N$===w_&&v8.size>0)return v8;let C$=new Map;for(let Z4 of X.state.messages){let f4=String(Z4?.id??"").trim(),a4=String(Z4?.role??"").trim();if(!f4)continue;if(a4==="user"||a4==="assistant"||a4==="tool")C$.set(f4,a4)}return w_=N$,v8=C$,C$}),f_=k6(()=>{let N$=Array.from(MJ.value.toolLineById.entries());return N$.sort((C$,Z4)=>C$[1]-Z4[1]),N$.map(([C$])=>C$)}),TX=sv({lines:k6(()=>MJ.value.lines),mainH:I}),{scrollTop:r,stickToBottom:J4,maxScroll:g4,visibleLines:Q6,onWheel:N2}=TX,b1=GC({nodeLike:$,store:X,mainY:w,mainH:I,scrollTop:r,lines:k6(()=>MJ.value.lines),focusMode:E,hoveredUserMessageId:i$,messageActionsTargetId:_6,showMessageActions:y$,copyTextToClipboard:NX,showCopyToast:x}),{messageSelectStart:hU,messageSelectEnd:y1,hasMessageSelection:F2,focusBrowserTextarea:n0,getSelectedMessageText:LJ,clearMessageSelection:_0,onMessageClick:W6,onMessagePointerDown:C8,onMessagePointerMove:k_,onMessagePointerUp:I_,onMessageContextMenu:S_}=b1;function mC(N$){if(!N$||N$.type==="none")return;if(n0(),N$.type==="selectToolCall"){X.selectToolCall(X.state.selectedToolCallId===N$.callId?null:N$.callId),E.value="input",vX(),v_();return}if(N$.type==="openApproval"){if(d4.value)r$.value=!0;return}if(N$.type==="toggleItem"){PJ.value=N$.messageId,T8.value++,X.toggleChecklist(N$.messageId,N$.part,N$.itemId);return}if(N$.type==="toggleCollapse"){PJ.value=N$.messageId,T8.value++,X.toggleBlockCollapsed(N$.messageId,N$.part,N$.partIndex);return}if(N$.type==="toggleBashOutput"){X.toggleBashOutput(N$.toolCallId),E.value="input",vX(),v_();return}if(N$.type==="showMessageActions")_6.value=N$.messageId,y$.value=!0}function cC(){let N$=_6.value;if(!N$)return;X.revertFromMessage(N$),y$.value=!1,_6.value=null,J4.value=!0}function dC(){let N$=_6.value;if(!N$)return;let C$=X.state.messages.find((f4)=>f4.id===N$);if(!C$)return;let Z4=UC(C$);if(Z4)NX(Z4).then((f4)=>x(f4?"Copied":"Copy failed")).catch(()=>x("Copy failed"));y$.value=!1,_6.value=null}function lC(){X.restoreRevertedMessages(),W4.value=!1,J4.value=!0}function iC(){W4.value=!1}async function rC(){let N$=_6.value;if(!N$)return;let C$=_C(X.state.messages,N$);if(!C$)return;y$.value=!1,_6.value=null,X4.value=0;try{await QC({sessionsApi:Z,store:X,seed:C$})}catch{x("Failed to fork session.")}J4.value=!0,F.value="",H.value=[]}let T_=k6(()=>X.state.selectedToolCallId);async function nC(){if(!T_.value||X.state.runningToolCallId)return;await X.runToolCall(T_.value)}function pC(N$){let C$=MJ.value.toolLineById.get(N$);if(C$==null)return;let Z4=Math.max(0,C$);if(Z4<r.value){r.value=O4(Z4,0,g4.value);return}let f4=r.value+Math.max(1,I.value)-1;if(C$>f4)r.value=O4(C$-Math.max(1,I.value)+1,0,g4.value)}function aC(N$){let C$=f_.value;if(C$.length===0)return;let Z4=T_.value,f4=Z4?C$.indexOf(Z4):-1,a4=(()=>{if(f4<0)return C$.length-1;let N1=f4+N$;if(N1<0)return C$.length-1;if(N1>=C$.length)return 0;return N1})(),j6=C$[a4];if(!j6)return;X.selectToolCall(j6),pC(j6)}function Rj(N$){let C$=Boolean(X.state.approval.pendingAutoRun)||Boolean(X.state.approval.active&&X.state.approval.active.status==="pending")||X.state.approval.queue.length>0;if(_$.value&&!X.state.paused&&!C$){x("Please wait for the current response to complete, or press Esc to interrupt.");return}let Z4=JJ(N$);Z4=Z4.replaceAll("","");let f4=Z4.trimEnd(),a4=H.value;if(!f4&&a4.length===0)return;let j6=FX(f4);if(j6.kind==="approvals"){F4(),F.value="";return}if(j6.kind==="approvals_invalid_args"){x("Use /approvals (no on/off)."),F.value="";return}if(j6.kind==="settings"){o$(),F.value="";return}if(j6.kind==="sessions"){h(),F.value="";return}if(j6.kind==="new"){Q4({after:async()=>J.push("home")}),F.value="";return}if(j6.kind==="redo"){if(X.hasRevertedMessages.value)W4.value=!0;F.value="";return}if(j6.kind==="rename"){let N1=K1.value;if(!Z||typeof Z.rename!=="function"){x("Rename is only available in Node/CLI mode."),F.value="";return}if(!N1){x("No active session to rename."),F.value="";return}let b8=String(j6.title??"").trim();if(!b8){x("Usage: /rename <title>"),F.value="";return}(async()=>{await Z.rename(N1,b8),await g({preferId:N1}),x(`Renamed session to: ${b8}`)})(),F.value="";return}if(j6.kind==="rename_invalid_args"){K2(),F.value="";return}if(J4.value=!0,a4.length>0)Z4=Z4.replace(/^[\s\u200B]*\]+/u,""),X.sendUserInput({content:Z4,focusFiles:a4});else X.send(Z4);H.value=[],q.value=N.value.length,F.value=""}async function Aj(){if(X.interrupt(),X.state.sessionId="",X.setEnvVar("GOATCHAIN_SESSION_ID",void 0),qJ()){let N$=globalThis.process;if(N$?.env)delete N$.env.GOATCHAIN_SESSION_ID}X.state.messages.splice(0,X.state.messages.length),X.state.revertedMessages.splice(0,X.state.revertedMessages.length),X.state.selectedToolCallId=null,X.state.runningToolCallId=null,X.state.paused=null,X.state.approval.active=null,X.state.approval.pendingAutoRun=null,X.state.approval.queue=[],X.state.approval.decisions={},X.state.approval.approvedToolCalls={},X.state.usage.prompt_tokens=0,X.state.usage.completion_tokens=0,X.state.usage.total_tokens=0,await J.push("home")}A8(()=>U.value.params,(N$)=>{if(N$?.open==="settings")o$(),J.replace("chat")},{immediate:!0});function oC(N$){X.setCwd(N$)}let tC=JC({nodeLike:$,store:X,events:_,input:F,inputWrapWidth:L,mentions:H,history:N,historyIndex:q,focusMode:E,toolCallIds:f_,selectedToolCallId:T_,moveToolSelection:aC,runSelected:nC,anyDialogOpen:yU,showCommands:a$,showTheme:x$,showSessions:Q$,showMessageActions:y$,showRedoConfirm:W4,showConfig:G$,showToolApprovals:L$,showApproval:r$,showAskUser:D4,showPathPicker:i,showExitConfirm:w4,openCommandPalette:AX,closeCommandPalette:DJ,openConfig:o$,closeConfig:F6,closePathPicker:c$,cycleUiMode:B,isLoading:_$,hasMessageSelection:F2,clearMessageSelection:_0,getSelectedMessageText:LJ,copyTextToClipboard:NX,showCopyToast:x,exitSessionToHome:Aj}),{onInputKeydown:sC,onSelectionKeydown:eC,onGlobalKeydown:$b,onGlobalKeydownCapture:Jb}=tC;function vX(){let N$=_.value;if(!N$||typeof N$.debugNodes!=="function"||typeof N$.focus!=="function")return;let C$=Math.floor(M.value),Z4=Math.floor(S.value),f4=Math.floor(P.value),a4=Math.floor(A.value),j6=(N$.debugNodes?.()??[]).filter((g1)=>g1?.visible&&g1?.focusable),N1=j6.find((g1)=>{let y6=g1?.rect;return y6&&y6.x===C$&&y6.y===Z4&&y6.w===f4&&y6.h===a4});if(N1?.id){N$.focus(N1.id);return}let b8=C$+Math.floor(Math.max(0,f4-1)/2),wj=Z4+Math.floor(Math.max(0,a4-1)/2),fj=j6.filter((g1)=>{let y6=g1?.rect;return y6&&b8>=y6.x&&wj>=y6.y&&b8<y6.x+y6.w&&wj<y6.y+y6.h});fj.sort((g1,y6)=>{let Ij=g1?.zIndex??0,Sj=y6?.zIndex??0;if(Sj!==Ij)return Sj-Ij;let Tj=g1?.rect??{w:0,h:0},vj=y6?.rect??{w:0,h:0};return Tj.w*Tj.h-vj.w*vj.h});let kj=fj[0];if(kj?.id)N$.focus(kj.id),G.invalidate()}async function v_(){await h1$(),queueMicrotask(()=>{queueMicrotask(()=>{setTimeout(()=>{n0(),vX()},0)})})}return A8(yU,(N$)=>{if(N$)return;v_()}),A8(_$,(N$,C$)=>{if(N$||!C$)return;if(yU.value||F2.value)return;E.value="input",v_()}),u1$(H0,{nodeLike:$,router:J,store:X,sessionsApi:Z,cols:Y,rows:K,contentW:f,mainY:w,mainW:R,mainH:I,scrollTop:r,visibleLines:Q6,messageRoleById:SX,messageSelectStart:hU,messageSelectEnd:y1,focusMode:E,hoveredUserMessageId:i$,onWheel:N2,onSelectionKeydown:eC,onMessageClick:W6,onMessagePointerDown:C8,onMessagePointerMove:k_,onMessagePointerUp:I_,onMessageContextMenu:S_,onLineClick:mC,focusBrowserTextarea:n0,showCopyToast:x,copyToastVisible:b,copyToastText:y,sessionHeaderTitle:R_,sessionHeaderSummary:S8,headerStatsDisplay:s,panelW:T,panelX:z,panelTopY:S,panelH:O,inputX:M,inputInnerW:P,inputLines:A,modelRowGap:k,input:F,focusFiles:H,pickerWorkspace:e,promptSuggestions:d$,showCommands:a$,showTheme:x$,showSessions:Q$,showMessageActions:y$,showRedoConfirm:W4,showConfig:G$,showToolApprovals:L$,showApproval:r$,showPathPicker:i,showRenameSession:l$,pathPickerMode:p,pathPickerQuery:l,pathPickerError:$$,send:Rj,onInputKeydown:sC,setContextCwd:oC,ctxPctChip:F$,modelInfo:K$,modeLabel:V$,assistantStatusDisplay:Y$,assistantStatusStyle:u$,footerH:v,footerRight:a,isLoading:_$,loadingDots:n,commandOptions:C1,commandIndex:$4,onCommandSelect:fX,closeCommandPalette:DJ,refreshSessions:g,sessionsLoading:y4,sessionsDeleteArmed:p$,sessionsList:e4,sessionsIndex:z$,showSwitchConfirm:Z$,switchConfirmTitle:k$,switchConfirmTargetLabel:t$,switchConfirmReason:q4,openSelectedSession:_4,createNewSession:Q4,confirmSwitch:n$,cancelSwitch:T$,messageActionsIndex:X4,messageActionsTargetId:_6,handleRevertMessage:cC,handleCopyMessage:dC,handleForkSession:rC,confirmRestore:lC,cancelRestore:iC,pickerW:D$,pickerH:v$,pathPickerTitle:A$,pathPickerPlaceholder:g$,configW:Z1,configH:jJ,modelId:P$,contextWindow:f$,temperature:V4,interleavedThinking:s4,baseUrl:U6,apiKeyDraft:z4,apiKeyMasked:C6,applyConfig:A6,closeConfig:F6,toolApprovalsW:RX,toolApprovalsH:bU,applyToolApprovals:E4,activeApproval:d4,approvalW:$6,approvalH:b6,activeAskUser:k8,showAskUser:D4,askUserW:b0,askUserH:B0,renameSessionW:gU,renameSessionH:EJ,renameSessionInitialValue:wX,openRenameSession:K2,applyRenameSession:A_,cancelRenameSession:xU,showExitConfirm:w4,exitSessionToHome:Aj}),()=>BJ(R4,{x:0,y:0,w:Y.value,h:K.value,zIndex:0,focusable:!1,onKeydownCapture:Jb,onKeydown:$b},()=>[BJ(t,{key:"bg",x:0,y:0,w:Y.value,h:K.value,value:"",style:nV,zIndex:-100}),BJ(Vv),BJ(Zv),BJ(Qv),BJ(Gv),BJ(pv),BJ(nv)])}});import{computed as G4,defineComponent as l1$,h as h4,inject as i1$,onBeforeUnmount as r1$,ref as T1,watch as HC}from"vue";import{defineComponent as m1$,h as i0}from"vue";var NC=m1$({name:"GoatChainCodexOAuthDialog",props:{modelValue:{type:Boolean,required:!0},w:{type:Number,default:70},h:{type:Number,default:28},oauthStatus:{type:String,required:!0},oauthEmail:{type:String,required:!0},oauthUrl:{type:String,required:!0},selectedModel:{type:String,default:""},codexModels:{type:Array,default:()=>[]},modelIndex:{type:Number,default:0}},emits:{"update:modelValue":($)=>!0,"update:selectedModel":($)=>!0,"update:modelIndex":($)=>!0,login:()=>!0,logout:()=>!0,close:()=>!0,selectModel:($)=>!0},setup($,{emit:J}){return()=>{if(!$.modelValue)return null;let U=Math.max(48,Math.floor($.w)),Q=Math.max(14,Math.floor($.h)),_=Math.max(0,U-4),G=Math.max(0,Q-4),V={fg:"white",dim:!0},X={fg:"white",bg:"black",dim:!0},Z={fg:"whiteBright",bg:"blackBright"},Y={fg:"greenBright"},K={fg:"yellowBright"},F=$.oauthStatus==="authenticated",N=$.oauthStatus==="loading",q=F?`✓ Logged in as ${$.oauthEmail}`:N?"⏳ Authenticating...":"✗ Not logged in",H=F?Y:N?K:V,E=F?"Use ↑↓ to navigate, Enter to select, or numbers 1-4":N?"Copy the URL below if browser did not open":$.oauthUrl?"Copy the OAuth URL below, or press Enter to open browser":"Press Enter to login with ChatGPT Pro/Plus, or Esc to close";return i0(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(D)=>J("update:modelValue",D),onKeydownCapture:(D)=>{if(D?.key==="Escape"){D.preventDefault?.(),D.stopPropagation?.(),J("close"),J("update:modelValue",!1);return}if(F&&$.codexModels.length>0){if(D?.key==="ArrowDown"){D.preventDefault?.(),D.stopPropagation?.();let B=($.modelIndex+1)%$.codexModels.length;J("update:modelIndex",B);return}if(D?.key==="ArrowUp"){D.preventDefault?.(),D.stopPropagation?.();let B=($.modelIndex-1+$.codexModels.length)%$.codexModels.length;J("update:modelIndex",B);return}}if(D?.key==="Enter"&&!N){if(D.preventDefault?.(),D.stopPropagation?.(),F){if($.codexModels.length>0){let B=$.codexModels[$.modelIndex];if(B){J("selectModel",B.id),J("update:selectedModel",B.id),J("close"),J("update:modelValue",!1);return}}J("logout")}else J("login");return}if(F&&$.codexModels.length>0){let B=D?.key;if(B>="1"&&B<="9"){let j=parseInt(B)-1;if(j<$.codexModels.length){D.preventDefault?.(),D.stopPropagation?.();let f=$.codexModels[j];J("selectModel",f.id),J("update:selectedModel",f.id),J("update:modelIndex",j),J("close"),J("update:modelValue",!1);return}}}},w:U,h:Q,title:"Codex OAuth Login",placement:"center",backdrop:!0,closeOnBackdrop:!1,padding:1,style:{fg:"blueBright",bg:"black"},buttons:F?[{label:"Logout",value:"logout",kind:"danger"},{label:"Close",value:"close",default:!0}]:N?[{label:"Cancel",value:"close"}]:[{label:"Login",value:"login",kind:"primary",default:!0},{label:"Cancel",value:"close"}],onConfirm:(D)=>{if(D?.value==="login")J("login");else if(D?.value==="logout")J("logout");else J("close")},onClose:()=>J("close")},()=>[i0(t,{x:0,y:0,w:_,value:E,style:V}),i0(N6,{x:0,y:2,w:_,h:3,border:!0,title:"Status",padding:0,style:X,clear:!0},()=>i0(t,{x:1,y:0,w:Math.max(0,_-4),value:q,style:H})),$.oauthUrl&&!F?i0(N6,{x:0,y:6,w:_,h:Math.min(12,Math.max(6,G-9)),border:!0,title:N?"OAuth URL (copy if browser did not open)":"OAuth URL (ready to use)",padding:1,style:{...X,fg:"yellowBright"},clear:!0},()=>{return((j)=>{try{let[f,R]=j.split("?");if(!R)return[j];let I=[f+"?"],w=R.split("&");return w.forEach((T,z)=>{let S=z===w.length-1,O=` ${T}${S?"":"&"}`;I.push(O)}),I}catch{let f=Math.max(50,_-6),R=[],I=j;while(I.length>0)R.push(I.substring(0,f)),I=I.substring(f);return R}})($.oauthUrl).map((j,f)=>i0(t,{x:0,y:f,w:Math.max(0,_-4),value:j,style:{fg:"cyanBright",bg:"blackBright"},wrap:!1}))}):null,F&&$.codexModels.length>0?(()=>{let D=Math.max(0,G-9),B=Math.max(0,D-2),j=1,f=Math.floor(B/1),R=0;if($.codexModels.length>f){let T=$.modelIndex;if(T>=R+f)R=T-f+1;else if(T<R)R=T}let w=$.codexModels.length>f?` [${R+1}-${Math.min(R+f,$.codexModels.length)} of ${$.codexModels.length}]`:"";return i0(N6,{x:0,y:6,w:_,h:Math.max(0,G-9),border:!0,title:`Select Model (↑↓/1-9, Enter to select)${w}`,padding:1,style:X,clear:!0},()=>{return $.codexModels.slice(R,R+f).map((T,z)=>{let S=R+z,O=S===$.modelIndex,M=T.id===$.selectedModel,P;if(O)P={fg:"black",bg:"cyanBright",bold:!0};else if(M)P={fg:"greenBright"};else P={fg:"whiteBright"};let A=`${M?" ✓":""}${O?" ◄":""}`,k=`${S+1}. ${T.name}${A}`,L=Math.max(0,_-4),v=k;if(T.description&&k.length<L-5){let C=L-k.length-3;if(C>10){let b=T.description.length>C?T.description.substring(0,C-1)+"…":T.description;v=`${k} - ${b}`}}return i0(t,{x:0,y:z*1,w:L,value:v,style:P})})})})():!N&&!$.oauthUrl?i0(N6,{x:0,y:6,w:_,h:Math.max(0,G-9),border:!0,title:"About Codex OAuth",padding:1,style:X,clear:!0},()=>[i0(t,{x:0,y:0,w:Math.max(0,_-4),value:"• Requires ChatGPT Pro/Plus subscription",style:Z}),i0(t,{x:0,y:1,w:Math.max(0,_-4),value:"• No API key costs (included in subscription)",style:Z}),i0(t,{x:0,y:2,w:Math.max(0,_-4),value:"• Access to Codex models (gpt-5.x)",style:Z})]):null])}}});import{ref as w8,watch as c1$}from"vue";function FC($){let J=w8(!1),U=w8("unauthenticated"),Q=w8(""),_=w8(""),G=w8(""),V=w8([]),X=w8(0);async function Z(){try{V.value=[...J2];let E=await $U("codex");if(E){U.value="authenticated",Q.value=E.email||"ChatGPT Account";let D=await DB();G.value=D.model||J2[0].id;let B=J2.findIndex((j)=>j.id===G.value);X.value=B>=0?B:0}else U.value="unauthenticated",Q.value="",G.value="",X.value=0}catch{U.value="unauthenticated",Q.value="",G.value="",X.value=0}}async function Y(){if(_.value||U.value==="authenticated"){console.log("Skipping URL generation: already have URL or authenticated");return}try{console.log("Starting OAuth URL generation..."),$.showToast("Generating OAuth URL..."),console.log("Starting OAuth server...");let{redirectUri:E}=await bf();console.log("OAuth server started, redirect URI:",E),console.log("Generating PKCE...");let D=await If();console.log("Generating state...");let B=Tf();console.log("Building authorize URL...");let j=vf(E,D,B);console.log("Generated OAuth URL:",j.substring(0,50)+"..."),_.value=j,globalThis.__goatchain_oauth_pending={pkce:D,state:B},$.showToast("OAuth URL ready! Copy it or press Enter to open browser.")}catch(E){console.error("Failed to generate OAuth URL:",E),$.showToast(`Failed to generate OAuth URL: ${E?.message||String(E)}`)}}async function K(){try{if(U.value="loading",!_.value)await Y();if(!_.value)throw Error("Failed to generate OAuth URL");$.showToast("Starting OAuth login...");let E=_.value,D=globalThis.__goatchain_oauth_pending;if(!D?.pkce||!D?.state)throw Error("OAuth session not initialized");try{await(await import("open")).default(E),$.showToast("Browser opened. If not, copy the URL from the dialog.")}catch{$.showToast("Copy the OAuth URL from the dialog to login.")}let j=await yf(D.pkce,D.state);c7(),_.value="",delete globalThis.__goatchain_oauth_pending;let f=hG(j),R=uG(j);await gG("codex",{type:"oauth",refresh:j.refresh_token,access:j.access_token,expires:Date.now()+(j.expires_in??3600)*1000,accountId:f,email:R}),U.value="authenticated",Q.value=R||"ChatGPT Account",V.value=[...J2];let w=(await DB()).model||J2[0].id;if(!J2.some((O)=>O.id===w))w=J2[0].id;G.value=w;let z=J2.findIndex((O)=>O.id===w);X.value=z>=0?z:0,await H(w),$.showToast("Successfully authenticated with Codex!");let S=globalThis.process;if(S?.env)S.env.GOATCHAIN_USE_CODEX_OAUTH="1"}catch(E){U.value="unauthenticated",$.showToast(`OAuth login failed: ${E?.message||"Unknown error"}`);try{c7()}catch{}}}async function F(){try{await wf("codex"),U.value="unauthenticated",Q.value="",_.value="",$.showToast("Logged out from Codex");let E=globalThis.process;if(E?.env)delete E.env.GOATCHAIN_USE_CODEX_OAUTH;delete globalThis.__goatchain_oauth_pending;try{c7()}catch{}q()}catch(E){$.showToast(`Logout failed: ${E?.message||"Unknown error"}`)}}function N(){J.value=!0}c1$(J,async(E)=>{if(E)try{if(await Z(),U.value==="unauthenticated")await Y()}catch(D){$.showToast(`Dialog initialization error: ${D?.message||String(D)}`),console.error("CodexOAuth dialog error:",D)}});function q(){if(J.value=!1,U.value==="unauthenticated"&&_.value)_.value="",delete globalThis.__goatchain_oauth_pending,c7()}async function H(E){try{G.value=E;let D=await $U("codex");if($.store)$.store.state.config.model=E,$.store.state.config.baseUrl=N8,$.store.state.config.apiKey=D?.access||m7,$.store.setEnvVar("GOATCHAIN_MODEL",E),$.store.setEnvVar("GOATCHAIN_OPENAI_BASE_URL",N8),$.store.setEnvVar("OPENAI_BASE_URL",N8),$.store.setEnvVar("OPENAI_API_KEY",D?.access||m7);let{filePath:B,cache:j}=await jB(),f={...j,updatedAt:Date.now(),settings:{...j.settings,model:E,baseUrl:N8,apiKey:D?.access||m7,authMethod:"oauth"}};if(await Lf(B,f),$.nodeLike){let R=globalThis.process;if(R?.env)R.env.GOATCHAIN_MODEL=E,R.env.GOATCHAIN_OPENAI_BASE_URL=N8,R.env.OPENAI_BASE_URL=N8,R.env.OPENAI_API_KEY=D?.access||m7,R.env.GOATCHAIN_USE_CODEX_OAUTH="1"}$.showToast(`Model switched to ${E}`)}catch(D){$.showToast(`Failed to select model: ${D?.message||"Unknown error"}`)}}return{showCodexOAuth:J,oauthStatus:U,oauthEmail:Q,oauthUrl:_,selectedModel:G,codexModels:V,modelIndex:X,openCodexOAuth:N,closeCodexOAuth:q,loginWithOAuth:K,logoutOAuth:F,selectModel:H}}var WC=7,d1$=["________ ________ ________ _________ ________ ___ ___ ________ ___ ________","|\\ ____\\|\\ __ \\|\\ __ \\|\\___ ___\\ |\\ ____\\|\\ \\|\\ \\|\\ __ \\|\\ \\|\\ ___ \\","\\ \\ \\___|\\ \\ \\|\\ \\ \\ \\|\\ \\|___ \\ \\_| \\ \\ \\___|\\ \\ \\\\\\ \\ \\ \\|\\ \\ \\ \\ \\ \\\\ \\ \\"," \\ \\ \\ __\\ \\ \\\\\\ \\ \\ __ \\ \\ \\ \\ \\ \\ \\ \\ \\ __ \\ \\ __ \\ \\ \\ \\ \\\\ \\ \\"," \\ \\ \\|\\ \\ \\ \\\\\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\____\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\\ \\ \\"," \\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\ \\__\\ \\ \\_______\\ \\__\\ \\__\\ \\__\\ \\__\\ \\__\\ \\__\\\\ \\__\\"," \\|_______|\\|_______|\\|__|\\|__| \\|__| \\|_______|\\|__|\\|__|\\|__|\\|__|\\|__|\\|__| \\|__|"];function qC($,J=1){return d1$}var BC="",OC="";async function n1$($){if(!$||$.includes("\x00"))return;try{let{spawn:J}=await import("node:child_process"),U=globalThis.process,Q=String(U?.platform||"");J(Q==="darwin"?"open":Q==="win32"?"explorer.exe":"xdg-open",[$],{shell:!1,detached:!0,stdio:"ignore"}).unref()}catch{}}function p1$($){return`[... ${($.match(/\n/g)||[]).length+1} lines]`}function a1$($){let J=String($||"");if(!J)return"[file]";return`[${J.split(/[/\\]/).filter(Boolean).pop()??J}]`}function o1$($,J){if(!$)return"";let U=[],Q=0;for(let _=0;_<$.length;){let G=$[_];if(G===BC){U.push(J[Q]??""),Q++,_+=1;continue}if(G===OC){_+=1;continue}let V=$.codePointAt(_)??0,X=String.fromCodePoint(V);U.push(X),_+=X.length}return U.join("")}function t1$($,J,U){if(!$)return"";let Q=[],_=0,G=0;for(let V=0;V<$.length;){let X=$[V];if(X===BC){let K=J[_]??"";Q.push(p1$(K)),_++,V+=1;continue}if(X===OC){Q.push(a1$(U[G]??"")),G++,V+=1;continue}let Z=$.codePointAt(V)??0,Y=String.fromCodePoint(Z);Q.push(Y),V+=Y.length}return Q.join("")}var Bj=l1$({name:"GoatChainHomePage",setup(){let $=LU(),J=p4(),{events:U}=L4(),Q=G4(()=>J.clipRect?.w??0),_=G4(()=>J.clipRect?.h??0),G=i1$(E8,null);if(!G)throw Error("GoatChainBridge is missing (did you forget to wrap with <GoatChainProvider />?)");let{store:V,sessions:X}=G,Z=qJ(),Y=T1(""),K=T1(!1),F=T1(!1),N=T1(0),q=T1([]),H=T1([]),E=T1(!1),D=T1(""),B=T1("Multiline Text"),j=T1(V.getMode?.()??"agent");function f(r=1){let J4=["plan","agent"],g4=j.value,N2=(J4.indexOf(g4)+r+J4.length)%J4.length,b1=J4[N2]??"agent";j.value=b1,V.setMode?.(b1)}function R(r){let J4=H.value[r];if(J4){D.value=J4;let g4=(J4.match(/\n/g)||[]).length+1;B.value=`Multiline Text (${g4} lines)`,E.value=!0}}function I(){E.value=!1}let w=DX(1200),T=w.visible,z=w.text,S=w.show;if(Z){let r=globalThis,J4=r.__VT_SHOW_COPY_TOAST__,g4=(Q6)=>S(Q6);r.__VT_SHOW_COPY_TOAST__=g4,r1$(()=>{if(r.__VT_SHOW_COPY_TOAST__===g4)if(J4)r.__VT_SHOW_COPY_TOAST__=J4;else delete r.__VT_SHOW_COPY_TOAST__})}let O=OX({store:V,nodeLike:Z,showToast:S,guardPendingApprovals:!1}),{showConfig:M,showToolApprovals:P,modelId:A,contextWindow:k,temperature:L,interleavedThinking:v,baseUrl:C,apiKeyDraft:b,apiKeyMasked:y,openConfig:x,closeConfig:c,applyConfig:s,openToolApprovals:F$,applyToolApprovals:K$}=O,V$=BX({store:V,sessionsApi:X,showToast:S}),{showSessions:Y$,showSwitchConfirm:u$,switchConfirmTitle:_$,switchConfirmTargetLabel:n,switchConfirmReason:a,confirmSwitch:m,cancelSwitch:G$,sessionsLoading:L$,sessionsDeleteArmed:P$,sessionsList:f$,sessionsIndex:V4,refreshSessions:s4,openSessionsDialog:U6,openSelectedSession:z4,createNewSession:C6}=V$,o$=HX({store:V,cols:Q,rows:_,nodeLike:Z}),{showPathPicker:F6,pathPickerMode:A6,pathPickerQuery:F4,pathPickerError:E4,pickerWorkspace:c4,pickerW:Q$,pickerH:Z$,pathPickerTitle:k$,pathPickerPlaceholder:t$,closePathPicker:q4}=o$,_4=FC({store:V,nodeLike:Z,showToast:S}),{showCodexOAuth:Q4,oauthStatus:n$,oauthEmail:T$,oauthUrl:y4,selectedModel:p$,codexModels:e4,modelIndex:z$,openCodexOAuth:g,closeCodexOAuth:h,loginWithOAuth:q$,logoutOAuth:i,selectModel:p}=_4;jX({store:V,nodeLike:Z,showToast:S});let l=[{value:"/sessions",detail:"List/pick sessions",onSelect:()=>{U6(),Y.value="",H.value=[]}},{value:"/settings",detail:"Configure model + API",onSelect:()=>{x(),Y.value="",H.value=[]}},{value:"/codexoath",detail:"Codex OAuth login (GPT-5)",onSelect:()=>{g(),Y.value="",H.value=[]}},{value:"/new",detail:"Start a new session",onSelect:()=>{C6(),Y.value="",H.value=[]}},{value:"/approvals",detail:"Configure tool approvals (auto/all)",onSelect:()=>{Y.value="/approvals",MJ()}}];HC(q,(r)=>{V.setFocusFiles(r)});let $$=G4(()=>{return[...WX({openSessionsDialog:()=>void U6(),createNewSession:()=>void C6(),openConfig:x,openToolApprovals:F$})]}),e=G4(()=>$$.value.map((r)=>({label:r.label,detail:r.detail}))),D$=G4(()=>({fg:"whiteBright",bg:"black"})),v$=G4(()=>({fg:"white",dim:!0,bg:"black"})),A$=G4(()=>({fg:"whiteBright",bg:"blackBright"})),g$=G4(()=>({fg:"whiteBright",bg:"blackBright"})),c$=G4(()=>({fg:"blueBright",bg:"blackBright"})),d$=G4(()=>Q.value>=70&&_.value>=26),y$=G4(()=>d$.value?1:0),X4=G4(()=>d$.value?2:1),W4=G4(()=>d$.value?qC("goat",y$.value):["goat"]),_6=G4(()=>d$.value?WC:1),i$=G4(()=>M$(W4.value[0]??"")),l$=G4(()=>i$.value+X4.value),Y4=G4(()=>Math.max(0,Math.floor((Q.value-l$.value)/2))),a$=G4(()=>{let r=Math.max(0,Math.floor(Q.value));if(r<=0)return 0;let J4=Math.min(44,r),g4=Math.max(J4,r-8);return O4(Math.floor(r*0.72),J4,g4)}),$4=G4(()=>Math.max(0,Math.floor((Q.value-a$.value)/2))),x$=2,r$=G4(()=>$4.value+1+x$),D4=G4(()=>Math.max(0,a$.value-1-x$)),w4=G4(()=>Math.max(1,D4.value)),d4=G4(()=>{if(!Y.value)return 1;let r=w4.value;if(r<=0)return 1;let J4=t1$(Y.value,H.value,q.value);return Math.max(1,K0(J4,r).length)}),$6=G4(()=>O4(d4.value,1,7)),b6=1,k8=1,b0=G4(()=>b6+$6.value+k8+1+b6),B0=2,Z1=G4(()=>{let r=Math.max(1,_.value-B0-_6.value-b0.value-3);return O4(Math.floor(_.value*0.32),1,r)}),jJ=G4(()=>Z1.value+_6.value+4),RX=G4(()=>jJ.value+b0.value-1),bU=G4(()=>jJ.value+b6),yU=G4(()=>bU.value+$6.value+k8),AX=G4(()=>Array.from({length:Math.max(0,b0.value)},()=>"┃").join(`
|
|
948
|
-
`)),DJ=G4(()=>F.value||F6.value||Y$.value||M.value||P.value||Q4.value||E.value);function K1(){if(Z)return;try{globalThis.document?.querySelector?.("[data-vt-host] textarea")?.focus?.()}catch{}}function I8(){let r=U.value;if(!r||typeof r.debugNodes!=="function"||typeof r.focus!=="function")return;let J4=Math.floor(r$.value),g4=Math.floor(bU.value),Q6=Math.floor(D4.value),N2=Math.floor($6.value),b1=(r.debugNodes?.()??[]).filter((_0)=>_0?.visible&&_0?.focusable),hU=b1.find((_0)=>{let W6=_0?.rect;return W6&&W6.x===J4&&W6.y===g4&&W6.w===Q6&&W6.h===N2});if(hU?.id){r.focus(hU.id);return}let y1=J4+Math.floor(Math.max(0,Q6-1)/2),F2=g4+Math.floor(Math.max(0,N2-1)/2),n0=b1.filter((_0)=>{let W6=_0?.rect;return W6&&y1>=W6.x&&F2>=W6.y&&y1<W6.x+W6.w&&F2<W6.y+W6.h});n0.sort((_0,W6)=>{let C8=_0?.zIndex??0,k_=W6?.zIndex??0;if(k_!==C8)return k_-C8;let I_=_0?.rect??{w:0,h:0},S_=W6?.rect??{w:0,h:0};return I_.w*I_.h-S_.w*S_.h});let LJ=n0[0];if(LJ?.id)r.focus(LJ.id)}HC(DJ,(r)=>{if(r)return;setTimeout(()=>{K1(),I8()},0)});let R_=G4(()=>{return{build:"■",label:String(V.state.config.model??"model")}}),wX=G4(()=>j.value),gU=" ",EJ=G4(()=>"tab"),K2=G4(()=>"mode"),xU=G4(()=>"ctrl+p"),A_=G4(()=>"commands"),S8=G4(()=>{return M$(EJ.value)+1+M$(K2.value)+M$(gU)+M$(xU.value)+1+M$(A_.value)}),v1=G4(()=>{let r=S8.value;if(r<=0)return 0;let J4=$4.value+a$.value-r,g4=Math.max(0,Q.value-r);return O4(J4,0,g4)}),C1=G4(()=>RX.value+2),fX=G4(()=>C1.value>=0&&C1.value<=_.value-B0-1&&v1.value+S8.value<=Q.value),kX=G4(()=>{return c4.value}),PJ=G4(()=>{let r=V.state.context?.env??{},J4=r.GOATCHAIN_VERSION||r.VUE_TERMINAL_VERSION;return J4?`v${J4}`:""});function T8(r){$.push(r)}function IX(r){V.setCwd(r)}async function MJ(){let J4=o1$(Y.value,H.value).trim(),g4=q.value;if(!J4&&g4.length===0)return;let Q6=FX(J4);if(Q6.kind==="approvals"){F$(),Y.value="",H.value=[];return}if(Q6.kind==="approvals_invalid_args"){S("Use /approvals (no on/off)."),Y.value="",H.value=[];return}if(Q6.kind==="settings"){x(),Y.value="",H.value=[];return}if(Q6.kind==="sessions"){await U6(),Y.value="",H.value=[];return}if(Q6.kind==="codexoath"){g(),Y.value="",H.value=[];return}if(Q6.kind==="new"){await C6(),Y.value="",H.value=[];return}if(Q6.kind==="redo"){S("Redo is only available in the chat view."),Y.value="",H.value=[];return}if(Q6.kind==="rename"||Q6.kind==="rename_invalid_args"){S("Rename is only available in the chat view (/rename <title>)."),Y.value="",H.value=[];return}if(Y.value="",H.value=[],T8("chat"),g4.length>0)V.sendUserInput({content:J4,focusFiles:g4});else V.sendUser(J4);q.value=[]}function w_(){F.value=!0,N.value=0}function v8(){F.value=!1}function SX(r){if(DJ.value)return;if(r?.key==="Tab"&&!r?.metaKey&&!r?.ctrlKey&&!r?.altKey)r?.stopPropagation?.(),r?.preventDefault?.(),f(r.shiftKey?-1:1)}function f_(r){if(r?.defaultPrevented)return;if((r?.ctrlKey||r?.metaKey)&&(r?.key==="p"||r?.key==="P")){r?.preventDefault?.(),w_();return}if((r?.ctrlKey||r?.metaKey)&&(r?.key==="k"||r?.key==="K")){r?.preventDefault?.(),x();return}if(r?.key==="Tab"&&!r?.metaKey&&!r?.ctrlKey&&!r?.altKey){r?.preventDefault?.(),f(r.shiftKey?-1:1);return}if(r?.key==="Escape")r?.preventDefault?.(),Y.value="",H.value=[]}function TX(r){if(v8(),!r)return;$$.value.find((g4)=>g4.label===r)?.run()}return()=>h4(R4,{x:0,y:0,w:Q.value,h:_.value,zIndex:0,focusable:!1,onKeydownCapture:SX},()=>[h4(t,{key:"bg",x:0,y:0,w:Q.value,h:_.value,value:"",style:D$.value,zIndex:-100}),h4(t,{key:"logo-shadow-open",x:Y4.value+1,y:Z1.value+1,value:W4.value.join(`
|
|
949
|
-
`),style:{fg:"blackBright",dim:!0,bg:"black"},zIndex:-70}),h4(t,{key:"logo-open",x:Y4.value,y:Z1.value,value:W4.value.join(`
|
|
950
|
-
`),style:{fg:"white",dim:!0,bold:!0,bg:"black"},zIndex:-60}),h4(t,{key:"panel-fill",x:$4.value,y:jJ.value,w:a$.value,h:b0.value,value:"",style:A$.value,zIndex:-20}),h4(t,{key:"panel-accent",x:$4.value,y:jJ.value,w:1,h:b0.value,value:AX.value,style:c$.value,zIndex:-19}),h4(R4,{key:"panel-hit",x:$4.value,y:jJ.value,w:a$.value,h:b0.value,zIndex:10,focusable:!1,onPointerdownCapture:()=>{K1(),I8()}}),h4(J6,{key:"prompt-input",x:r$.value,y:bU.value,w:D4.value,h:$6.value,modelValue:Y.value,"onUpdate:modelValue":(r)=>Y.value=r,autoFocus:!DJ.value&&!K.value,cursorShape:"bar",cursorBlink:!1,placeholder:"Ask anything... (newline: Shift+Enter or Ctrl+J)",placeholderWhenFocused:!0,style:g$.value,plugins:[DU()],promptSuggestions:l,mentionWorkspace:Z?c4.value:"",mentionMode:"any",collectMentions:!0,mentions:q.value,"onUpdate:mentions":(r)=>q.value=[...r],onMentionClick:(r,J4)=>{if(!Z)return;if(J4?.metaKey||J4?.ctrlKey)n1$(r)},collapseMultiline:!0,multilineTexts:H.value,"onUpdate:multilineTexts":(r)=>H.value=[...r],onMultilineClick:R,onChange:()=>void MJ(),onKeydown:(r)=>f_(r),onFocus:()=>{K.value=!0},onBlur:()=>K.value=!1,zIndex:11}),(()=>{let r=yU.value,J4=R_.value.build,g4=R_.value.label,Q6=M$(J4),N2=M$(g4),b1=Q6+1+N2,hU=2,y1=r$.value+Math.max(0,w4.value-b1-2),F2=Math.max(0,y1-r$.value-1),n0=[];if(F2>0){let LJ=wX.value,_0=` ${LJ.toUpperCase()} `,W6=LJ==="plan"?"magentaBright":"greenBright",C8=Math.min(F2,M$(_0));n0.push(h4(t,{key:"panel-mode",x:r$.value,y:r,w:C8,value:_0,style:{fg:"black",bg:W6,bold:!0},zIndex:-18}))}return n0.push(h4(t,{key:"model-chip",x:y1,y:r,value:J4,style:{fg:"blueBright",bold:!0,bg:"blackBright"},zIndex:-18})),n0.push(h4(t,{key:"model-label",x:y1+Q6+1,y:r,w:Math.max(0,r$.value+w4.value-(y1+Q6+1)),value:g4,style:{fg:"whiteBright",dim:!0,bg:"blackBright"},zIndex:-18})),n0})(),fX.value?[h4(t,{key:"hints-bg",x:v1.value,y:C1.value,w:S8.value,value:"",style:{bg:"black"},zIndex:4}),h4(t,{key:"hints-key1",x:v1.value,y:C1.value,value:EJ.value,style:{fg:"whiteBright",bold:!0,bg:"black"},clear:!1,zIndex:5}),h4(t,{key:"hints-label1",x:v1.value+M$(EJ.value)+1,y:C1.value,value:K2.value,style:{fg:"white",dim:!0,bg:"black"},clear:!1,zIndex:5}),h4(t,{key:"hints-key2",x:v1.value+M$(EJ.value)+1+M$(K2.value)+M$(gU),y:C1.value,value:xU.value,style:{fg:"whiteBright",bold:!0,bg:"black"},clear:!1,zIndex:5}),h4(t,{key:"hints-label2",x:v1.value+M$(EJ.value)+1+M$(K2.value)+M$(gU)+M$(xU.value)+1,y:C1.value,value:A_.value,style:{fg:"white",dim:!0,bg:"black"},clear:!1,zIndex:5})]:null,_.value>0?h4(t,{key:"footer-bg",x:0,y:_.value-B0,w:Q.value,value:"",style:D$.value,zIndex:20}):null,_.value>0?h4(t,{key:"footer-left",x:2,y:_.value-B0,w:Math.max(0,Q.value-4),value:`cwd ${kX.value}`,style:v$.value,clear:!1,zIndex:21}):null,_.value>0&&PJ.value?h4(t,{key:"footer-right",x:Math.max(2,Q.value-2-M$(PJ.value)),y:_.value-B0,value:PJ.value,style:v$.value,clear:!1,zIndex:21}):null,h4(oV,{modelValue:F.value,"onUpdate:modelValue":(r)=>F.value=r,title:"Commands",options:e.value,selectedIndex:N.value,"onUpdate:selectedIndex":(r)=>N.value=r,onSelect:(r)=>TX(r),onClose:v8}),h4(sV,{modelValue:F6.value,"onUpdate:modelValue":(r)=>{if(!r)q4();else F6.value=!0},w:Q$.value,h:Z$.value,title:k$.value,workspace:c4.value,mode:A6.value,query:F4.value,"onUpdate:query":(r)=>F4.value=r,placeholder:t$.value,onInvalid:(r)=>E4.value=r,onSelect:(r)=>{if(A6.value==="directory")IX(r);else if(!q.value.includes(r))q.value=[...q.value,r];q4()},onClose:q4}),h4(eV,{modelValue:Y$.value,"onUpdate:modelValue":(r)=>{if(Y$.value=r,!r)P$.value=!1},loading:L$.value,deleteArmed:P$.value,sessions:f$.value,selectedIndex:V4.value,"onUpdate:selectedIndex":(r)=>{V4.value=r,P$.value=!1},onOpen:async()=>{await z4({after:async()=>T8("chat")})},onNew:async()=>{await C6()},onDelete:async()=>{let r=X,J4=f$.value[V4.value];if(!r||!J4)return;let g4=V4.value;if(!P$.value){P$.value=!0,S("Press Delete again to confirm.");return}P$.value=!1,await r.delete(J4.id),await s4({preferIndex:g4})},onRefresh:async()=>{P$.value=!1,await s4()}}),h4(JX,{modelValue:u$.value,"onUpdate:modelValue":(r)=>{if(u$.value=r,!r)G$()},title:_$.value,targetLabel:n.value,reason:a.value,onConfirm:()=>void m()}),h4(UX,{modelValue:M.value,"onUpdate:modelValue":(r)=>M.value=r,w:O4(Math.floor(Q.value*0.78),56,84),h:O4(24,18,Math.max(18,_.value-4)),modelId:A.value,"onUpdate:modelId":(r)=>A.value=r,contextWindow:k.value,"onUpdate:contextWindow":(r)=>k.value=r,temperature:L.value,"onUpdate:temperature":(r)=>L.value=r,interleavedThinking:v.value,"onUpdate:interleavedThinking":(r)=>v.value=r,baseUrl:C.value,"onUpdate:baseUrl":(r)=>C.value=r,apiKeyDraft:b.value,"onUpdate:apiKeyDraft":(r)=>b.value=r,apiKeyMasked:y.value,onApply:s,onCancel:c}),h4(GX,{modelValue:P.value,"onUpdate:modelValue":(r)=>P.value=r,mode:String(V.state.approval.mode??"auto"),w:O4(Math.floor(Q.value*0.62),46,86),h:O4(14,11,Math.max(11,_.value-6)),onSelect:(r)=>{K$(r),P.value=!1}}),h4(NC,{modelValue:Q4.value,"onUpdate:modelValue":(r)=>Q4.value=r,w:O4(Math.floor(Q.value*0.78),70,94),h:O4(28,18,Math.max(18,_.value-4)),oauthStatus:n$.value,oauthEmail:T$.value,oauthUrl:y4.value,selectedModel:p$.value,"onUpdate:selectedModel":(r)=>p$.value=r,codexModels:e4.value,modelIndex:z$.value,"onUpdate:modelIndex":(r)=>z$.value=r,onLogin:()=>void q$(),onLogout:()=>void i(),onSelectModel:(r)=>void p(r),onClose:h}),...ZX({notification:V.upgradeNotification?.value,cols:Q.value,onDismiss:()=>{V.dismissUpgradeNotification?.()}}),...XX({visible:T,text:z,cols:Q}),h4(OV,{visible:E.value,content:D.value,title:B.value,onClose:I,zIndex:2000})])}});import{defineComponent as P2$,h as yC,inject as M2$,onUnmounted as L2$,provide as z2$,ref as gC}from"vue";import{computed as EX,reactive as D2$,watch as vC}from"vue";function s1$($,J){let U=$.replace(/\[/g,"\\[").replace(/\]/g,"\\]"),Q=J.replace(/\)/g,"\\)");return`- [${U}](<${Q}>)`}function e1$($){let J=($??[]).map((Q)=>String(Q??"")).filter(Boolean);if(!J.length)return"";return`[focus_files]
|
|
951
|
-
${J.map((Q)=>{let _=String(Q??""),G=_.split(/[/\\]/).filter(Boolean).pop()??_;return s1$(G,_)}).join(`
|
|
952
|
-
`)}
|
|
953
|
-
|
|
954
|
-
`}function $2$($){return{id:$.id,type:"function",function:{name:$.name,arguments:$.arguments}}}function J2$($){if($.role==="user")return{role:"user",content:`${e1$($.focusFiles)}${$.content??""}`};if($.role==="tool")return{role:"tool",tool_call_id:$.result.id,content:$.result.output,metadata:$.result.status==="error"?{error:!0}:void 0};let J=$.parts.filter((_)=>_.type==="markdown").map((_)=>_.markdown).join(""),U=$.parts.flatMap((_)=>_.type==="tool_call"?[_.call]:[]),Q=U.length?U.map($2$):void 0;if(!J&&(!Q||Q.length===0))return null;return{role:"assistant",content:J||"",tool_calls:Q}}function U2$($){if($.role!=="assistant")return!1;let J=$.parts.find((Q)=>Q.type==="status");if(J?.type==="status"&&J.text==="Interrupted.")return!0;return $.parts.filter((Q)=>Q.type==="markdown").map((Q)=>String(Q.markdown??"")).join(`
|
|
955
|
-
`).includes("> **Interrupted** · Response canceled by user (`Esc`).")}function _2$($){let J=[];for(let U of $.parts)if(U.type==="tool_call")J.push(String(U.call.id??"").trim());else if(U.type==="tool_output")J.push(String(U.toolCallId??"").trim());else if(U.type==="tool_result")J.push(String(U.result.id??"").trim());return J.filter(Boolean)}function Oj($){let J=[],U=new Set;for(let Q of $){if(Q.role==="tool"&&U.has(String(Q.result.id??"").trim()))continue;if(Q.role==="assistant"&&U2$(Q)){if(J.length&&J[J.length-1]?.role==="user")J.pop();for(let _ of _2$(Q))U.add(_);continue}J.push(Q)}return J}function jC($,J){let U=[];U.push({role:"system",content:String($??"")});for(let Q of Oj(J)){let _=J2$(Q);if(_)U.push(_)}return U}function DC($){let J=(G)=>String($?.[G]??"").trim();return{str:J,bool:(G)=>{let V=J(G).toLowerCase();if(!V)return;if(V==="1"||V==="true"||V==="yes"||V==="on")return!0;if(V==="0"||V==="false"||V==="no"||V==="off")return!1;return},int:(G)=>{let V=J(G);if(!V)return;let X=Number.parseInt(V,10);return Number.isFinite(X)?X:void 0},float:(G)=>{let V=J(G);if(!V)return;let X=Number.parseFloat(V);return Number.isFinite(X)?X:void 0}}}function EC($){let J=$.str("GOATCHAIN_TOOL_APPROVALS").toLowerCase(),U=J==="all"?"all":"auto";if(!J)return $.bool("GOATCHAIN_SKIP_APPROVAL")?"all":"auto";return U}function PC($){return{model:$.str("GOATCHAIN_MODEL")||"deepseek-v3.1",context_window:$.int("GOATCHAIN_CONTEXT_WINDOW")||128000,temperature:$.float("GOATCHAIN_TEMPERATURE")??0.7,interleaved_thinking:$.bool("GOATCHAIN_INTERLEAVED_THINKING")??!1}}function MC($){return $.str("GOATCHAIN_SESSION_ID")||""}function LC($){return{idleMs:$.int("GOATCHAIN_STREAM_IDLE_TIMEOUT_MS")??90000,totalMs:$.int("GOATCHAIN_STREAM_TOTAL_TIMEOUT_MS")??300000}}function jj($){if(!$)return"Unknown error.";if($ instanceof Error)return $.stack||$.message||String($);if(typeof $==="string")return $.trim()?$:"Unknown error.";if(typeof $==="object"){let J=$?.message;if(typeof J==="string"&&J.trim())return J.trim()}try{return kU($)}catch{return String($)}}function OJ($,J){let U=Boolean(String(J?.OPENAI_API_KEY??"").trim()),Q=$.toLowerCase();if(Q.includes("max_tokens")||Q.includes("max tokens")||Q.includes("context length")||Q.includes("token")&&Q.includes("limit"))return"Hint: reduce context size by starting a new session or summarizing previous messages.";if(!U||Q.includes("api key")||Q.includes("openai_api_key")||Q.includes("unauthorized")||Q.includes("401"))return"Hint: set `OPENAI_API_KEY` via `/settings` (or Ctrl+K), then retry.";if(Q.includes("etimedout")||Q.includes("timeout")||Q.includes("econnreset")||Q.includes("enotfound")||Q.includes("fetch failed"))return"Hint: check network / proxy / `GOATCHAIN_OPENAI_BASE_URL`, then retry.";return null}function Q2$($){let U=String($??"").replace(/\\/g,"/").split("/").filter(Boolean);return(U[U.length-1]??"").trim()}function RC($){let J=Q2$($).toLowerCase();if(!J)return null;if(J==="dockerfile")return"dockerfile";if(J==="makefile")return"make";if(J.endsWith(".d.ts"))return"ts";switch(J.includes(".")?J.split(".").pop()??"":""){case"ts":return"ts";case"tsx":return"tsx";case"js":return"js";case"jsx":return"jsx";case"mjs":return"js";case"cjs":return"js";case"json":return"json";case"jsonc":return"jsonc";case"md":return"md";case"vue":return"vue";case"html":return"html";case"css":return"css";case"scss":return"scss";case"less":return"less";case"yml":return"yaml";case"yaml":return"yaml";case"toml":return"toml";case"xml":return"xml";case"sql":return"sql";case"sh":return"bash";case"bash":return"bash";case"zsh":return"bash";case"fish":return"fish";case"py":return"python";case"go":return"go";case"rs":return"rust";case"c":return"c";case"cc":return"cpp";case"cpp":return"cpp";case"h":return"cpp";case"hpp":return"cpp";case"java":return"java";case"kt":return"kotlin";case"swift":return"swift";case"rb":return"ruby";case"php":return"php";case"diff":return"diff";case"patch":return"diff";case"graphql":return"graphql";case"gql":return"graphql";default:return"text"}}function zC($){let U=String($??"").trim().match(/^#?([0-9a-f]{6})([0-9a-f]{2})?$/i);if(!U)return null;let Q=U[1],_=Number.parseInt(Q.slice(0,2),16),G=Number.parseInt(Q.slice(2,4),16),V=Number.parseInt(Q.slice(4,6),16);return Number.isFinite(_)&&Number.isFinite(G)&&Number.isFinite(V)?{r:_,g:G,b:V}:null}function Dj($){return`\x1B[${$.join(";")}m`}function G2$($){return Dj([38,2,$.r,$.g,$.b])}function V2$($){let J=Number($??0),U=[];if(J&2)U.push(1);if(J&1)U.push(3);if(J&4)U.push(4);return U}function X2$($,J){let U=String($??"").replace(/\r/g,"").split(`
|
|
956
|
-
`);if(U.length<=J)return{text:U.join(`
|
|
957
|
-
`),truncated:!1};return{text:U.slice(0,J).join(`
|
|
958
|
-
`),truncated:!0}}async function AC($){let J=String($.language??"").trim()||"text",U=String($.theme??"github-dark").trim()||"github-dark",Q=Math.max(1,Math.floor($.maxLines??24)),G=X2$($.code,Q).text;if(!G.trim())return null;try{let V=await import("shiki"),X=V.codeToTokensBase,Z=V.getSingletonHighlighter;if(typeof X!=="function"||typeof Z!=="function")return null;let Y=await X(G,{lang:J,theme:U}),K=await Z(),F=K?.getTheme?K.getTheme(U):null,N=String(F?.fg??"#ffffff"),q=zC(N)??{r:255,g:255,b:255},H="";for(let E=0;E<Y.length;E++){let D=Y[E];for(let B of D){let j=zC(B?.color)??q,f=V2$(B?.fontStyle);if(H+=G2$(j),f.length)H+=Dj(f);H+=String(B?.content??""),H+=Dj([0])}if(E<Y.length-1)H+=`
|
|
959
|
-
`}return H}catch{return null}}function Y2$($,J,U){let Q=$.find((G)=>G.id===J);if(!Q||Q.role!=="assistant")return null;let _=Q.parts.find((G)=>G.type==="tool_call"&&G.call.id===U);return _?.call?.name?String(_.call.name):null}function Z2$($,J,U){let Q=$.find((G)=>G.id===J);if(!Q||Q.role!=="assistant")return null;let _=Q.parts.find((G)=>G.type==="tool_call"&&G.call.id===U);return _?.call?_.call:null}function K2$($){let J=$??{},U=[J.file_path,J.filePath,J.path];for(let Q of U)if(typeof Q==="string"&&Q.trim())return Q.trim();return null}function N2$($,J){return!1}function wC($){let J=String($.result.id??"").trim();if(!J)return;let U=Y2$($.state.messages,$.assistantId,J),Q=Z2$($.state.messages,$.assistantId,J),_=K2$(Q?.arguments);if(!N2$(U,_))return;let G=RC(_);if(!G)return;(async()=>{let V=await AC({code:$.result.output,language:G,maxLines:10});if(!V||!V.trim())return;$.updateAssistant($.assistantId,(X)=>{let Z=X.parts.slice(),Y=Z.findIndex((F)=>F.type==="tool_result"&&F.result.id===J);if(Y<0)return X;let K=Z[Y];if(K.result.output!==$.result.output)return X;if(K.result.outputAnsi&&K.result.outputAnsi.trim())return X;return Z[Y]={type:"tool_result",result:{...K.result,outputAnsi:V}},{...X,parts:Z}})})()}var F2$=0;function vU($){return`${$}_${Date.now()}_${F2$++}`}import{computed as fC}from"vue";function kC($){function J(z){$.messages.push(z)}function U(z,S){let O=$.messages.findIndex((M)=>M.id===z);if(O>=0)$.messages[O]=S}function Q(z,S){let O=$.messages.find((M)=>M.id===z);if(!O||O.role!=="assistant")return;U(z,S(O))}function _(z,S){Q(z,(O)=>{let M=O.parts.map((P)=>P.type==="status"?{type:"status",text:S}:P);return{...O,parts:M}})}function G(z,S,O){let M=String(S??"");Q(z,(P)=>{let A=P.parts.slice(),k=-1;if(O!==void 0){let v=0;for(let C=0;C<A.length;C++)if(A[C].type==="thinking"){if(v===O){k=C;break}v++}}else k=A.findLastIndex((v)=>v.type==="thinking");if(k>=0){let v=A[k];return A[k]={type:"thinking",title:v.title,collapsed:v.collapsed,content:M},{...P,parts:A}}let L=Math.max(0,A.findIndex((v)=>v.type==="status")+1);return A.splice(L,0,{type:"thinking",title:"Thinking",collapsed:!1,content:M}),{...P,parts:A}})}function V(z){Q(z,(S)=>{let O=S.parts.slice();return O.push({type:"thinking",title:"Thinking",collapsed:!0,content:""}),{...S,parts:O}})}function X(z,S,O){Q(z,(M)=>{let P=M.parts.slice(),A=-1,k=0;for(let L=0;L<P.length;L++)if(P[L].type==="thinking"){if(k===S){A=L;break}k++}if(A>=0){let L=P[A];return P[A]={type:"thinking",title:L.title,collapsed:L.collapsed,content:O!==void 0?O:L.content},{...M,parts:P}}return M})}function Z(z,S){let O=String(S??"");if(!O)return;Q(z,(M)=>{let P=M.parts[M.parts.length-1];if(P?.type==="markdown")return M.parts[M.parts.length-1]={type:"markdown",markdown:`${P.markdown}${O}`},{...M,parts:M.parts};return M.parts.push({type:"markdown",markdown:O}),{...M,parts:M.parts}})}function Y(z,S){let O=Number(S?.durationMs);if(!Number.isFinite(O)||O<0)return;let M=String(S?.modelId??"").trim()||void 0;Q(z,(P)=>{let A=P.parts.slice();return A.push({type:"llm_meta",durationMs:O,...M?{modelId:M}:{}}),{...P,parts:A}})}function K(z,S,O,M){let P=String(S??"").trim();if(!P)return;let A=String(O??"").trim()||"tool",k=String(M??"");Q(z,(L)=>{let v=L.parts,C=-1;for(let y=v.length-1;y>=0;y--){let x=v[y];if(x?.type==="tool_call"&&x?.call?.id===P){C=y;break}}if(C>=0){let y=v[C],x=y.call.argumentsText??"",c={...y.call,name:A,argumentsText:`${x}${k}`};return v[C]={type:"tool_call",call:c},{...L,parts:L.parts}}let b={id:P,name:A,arguments:{},argumentsText:k};return v.push({type:"tool_call",call:b}),{...L,parts:L.parts}})}function F(z,S,O,M){let P=String(S??"").trim();if(!P)return;Q(z,(A)=>{let k=A.parts.slice(),L=k.findIndex((y)=>y.type==="tool_call"&&y.call.id===P),v=L>=0&&k[L]?.type==="tool_call"?k[L].call.argumentsText:void 0,b={type:"tool_call",call:{id:P,name:O,arguments:M,argumentsText:v}};if(L>=0)k[L]=b;else k.push(b);return{...A,parts:k}})}function N(z,S,O){let M=String(S??"").trim();if(!M)return;let P=String(O??"").trim()||"tool";Q(z,(A)=>{let k=A.parts,L=k.findIndex((b)=>b?.type==="tool_output"&&b?.toolCallId===M),v={type:"tool_output",toolCallId:M,toolName:P,output:""};if(L>=0)return k[L]=v,{...A,parts:A.parts};let C=k.findIndex((b)=>b?.type==="tool_call"&&b?.call?.id===M);if(C>=0){let b=C+1;while(b<k.length&&k[b]?.type==="approve"&&k[b]?.request?.toolCallId===M)b++;k.splice(b,0,v)}else k.push(v);return{...A,parts:A.parts}})}function q(z,S,O,M){let P=String(S??"").trim();if(!P)return;let A=String(M??"");if(!A)return;let k=String(O??"").trim()||"tool";Q(z,(L)=>{let v=L.parts,C=v.findIndex((x)=>x?.type==="tool_output"&&x?.toolCallId===P);if(C>=0){let x=v[C];return v[C]={type:"tool_output",toolCallId:P,toolName:x.toolName||k,output:`${x.output}${A}`},{...L,parts:L.parts}}let b={type:"tool_output",toolCallId:P,toolName:k,output:A},y=v.findIndex((x)=>x?.type==="tool_call"&&x?.call?.id===P);if(y>=0){let x=y+1;while(x<v.length&&v[x]?.type==="approve"&&v[x]?.request?.toolCallId===P)x++;v.splice(x,0,b)}else v.push(b);return{...L,parts:L.parts}})}function H(z,S){let O=String(S.id??"").trim();if(!O)return;Q(z,(M)=>{let P=M.parts.slice(),A=P.findIndex((v)=>v.type==="tool_call"&&v.call.id===O),L=P.filter((v)=>!(v.type==="tool_result"&&v.result.id===O)).slice();if(A>=0){let v=L.findIndex((C)=>C.type==="tool_call"&&C.call.id===O);if(v>=0){let C=v+1;while(C<L.length&&L[C]?.type==="approve"&&L[C]?.request?.toolCallId===O)C++;while(C<L.length&&L[C]?.type==="tool_output"&&L[C]?.toolCallId===O)C++;L.splice(C,0,{type:"tool_result",result:S})}else L.push({type:"tool_result",result:S})}else L.push({type:"tool_result",result:S});return{...M,parts:L}})}function E(z,S){Q(z,(O)=>{if(O.parts.some((k)=>k.type==="approve"&&k.request.toolCallId===S.toolCallId&&k.request.status==="pending"))return O;let P=O.parts.slice(),A=P.findIndex((k)=>k.type==="tool_call"&&k.call.id===S.toolCallId);if(A>=0)P.splice(A+1,0,{type:"approve",request:S});else P.push({type:"approve",request:S});return{...O,parts:P}})}function D(z,S,O){let M=$.messages.find((A)=>A.id===z);if(!M||M.role!=="assistant")return;let P=M.parts.map((A)=>{if(A.type!==S)return A;return{...A,items:A.items.map((k)=>k.id===O?{...k,done:!k.done}:k)}});U(z,{...M,parts:P})}function B(z,S,O){let M=$.messages.find((A)=>A.id===z);if(!M||M.role!=="assistant")return;let P=M.parts.map((A,k)=>{if(A.type!==S)return A;if(O!==void 0&&k!==O)return A;return{...A,collapsed:!A.collapsed}});U(z,{...M,parts:P})}function j(z){let S=$.messages.findIndex((M)=>M.id===z);if(S<0)return 0;let O=$.messages.splice(S);return $.revertedMessages=O,O.length}function f(){if($.revertedMessages.length===0)return 0;let z=$.revertedMessages.length;return $.messages.push(...$.revertedMessages),$.revertedMessages=[],z}function R(){$.revertedMessages=[]}let I=fC(()=>$.revertedMessages.length>0),w=fC(()=>$.revertedMessages.length);function T(z,S,O,M){let P=M?.todos;if(!Array.isArray(P))return;let A=P.map((L,v)=>({id:`${O}:${v}`,text:String(L?.content??"").trim(),done:String(L?.status??"")==="completed"})).filter((L)=>Boolean(L.text));if(A.length===0)return;let k=S==="plan"?"Plan":"Todo";Q(z,(L)=>{let v=L.parts.slice(),C=v.findIndex((b)=>b.type===S&&b.title===k);if(C>=0){let b=v[C];return v[C]={type:S,title:k,collapsed:Boolean(b?.collapsed),items:A},{...L,parts:v}}return v.push({type:S,title:k,collapsed:!1,items:A}),{...L,parts:v}})}return{pushMessage:J,replaceMessage:U,updateAssistant:Q,setAssistantStatus:_,setAssistantThinking:G,startNewThinkingBlock:V,endThinkingBlock:X,appendAssistantMarkdown:Z,appendAssistantLlmMeta:Y,upsertToolCallDelta:K,upsertToolCallEnd:F,upsertToolOutputStart:N,appendToolOutputDelta:q,attachToolResultPart:H,insertApprovalPart:E,toggleChecklist:D,toggleBlockCollapsed:B,revertFromMessage:j,restoreRevertedMessages:f,clearRevertedMessages:R,hasRevertedMessages:I,revertedMessageCount:w,upsertChecklistPartFromGoatChain:T}}var W2$=["iteration_start","text_delta","thinking_start","thinking_delta","thinking_end","tool_call_start","tool_call_delta","tool_call_end","tool_output_start","tool_output_delta","tool_result","tool_approval_requested","requires_action","tool_skipped","iteration_end","done","error"];function IC($){let J=$?.metadata?.originalEventType;return W2$.includes(J)?J:null}function CU($){if(!$)return"";if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>String(J?.text??"")).join("");return""}var q2$=180;function Ej($){return G1($).replace(/\s+/g," ").trim()}function H2$($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return`${$.slice(0,J-3).trimEnd()}...`}function B2$($,J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let U=J;if(String($??"").toLowerCase()==="bash"){let G=typeof U.command==="string"?Ej(U.command):"",V=typeof U.description==="string"?Ej(U.description):"";if(G&&V)return`Command: ${G} - ${V}`;if(G)return`Command: ${G}`;if(V)return`Description: ${V}`}let _=Ej(kU(U));if(!_||_==="{}"||_==="null")return null;return`Args: ${_}`}function O2$($,J,U){let Q=B2$(J,U);if(!Q)return $;return`${$} ${H2$(Q,q2$)}`}function SC($){let Q=25,_=null,G=null,V=null,X=null;function Z(){return new Promise((z)=>{let S=globalThis.setImmediate;if(typeof S==="function")S(z);else setTimeout(z,0)})}function Y(){let z=V;V=null;try{z?.abort()}catch{}}function K(){let z=_;if(_=null,Y(),!z)return;try{z.return?.()}catch{}}function F(){let z=null;return{promise:new Promise((O)=>{z=O}),resolve:()=>z?.()}}function N(){let z=G;G=null,Y(),z?.resolve()}function q(z,S){let O=$.state.messages.find((P)=>P.id===z);if(!O||O.role!=="assistant")return null;let M=O.parts.find((P)=>P.type==="tool_call"&&P.call.id===S);return M?.call?.name?String(M.call.name):null}let H=-1,E=new Map;function D(z){let S=String(z??"").trim();if(!S)return null;let O=$.state.messages.length;if(O!==H)E.clear(),H=O;let M=E.get(S);if(M)return M;for(let P=$.state.messages.length-1;P>=0;P--){let A=$.state.messages[P];if(!A||A.role!=="assistant")continue;for(let k of A.parts)if(k.type==="tool_call"&&k.call.id===S){let L=String(k.call.name??"").trim()||"tool",v={assistantId:A.id,toolName:L};return E.set(S,v),v}}return null}function B(z){let S=String(z??"").trim();if(!S)return null;for(let O=$.state.messages.length-1;O>=0;O--){let M=$.state.messages[O];if(!M||M.role!=="assistant")continue;for(let P of M.parts)if(P.type==="tool_call"&&P.call.id===S){let A=P.call.arguments;if(A&&typeof A==="object"&&!Array.isArray(A))return A;return null}}return null}function j(z,S){let O=String(z?.tool_call_id??z?.toolCallId??z?.callId??"").trim();if(!O)return b4("missing_tool_call_id",{session_id:String($.state.sessionId??""),event_type:S.eventType,assistant_id:S.assistantId,metadata_keys:Object.keys(z??{}).filter((M)=>M.toLowerCase().includes("call")||M.toLowerCase().includes("id"))}),"";return O}let f={assistantId(z){if(!z||typeof z!=="string"||!z.trim())throw Error(`Invalid assistant ID: ${JSON.stringify(z)}`)},toolCallId(z){let S=String(z??"").trim();if(!S)throw Error("Tool call ID cannot be empty");return S},toolName(z,S="tool"){return String(z??"").trim()||S},sessionId(z){if(z&&typeof z==="string"&&!z.trim())throw Error("Session ID cannot be empty string")}};function R(z){if(!z)return z;if(z.tool_call_id&&!z.toolCallId)z.toolCallId=z.tool_call_id;if(z.callId&&!z.toolCallId)z.toolCallId=z.callId;if(z.tool_name&&!z.toolName)z.toolName=z.tool_name;return z}function I(z){let S=$.state.messages.find((O)=>O.id===z);if(!S||S.role!=="assistant")return!1;return S.parts.some((O)=>O.type==="markdown"&&Boolean(String(O.markdown??"").trim()))}function w(z){if(z.appendToExisting)return["","","> **Interrupted** · Response canceled by user (`Esc`)."].join(`
|
|
960
|
-
`);return"> **Interrupted** · Response canceled by user (`Esc`)."}async function T(z){let S=$.id("round");if(X!==null)return b4("agent_round_concurrent",{session_id:String($.state.sessionId??""),existing_round:X,new_round:S}),{assistantId:$.id("m"),toolCalls:[],success:!1,error:Error("Cannot run agent round while another round is already running")};X=S;try{let O=(z?.baseMessages??$.state.messages).slice(),M=String($.state.context?.system??""),P=$.buildAcpConversation(M,O),A=$.id("m");f.assistantId(A),f.sessionId($.state.sessionId),$.state.thinking.active=!1,$.pushMessage({id:A,role:"assistant",parts:[{type:"status",text:""}]});let k=String($.state.sessionId??"").trim(),L={...k?{session_id:k}:{},cwd:$.state.context.cwd,env:$.state.context.env};V=new AbortController,L.signal=V.signal;let v=z?.toolContext,C=$.state.approval.mode==="all"?{...v??{},approval:{...v?.approval??{},autoApprove:!0}}:v;if(C)L.toolContext=C;if(z?.toolContext)L.resume=!0;let b=()=>{let x=$.state.messages.find((s)=>s.id===A);if(!x||x.role!=="assistant")return"";let c=x.parts.find((s)=>s.type==="status");return String(c?.text??"")},y={isThinking:!1,start(){if(this.isThinking)return;this.isThinking=!0,$.state.thinking.active=!0},end(){if(!this.isThinking){if($.state.thinking.active)b4("thinking_state_inconsistent",{session_id:String($.state.sessionId??""),was_active:!0}),$.state.thinking.active=!1;return}this.isThinking=!1,$.state.thinking.active=!1;let x=b();if(/^thinking\\b/i.test(x))$.setAssistantStatus(A,"")},forceEnd(){let x=this.isThinking||$.state.thinking.active;if(this.isThinking=!1,$.state.thinking.active=!1,x){let c=b();if(/^thinking\\b/i.test(c))$.setAssistantStatus(A,"");b4("thinking_force_ended",{session_id:String($.state.sessionId??"")})}},validate(){let x=this.isThinking,c=$.state.thinking.active;if(x!==c)return b4("thinking_state_mismatch",{session_id:String($.state.sessionId??""),local_active:x,state_active:c}),!1;return!0}};try{let U6=function(F4){return{tool_result:10,tool_output_delta:9,tool_output_start:8,error:7,done:5}[F4||""]??0};$.state.runningAgentRound=!0,b4("agent_round_start",{session_id:String($.state.sessionId??""),resume:Boolean(z?.toolContext)});let x=$.agent.receiveMessage(P,L);_=x;let c=F();G=c;let s=Date.now(),F$=s,K$=0,V$=[],Y$=-1,u$=s,_$=s,n={counts:{},textChars:0,thinkingChars:0,toolArgsChars:0,toolOutputChars:0},a=()=>y.start(),m=()=>y.end(),G$=null,L$=500,P$=50,f$=null,V4=1000,s4=32,z4=async(F4)=>{let E4=Date.now();if(!(Boolean(F4?.force)||E4-u$>=Q))return;u$=E4,await Z()},C6=(F4,E4=1)=>{let c4=String(F4??"").trim();if(!c4)return;n.counts[c4]=(n.counts[c4]??0)+E4},o$=(F4)=>{let E4=Date.now();if(!(Boolean(F4?.force)||E4-_$>=1000))return;_$=E4,b4("agent_round_stats",{session_id:String($.state.sessionId??""),counts:n.counts,textChars:n.textChars,thinkingChars:n.thinkingChars,toolArgsChars:n.toolArgsChars,toolOutputChars:n.toolOutputChars})},F6=async(F4,E4)=>{let c4=Math.max(0,Math.floor(E4));if(c4<=0)return{kind:"timeout"};let Q$=null,Z$=!1,k$=c.promise.then(()=>{Z$=!0});try{let t$=new Promise((Q4)=>{Q$=setTimeout(()=>Q4({kind:"timeout"}),c4)}),q4=c.promise.then(()=>({kind:"abort"})),_4=await Promise.race([q4,F4.then((Q4)=>({kind:"value",value:Q4})),t$]);if(Z$)return{kind:"abort"};return _4}finally{if(Q$)clearTimeout(Q$);k$.catch(()=>{})}};while(!0){let F4=Date.now(),E4=$.streamTotalTimeoutMs-(F4-s),Q$=(f$?Math.max($.streamIdleTimeoutMs,V4*2):$.streamIdleTimeoutMs)-(F4-F$),Z$=$.state.approval.active,k$=Boolean(Z$)&&Z$.status==="pending"&&$.state.paused?.kind==="tool_approval"&&SU($.state.approval.mode,Z$),t$;if(k$){if(!G$)G$=F4;let z$=F4-G$,g=Math.min(P$*(1+Math.floor(z$/200)),P$*4);t$=Math.min(Math.min(E4,Q$),g)}else{if(G$)b4("auto_approve_wait_end",{session_id:String($.state.sessionId??""),waited_ms:F4-G$}),G$=null;t$=Math.min(E4,Q$)}let q4=await F6(x.next(),t$);if(q4.kind==="abort"){y.forceEnd(),$.appendAssistantMarkdown(A,w({appendToExisting:I(A)})),$.state.paused=null,$.state.approval.active=null,$.state.approval.pendingAutoRun=null,$.state.approval.queue=[],$.state.approval.decisions={},$.setAssistantStatus(A,"Interrupted.");break}if(q4.kind==="timeout"){if(k$){let q$=G$?F4-G$:0;if(q$>L$||Q$<=0){b4("auto_approve_timeout_trigger_resume",{session_id:String($.state.sessionId??""),waited_ms:q$,idle_left_ms:Q$,total_left_ms:E4}),$.setAssistantStatus(A,"Awaiting approval…");break}else continue}if(f$){let q$=F4-f$;if(q$<=V4*2){b4("timeout_during_done_drain_extend",{session_id:String($.state.sessionId??""),drain_elapsed_ms:q$,idle_left_ms:Q$,total_left_ms:E4});continue}}let z$=$.state.context?.env,g=["Agent stream timed out.","",`idle_timeout_ms=${$.streamIdleTimeoutMs}`,`total_timeout_ms=${$.streamTotalTimeoutMs}`,...f$?[`done_received_at=${new Date(f$).toISOString()}`,`drain_elapsed_ms=${F4-f$}`]:[]].join(`
|
|
961
|
-
`),h=OJ(g,z$)||"Hint: retry or start a new session if context is too large.";$.appendAssistantMarkdown(A,["# Error","","```text",g,"```","",h].join(`
|
|
962
|
-
`)),$.state.paused=null,$.state.approval.active=null,$.state.approval.pendingAutoRun=null,$.state.approval.queue=[],$.state.approval.decisions={},y.forceEnd(),Y(),b4("agent_round_timeout",{session_id:String($.state.sessionId??""),idle_timeout_ms:$.streamIdleTimeoutMs,total_timeout_ms:$.streamTotalTimeoutMs,thinking_was_active:y.isThinking,auto_approve_waited_ms:G$?F4-G$:void 0,done_received:f$!==null,drain_elapsed_ms:f$?F4-f$:void 0,drain_steps:K$}),$.setAssistantStatus(A,"Error.");break}let{value:_4,done:Q4}=q4.value;if(Q4)break;let n$=_4;F$=Date.now();let T$=n$?.metadata;T$=R(T$);let y4=String(T$?.session_id??"").trim();if(y4&&y4!==$.state.sessionId)$.state.sessionId=y4;if(T$?.usage)$.applyUsageFromSession(T$.usage);let p$=IC(n$)??String(T$?.originalEventType??"");if(C6(p$||`${n$.role}_message`),p$==="tool_output_start"){let z$=j(T$,{eventType:p$,assistantId:A});if(z$){let g=D(z$),h=f.toolName(T$?.toolName??T$?.tool_name??g?.toolName??q(A,z$)),q$=g?.assistantId??A;$.upsertToolOutputStart(q$,z$,h)}await z4(),o$();continue}if(p$==="tool_output_delta"){let z$=j(T$,{eventType:p$,assistantId:A});if(z$){let g=D(z$),h=f.toolName(T$?.toolName??T$?.tool_name??g?.toolName??q(A,z$)),q$=g?.assistantId??A,i=String(T$?.delta??CU(n$.content)??"");if(i)$.appendToolOutputDelta(q$,z$,h,i),n.toolOutputChars+=i.length,await z4(),o$()}else await z4(),o$();continue}if(p$==="thinking_start"){Y$+=1,V$[Y$]="",$.startNewThinkingBlock(A),a(),await z4(),o$();continue}if(p$==="thinking_delta"){a();let z$=CU(n$.content);if(z$&&Y$>=0)V$[Y$]+=z$,$.setAssistantThinking(A,V$[Y$],Y$),n.thinkingChars+=z$.length,await z4(),o$();continue}if(p$==="thinking_end"){m();let z$=CU(n$.content);if(z$&&Y$>=0){let g=V$[Y$];if(z$&&z$!==g){if(g&&z$.startsWith(g))V$[Y$]=z$;else if(g&&!g.startsWith(z$))V$[Y$]+=z$;else if(!g)V$[Y$]=z$}$.endThinkingBlock(A,Y$,V$[Y$])}await z4(),o$();continue}if($.state.thinking.active)m();if(p$==="tool_call_delta"){$.upsertToolCallDelta(A,String(T$?.callId??""),T$?.toolName,T$?.argsTextDelta),n.toolArgsChars+=String(T$?.argsTextDelta??"").length,await z4(),o$();continue}if(n$.role==="assistant"){let z$=n$?.metadata,g=CU(n$.content),h=String(g??"").trim(),q$=(()=>{if(!h)return!1;if((p$==="tool_approval_requested"||Boolean(z$?.approval_requested))&&/^tool approval requested:/i.test(h))return!0;if((p$==="requires_action"||Boolean(z$?.requires_action))&&/^action required:/i.test(h))return!0;return!1})();if(g&&!q$)b4("stream.append",{chars:g.length,total:n.textChars+g.length,preview:g.slice(0,100)}),$.appendAssistantMarkdown(A,g),await z4(),n.textChars+=String(g).length,o$();let i=Array.isArray(n$.tool_calls)?n$.tool_calls:[];for(let p of i){let l=f.toolName(p?.function?.name),$$=p?.function?.arguments,e={};if($$&&typeof $$==="object"&&!Array.isArray($$))e=$$;else if(typeof $$==="string")try{let D$=JSON.parse($$);e=D$&&typeof D$==="object"&&!Array.isArray(D$)?D$:{_raw:$$}}catch{e={_raw:$$}}$.upsertToolCallEnd(A,String(p.id??""),l,e)}if(i.length)await z4();if(i.length)o$();if(z$?.approval_requested&&z$?.tool_call_id&&z$?.tool_name){let p=String(z$.tool_call_id),l=String(z$.tool_name),$$=z$.risk_level,e=z$?.approval_args??z$?.approvalArgs??z$?.args,D$;if(e&&typeof e==="object"&&!Array.isArray(e))D$=e;else if(typeof e==="string"&&e.trim())try{let W4=JSON.parse(e);if(W4&&typeof W4==="object"&&!Array.isArray(W4))D$=W4;else D$={_raw:e}}catch{D$={_raw:e}}let A$=(Boolean(D$&&Object.keys(D$).length>0)?D$:null)??B(p)??D$??void 0,g$=$$==="critical"?"require_action":$$==="high"?"require_action":"pass",c$={id:$.id("approve"),toolCallId:p,tool:l,permission:g$,reason:O2$(`GoatChain approval required (${String($$??"unknown")}).`,l,A$),...A$?{args:A$}:{},source:"goatchain",riskLevel:$$,status:"pending"},y$=D(p)?.assistantId??A;if(!($.state.approval.active?.toolCallId===p||$.state.approval.queue.some((W4)=>W4.request.toolCallId===p))){if(!$.state.approval.active&&$.state.approval.queue.length===0)$.state.approval.decisions={};if($.insertApprovalPart(y$,c$),!$.state.approval.active)$.state.approval.active=c$,$.state.approval.pendingAutoRun={assistantId:y$,toolCallId:p},$.setAssistantStatus(A,SU($.state.approval.mode,c$)?`Auto-approving (${String($$??"risk")})…`:`Awaiting approval (${String($$??"risk")})…`);else $.state.approval.queue.push({request:c$,assistantId:y$})}b4("approval_requested",{session_id:String($.state.sessionId??""),tool_call_id:p,tool_name:l,risk_level:$$}),await z4(),o$()}if(z$?.requires_action)$.state.paused={kind:String(z$?.kind??"")==="ask_user"?"ask_user":"tool_approval",toolCallId:z$?.tool_call_id??z$?.toolCallId,questions:z$?.questions},$.setAssistantStatus(A,$.state.paused.kind==="ask_user"?"Awaiting answers…":"Awaiting approval…"),b4("requires_action",{session_id:String($.state.sessionId??""),kind:z$?.kind,tool_call_id:z$?.tool_call_id??z$?.toolCallId}),await z4(),o$()}else if(n$.role==="tool"){let z$=CU(n$.content),g=String(n$.tool_call_id??""),h=n$?.metadata?.error===!0,q$={id:g||$.id("tool"),output:z$,status:h?"error":"success"},i=g?D(g):null,p=i?.assistantId??A;$.pushMessage({id:$.id("m"),role:"tool",result:q$}),$.attachToolResultPart(p,q$),$.scheduleToolResultHighlight(p,q$),await z4(),o$();let l=g?i?.toolName??q(A,g):null,$$=n$?.metadata?.structuredContent;if(l==="TodoWrite")$.upsertChecklistPartFromGoatChain(p,"todo",g,$$);else if(l==="TodoPlan")$.upsertChecklistPartFromGoatChain(p,"plan",g,$$)}let e4=n$?.metadata;if(e4?.done){if(!f$)if(f$=Date.now(),await $.refreshUsageFromPersistedSession(),m(),$.appendAssistantLlmMeta(A,{durationMs:Math.max(0,f$-s),modelId:String(e4?.modelId??"").trim()||void 0}),b4("agent_round_done",{session_id:String($.state.sessionId??""),stopReason:e4?.stopReason,modelStopReason:e4?.modelStopReason,error:Boolean(e4?.error)}),o$({force:!0}),e4?.stopReason==="approval_required"||$.state.paused)$.setAssistantStatus(A,$.state.paused?.kind==="ask_user"?"Awaiting answers…":"Awaiting approval…");else{if(e4?.error)$.ensureErrorVisibleInTranscript(A,e4.error);$.setAssistantStatus(A,e4?.error?"Error.":"Done.")}let z$=f$?Date.now()-f$:1/0;K$+=1;let g=U6(p$);if(!(K$<=s4&&z$<=V4&&(g>0||K$===1))){if(K$>s4)b4("done_drain_step_limit",{session_id:String($.state.sessionId??""),steps:K$,last_event_type:p$});else if(z$>V4)b4("done_drain_time_limit",{session_id:String($.state.sessionId??""),duration_ms:z$,last_event_type:p$});else if(g===0&&K$>1)b4("done_drain_skip_low_priority",{session_id:String($.state.sessionId??""),event_type:p$,step:K$});break}continue}}if(!$.state.paused){let F4=$.state.messages.find((c4)=>c4.id===A),E4=F4&&F4.role==="assistant"?F4.parts.find((c4)=>c4.type==="status"):null;if(E4&&E4.text==="Thinking…")$.setAssistantStatus(A,"Done.")}let A6=(()=>{let F4=$.state.messages.find((E4)=>E4.id===A);if(!F4||F4.role!=="assistant")return[];return F4.parts.flatMap((E4)=>E4.type==="tool_call"?[E4.call]:[])})();return{assistantId:A,toolCalls:A6,success:!0}}catch(x){y.forceEnd();let c=x instanceof Error?x:Error(String(x)),s=c.stack||c.message||String(x),F$=$.state.context?.env,K$=OJ(s,F$);$.appendAssistantMarkdown(A,["# Error","","```text",s,"```",...K$?["",K$]:[]].join(`
|
|
963
|
-
`)),$.setAssistantStatus(A,"Error."),b4("agent_round_error",{session_id:String($.state.sessionId??""),error_message:c.message,error_name:c.name,assistant_id:A});let V$=(()=>{let Y$=$.state.messages.find((u$)=>u$.id===A);if(!Y$||Y$.role!=="assistant")return[];return Y$.parts.flatMap((u$)=>u$.type==="tool_call"?[u$.call]:[])})();return{assistantId:A,toolCalls:V$,success:!1,error:c}}finally{if(X===S){if(_)K();if(G)N()}y.forceEnd(),$.state.runningAgentRound=!1,X=null}}catch(O){throw O}finally{X=null}}return{runAgentRound:T,cancelActiveAgentStream:K,abortActiveAgentRound:N}}function j2$($){let J=String($.name??"").toLowerCase();if(J==="search")return{permission:"require_action",reason:"Search may access the network."};if(J==="bash")return{permission:"require_action",reason:"Bash can execute commands."};if(J==="grep")return{permission:"pass",reason:"Grep may read local files."};return null}function TC($){function J(G,V){let X=j2$(V);if(!X)return"ok";if(ev($.state.approval.mode,X.permission))return"ok";if($.state.approval.approvedToolCalls[V.id])return"ok";let Z=$.state.approval.active;if(Z?.toolCallId===V.id)return"pending";if(Z)return $.setAssistantStatus(G,`Another approval is pending (${Z.permission})…`),"pending";let Y={id:$.id("approve"),toolCallId:V.id,tool:V.name,permission:X.permission,reason:X.reason,args:V.arguments,status:"pending"};return $.state.approval.active=Y,$.state.approval.pendingAutoRun={assistantId:G,toolCallId:V.id},$.insertApprovalPart(G,Y),$.setAssistantStatus(G,`Awaiting approval (${X.permission})…`),"pending"}function U(G){for(let V of $.state.messages){if(V.role!=="assistant")continue;for(let X of V.parts)if(X.type==="tool_call"&&X.call.id===G)return{messageId:V.id,call:X.call}}return null}async function Q(G){let V=$.state.approval.active;if(!V)return;let X={...V,status:G},Y=$.state.approval.pendingAutoRun?.assistantId;if(Y)$.updateAssistant(Y,(N)=>{let q=N.parts.map((H)=>{if(H.type==="approve"&&H.request.id===V.id)return{type:"approve",request:X};return H});return{...N,parts:q}});if((V.source??"local")==="goatchain"){$.state.approval.decisions[V.toolCallId]=G==="approved"?{approved:!0}:{approved:!1,reason:V.reason||"User denied approval"};let N=$.state.approval.queue.shift()??null;if(N){if($.state.approval.active=N.request,$.state.approval.pendingAutoRun={assistantId:N.assistantId,toolCallId:N.request.toolCallId},$.state.paused?.kind==="tool_approval")$.state.paused={...$.state.paused,toolCallId:N.request.toolCallId};$.setAssistantStatus(N.assistantId,`Awaiting approval (${String(N.request.riskLevel??N.request.permission??"risk")})…`);return}$.state.approval.active=null,$.state.approval.pendingAutoRun=null;let q={...$.state.approval.decisions};$.state.approval.decisions={};let H=Object.values(q).some((B)=>B.approved),E=Object.values(q).some((B)=>!B.approved);if(Y){let B=H&&!E?"Approved. Resuming…":E&&!H?"Denied. Resuming…":"Resuming…";$.setAssistantStatus(Y,B)}let D=async()=>{$.state.paused=null,await $.runAgentRound({toolContext:{approval:{decisions:q}}})};if($.isInSendQueueRun()){await D();return}await $.serializeReceive(D);return}if(G==="approved")$.state.approval.approvedToolCalls[V.toolCallId]=!0;if($.state.approval.active=null,$.state.approval.pendingAutoRun=null,G==="denied"){if(!Y)return;$.setAssistantStatus(Y,"Permission denied.");let N=["# Tool permission denied","",`- tool: \`${V.tool}\``,`- permission: \`${V.permission}\``,"","You can re-select the tool_call and try again."].join(`
|
|
964
|
-
`);$.pushMessage({id:$.id("m"),role:"assistant",parts:[{type:"markdown",markdown:N}]});return}if(!Y)return;$.setAssistantStatus(Y,`Running ${V.tool}…`),await $.sleep(180);let K=await _(V.toolCallId);if($.setAssistantStatus(Y,"Done."),!K)return;let F=["# Approved + executed tool","",`Permission \`${V.permission}\` approved for \`${V.tool}\`.`,"","```text",G1(K.output).split(`
|
|
965
|
-
`).slice(0,8).join(`
|
|
966
|
-
`),"```"].join(`
|
|
967
|
-
`);$.pushMessage({id:$.id("m"),role:"assistant",parts:[{type:"markdown",markdown:F}]})}async function _(G){if($.externalAgentProvided)return null;let V=U(G);if(!V)return null;if(!$.state.approval.approvedToolCalls[G]){if(J(V.messageId,V.call)==="pending")return null}$.state.runningToolCallId=G;try{let X=await(async()=>{try{return await $.toolRunner(V.call)}catch(Z){let Y=Z instanceof Error?Z.stack||Z.message:String(Z);return{id:G,status:"error",output:`Tool runner error:
|
|
968
|
-
${Y}`}}})();return $.pushMessage({id:$.id("m"),role:"tool",result:X}),$.attachToolResultPart(V.messageId,X),X}finally{$.state.runningToolCallId=null}}return{ensureApproved:J,findToolCall:U,resolveActiveApproval:Q,runToolCall:_}}async function f8($){await new Promise((J)=>setTimeout(J,$))}function CC($){let J=Boolean($.agent),U=$.context?.env,Q=DC(U),_=EC(Q),G=D2$({config:{...PC(Q)},usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0,budget:4000},runningAgentRound:!1,thinking:{active:!1},ui:{theme:{preset:"goatchain",overrides:{}},debugPerfPanel:!1,upgradeNotification:{visible:!1,message:""}},context:$.context,messages:[],revertedMessages:[],selectedToolCallId:null,runningToolCallId:null,expandedBashOutputs:new Set,sessionId:MC(Q),paused:null,approval:{active:null,approvedToolCalls:{},pendingAutoRun:null,mode:_,queue:[],decisions:{}}}),V=LC(Q),X=V.idleMs,Z=V.totalMs,Y=!1,K=$.agent;function F(){if(Y)return!1;let i=G.approval.active;if(!i||i.status!=="pending")return!1;if(!SU(G.approval.mode,i))return!1;if(G.runningAgentRound)return!1;return!0}let N=EX(()=>{let i=Math.max(1,G.usage.budget);return Math.min(1,G.usage.total_tokens/i)}),q=EX(()=>{let i=`${G.context.system}
|
|
969
|
-
`,p=G.context.focusFiles;if(p?.length){let l=p.map(($$)=>{let e=String($$??"");return`- [${e.split(/[/\\]/).filter(Boolean).pop()??e}](${e})`});i+=`
|
|
970
|
-
[focus_files]
|
|
971
|
-
${l.join(`
|
|
972
|
-
`)}
|
|
973
|
-
`}for(let l of Oj(G.messages)){if(l.role==="user"){if(l.focusFiles?.length){let $$=l.focusFiles.map((e)=>{let D$=String(e??"");return`- [${D$.split(/[/\\]/).filter(Boolean).pop()??D$}](${D$})`});i+=`
|
|
974
|
-
[user_focus_files]
|
|
975
|
-
${$$.join(`
|
|
976
|
-
`)}
|
|
977
|
-
`}i+=`
|
|
978
|
-
[user]
|
|
979
|
-
${l.content}
|
|
980
|
-
`;continue}if(l.role==="tool"){i+=`
|
|
981
|
-
[tool]
|
|
982
|
-
${l.result.output}
|
|
983
|
-
`;continue}i+=`
|
|
984
|
-
[assistant]
|
|
985
|
-
`;for(let $$ of l.parts)if($$.type==="status")i+=`${$$.text}
|
|
986
|
-
`;else if($$.type==="markdown")i+=`${$$.markdown}
|
|
987
|
-
`;else if($$.type==="tool_call")i+=`${$$.call.name} ${kU($$.call.arguments)}
|
|
988
|
-
`;else if($$.type==="tool_result")i+=`${$$.result.output}
|
|
989
|
-
`;else if($$.type==="approve")i+=`approve ${$$.request.permission} ${$$.request.tool} ${$$.request.status}
|
|
990
|
-
`;else if($$.type==="todo"||$$.type==="plan")i+=`${$$.title}
|
|
991
|
-
${$$.items.map((e)=>`- ${e.done?"[x]":"[ ]"} ${e.text}`).join(`
|
|
992
|
-
`)}
|
|
993
|
-
`}return Kv(i)}),H=EX(()=>{let i=Math.max(1,G.config.context_window);return Math.min(1,q.value/i)});function E(i){if(!i||typeof i!=="object")return;let p=i,l=Number(p.promptTokens??p.prompt_tokens),$$=Number(p.completionTokens??p.completion_tokens),e=Number(p.totalTokens??p.total_tokens);if(Number.isFinite(l))G.usage.prompt_tokens=l;if(Number.isFinite($$))G.usage.completion_tokens=$$;if(Number.isFinite(l)&&Number.isFinite($$))G.usage.total_tokens=l+$$;else if(Number.isFinite(e))G.usage.total_tokens=e}async function D(){let i=String(G.sessionId??"").trim();if(!i)return;let p=G.context?.env,l=Boolean(String(p?.GOATCHAIN_STATE_DIR??globalThis?.process?.env?.GOATCHAIN_STATE_DIR??"").trim()),$$=Boolean(String(p?.GOATCHAIN_HOME??globalThis?.process?.env?.GOATCHAIN_HOME??"").trim()),e=async()=>{try{let[{homedir:v$},A$]=await Promise.all([import("node:os"),import("node:path")]),g$=globalThis?.process?.env,c$=(X4)=>String(p?.[X4]??g$?.[X4]??"").trim()||void 0,d$=c$("GOATCHAIN_HOME");if(d$)return A$.resolve(d$,$J,yG);let y$=c$("XDG_CONFIG_HOME");if(y$)return A$.resolve(y$,e9,$J,yG);return A$.resolve(v$(),e9,$J,yG)}catch{return null}},D$=String(p?.GOATCHAIN_STATE_DIR??globalThis?.process?.env?.GOATCHAIN_STATE_DIR??"").trim();if(!D$)D$=await e()??"";if(!D$)return;try{let[{readFile:v$},A$]=await Promise.all([import("node:fs/promises"),import("node:path")]),g$=A$.join(D$,i,"session.json");for(let c$=0;c$<40;c$++){try{let d$=await v$(g$,"utf8"),X4=JSON.parse(d$)?.stats?.usage;if(X4&&typeof X4==="object"){E(X4);return}}catch{if(!l&&!$$)return}if(l||$$)await f8(50);else return}}catch{}}function B(i){let p=G.context,l=(i??[]).map(($$)=>String($$??"")).filter(Boolean);G.context={...p??{},focusFiles:l.length?l:void 0}}function j(i){let p=G.context,l=String(i??"").trim()||".";G.context={...p??{},cwd:l}}function f(i,p){let l=G.context,$$={...l?.env??{}},e=String(i??"").trim();if(!e)return;let D$=p==null?"":String(p);if(!D$)delete $$[e];else $$[e]=D$;G.context={...l??{},env:$$}}function R(i){f("GOATCHAIN_AGENT",i)}function I(i){G.ui.theme.preset=i}function w(i,p){let l=i,$$=G.ui.theme.overrides??{};if(!p||!p.fg&&!p.bg){let{[l]:e,...D$}=$$;G.ui.theme.overrides=D$;return}G.ui.theme.overrides={...$$,[l]:{fg:p.fg,bg:p.bg}}}function T(){G.ui.theme.overrides={}}let z=kC(G),{pushMessage:S,updateAssistant:O,setAssistantStatus:M,setAssistantThinking:P,startNewThinkingBlock:A,endThinkingBlock:k,appendAssistantMarkdown:L,appendAssistantLlmMeta:v,upsertToolCallDelta:C,upsertToolCallEnd:b,upsertToolOutputStart:y,appendToolOutputDelta:x,attachToolResultPart:c,insertApprovalPart:s,toggleChecklist:F$,toggleBlockCollapsed:K$,revertFromMessage:V$,restoreRevertedMessages:Y$,clearRevertedMessages:u$,hasRevertedMessages:_$,revertedMessageCount:n,upsertChecklistPartFromGoatChain:a}=z;function m(i){G.selectedToolCallId=i}function G$(i){let p=new Set(G.expandedBashOutputs);if(p.has(i))p.delete(i);else p.add(i);G.expandedBashOutputs=p}function L$(i,p){let l=G.messages.find((d$)=>d$.id===i);if(!l||l.role!=="assistant")return;let e=l.parts.flatMap((d$)=>d$.type==="markdown"?[String(d$.markdown??"")]:[]).join(`
|
|
994
|
-
`),D$=e.trim();if(/\nHint:/.test(e))return;let A$=G.context?.env,g$="",c$=null;if(typeof p==="boolean"&&p)c$=OJ(e,A$);else if(p){g$=jj(p);let d$=/(?:^|\n)#+\s*error\b/i.test(e),y$=g$.trim()?e.includes(g$):!1;if(!d$&&!y$){c$=OJ(g$,A$),L(i,`${D$?`
|
|
995
|
-
|
|
996
|
-
`:""}${["# Error","","```text",g$,"```",...c$?["",c$]:[]].join(`
|
|
997
|
-
`)}`);return}c$=OJ(g$,A$)}if(c$)L(i,`
|
|
998
|
-
|
|
999
|
-
${c$}`)}function P$(i,p){wC({state:G,assistantId:i,result:p,updateAssistant:O})}let f$=Promise.resolve(),V4=!1,s4=null,U6=null,z4=0,C6=60,o$=async(i)=>{f$=f$.then(i,i),await f$},F6=SC({state:G,agent:K,id:vU,buildAcpConversation:jC,streamIdleTimeoutMs:X,streamTotalTimeoutMs:Z,pushMessage:S,setAssistantStatus:M,setAssistantThinking:P,startNewThinkingBlock:A,endThinkingBlock:k,appendAssistantMarkdown:L,appendAssistantLlmMeta:v,upsertToolCallDelta:C,upsertToolCallEnd:b,upsertToolOutputStart:y,appendToolOutputDelta:x,insertApprovalPart:s,attachToolResultPart:c,scheduleToolResultHighlight:P$,upsertChecklistPartFromGoatChain:a,applyUsageFromSession:E,refreshUsageFromPersistedSession:D,ensureErrorVisibleInTranscript:L$}),{runAgentRound:A6,cancelActiveAgentStream:F4,abortActiveAgentRound:E4}=F6,c4=TC({state:G,externalAgentProvided:J,toolRunner:$.toolRunner,id:vU,pushMessage:S,updateAssistant:O,setAssistantStatus:M,insertApprovalPart:s,attachToolResultPart:c,runAgentRound:(i)=>A6(i),sleep:f8,serializeReceive:o$,isInSendQueueRun:()=>Y}),{ensureApproved:Q$,findToolCall:Z$,resolveActiveApproval:k$,runToolCall:t$}=c4;vC(()=>G.approval.mode,()=>{if(F())k$("approved")}),vC(()=>G.runningAgentRound,(i)=>{if(i)return;if(F())k$("approved")});function q4(){if(G.runningAgentRound)return!0;if(G.paused)return!0;return Boolean(G.approval.active&&G.approval.active.status==="pending")}function _4(i,p){let l=String(i??""),$$=p?.length?[...p]:void 0;if(U6){let D$=G.messages.findIndex((v$)=>v$.role==="user"&&v$.id===U6);if(D$>=0){let v$=G.messages[D$];G.messages[D$]={...v$,content:l,focusFiles:$$};return}}let e=vU("m");U6=e,S({id:e,role:"user",content:l,focusFiles:$$})}async function Q4(i){let p=typeof i==="string"?i:i.content,l=typeof i==="string"?void 0:i.focusFiles,$$=G1(p);if(!$$&&!l?.length)return;if(l?.length)B(l);if(s4={content:$$,...l?.length?{focusFiles:l}:{}},_4($$,l),q4())z4=Date.now()+C6,n$(),G.paused=null,G.approval.active=null,G.approval.pendingAutoRun=null,G.approval.queue=[],G.approval.decisions={};let e=async()=>{if(V4)return;V4=!0;try{while(s4){let D$=Date.now();if(z4>D$){await f8(z4-D$);continue}s4=null,U6=null,Y=!0;let v$=G.messages.slice();try{let{assistantId:A$,toolCalls:g$,success:c$,error:d$}=await A6({baseMessages:v$});if(!c$&&d$){console.warn("Agent round failed:",d$.message),G.runningAgentRound=!1,Y=!1;continue}if(G.paused){if(G.paused.kind==="tool_approval")for(let y$=0;y$<16;y$++){let X4=G.approval.active;if(!X4||X4.status!=="pending")break;if(!SU(G.approval.mode,X4))break;if(await k$("approved"),!G.paused||G.paused.kind!=="tool_approval")break}continue}if(J)continue;if(await f8(500),M(A$,g$.length?"Planning…":"Drafting…"),await f8(500),g$[0]){if(G.messages.some((W4)=>W4.role==="tool"&&W4.result.id===g$[0].id)){M(A$,"Done.");continue}if(Q$(A$,g$[0])==="pending")continue;M(A$,`Running ${g$[0].name}…`),await f8(500);let X4=await t$(g$[0].id);if(await f8(300),M(A$,"Done."),X4){let W4=["# Summary","","Here is a mocked end-to-end flow:","",`- Ran \`${g$[0].name}\` and captured a tool result`,"- Rendered markdown + code fences","","## Tool output (excerpt)","","```text",G1(X4.output).split(`
|
|
1000
|
-
`).slice(0,8).join(`
|
|
1001
|
-
`),"```","","## Next","","- You can select a `tool_call` on the left and re-run it","- (Coming next) approval-gated tools + context token breakdown"].join(`
|
|
1002
|
-
`);S({id:vU("m"),role:"assistant",parts:[{type:"markdown",markdown:W4}]})}}else M(A$,"Done.")}catch(A$){E4(),F4(),G.runningAgentRound=!1,G.runningToolCallId=null,G.paused=null,G.approval.active=null,G.approval.pendingAutoRun=null,G.approval.queue=[],G.approval.decisions={};let g$=G.context?.env,c$=jj(A$),d$=OJ(c$,g$),y$=["# Error","","```text",c$,"```",...d$?["",d$]:[]].join(`
|
|
1003
|
-
`);S({id:vU("m"),role:"assistant",parts:[{type:"status",text:"Error."},{type:"markdown",markdown:y$}]})}finally{Y=!1}}}finally{V4=!1}};f$=f$.then(e,e),await f$}function n$(){if(G.runningAgentRound)E4(),F4(),G.runningAgentRound=!1;if(G.runningToolCallId){let i=G.runningToolCallId;G.runningToolCallId=null;let p=Z$(i);if(p)M(p.messageId,"Interrupted.")}if(G.approval.pendingAutoRun||G.approval.active||G.approval.queue.length)G.approval.active=null,G.approval.pendingAutoRun=null,G.approval.queue=[],G.approval.decisions={}}async function T$(i){let p=G.paused;if(!p||p.kind!=="ask_user")return;let l=String(p.toolCallId??"").trim();if(!l)return;G.paused=null,await o$(async()=>{let e=await A6({toolContext:{askUser:{answers:{[l]:{...i}}}}});if(!e.success&&e.error)console.warn("Failed to resume after ask user:",e.error.message)})}async function y4(){let i=G.paused;if(!i||i.kind!=="ask_user")return;let p=String(i.toolCallId??"").trim();if(!p)return;G.paused=null,await o$(async()=>{let $$=await A6({toolContext:{askUser:{answers:{},rejected:{[p]:"User cancelled the question"}}}});if(!$$.success&&$$.error)console.warn("Failed to resume after cancel ask user:",$$.error.message)})}function p$(i){if(typeof K.setMode==="function")K.setMode(i)}function e4(){if(typeof K.getMode==="function")return K.getMode();return"agent"}let z$=null;function g(i){if(G.ui.upgradeNotification.visible=!0,G.ui.upgradeNotification.message=i,z$)clearTimeout(z$);z$=setTimeout(()=>{h(),z$=null},3000)}function h(){if(G.ui.upgradeNotification.visible=!1,G.ui.upgradeNotification.message="",z$)clearTimeout(z$),z$=null}let q$=EX(()=>G.ui.upgradeNotification);return{state:G,usagePct:N,contextTokens:q,contextPct:H,scheduleToolResultHighlight:P$,selectToolCall:m,toggleBashOutput:G$,toggleChecklist:F$,toggleBlockCollapsed:K$,send:Q4,sendUser:Q4,sendUserInput:(i)=>Q4(i),setFocusFiles:B,setCwd:j,setEnvVar:f,setAgent:R,setThemePreset:I,setMessageTypeThemeOverride:w,resetThemeOverrides:T,approve:()=>k$("approved"),deny:()=>k$("denied"),runToolCall:t$,interrupt:n$,submitAskUserAnswers:T$,cancelAskUser:y4,revertFromMessage:V$,restoreRevertedMessages:Y$,clearRevertedMessages:u$,hasRevertedMessages:_$,revertedMessageCount:n,setMode:p$,getMode:e4,upgradeNotification:q$,showUpgradeNotification:g,dismissUpgradeNotification:h}}import{defineComponent as E2$,h as PX}from"vue";var bC=E2$({name:"GoatChainExitAppDialog",props:{modelValue:{type:Boolean,required:!0},reason:{type:String,default:""}},emits:{"update:modelValue":($)=>!0,exit:()=>!0},setup($,{emit:J}){return()=>{if(!$.modelValue)return null;let U=String($.reason??"").trim();return PX(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(Q)=>J("update:modelValue",Q),onKeydownCapture:(Q)=>{if(Q?.key==="Escape"){Q.preventDefault?.(),Q.stopPropagation?.(),J("update:modelValue",!1);return}if(typeof Q?.key==="string"&&Q.key.length===1&&!Q.ctrlKey&&!Q.metaKey&&!Q.altKey)Q.preventDefault?.(),Q.stopPropagation?.()},w:64,h:12,title:"Exit GoatChain",placement:"center",backdrop:!1,padding:1,style:{fg:"yellowBright",bg:"black"},buttons:[{label:"Cancel",value:"cancel"},{label:"Exit",value:"exit",kind:"primary",default:!0}],onConfirm:(Q)=>{if(Q?.value==="exit")J("exit");J("update:modelValue",!1)},onClose:()=>J("update:modelValue",!1)},()=>[PX(t,{x:0,y:0,w:60,wrap:!0,value:"Exit now?",style:{fg:"whiteBright",bg:"black"}}),PX(t,{x:0,y:2,w:60,wrap:!0,value:"An agent response is still in progress. Exiting will interrupt it.",style:{fg:"white",dim:!0,bg:"black"}}),U?PX(t,{x:0,y:4,w:60,wrap:!0,value:`Reason: ${U}`,style:{fg:"white",dim:!0,bg:"black"}}):null])}}});var Pj=P2$({name:"GoatChainProvider",props:{toolRunner:{type:Function,required:!0},context:{type:Object,required:!0},agent:{type:Object,required:!0},onStoreCreated:{type:Function,default:void 0},sessions:{type:Object,default:void 0}},setup($,{slots:J}){if(M2$(E8,null))return()=>J.default?.();let Q=CC({toolRunner:$.toolRunner,context:$.context,agent:$.agent});$.onStoreCreated?.(Q),z2$(E8,{store:Q,sessions:$.sessions});let _=gC(!1),G=gC(""),V=()=>{let Z=Q.state;if(Z.runningAgentRound)return"Agent is still responding";if(Z.paused?.kind==="ask_user")return"Awaiting AskUser answers";if(Z.paused?.kind==="tool_approval")return"Awaiting tool approval";if(Z.approval?.active?.status==="pending")return"Pending approval";return""},X=Yk({isBusy:()=>{let Z=Q.state;if(Z.runningAgentRound)return!0;if(Z.paused)return!0;return Boolean(Z.approval?.active&&Z.approval.active.status==="pending")},showConfirm:()=>{G.value=V(),_.value=!0}});return L2$(()=>X()),()=>yC("div",null,[J.default?.(),yC(bC,{modelValue:_.value,"onUpdate:modelValue":(Z)=>_.value=Z,reason:G.value,onExit:()=>rG()})])}});var MX=[{name:"home",component:Bj},{name:"chat",component:Hj}];function R2$($){if(typeof $==="string")return $;if($&&typeof $==="object"&&"name"in $)return String($.name??"");return""}function A2$($,J){let U=R2$(J)||"home";return $.some((Q)=>Q.name===U)?U:"home"}function Mj($){return MV({routes:MX,initialRoute:A2$(MX,$?.initialRoute??"home")})}import{defineComponent as w2$,h as xC}from"vue";var Lj=w2$({name:"GoatChainShell",props:{toolRunner:{type:Function,required:!0},context:{type:Object,required:!0},agent:{type:Object,required:!0},onStoreCreated:{type:Function,default:void 0},sessions:{type:Object,default:void 0}},setup($){return()=>xC(Pj,{toolRunner:$.toolRunner,context:$.context,agent:$.agent,onStoreCreated:$.onStoreCreated,sessions:$.sessions},()=>xC(LV,{routes:MX}))}});var zX=process.env.GOATCHAIN_DEBUG==="1"||process.argv.includes("--debug"),LX=process.env.GOATCHAIN_DEBUG_LOG||"./goatchain-debug.log",hC=1500;function r0($,J){if(!zX)return;let Q=`[${new Date().toISOString()}] ${$}${J?`: ${JSON.stringify(J,null,2)}`:""}
|
|
1004
|
-
`;try{f2$(LX,Q)}catch{}}function uC(){if(!zX)return;k2$(LX,`=== GoatChain Debug Log ===
|
|
1005
|
-
Started at: ${new Date().toISOString()}
|
|
1006
|
-
PID: ${process.pid}
|
|
1007
|
-
Argv: ${JSON.stringify(process.argv)}
|
|
1008
|
-
Bun: ${typeof globalThis.Bun<"u"}
|
|
1009
|
-
|
|
1010
|
-
`),process.on("uncaughtException",($,J)=>{r0("UNCAUGHT EXCEPTION",{origin:J,error:$.message,stack:$.stack}),console.error(`
|
|
1011
|
-
|
|
1012
|
-
=== CRASH: Uncaught Exception ===`),console.error("Error:",$.message),console.error("Stack:",$.stack),console.error(`
|
|
1013
|
-
Debug log written to: ${LX}`),zj(1)}),process.on("unhandledRejection",($,J)=>{let U=$ instanceof Error?$:Error(String($));r0("UNHANDLED REJECTION",{error:U.message,stack:U.stack}),console.error(`
|
|
1014
|
-
|
|
1015
|
-
=== CRASH: Unhandled Promise Rejection ===`),console.error("Reason:",U.message),console.error("Stack:",U.stack),console.error(`
|
|
1016
|
-
Debug log written to: ${LX}`),zj(1)}),process.on("SIGINT",()=>{r0("Received SIGINT")}),process.on("SIGTERM",()=>{r0("Received SIGTERM")}),r0("Crash handlers installed")}function zj($){let J=Number.isFinite($)?Math.trunc($):1;process.exitCode=J;try{rG();return}catch{}setTimeout(()=>{try{process.exit(J)}catch{}},1500).unref?.()}function I2$($){let J=String($??"").trim();if(!J)return;let U=globalThis.__GOATCHAIN_UPGRADE_TOAST__;if(typeof U==="function"){U(J);return}if(!process.env.GOATCHAIN_STARTUP_UPGRADE_TOAST)process.env.GOATCHAIN_STARTUP_UPGRADE_TOAST=J}async function S2$($,J){return await Promise.race([$,new Promise((U)=>setTimeout(()=>U(null),J))])}async function T2$($){let J=globalThis.process;if(!J)throw Error("runCli is only supported in Node");let U=$??J.argv?.slice(2)??[];if(bX(U)){console.log(yX());return}let Q=Cj(U,{stdout:J.stdout}),_=String(J.env.GOATCHAIN_TERM_TITLE_BASE??"").trim()||String(Q.app??"").trim()||"goatchain";if(J.env.GOATCHAIN_TERM_TITLE_BASE=_,z_(_,{stdout:J.stdout}),Q.debug){if(J.env.GOATCHAIN_DEBUG="1",!zX)zX=!0,uC()}if(r0("[CLI] runCli() called"),r0("[CLI] args",{app:Q.app,cols:Q.cols,rows:Q.rows}),Q.approvals)J.env.GOATCHAIN_TOOL_APPROVALS=Q.approvals;let G=Q.app==="goatchain"?(X)=>{let Z=Mj({initialRoute:Q.initialRoute||"home"});X.use(Z)}:void 0;r0("[CLI] Before createGoatChainShellProps");let V=Q.app==="goatchain"?await SB({cwd:String(J.cwd?.()??"."),env:J.env}):{cols:Q.cols,rows:Q.rows};r0("[CLI] After createGoatChainShellProps"),r0("[CLI] About to call runTerminalUi"),await yI({proc:J,cols:Q.cols,rows:Q.rows,sizeLocked:Q.sizeLocked,component:Lj,props:V,install:G,defaultStyle:Q.app==="goatchain"?{fg:"whiteBright",bg:"black"}:void 0,palette:Q.app==="goatchain"?{blackBright:"#262626"}:void 0,defaultBg:Q.app==="goatchain"?"black":void 0,altScreen:Q.altScreen,enableMouse:Q.enableMouse,recordPath:Q.recordPath,replayPath:Q.replayPath,snapshotPath:Q.snapshotPath})}async function v2$(){if(uC(),bX(process.argv.slice(2))){console.log(yX());try{process.stdin?.pause?.()}catch{}process.exit(0)}let $=!1,J=(_)=>{if($||!_)return;$=!0,I2$(_)},U=kT();U.then(J).catch((_)=>{r0("[CLI] npm upgrade check failed",{error:_ instanceof Error?_.message:String(_)})});let Q=await S2$(U,hC);if(Q===null)r0("[CLI] npm upgrade check timed out",{timeoutMs:hC});J(Q),await T2$()}if(E$.main==E$.module||import.meta.url===`file://${process.argv[1]}`)v2$().catch(($)=>{console.error("Fatal error during setup:",$),zj(1)});export{T2$ as runCli};
|