goatchain-cli 0.0.5-beta.8 → 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 Jb}from"node:module";var tC=Object.create;var{getPrototypeOf:sC,defineProperty:vX,getOwnPropertyNames:eC}=Object;var $b=Object.prototype.hasOwnProperty;var U4=($,J,U)=>{U=$!=null?tC(sC($)):{};let Q=J||!$||!$.__esModule?vX(U,"default",{value:$,enumerable:!0}):U;for(let _ of eC($))if(!$b.call(Q,_))vX(Q,_,{get:()=>$[_],enumerable:!0});return Q};var J$=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var O0=($,J)=>{for(var U in J)vX($,U,{get:J[U],enumerable:!0,configurable:!0,set:(Q)=>J[U]=()=>Q})};var CX=($,J)=>()=>($&&(J=$($=0)),J);var E$=Jb(import.meta.url);var CE=J$((TE)=>{Object.defineProperty(TE,"__esModule",{value:!0});TE.splitWhen=TE.flatten=void 0;function Nx($){return $.reduce((J,U)=>[].concat(J,U),[])}TE.flatten=Nx;function Fx($,J){let U=[[]],Q=0;for(let _ of $)if(J(_))Q++,U[Q]=[];else U[Q].push(_);return U}TE.splitWhen=Fx});var gE=J$((bE)=>{Object.defineProperty(bE,"__esModule",{value:!0});bE.isEnoentCodeError=void 0;function qx($){return $.code==="ENOENT"}bE.isEnoentCodeError=qx});var mE=J$((hE)=>{Object.defineProperty(hE,"__esModule",{value:!0});hE.createDirentFromStats=void 0;class xE{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 Hx($,J){return new xE($,J)}hE.createDirentFromStats=Hx});var nE=J$((iE)=>{Object.defineProperty(iE,"__esModule",{value:!0});iE.convertPosixPathToPattern=iE.convertWindowsPathToPattern=iE.convertPathToPattern=iE.escapePosixPath=iE.escapeWindowsPath=iE.escape=iE.removeLeadingDotSegment=iE.makeAbsolute=iE.unixify=void 0;var Bx=E$("os"),Ox=E$("path"),cE=Bx.platform()==="win32",jx=2,Dx=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,Ex=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,Px=/^\\\\([.?])/,Mx=/\\(?![!()+@[\]{}])/g;function Lx($){return $.replace(/\\/g,"/")}iE.unixify=Lx;function zx($,J){return Ox.resolve($,J)}iE.makeAbsolute=zx;function Rx($){if($.charAt(0)==="."){let J=$.charAt(1);if(J==="/"||J==="\\")return $.slice(jx)}return $}iE.removeLeadingDotSegment=Rx;iE.escape=cE?cY:dY;function cY($){return $.replace(Ex,"\\$2")}iE.escapeWindowsPath=cY;function dY($){return $.replace(Dx,"\\$2")}iE.escapePosixPath=dY;iE.convertPathToPattern=cE?dE:lE;function dE($){return cY($).replace(Px,"//$1").replace(Mx,"/")}iE.convertWindowsPathToPattern=dE;function lE($){return dY($)}iE.convertPosixPathToPattern=lE});var aE=J$((yV$,pE)=>{/*!
|
|
2
|
-
* is-extglob <https://github.com/jonschlinkert/is-extglob>
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) 2014-2016, Jon Schlinkert.
|
|
5
|
-
* Licensed under the MIT License.
|
|
6
|
-
*/pE.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 sE=J$((gV$,tE)=>{/*!
|
|
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 Cx=aE(),oE={"{":"}","(":")","[":"]"},bx=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=oE[X];if(Z){var Y=$.indexOf(Z,J);if(Y!==-1)J=Y+1}if($[J]==="!")return!0}else J++}return!1},yx=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=oE[U];if(Q){var _=$.indexOf(Q,J);if(_!==-1)J=_+1}if($[J]==="!")return!0}else J++}return!1};tE.exports=function(J,U){if(typeof J!=="string"||J==="")return!1;if(Cx(J))return!0;var Q=bx;if(U&&U.strict===!1)Q=yx;return Q(J)}});var $P=J$((xV$,eE)=>{var gx=sE(),xx=E$("path").posix.dirname,hx=E$("os").platform()==="win32",lY="/",ux=/\\/g,mx=/[\{\[].*[\}\]]$/,cx=/(^|[^\\])([\{\[]|\([^\)]+$)/,dx=/\\([\!\*\?\|\[\]\(\)\{\}])/g;eE.exports=function(J,U){var Q=Object.assign({flipBackslashes:!0},U);if(Q.flipBackslashes&&hx&&J.indexOf(lY)<0)J=J.replace(ux,lY);if(mx.test(J))J+=lY;J+="a";do J=xx(J);while(gx(J)||cx.test(J));return J.replace(dx,"$1")}});var LQ=J$((lx)=>{lx.isInteger=($)=>{if(typeof $==="number")return Number.isInteger($);if(typeof $==="string"&&$.trim()!=="")return Number.isInteger(Number($));return!1};lx.find=($,J)=>$.nodes.find((U)=>U.type===J);lx.exceedsLimit=($,J,U=1,Q)=>{if(Q===!1)return!1;if(!lx.isInteger($)||!lx.isInteger(J))return!1;return(Number(J)-Number($))/Number(U)>=Q};lx.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}};lx.encloseBrace=($)=>{if($.type!=="brace")return!1;if($.commas>>0+$.ranges>>0===0)return $.invalid=!0,!0;return!1};lx.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};lx.isOpenOrClose=($)=>{if($.type==="open"||$.type==="close")return!0;return $.open===!0||$.close===!0};lx.reduce=($)=>$.reduce((J,U)=>{if(U.type==="text")J.push(U.value);if(U.type==="range")U.type="text";return J},[]);lx.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 zQ=J$((uV$,UP)=>{var JP=LQ();UP.exports=($,J={})=>{let U=(Q,_={})=>{let G=J.escapeInvalid&&JP.isInvalidBrace(_),V=Q.invalid===!0&&J.escapeInvalid===!0,X="";if(Q.value){if((G||V)&&JP.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 QP=J$((mV$,_P)=>{/*!
|
|
12
|
-
* is-number <https://github.com/jonschlinkert/is-number>
|
|
13
|
-
*
|
|
14
|
-
* Copyright (c) 2014-present, Jon Schlinkert.
|
|
15
|
-
* Released under the MIT License.
|
|
16
|
-
*/_P.exports=function($){if(typeof $==="number")return $-$===0;if(typeof $==="string"&&$.trim()!=="")return Number.isFinite?Number.isFinite(+$):isFinite(+$);return!1}});var WP=J$((cV$,FP)=>{/*!
|
|
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 GP=QP(),oJ=($,J,U)=>{if(GP($)===!1)throw TypeError("toRegexRange: expected the first argument to be a number");if(J===void 0||$===J)return String($);if(GP(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(oJ.cache.hasOwnProperty(Z))return oJ.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=NP($)||NP(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=VP(E,Math.abs(Y),N,Q),Y=N.a=0}if(K>=0)q=VP(Y,K,N,Q);if(N.negatives=H,N.positives=q,N.result=ex(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 oJ.cache[Z]=N,N.result};function ex($,J,U){let Q=rY($,J,"-",!1,U)||[],_=rY(J,$,"",!1,U)||[],G=rY($,J,"-?",!0,U)||[];return Q.concat(G).concat(_).join("|")}function $h($,J){let U=1,Q=1,_=YP($,U),G=new Set([J]);while($<=_&&_<=J)G.add(_),U+=1,_=YP($,U);_=ZP(J+1,Q)-1;while($<_&&_<=J)G.add(_),Q+=1,_=ZP(J+1,Q)-1;return G=[...G],G.sort(_h),G}function Jh($,J,U){if($===J)return{pattern:$,count:[],digits:0};let Q=Uh($,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+=Qh(Z,Y,U);else V++}if(V)G+=U.shorthand===!0?"\\d":"[0-9]";return{pattern:G,count:[V],digits:_}}function VP($,J,U,Q){let _=$h($,J),G=[],V=$,X;for(let Z=0;Z<_.length;Z++){let Y=_[Z],K=Jh(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+KP(X.count),V=Y+1;continue}if(U.isPadded)F=Gh(Y,U,Q);K.string=F+K.pattern+KP(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&&!XP(J,"string",X))G.push(U+X);if(Q&&XP(J,"string",X))G.push(U+X)}return G}function Uh($,J){let U=[];for(let Q=0;Q<$.length;Q++)U.push([$[Q],J[Q]]);return U}function _h($,J){return $>J?1:J>$?-1:0}function XP($,J,U){return $.some((Q)=>Q[J]===U)}function YP($,J){return Number(String($).slice(0,-J)+"9".repeat(J))}function ZP($,J){return $-$%Math.pow(10,J)}function KP($){let[J=0,U=""]=$;if(U||J>1)return`{${J+(U?","+U:"")}}`;return""}function Qh($,J,U){return`[${$}${J-$===1?"":"-"}${J}]`}function NP($){return/^-?(0+)\d/.test($)}function Gh($,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}}`}}oJ.cache={};oJ.clearCache=()=>oJ.cache={};FP.exports=oJ});var aY=J$((dV$,EP)=>{/*!
|
|
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 Vh=E$("util"),HP=WP(),qP=($)=>$!==null&&typeof $==="object"&&!Array.isArray($),Xh=($)=>{return(J)=>$===!0?Number(J):String(J)},nY=($)=>{return typeof $==="number"||typeof $==="string"&&$!==""},n_=($)=>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},Yh=($,J,U)=>{if(typeof $==="string"||typeof J==="string")return!0;return U.stringify===!0},Zh=($,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 $},AQ=($,J)=>{let U=$[0]==="-"?"-":"";if(U)$=$.slice(1),J--;while($.length<J)$="0"+$;return U?"-"+$:$},Kh=($,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)=>AQ(String(X),U)).join("|");if($.negatives.length)G=`-(${Q}${$.negatives.map((X)=>AQ(String(X),U)).join("|")})`;if(_&&G)V=`${_}|${G}`;else V=_||G;if(J.wrap)return`(${Q}${V})`;return V},BP=($,J,U,Q)=>{if(U)return HP($,J,{wrap:!1,...Q});let _=String.fromCharCode($);if($===J)return _;let G=String.fromCharCode(J);return`[${_}-${G}]`},OP=($,J,U)=>{if(Array.isArray($)){let Q=U.wrap===!0,_=U.capture?"":"?:";return Q?`(${_}${$.join("|")})`:$.join("|")}return HP($,J,U)},jP=(...$)=>{return RangeError("Invalid range arguments: "+Vh.inspect(...$))},DP=($,J,U)=>{if(U.strictRanges===!0)throw jP([$,J]);return[]},Nh=($,J)=>{if(J.strictRanges===!0)throw TypeError(`Expected step "${$}" to be a number`);return[]},Fh=($,J,U=1,Q={})=>{let _=Number($),G=Number(J);if(!Number.isInteger(_)||!Number.isInteger(G)){if(Q.strictRanges===!0)throw jP([$,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&&Yh($,J,Q)===!1,q=Q.transform||Xh(N);if(Q.toRegex&&U===1)return BP(AQ($,F),AQ(J,F),!0,Q);let H={negatives:[],positives:[]},E=(D)=>H[D<0?"negatives":"positives"].push(Math.abs(D)),j=[],B=0;while(V?_>=G:_<=G){if(Q.toRegex===!0&&U>1)E(_);else j.push(Zh(q(_,B),F,N));_=V?_-U:_+U,B++}if(Q.toRegex===!0)return U>1?Kh(H,Q,F):OP(j,null,{wrap:!1,...Q});return j},Wh=($,J,U=1,Q={})=>{if(!n_($)&&$.length>1||!n_(J)&&J.length>1)return DP($,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 BP(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 OP(K,null,{wrap:!1,options:Q});return K},RQ=($,J,U,Q={})=>{if(J==null&&nY($))return[$];if(!nY($)||!nY(J))return DP($,J,Q);if(typeof U==="function")return RQ($,J,1,{transform:U});if(qP(U))return RQ($,J,0,U);let _={...Q};if(_.capture===!0)_.wrap=!0;if(U=U||_.step||1,!n_(U)){if(U!=null&&!qP(U))return Nh(U,_);return RQ($,J,1,U)}if(n_($)&&n_(J))return Fh($,J,U,_);return Wh($,J,Math.max(Math.abs(U),1),_)};EP.exports=RQ});var LP=J$((lV$,MP)=>{var qh=aY(),PP=LQ(),Hh=($,J={})=>{let U=(Q,_={})=>{let G=PP.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=PP.reduce(Q.nodes),F=qh(...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($)};MP.exports=Hh});var AP=J$((iV$,RP)=>{var Bh=aY(),zP=zQ(),W9=LQ(),tJ=($="",J="",U=!1)=>{let Q=[];if($=[].concat($),J=[].concat(J),!J.length)return $;if(!$.length)return U?W9.flatten(J).map((_)=>`{${_}}`):J;for(let _ of $)if(Array.isArray(_))for(let G of _)Q.push(tJ(G,J,U));else for(let G of J){if(U===!0&&typeof G==="string")G=`{${G}}`;Q.push(Array.isArray(G)?tJ(_,G,U):_+G)}return W9.flatten(Q)},Oh=($,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(tJ(X.pop(),zP(_,J)));return}if(_.type==="brace"&&_.invalid!==!0&&_.nodes.length===2){X.push(tJ(X.pop(),["{}"]));return}if(_.nodes&&_.ranges>0){let F=W9.reduce(_.nodes);if(W9.exceedsLimit(...F,J.step,U))throw RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let N=Bh(...F,J);if(N.length===0)N=zP(_,J);X.push(tJ(X.pop(),N)),_.nodes=[];return}let Z=W9.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(tJ(X.pop(),Y,Z));continue}if(N.value&&N.type!=="open"){Y.push(tJ(Y.pop(),N.value));continue}if(N.nodes)Q(N,_)}return Y};return W9.flatten(Q($))};RP.exports=Oh});var fP=J$((rV$,wP)=>{wP.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 vP=J$((nV$,TP)=>{var jh=zQ(),{MAX_LENGTH:kP,CHAR_BACKSLASH:oY,CHAR_BACKTICK:Dh,CHAR_COMMA:Eh,CHAR_DOT:Ph,CHAR_LEFT_PARENTHESES:Mh,CHAR_RIGHT_PARENTHESES:Lh,CHAR_LEFT_CURLY_BRACE:zh,CHAR_RIGHT_CURLY_BRACE:Rh,CHAR_LEFT_SQUARE_BRACKET:IP,CHAR_RIGHT_SQUARE_BRACKET:SP,CHAR_DOUBLE_QUOTE:Ah,CHAR_SINGLE_QUOTE:wh,CHAR_NO_BREAK_SPACE:fh,CHAR_ZERO_WIDTH_NOBREAK_SPACE:kh}=fP(),Ih=($,J={})=>{if(typeof $!=="string")throw TypeError("Expected a string");let U=J||{},Q=typeof U.maxLength==="number"?Math.min(kP,U.maxLength):kP;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===kh||N===fh)continue;if(N===oY){H({type:"text",value:(J.keepEscaping?N:"")+q()});continue}if(N===SP){H({type:"text",value:"\\"+N});continue}if(N===IP){Z++;let E;while(K<Y&&(E=q())){if(N+=E,E===IP){Z++;continue}if(E===oY){N+=q();continue}if(E===SP){if(Z--,Z===0)break}}H({type:"text",value:N});continue}if(N===Mh){V=H({type:"paren",nodes:[]}),G.push(V),H({type:"text",value:N});continue}if(N===Lh){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===Ah||N===wh||N===Dh){let E=N,j;if(J.keepQuotes!==!0)N="";while(K<Y&&(j=q())){if(j===oY){N+=j+q();continue}if(j===E){if(J.keepQuotes===!0)N+=j;break}N+=j}H({type:"text",value:N});continue}if(N===zh){F++;let j={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(j),G.push(V),H({type:"open",value:N});continue}if(N===Rh){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===Eh&&F>0){if(V.ranges>0){V.ranges=0;let E=V.nodes.shift();V.nodes=[E,{type:"text",value:jh(V)}]}H({type:"comma",value:N}),V.commas++;continue}if(N===Ph&&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 j=E[E.length-1];j.value+=X.value+N,X=j,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],j=E.nodes.indexOf(V);E.nodes.splice(j,1,...V.nodes)}while(G.length>0);return H({type:"eos"}),_};TP.exports=Ih});var yP=J$((pV$,bP)=>{var CP=zQ(),Sh=LP(),Th=AP(),vh=vP(),R0=($,J={})=>{let U=[];if(Array.isArray($))for(let Q of $){let _=R0.create(Q,J);if(Array.isArray(_))U.push(..._);else U.push(_)}else U=[].concat(R0.create($,J));if(J&&J.expand===!0&&J.nodupes===!0)U=[...new Set(U)];return U};R0.parse=($,J={})=>vh($,J);R0.stringify=($,J={})=>{if(typeof $==="string")return CP(R0.parse($,J),J);return CP($,J)};R0.compile=($,J={})=>{if(typeof $==="string")$=R0.parse($,J);return Sh($,J)};R0.expand=($,J={})=>{if(typeof $==="string")$=R0.parse($,J);let U=Th($,J);if(J.noempty===!0)U=U.filter(Boolean);if(J.nodupes===!0)U=[...new Set(U)];return U};R0.create=($,J={})=>{if($===""||$.length<3)return[$];return J.expand!==!0?R0.compile($,J):R0.expand($,J)};bP.exports=R0});var p_=J$((aV$,xP)=>{var Ch=E$("path"),gP={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:"(?:^|\\/)"},bh={...gP,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:"(?:[\\\\/]|$)"},yh={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"};xP.exports={MAX_LENGTH:65536,POSIX_REGEX_SOURCE:yh,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:Ch.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?bh:gP}}});var a_=J$((dh)=>{var gh=E$("path"),xh=process.platform==="win32",{REGEX_BACKSLASH:hh,REGEX_REMOVE_BACKSLASH:uh,REGEX_SPECIAL_CHARS:mh,REGEX_SPECIAL_CHARS_GLOBAL:ch}=p_();dh.isObject=($)=>$!==null&&typeof $==="object"&&!Array.isArray($);dh.hasRegexChars=($)=>mh.test($);dh.isRegexChar=($)=>$.length===1&&dh.hasRegexChars($);dh.escapeRegex=($)=>$.replace(ch,"\\$1");dh.toPosixSlashes=($)=>$.replace(hh,"/");dh.removeBackslashes=($)=>{return $.replace(uh,(J)=>{return J==="\\"?"":J})};dh.supportsLookbehinds=()=>{let $=process.version.slice(1).split(".").map(Number);if($.length===3&&$[0]>=9||$[0]===8&&$[1]>=10)return!0;return!1};dh.isWindows=($)=>{if($&&typeof $.windows==="boolean")return $.windows;return xh===!0||gh.sep==="\\"};dh.escapeLast=($,J,U)=>{let Q=$.lastIndexOf(J,U);if(Q===-1)return $;if($[Q-1]==="\\")return dh.escapeLast($,J,Q-1);return`${$.slice(0,Q)}\\${$.slice(Q)}`};dh.removePrefix=($,J={})=>{let U=$;if(U.startsWith("./"))U=U.slice(2),J.prefix="./";return U};dh.wrapOutput=($,J={},U={})=>{let Q=U.contains?"":"^",_=U.contains?"":"$",G=`${Q}(?:${$})${_}`;if(J.negated===!0)G=`(?:^(?!${G}).*$)`;return G}});var pP=J$((tV$,nP)=>{var mP=a_(),{CHAR_ASTERISK:tY,CHAR_AT:eh,CHAR_BACKWARD_SLASH:o_,CHAR_COMMA:$u,CHAR_DOT:sY,CHAR_EXCLAMATION_MARK:eY,CHAR_FORWARD_SLASH:rP,CHAR_LEFT_CURLY_BRACE:$Z,CHAR_LEFT_PARENTHESES:JZ,CHAR_LEFT_SQUARE_BRACKET:Ju,CHAR_PLUS:Uu,CHAR_QUESTION_MARK:cP,CHAR_RIGHT_CURLY_BRACE:_u,CHAR_RIGHT_PARENTHESES:dP,CHAR_RIGHT_SQUARE_BRACKET:Qu}=p_(),lP=($)=>{return $===rP||$===o_},iP=($)=>{if($.isPrefix!==!0)$.depth=$.isGlobstar?1/0:1},Gu=($,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,j=!1,B=!1,D=!1,w=!1,A=!1,I=!1,f=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===o_){if(D=S.backslashes=!0,z=P(),z===$Z)B=!0;continue}if(B===!0||z===$Z){f++;while(O()!==!0&&(z=P())){if(z===o_){D=S.backslashes=!0,P();continue}if(z===$Z){f++;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===$u){if(N=S.isBrace=!0,H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===_u){if(f--,f===0){B=!1,N=S.isBrace=!0,I=!0;break}}}if(_===!0)continue;break}if(z===rP){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===Uu||z===eh||z===tY||z===cP||z===eY)===!0&&M()===JZ){if(H=S.isGlob=!0,E=S.isExtglob=!0,I=!0,z===eY&&Y===K)A=!0;if(_===!0){while(O()!==!0&&(z=P())){if(z===o_){D=S.backslashes=!0,z=P();continue}if(z===dP){H=S.isGlob=!0,I=!0;break}}continue}break}}if(z===tY){if(T===tY)j=S.isGlobstar=!0;if(H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===cP){if(H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===Ju){while(O()!==!0&&(C=P())){if(C===o_){D=S.backslashes=!0,P();continue}if(C===Qu){q=S.isBracket=!0,H=S.isGlob=!0,I=!0;break}}if(_===!0)continue;break}if(U.nonegate!==!0&&z===eY&&Y===K){w=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){D=S.backslashes=!0,z=P();continue}if(z===dP){I=!0;break}}continue}break}if(H===!0){if(I=!0,_===!0)continue;break}}if(U.noext===!0)E=!1,H=!1;let R=Z,k="",L="";if(K>0)k=Z.slice(0,K),Z=Z.slice(K),F-=K;if(R&&H===!0&&F>0)R=Z.slice(0,F),L=Z.slice(F);else if(H===!0)R="",L=Z;else R=Z;if(R&&R!==""&&R!=="/"&&R!==Z){if(lP(R.charCodeAt(R.length-1)))R=R.slice(0,-1)}if(U.unescape===!0){if(L)L=mP.removeBackslashes(L);if(R&&D===!0)R=mP.removeBackslashes(R)}let v={prefix:k,input:$,start:K,base:R,glob:L,isBrace:N,isBracket:q,isGlob:H,isExtglob:E,isGlobstar:j,negated:w,negatedExtglob:A};if(U.tokens===!0){if(v.maxDepth=0,!lP(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;iP(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,iP(V[V.length-1]),v.maxDepth+=V[V.length-1].depth}v.slashes=G,v.parts=X}return v};nP.exports=Gu});var tP=J$((sV$,oP)=>{var wQ=p_(),A0=a_(),{MAX_LENGTH:fQ,POSIX_REGEX_SOURCE:Vu,REGEX_NON_SPECIAL_CHARS:Xu,REGEX_SPECIAL_CHARS_BACKREF:Yu,REPLACEMENTS:aP}=wQ,Zu=($,J)=>{if(typeof J.expandRange==="function")return J.expandRange(...$,J);$.sort();let U=`[${$.join("-")}]`;try{new RegExp(U)}catch(Q){return $.map((_)=>A0.escapeRegex(_)).join("..")}return U},q9=($,J)=>{return`Missing ${$}: "${J}" - use "\\\\${J}" to match literal characters`},UZ=($,J)=>{if(typeof $!=="string")throw TypeError("Expected a string");$=aP[$]||$;let U={...J},Q=typeof U.maxLength==="number"?Math.min(fQ,U.maxLength):fQ,_=$.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=A0.isWindows(J),Y=wQ.globChars(Z),K=wQ.extglobChars(Y),{DOT_LITERAL:F,PLUS_LITERAL:N,SLASH_LITERAL:q,ONE_CHAR:H,DOTS_SLASH:E,NO_DOT:j,NO_DOT_SLASH:B,NO_DOTS_SLASH:D,QMARK:w,QMARK_NO_DOT:A,STAR:I,START_ANCHOR:f}=Y,T=(n)=>{return`(${X}(?:(?!${f}${n.dot?E:F}).)*?)`},z=U.dot?"":j,S=U.dot?w:A,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};$=A0.removePrefix($,M),_=$.length;let P=[],R=[],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(Yu,(m,G$,L$,P$,f$,V4)=>{if(P$==="\\")return n=!0,m;if(P$==="?"){if(G$)return G$+P$+(f$?w.repeat(f$.length):"");if(V4===0)return S+(f$?w.repeat(f$.length):"");return w.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=A0.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$=Vu[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=A0.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(q9("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(q9("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(q9("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||A0.hasRegexChars(m))continue;let G$=A0.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};R.push(m),Y$(m);continue}if(v==="}"){let m=R[R.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$=Zu(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"),R.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$=R[R.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=R[R.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$==="<"&&!A0.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:A});continue}Y$({type:"qmark",value:v,output:w});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=Xu.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+=D,L.output+=D;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(q9("closing","]"));M.output=A0.escapeLast(M.output,"["),V$("brackets")}while(M.parens>0){if(U.strictBrackets===!0)throw SyntaxError(q9("closing",")"));M.output=A0.escapeLast(M.output,"("),V$("parens")}while(M.braces>0){if(U.strictBrackets===!0)throw SyntaxError(q9("closing","}"));M.output=A0.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(fQ,U.maxLength):fQ,_=$.length;if(_>Q)throw SyntaxError(`Input length: ${_}, exceeds maximum allowed length: ${Q}`);$=aP[$]||$;let G=A0.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}=wQ.globChars(G),E=U.dot?F:K,j=U.dot?N:K,B=U.capture?"":"?:",D={negated:!1,prefix:""},w=U.bash===!0?".*?":q;if(U.capture)w=`(${w})`;let A=(z)=>{if(z.noglobstar===!0)return w;return`(${B}(?:(?!${H}${z.dot?Y:V}).)*?)`},I=(z)=>{switch(z){case"*":return`${E}${Z}${w}`;case".*":return`${V}${Z}${w}`;case"*.*":return`${E}${w}${V}${Z}${w}`;case"*/*":return`${E}${w}${X}${Z}${j}${w}`;case"**":return E+A(U);case"**/*":return`(?:${E}${A(U)}${X})?${j}${Z}${w}`;case"**/*.*":return`(?:${E}${A(U)}${X})?${j}${w}${V}${Z}${w}`;case"**/.*":return`(?:${E}${A(U)}${X})?${V}${Z}${w}`;default:{let S=/^(.*?)\.(\w+)$/.exec(z);if(!S)return;let O=I(S[1]);if(!O)return;return O+V+S[2]}}},f=A0.removePrefix($,D),T=I(f);if(T&&U.strictSlashes!==!0)T+=`${X}?`;return T};oP.exports=UZ});var eP=J$((eV$,sP)=>{var Ku=E$("path"),Nu=pP(),_Z=tP(),QZ=a_(),Fu=p_(),Wu=($)=>$&&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=Wu($)&&$.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(Ku.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)=>Nu($,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=Fu;sP.exports=V6});var GM=J$(($X$,QM)=>{var JM=E$("util"),UM=yP(),P1=eP(),GZ=a_(),$M=($)=>$===""||$==="./",_M=($)=>{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: "${JM.inspect($)}"`);if(Array.isArray(J))return J.some((Q)=>l4.contains($,Q,U));if(typeof J==="string"){if($M($)||$M(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: "${JM.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 UM(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||!_M($))return[$];return UM($,J)};l4.braceExpand=($,J)=>{if(typeof $!=="string")throw TypeError("Expected a string");return l4.braces($,{...J,expand:!0})};l4.hasBraces=_M;QM.exports=l4});var OM=J$((HM)=>{Object.defineProperty(HM,"__esModule",{value:!0});HM.isAbsolute=HM.partitionAbsoluteAndRelative=HM.removeDuplicateSlashes=HM.matchAny=HM.convertPatternsToRe=HM.makeRe=HM.getPatternParts=HM.expandBraceExpansion=HM.expandPatternsWithBraceExpansion=HM.isAffectDepthOfReadingPattern=HM.endsWithSlashGlobStar=HM.hasGlobStar=HM.getBaseDirectory=HM.isPatternRelatedToParentDirectory=HM.getPatternsOutsideCurrentDirectory=HM.getPatternsInsideCurrentDirectory=HM.getPositivePatterns=HM.getNegativePatterns=HM.isPositivePattern=HM.isNegativePattern=HM.convertToNegativePattern=HM.convertToPositivePattern=HM.isDynamicPattern=HM.isStaticPattern=void 0;var VM=E$("path"),qu=$P(),VZ=GM(),XM="**",Hu="\\",Bu=/[*?]|^!/,Ou=/\[[^[]*]/,ju=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,Du=/[!*+?@]\([^(]*\)/,Eu=/,|\.\./,Pu=/(?!^)\/{2,}/g;function YM($,J={}){return!ZM($,J)}HM.isStaticPattern=YM;function ZM($,J={}){if($==="")return!1;if(J.caseSensitiveMatch===!1||$.includes(Hu))return!0;if(Bu.test($)||Ou.test($)||ju.test($))return!0;if(J.extglob!==!1&&Du.test($))return!0;if(J.braceExpansion!==!1&&Mu($))return!0;return!1}HM.isDynamicPattern=ZM;function Mu($){let J=$.indexOf("{");if(J===-1)return!1;let U=$.indexOf("}",J+1);if(U===-1)return!1;let Q=$.slice(J,U);return Eu.test(Q)}function Lu($){return kQ($)?$.slice(1):$}HM.convertToPositivePattern=Lu;function zu($){return"!"+$}HM.convertToNegativePattern=zu;function kQ($){return $.startsWith("!")&&$[1]!=="("}HM.isNegativePattern=kQ;function KM($){return!kQ($)}HM.isPositivePattern=KM;function Ru($){return $.filter(kQ)}HM.getNegativePatterns=Ru;function Au($){return $.filter(KM)}HM.getPositivePatterns=Au;function wu($){return $.filter((J)=>!XZ(J))}HM.getPatternsInsideCurrentDirectory=wu;function fu($){return $.filter(XZ)}HM.getPatternsOutsideCurrentDirectory=fu;function XZ($){return $.startsWith("..")||$.startsWith("./..")}HM.isPatternRelatedToParentDirectory=XZ;function ku($){return qu($,{flipBackslashes:!1})}HM.getBaseDirectory=ku;function Iu($){return $.includes(XM)}HM.hasGlobStar=Iu;function NM($){return $.endsWith("/"+XM)}HM.endsWithSlashGlobStar=NM;function Su($){let J=VM.basename($);return NM($)||YM(J)}HM.isAffectDepthOfReadingPattern=Su;function Tu($){return $.reduce((J,U)=>{return J.concat(FM(U))},[])}HM.expandPatternsWithBraceExpansion=Tu;function FM($){let J=VZ.braces($,{expand:!0,nodupes:!0,keepEscaping:!0});return J.sort((U,Q)=>U.length-Q.length),J.filter((U)=>U!=="")}HM.expandBraceExpansion=FM;function vu($,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}HM.getPatternParts=vu;function WM($,J){return VZ.makeRe($,J)}HM.makeRe=WM;function Cu($,J){return $.map((U)=>WM(U,J))}HM.convertPatternsToRe=Cu;function bu($,J){return J.some((U)=>U.test($))}HM.matchAny=bu;function yu($){return $.replace(Pu,"/")}HM.removeDuplicateSlashes=yu;function gu($){let J=[],U=[];for(let Q of $)if(qM(Q))J.push(Q);else U.push(Q);return[J,U]}HM.partitionAbsoluteAndRelative=gu;function qM($){return VM.isAbsolute($)}HM.isAbsolute=qM});var PM=J$((UX$,EM)=>{var Xm=E$("stream"),jM=Xm.PassThrough,Ym=Array.prototype.slice;EM.exports=Zm;function Zm(){let $=[],J=Ym.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=jM(Q);function X(){for(let K=0,F=arguments.length;K<F;K++)$.push(DM(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",j);N()}function j(B){V.emit("error",B)}if(H._readableState.endEmitted)return N();if(H.on("merge2UnpipeEnd",E),H.on("end",E),G)H.on("error",j);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 DM($,J){if(!Array.isArray($)){if(!$._readableState&&$.pipe)$=$.pipe(jM(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]=DM($[U],J);return $}});var RM=J$((LM)=>{Object.defineProperty(LM,"__esModule",{value:!0});LM.merge=void 0;var Km=PM();function Nm($){let J=Km($);return $.forEach((U)=>{U.once("error",(Q)=>J.emit("error",Q))}),J.once("close",()=>MM($)),J.once("end",()=>MM($)),J}LM.merge=Nm;function MM($){$.forEach((J)=>J.emit("close"))}});var fM=J$((AM)=>{Object.defineProperty(AM,"__esModule",{value:!0});AM.isEmpty=AM.isString=void 0;function Fm($){return typeof $==="string"}AM.isString=Fm;function Wm($){return $===""}AM.isEmpty=Wm});var o1=J$((kM)=>{Object.defineProperty(kM,"__esModule",{value:!0});kM.string=kM.stream=kM.pattern=kM.path=kM.fs=kM.errno=kM.array=void 0;var Hm=CE();kM.array=Hm;var Bm=gE();kM.errno=Bm;var Om=mE();kM.fs=Om;var jm=nE();kM.path=jm;var Dm=OM();kM.pattern=Dm;var Em=RM();kM.stream=Em;var Pm=fM();kM.string=Pm});var yM=J$((CM)=>{Object.defineProperty(CM,"__esModule",{value:!0});CM.convertPatternGroupToTask=CM.convertPatternGroupsToTasks=CM.groupPatternsByBaseDirectory=CM.getNegativePatternsAsPositive=CM.getPositivePatterns=CM.convertPatternsToTasks=CM.generate=void 0;var t0=o1();function fm($,J){let U=SM($,J),Q=SM(J.ignore,J),_=TM(U),G=vM(U,Q),V=_.filter((K)=>t0.pattern.isStaticPattern(K,J)),X=_.filter((K)=>t0.pattern.isDynamicPattern(K,J)),Z=YZ(V,G,!1),Y=YZ(X,G,!0);return Z.concat(Y)}CM.generate=fm;function SM($,J){let U=$;if(J.braceExpansion)U=t0.pattern.expandPatternsWithBraceExpansion(U);if(J.baseNameMatch)U=U.map((Q)=>Q.includes("/")?Q:`**/${Q}`);return U.map((Q)=>t0.pattern.removeDuplicateSlashes(Q))}function YZ($,J,U){let Q=[],_=t0.pattern.getPatternsOutsideCurrentDirectory($),G=t0.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}CM.convertPatternsToTasks=YZ;function TM($){return t0.pattern.getPositivePatterns($)}CM.getPositivePatterns=TM;function vM($,J){return t0.pattern.getNegativePatterns($).concat(J).map(t0.pattern.convertToPositivePattern)}CM.getNegativePatternsAsPositive=vM;function ZZ($){let J={};return $.reduce((U,Q)=>{let _=t0.pattern.getBaseDirectory(Q);if(_ in U)U[_].push(Q);else U[_]=[Q];return U},J)}CM.groupPatternsByBaseDirectory=ZZ;function KZ($,J,U){return Object.keys($).map((Q)=>{return NZ(Q,$[Q],J,U)})}CM.convertPatternGroupsToTasks=KZ;function NZ($,J,U,Q){return{dynamic:Q,positive:J,negative:U,base:$,patterns:[].concat(J,U.map(t0.pattern.convertToNegativePattern))}}CM.convertPatternGroupToTask=NZ});var uM=J$((xM)=>{Object.defineProperty(xM,"__esModule",{value:!0});xM.read=void 0;function bm($,J,U){J.fs.lstat($,(Q,_)=>{if(Q!==null){gM(U,Q);return}if(!_.isSymbolicLink()||!J.followSymbolicLink){FZ(U,_);return}J.fs.stat($,(G,V)=>{if(G!==null){if(J.throwErrorOnBrokenSymbolicLink){gM(U,G);return}FZ(U,_);return}if(J.markSymbolicLink)V.isSymbolicLink=()=>!0;FZ(U,V)})})}xM.read=bm;function gM($,J){$(J)}function FZ($,J){$(null,J)}});var dM=J$((mM)=>{Object.defineProperty(mM,"__esModule",{value:!0});mM.read=void 0;function ym($,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}}mM.read=ym});var rM=J$((lM)=>{Object.defineProperty(lM,"__esModule",{value:!0});lM.createFileSystemAdapter=lM.FILE_SYSTEM_ADAPTER=void 0;var IQ=E$("fs");lM.FILE_SYSTEM_ADAPTER={lstat:IQ.lstat,stat:IQ.stat,lstatSync:IQ.lstatSync,statSync:IQ.statSync};function gm($){if($===void 0)return lM.FILE_SYSTEM_ADAPTER;return Object.assign(Object.assign({},lM.FILE_SYSTEM_ADAPTER),$)}lM.createFileSystemAdapter=gm});var aM=J$((pM)=>{Object.defineProperty(pM,"__esModule",{value:!0});var xm=rM();class nM{constructor($={}){this._options=$,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=xm.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}}pM.default=nM});var sJ=J$((tM)=>{Object.defineProperty(tM,"__esModule",{value:!0});tM.statSync=tM.stat=tM.Settings=void 0;var oM=uM(),um=dM(),qZ=aM();tM.Settings=qZ.default;function mm($,J,U){if(typeof J==="function"){oM.read($,HZ(),J);return}oM.read($,HZ(J),U)}tM.stat=mm;function cm($,J){let U=HZ(J);return um.read($,U)}tM.statSync=cm;function HZ($={}){if($ instanceof qZ.default)return $;return new qZ.default($)}});var JL=J$((FX$,$L)=>{/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var eM;$L.exports=typeof queueMicrotask==="function"?queueMicrotask.bind(typeof window<"u"?window:global):($)=>(eM||(eM=Promise.resolve())).then($).catch((J)=>setTimeout(()=>{throw J},0))});var _L=J$((WX$,UL)=>{/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */UL.exports=rm;var im=JL();function rm($,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)im(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$((VL)=>{Object.defineProperty(VL,"__esModule",{value:!0});VL.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var SQ=process.versions.node.split(".");if(SQ[0]===void 0||SQ[1]===void 0)throw Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var QL=Number.parseInt(SQ[0],10),nm=Number.parseInt(SQ[1],10),GL=10,pm=10,am=QL>GL,om=QL===GL&&nm>=pm;VL.IS_SUPPORT_READDIR_WITH_FILE_TYPES=am||om});var NL=J$((ZL)=>{Object.defineProperty(ZL,"__esModule",{value:!0});ZL.createDirentFromStats=void 0;class YL{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 tm($,J){return new YL($,J)}ZL.createDirentFromStats=tm});var OZ=J$((FL)=>{Object.defineProperty(FL,"__esModule",{value:!0});FL.fs=void 0;var sm=NL();FL.fs=sm});var jZ=J$((qL)=>{Object.defineProperty(qL,"__esModule",{value:!0});qL.joinPathSegments=void 0;function em($,J,U){if($.endsWith(U))return $+J;return $+U+J}qL.joinPathSegments=em});var LL=J$((PL)=>{Object.defineProperty(PL,"__esModule",{value:!0});PL.readdir=PL.readdirWithFileTypes=PL.read=void 0;var $c=sJ(),BL=_L(),Jc=BZ(),OL=OZ(),jL=jZ();function Uc($,J,U){if(!J.stats&&Jc.IS_SUPPORT_READDIR_WITH_FILE_TYPES){DL($,J,U);return}EL($,J,U)}PL.read=Uc;function DL($,J,U){J.fs.readdir($,{withFileTypes:!0},(Q,_)=>{if(Q!==null){TQ(U,Q);return}let G=_.map((X)=>({dirent:X,name:X.name,path:jL.joinPathSegments($,X.name,J.pathSegmentSeparator)}));if(!J.followSymbolicLinks){DZ(U,G);return}let V=G.map((X)=>_c(X,J));BL(V,(X,Z)=>{if(X!==null){TQ(U,X);return}DZ(U,Z)})})}PL.readdirWithFileTypes=DL;function _c($,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=OL.fs.createDirentFromStats($.name,_),U(null,$)})}}function EL($,J,U){J.fs.readdir($,(Q,_)=>{if(Q!==null){TQ(U,Q);return}let G=_.map((V)=>{let X=jL.joinPathSegments($,V,J.pathSegmentSeparator);return(Z)=>{$c.stat(X,J.fsStatSettings,(Y,K)=>{if(Y!==null){Z(Y);return}let F={name:V,path:X,dirent:OL.fs.createDirentFromStats(V,K)};if(J.stats)F.stats=K;Z(null,F)})}});BL(G,(V,X)=>{if(V!==null){TQ(U,V);return}DZ(U,X)})})}PL.readdir=EL;function TQ($,J){$(J)}function DZ($,J){$(null,J)}});var IL=J$((fL)=>{Object.defineProperty(fL,"__esModule",{value:!0});fL.readdir=fL.readdirWithFileTypes=fL.read=void 0;var Vc=sJ(),Xc=BZ(),zL=OZ(),RL=jZ();function Yc($,J){if(!J.stats&&Xc.IS_SUPPORT_READDIR_WITH_FILE_TYPES)return AL($,J);return wL($,J)}fL.read=Yc;function AL($,J){return J.fs.readdirSync($,{withFileTypes:!0}).map((Q)=>{let _={dirent:Q,name:Q.name,path:RL.joinPathSegments($,Q.name,J.pathSegmentSeparator)};if(_.dirent.isSymbolicLink()&&J.followSymbolicLinks)try{let G=J.fs.statSync(_.path);_.dirent=zL.fs.createDirentFromStats(_.name,G)}catch(G){if(J.throwErrorOnBrokenSymbolicLink)throw G}return _})}fL.readdirWithFileTypes=AL;function wL($,J){return J.fs.readdirSync($).map((Q)=>{let _=RL.joinPathSegments($,Q,J.pathSegmentSeparator),G=Vc.statSync(_,J.fsStatSettings),V={name:Q,path:_,dirent:zL.fs.createDirentFromStats(Q,G)};if(J.stats)V.stats=G;return V})}fL.readdir=wL});var vL=J$((SL)=>{Object.defineProperty(SL,"__esModule",{value:!0});SL.createFileSystemAdapter=SL.FILE_SYSTEM_ADAPTER=void 0;var H9=E$("fs");SL.FILE_SYSTEM_ADAPTER={lstat:H9.lstat,stat:H9.stat,lstatSync:H9.lstatSync,statSync:H9.statSync,readdir:H9.readdir,readdirSync:H9.readdirSync};function Nc($){if($===void 0)return SL.FILE_SYSTEM_ADAPTER;return Object.assign(Object.assign({},SL.FILE_SYSTEM_ADAPTER),$)}SL.createFileSystemAdapter=Nc});var yL=J$((bL)=>{Object.defineProperty(bL,"__esModule",{value:!0});var Fc=E$("path"),Wc=sJ(),qc=vL();class CL{constructor($={}){this._options=$,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=qc.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,Fc.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new Wc.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue($,J){return $!==null&&$!==void 0?$:J}}bL.default=CL});var vQ=J$((xL)=>{Object.defineProperty(xL,"__esModule",{value:!0});xL.Settings=xL.scandirSync=xL.scandir=void 0;var gL=LL(),Bc=IL(),PZ=yL();xL.Settings=PZ.default;function Oc($,J,U){if(typeof J==="function"){gL.read($,MZ(),J);return}gL.read($,MZ(J),U)}xL.scandir=Oc;function jc($,J){let U=MZ(J);return Bc.read($,U)}xL.scandirSync=jc;function MZ($={}){if($ instanceof PZ.default)return $;return new PZ.default($)}});var mL=J$((LX$,uL)=>{function Pc($){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:_}}uL.exports=Pc});var dL=J$((zX$,LZ)=>{var Mc=mL();function cL($,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=Mc(Lc),_=null,G=null,V=0,X=null,Z={push:E,drain:G0,saturated:G0,pause:K,paused:!1,get concurrency(){return U},set concurrency(f){if(!(f>=1))throw Error("fastqueue concurrency must be equal to or greater than 1");if(U=f,Z.paused)return;for(;_&&V<U;)V++,B()},running:Y,resume:q,idle:H,length:F,getQueue:N,unshift:j,empty:G0,kill:D,killAndDrain:w,error:I,abort:A};return Z;function Y(){return V}function K(){Z.paused=!0}function F(){var f=_,T=0;while(f)f=f.next,T++;return T}function N(){var f=_,T=[];while(f)T.push(f.value),f=f.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(f,T){var z=Q.get();if(z.context=$,z.release=B,z.value=f,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 j(f,T){var z=Q.get();if(z.context=$,z.release=B,z.value=f,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(f){if(f)Q.release(f);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 D(){_=null,G=null,Z.drain=G0}function w(){_=null,G=null,Z.drain(),Z.drain=G0}function A(){var f=_;_=null,G=null;while(f){var{next:T,callback:z,errorHandler:S,value:O,context:M}=f;if(f.value=null,f.callback=G0,f.errorHandler=null,S)S(Error("abort"),O);z.call(M,Error("abort")),f.release(f),f=T}Z.drain=G0}function I(f){X=f}}function G0(){}function Lc(){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 zc($,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 _=cL($,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=cL;LZ.exports.promise=zc});var CQ=J$((lL)=>{Object.defineProperty(lL,"__esModule",{value:!0});lL.joinPathSegments=lL.replacePathSegmentSeparator=lL.isAppliedFilter=lL.isFatalError=void 0;function Rc($,J){if($.errorFilter===null)return!0;return!$.errorFilter(J)}lL.isFatalError=Rc;function Ac($,J){return $===null||$(J)}lL.isAppliedFilter=Ac;function wc($,J){return $.split(/[/\\]/).join(J)}lL.replacePathSegmentSeparator=wc;function fc($,J,U){if($==="")return J;if($.endsWith(U))return $+J;return $+U+J}lL.joinPathSegments=fc});var zZ=J$((nL)=>{Object.defineProperty(nL,"__esModule",{value:!0});var Tc=CQ();class rL{constructor($,J){this._root=$,this._settings=J,this._root=Tc.replacePathSegmentSeparator($,J.pathSegmentSeparator)}}nL.default=rL});var RZ=J$((aL)=>{Object.defineProperty(aL,"__esModule",{value:!0});var Cc=E$("events"),bc=vQ(),yc=dL(),bQ=CQ(),gc=zZ();class pL extends gc.default{constructor($,J){super($,J);this._settings=J,this._scandir=bc.scandir,this._emitter=new Cc.EventEmitter,this._queue=yc(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||!bQ.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=bQ.joinPathSegments(J,$.name,this._settings.pathSegmentSeparator);if(bQ.isAppliedFilter(this._settings.entryFilter,$))this._emitEntry($);if($.dirent.isDirectory()&&bQ.isAppliedFilter(this._settings.deepFilter,$))this._pushToQueue(U,J===void 0?void 0:$.path)}_emitEntry($){this._emitter.emit("entry",$)}}aL.default=pL});var sL=J$((tL)=>{Object.defineProperty(tL,"__esModule",{value:!0});var hc=RZ();class oL{constructor($,J){this._root=$,this._settings=J,this._reader=new hc.default(this._root,this._settings),this._storage=[]}read($){this._reader.onError((J)=>{uc($,J)}),this._reader.onEntry((J)=>{this._storage.push(J)}),this._reader.onEnd(()=>{mc($,this._storage)}),this._reader.read()}}tL.default=oL;function uc($,J){$(J)}function mc($,J){$(null,J)}});var Jz=J$(($z)=>{Object.defineProperty($z,"__esModule",{value:!0});var dc=E$("stream"),lc=RZ();class eL{constructor($,J){this._root=$,this._settings=J,this._reader=new lc.default(this._root,this._settings),this._stream=new dc.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}}$z.default=eL});var Qz=J$((_z)=>{Object.defineProperty(_z,"__esModule",{value:!0});var rc=vQ(),yQ=CQ(),nc=zZ();class Uz extends nc.default{constructor(){super(...arguments);this._scandir=rc.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(!yQ.isFatalError(this._settings,$))return;throw $}_handleEntry($,J){let U=$.path;if(J!==void 0)$.path=yQ.joinPathSegments(J,$.name,this._settings.pathSegmentSeparator);if(yQ.isAppliedFilter(this._settings.entryFilter,$))this._pushToStorage($);if($.dirent.isDirectory()&&yQ.isAppliedFilter(this._settings.deepFilter,$))this._pushToQueue(U,J===void 0?void 0:$.path)}_pushToStorage($){this._storage.push($)}}_z.default=Uz});var Xz=J$((Vz)=>{Object.defineProperty(Vz,"__esModule",{value:!0});var ac=Qz();class Gz{constructor($,J){this._root=$,this._settings=J,this._reader=new ac.default(this._root,this._settings)}read(){return this._reader.read()}}Vz.default=Gz});var Kz=J$((Zz)=>{Object.defineProperty(Zz,"__esModule",{value:!0});var tc=E$("path"),sc=vQ();class Yz{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,tc.sep),this.fsScandirSettings=new sc.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}}Zz.default=Yz});var xQ=J$((Fz)=>{Object.defineProperty(Fz,"__esModule",{value:!0});Fz.Settings=Fz.walkStream=Fz.walkSync=Fz.walk=void 0;var Nz=sL(),$d=Jz(),Jd=Xz(),AZ=Kz();Fz.Settings=AZ.default;function Ud($,J,U){if(typeof J==="function"){new Nz.default($,gQ()).read(J);return}new Nz.default($,gQ(J)).read(U)}Fz.walk=Ud;function _d($,J){let U=gQ(J);return new Jd.default($,U).read()}Fz.walkSync=_d;function Qd($,J){let U=gQ(J);return new $d.default($,U).read()}Fz.walkStream=Qd;function gQ($={}){if($ instanceof AZ.default)return $;return new AZ.default($)}});var hQ=J$((Bz)=>{Object.defineProperty(Bz,"__esModule",{value:!0});var Yd=E$("path"),Zd=sJ(),qz=o1();class Hz{constructor($){this._settings=$,this._fsStatSettings=new Zd.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath($){return Yd.resolve(this._settings.cwd,$)}_makeEntry($,J){let U={name:J,path:J,dirent:qz.fs.createDirentFromStats(J,$)};if(this._settings.stats)U.stats=$;return U}_isFatalError($){return!qz.errno.isEnoentCodeError($)&&!this._settings.suppressErrors}}Bz.default=Hz});var wZ=J$((jz)=>{Object.defineProperty(jz,"__esModule",{value:!0});var Nd=E$("stream"),Fd=sJ(),Wd=xQ(),qd=hQ();class Oz extends qd.default{constructor(){super(...arguments);this._walkStream=Wd.walkStream,this._stat=Fd.stat}dynamic($,J){return this._walkStream($,J)}static($,J){let U=$.map(this._getFullEntryPath,this),Q=new Nd.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)})})}}jz.default=Oz});var Pz=J$((Ez)=>{Object.defineProperty(Ez,"__esModule",{value:!0});var Bd=xQ(),Od=hQ(),jd=wZ();class Dz extends Od.default{constructor(){super(...arguments);this._walkAsync=Bd.walk,this._readerStream=new jd.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))})}}Ez.default=Dz});var zz=J$((Lz)=>{Object.defineProperty(Lz,"__esModule",{value:!0});var t_=o1();class Mz{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 t_.pattern.getPatternParts($,this._micromatchOptions).map((U)=>{if(!t_.pattern.isDynamicPattern(U,this._settings))return{dynamic:!1,pattern:U};return{dynamic:!0,pattern:U,patternRe:t_.pattern.makeRe(U,this._micromatchOptions)}})}_splitSegmentsIntoSections($){return t_.array.splitWhen($,(J)=>J.dynamic&&t_.pattern.hasGlobStar(J.pattern))}}Lz.default=Mz});var wz=J$((Az)=>{Object.defineProperty(Az,"__esModule",{value:!0});var Pd=zz();class Rz extends Pd.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}}Az.default=Rz});var Iz=J$((kz)=>{Object.defineProperty(kz,"__esModule",{value:!0});var uQ=o1(),Ld=wz();class fz{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 Ld.default($,this._settings,this._micromatchOptions)}_getNegativePatternsRe($){let J=$.filter(uQ.pattern.isAffectDepthOfReadingPattern);return uQ.pattern.convertPatternsToRe(J,this._micromatchOptions)}_filter($,J,U,Q){if(this._isSkippedByDeep($,J.path))return!1;if(this._isSkippedSymbolicLink(J))return!1;let _=uQ.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!uQ.pattern.matchAny($,J)}}kz.default=fz});var vz=J$((Tz)=>{Object.defineProperty(Tz,"__esModule",{value:!0});var g2=o1();class Sz{constructor($,J){this._settings=$,this._micromatchOptions=J,this.index=new Map}getFilter($,J){let[U,Q]=g2.pattern.partitionAbsoluteAndRelative(J),_={positive:{all:g2.pattern.convertPatternsToRe($,this._micromatchOptions)},negative:{absolute:g2.pattern.convertPatternsToRe(U,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:g2.pattern.convertPatternsToRe(Q,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return(G)=>this._filter(G,_)}_filter($,J){let U=g2.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=g2.path.makeAbsolute(this._settings.cwd,$);return this._isMatchToPatterns(Q,J,U)}_isMatchToPatterns($,J,U){if(J.length===0)return!1;let Q=g2.pattern.matchAny($,J);if(!Q&&U)return g2.pattern.matchAny($+"/",J);return Q}}Tz.default=Sz});var yz=J$((bz)=>{Object.defineProperty(bz,"__esModule",{value:!0});var Ad=o1();class Cz{constructor($){this._settings=$}getFilter(){return($)=>this._isNonFatalError($)}_isNonFatalError($){return Ad.errno.isEnoentCodeError($)||this._settings.suppressErrors}}bz.default=Cz});var uz=J$((hz)=>{Object.defineProperty(hz,"__esModule",{value:!0});var gz=o1();class xz{constructor($){this._settings=$}getTransformer(){return($)=>this._transform($)}_transform($){let J=$.path;if(this._settings.absolute)J=gz.path.makeAbsolute(this._settings.cwd,J),J=gz.path.unixify(J);if(this._settings.markDirectories&&$.dirent.isDirectory())J+="/";if(!this._settings.objectMode)return J;return Object.assign(Object.assign({},$),{path:J})}}hz.default=xz});var mQ=J$((cz)=>{Object.defineProperty(cz,"__esModule",{value:!0});var kd=E$("path"),Id=Iz(),Sd=vz(),Td=yz(),vd=uz();class mz{constructor($){this._settings=$,this.errorFilter=new Td.default(this._settings),this.entryFilter=new Sd.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new Id.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new vd.default(this._settings)}_getRootDirectory($){return kd.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}}}cz.default=mz});var iz=J$((lz)=>{Object.defineProperty(lz,"__esModule",{value:!0});var bd=Pz(),yd=mQ();class dz extends yd.default{constructor(){super(...arguments);this._reader=new bd.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)}}lz.default=dz});var pz=J$((nz)=>{Object.defineProperty(nz,"__esModule",{value:!0});var xd=E$("stream"),hd=wZ(),ud=mQ();class rz extends ud.default{constructor(){super(...arguments);this._reader=new hd.default(this._settings)}read($){let J=this._getRootDirectory($),U=this._getReaderOptions($),Q=this.api(J,$,U),_=new xd.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)}}nz.default=rz});var tz=J$((oz)=>{Object.defineProperty(oz,"__esModule",{value:!0});var cd=sJ(),dd=xQ(),ld=hQ();class az extends ld.default{constructor(){super(...arguments);this._walkSync=dd.walkSync,this._statSync=cd.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)}}oz.default=az});var $R=J$((ez)=>{Object.defineProperty(ez,"__esModule",{value:!0});var rd=tz(),nd=mQ();class sz extends nd.default{constructor(){super(...arguments);this._reader=new rd.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)}}ez.default=sz});var _R=J$((UR)=>{Object.defineProperty(UR,"__esModule",{value:!0});UR.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var B9=E$("fs"),ad=E$("os"),od=Math.max(ad.cpus().length,1);UR.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:B9.lstat,lstatSync:B9.lstatSync,stat:B9.stat,statSync:B9.statSync,readdir:B9.readdir,readdirSync:B9.readdirSync};class JR{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,od),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({},UR.DEFAULT_FILE_SYSTEM_ADAPTER),$)}}UR.default=JR});var VR=J$((aX$,GR)=>{var QR=yM(),sd=iz(),ed=pz(),$l=$R(),kZ=_R(),g0=o1();async function IZ($,J){s0($);let U=SZ($,sd.default,J),Q=await Promise.all(U);return g0.array.flatten(Q)}(function($){$.glob=$,$.globSync=J,$.globStream=U,$.async=$;function J(Y,K){s0(Y);let F=SZ(Y,$l.default,K);return g0.array.flatten(F)}$.sync=J;function U(Y,K){s0(Y);let F=SZ(Y,ed.default,K);return g0.stream.merge(F)}$.stream=U;function Q(Y,K){s0(Y);let F=[].concat(Y),N=new kZ.default(K);return QR.generate(F,N)}$.generateTasks=Q;function _(Y,K){s0(Y);let F=new kZ.default(K);return g0.pattern.isDynamicPattern(Y,F)}$.isDynamicPattern=_;function G(Y){return s0(Y),g0.path.escape(Y)}$.escapePath=G;function V(Y){return s0(Y),g0.path.convertPathToPattern(Y)}$.convertPathToPattern=V;let X;(function(Y){function K(N){return s0(N),g0.path.escapePosixPath(N)}Y.escapePath=K;function F(N){return s0(N),g0.path.convertPosixPathToPattern(N)}Y.convertPathToPattern=F})(X=$.posix||($.posix={}));let Z;(function(Y){function K(N){return s0(N),g0.path.escapeWindowsPath(N)}Y.escapePath=K;function F(N){return s0(N),g0.path.convertWindowsPathToPattern(N)}Y.convertPathToPattern=F})(Z=$.win32||($.win32={}))})(IZ||(IZ={}));function SZ($,J,U){let Q=[].concat($),_=new kZ.default(U),G=QR.generate(Q,_),V=new J(_);return G.map(V.read,V)}function s0($){if(![].concat($).every((Q)=>g0.string.isString(Q)&&!g0.string.isEmpty(Q)))throw TypeError("Patterns must be a string (non empty) or an array of strings")}GR.exports=IZ});var s_=J$((oX$,YR)=>{var XR={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:"/"},Jl={...XR,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:"\\"},Ul={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"};YR.exports={MAX_LENGTH:65536,POSIX_REGEX_SOURCE:Ul,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?Jl:XR}}});var e_=J$((Xl)=>{var{REGEX_BACKSLASH:_l,REGEX_REMOVE_BACKSLASH:Ql,REGEX_SPECIAL_CHARS:Gl,REGEX_SPECIAL_CHARS_GLOBAL:Vl}=s_();Xl.isObject=($)=>$!==null&&typeof $==="object"&&!Array.isArray($);Xl.hasRegexChars=($)=>Gl.test($);Xl.isRegexChar=($)=>$.length===1&&Xl.hasRegexChars($);Xl.escapeRegex=($)=>$.replace(Vl,"\\$1");Xl.toPosixSlashes=($)=>$.replace(_l,"/");Xl.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};Xl.removeBackslashes=($)=>{return $.replace(Ql,(J)=>{return J==="\\"?"":J})};Xl.escapeLast=($,J,U)=>{let Q=$.lastIndexOf(J,U);if(Q===-1)return $;if($[Q-1]==="\\")return Xl.escapeLast($,J,Q-1);return`${$.slice(0,Q)}\\${$.slice(Q)}`};Xl.removePrefix=($,J={})=>{let U=$;if(U.startsWith("./"))U=U.slice(2),J.prefix="./";return U};Xl.wrapOutput=($,J={},U={})=>{let Q=U.contains?"":"^",_=U.contains?"":"$",G=`${Q}(?:${$})${_}`;if(J.negated===!0)G=`(?:^(?!${G}).*$)`;return G};Xl.basename=($,{windows:J}={})=>{let U=$.split(J?/[\\/]/:"/"),Q=U[U.length-1];if(Q==="")return U[U.length-2];return Q}});var jR=J$((sX$,OR)=>{var NR=e_(),{CHAR_ASTERISK:TZ,CHAR_AT:Ol,CHAR_BACKWARD_SLASH:$5,CHAR_COMMA:jl,CHAR_DOT:vZ,CHAR_EXCLAMATION_MARK:CZ,CHAR_FORWARD_SLASH:BR,CHAR_LEFT_CURLY_BRACE:bZ,CHAR_LEFT_PARENTHESES:yZ,CHAR_LEFT_SQUARE_BRACKET:Dl,CHAR_PLUS:El,CHAR_QUESTION_MARK:FR,CHAR_RIGHT_CURLY_BRACE:Pl,CHAR_RIGHT_PARENTHESES:WR,CHAR_RIGHT_SQUARE_BRACKET:Ml}=s_(),qR=($)=>{return $===BR||$===$5},HR=($)=>{if($.isPrefix!==!0)$.depth=$.isGlobstar?1/0:1},Ll=($,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,j=!1,B=!1,D=!1,w=!1,A=!1,I=!1,f=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===$5){if(D=S.backslashes=!0,z=P(),z===bZ)B=!0;continue}if(B===!0||z===bZ){f++;while(O()!==!0&&(z=P())){if(z===$5){D=S.backslashes=!0,P();continue}if(z===bZ){f++;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===jl){if(N=S.isBrace=!0,H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===Pl){if(f--,f===0){B=!1,N=S.isBrace=!0,I=!0;break}}}if(_===!0)continue;break}if(z===BR){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===El||z===Ol||z===TZ||z===FR||z===CZ)===!0&&M()===yZ){if(H=S.isGlob=!0,E=S.isExtglob=!0,I=!0,z===CZ&&Y===K)A=!0;if(_===!0){while(O()!==!0&&(z=P())){if(z===$5){D=S.backslashes=!0,z=P();continue}if(z===WR){H=S.isGlob=!0,I=!0;break}}continue}break}}if(z===TZ){if(T===TZ)j=S.isGlobstar=!0;if(H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===FR){if(H=S.isGlob=!0,I=!0,_===!0)continue;break}if(z===Dl){while(O()!==!0&&(C=P())){if(C===$5){D=S.backslashes=!0,P();continue}if(C===Ml){q=S.isBracket=!0,H=S.isGlob=!0,I=!0;break}}if(_===!0)continue;break}if(U.nonegate!==!0&&z===CZ&&Y===K){w=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){D=S.backslashes=!0,z=P();continue}if(z===WR){I=!0;break}}continue}break}if(H===!0){if(I=!0,_===!0)continue;break}}if(U.noext===!0)E=!1,H=!1;let R=Z,k="",L="";if(K>0)k=Z.slice(0,K),Z=Z.slice(K),F-=K;if(R&&H===!0&&F>0)R=Z.slice(0,F),L=Z.slice(F);else if(H===!0)R="",L=Z;else R=Z;if(R&&R!==""&&R!=="/"&&R!==Z){if(qR(R.charCodeAt(R.length-1)))R=R.slice(0,-1)}if(U.unescape===!0){if(L)L=NR.removeBackslashes(L);if(R&&D===!0)R=NR.removeBackslashes(R)}let v={prefix:k,input:$,start:K,base:R,glob:L,isBrace:N,isBracket:q,isGlob:H,isExtglob:E,isGlobstar:j,negated:w,negatedExtglob:A};if(U.tokens===!0){if(v.maxDepth=0,!qR(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;HR(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,HR(V[V.length-1]),v.maxDepth+=V[V.length-1].depth}v.slashes=G,v.parts=X}return v};OR.exports=Ll});var PR=J$((eX$,ER)=>{var cQ=s_(),M1=e_(),{MAX_LENGTH:dQ,POSIX_REGEX_SOURCE:zl,REGEX_NON_SPECIAL_CHARS:Rl,REGEX_SPECIAL_CHARS_BACKREF:Al,REPLACEMENTS:DR}=cQ,wl=($,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},O9=($,J)=>{return`Missing ${$}: "${J}" - use "\\\\${J}" to match literal characters`},gZ=($,J)=>{if(typeof $!=="string")throw TypeError("Expected a string");$=DR[$]||$;let U={...J},Q=typeof U.maxLength==="number"?Math.min(dQ,U.maxLength):dQ,_=$.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=cQ.globChars(U.windows),Y=cQ.extglobChars(Z),{DOT_LITERAL:K,PLUS_LITERAL:F,SLASH_LITERAL:N,ONE_CHAR:q,DOTS_SLASH:H,NO_DOT:E,NO_DOT_SLASH:j,NO_DOTS_SLASH:B,QMARK:D,QMARK_NO_DOT:w,STAR:A,START_ANCHOR:I}=Z,f=(_$)=>{return`(${X}(?:(?!${I}${_$.dot?H:K}).)*?)`},T=U.dot?"":E,z=U.dot?D:w,S=U.bash===!0?f(U):A;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=[],R=[],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[_$]++,R.push(_$)},K$=(_$)=>{O[_$]--,R.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=f(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(Al,(a,m,G$,L$,P$,f$)=>{if(L$==="\\")return _$=!0,a;if(L$==="?"){if(m)return m+L$+(P$?D.repeat(P$.length):"");if(f$===0)return z+(P$?D.repeat(P$.length):"");return D.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$=zl[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(O9("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(O9("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(O9("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=wl(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&&R[R.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:w});continue}V$({type:"qmark",value:L,output:D});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=Rl.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=f(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=f(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=`${f(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}|${f(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=f(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+=j,k.output+=j;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(O9("closing","]"));O.output=M1.escapeLast(O.output,"["),K$("brackets")}while(O.parens>0){if(U.strictBrackets===!0)throw SyntaxError(O9("closing",")"));O.output=M1.escapeLast(O.output,"("),K$("parens")}while(O.braces>0){if(U.strictBrackets===!0)throw SyntaxError(O9("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(dQ,U.maxLength):dQ,_=$.length;if(_>Q)throw SyntaxError(`Input length: ${_}, exceeds maximum allowed length: ${Q}`);$=DR[$]||$;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}=cQ.globChars(U.windows),H=U.dot?K:Y,E=U.dot?F:Y,j=U.capture?"":"?:",B={negated:!1,prefix:""},D=U.bash===!0?".*?":N;if(U.capture)D=`(${D})`;let w=(T)=>{if(T.noglobstar===!0)return D;return`(${j}(?:(?!${q}${T.dot?Z:G}).)*?)`},A=(T)=>{switch(T){case"*":return`${H}${X}${D}`;case".*":return`${G}${X}${D}`;case"*.*":return`${H}${D}${G}${X}${D}`;case"*/*":return`${H}${D}${V}${X}${E}${D}`;case"**":return H+w(U);case"**/*":return`(?:${H}${w(U)}${V})?${E}${X}${D}`;case"**/*.*":return`(?:${H}${w(U)}${V})?${E}${D}${G}${X}${D}`;case"**/.*":return`(?:${H}${w(U)}${V})?${G}${X}${D}`;default:{let z=/^(.*?)\.(\w+)$/.exec(T);if(!z)return;let S=A(z[1]);if(!S)return;return S+G+z[2]}}},I=M1.removePrefix($,B),f=A(I);if(f&&U.strictSlashes!==!0)f+=`${V}?`;return f};ER.exports=gZ});var zR=J$(($Y$,LR)=>{var fl=jR(),xZ=PR(),MR=e_(),kl=s_(),Il=($)=>$&&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=Il($)&&$.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||(_?MR.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(MR.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)=>fl($,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=kl;LR.exports=X6});var fR=J$((JY$,wR)=>{var RR=zR(),Sl=e_();function AR($,J,U=!1){if(J&&(J.windows===null||J.windows===void 0))J={...J,windows:Sl.isWindows()};return RR($,J,U)}Object.assign(AR,RR);wR.exports=AR});var Uf=J$((kF$,Ca)=>{Ca.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 Yf=J$((IF$,J2)=>{var FB=E$("fs"),yG=E$("path"),ba=E$("os"),ya=E$("crypto"),ga=Uf(),WB=ga.version,_f=["\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 xa(){return _f[Math.floor(Math.random()*_f.length)]}function s9($){if(typeof $==="string")return!["false","0","no","off",""].includes($.toLowerCase());return Boolean($)}function ha(){return process.stdout.isTTY}function ua($){return ha()?`\x1B[2m${$}\x1B[0m`:$}var ma=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function ca($){let J={},U=$.toString();U=U.replace(/\r\n?/mg,`
|
|
28
|
-
`);let Q;while((Q=ma.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 da($){$=$||{};let J=Xf($);$.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=Vf($).split(","),_=Q.length,G;for(let V=0;V<_;V++)try{let X=Q[V].trim(),Z=ia(U,X);G=L6.decrypt(Z.ciphertext,Z.key);break}catch(X){if(V+1>=_)throw X}return L6.parse(G)}function la($){console.error(`[dotenv@${WB}][WARN] ${$}`)}function u5($){console.log(`[dotenv@${WB}][DEBUG] ${$}`)}function Gf($){console.log(`[dotenv@${WB}] ${$}`)}function Vf($){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 ia($,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 Xf($){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=yG.resolve(process.cwd(),".env.vault");if(FB.existsSync(J))return J;return null}function Qf($){return $[0]==="~"?yG.join(ba.homedir(),$.slice(1)):$}function ra($){let J=s9(process.env.DOTENV_CONFIG_DEBUG||$&&$.debug),U=s9(process.env.DOTENV_CONFIG_QUIET||$&&$.quiet);if(J||!U)Gf("Loading env from encrypted .env.vault");let Q=L6._parseVault($),_=process.env;if($&&$.processEnv!=null)_=$.processEnv;return L6.populate(_,Q,$),{parsed:Q}}function na($){let J=yG.resolve(process.cwd(),".env"),U="utf8",Q=process.env;if($&&$.processEnv!=null)Q=$.processEnv;let _=s9(Q.DOTENV_CONFIG_DEBUG||$&&$.debug),G=s9(Q.DOTENV_CONFIG_QUIET||$&&$.quiet);if($&&$.encoding)U=$.encoding;else if(_)u5("No encoding is specified. UTF-8 is used by default");let V=[J];if($&&$.path)if(!Array.isArray($.path))V=[Qf($.path)];else{V=[];for(let K of $.path)V.push(Qf(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(_)u5(`Failed to load ${K} ${F.message}`);X=F}let Y=L6.populate(Q,Z,$);if(_=s9(Q.DOTENV_CONFIG_DEBUG||_),G=s9(Q.DOTENV_CONFIG_QUIET||G),_||!G){let K=Object.keys(Y).length,F=[];for(let N of V)try{let q=yG.relative(process.cwd(),N);F.push(q)}catch(q){if(_)u5(`Failed to load ${N} ${q.message}`);X=q}Gf(`injecting env (${K}) from ${F.join(",")} ${ua(`-- tip: ${xa()}`)}`)}if(X)return{parsed:Z,error:X};else return{parsed:Z}}function pa($){if(Vf($).length===0)return L6.configDotenv($);let J=Xf($);if(!J)return la(`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 aa($,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=ya.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 oa($,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)u5(`"${V}" is already defined and WAS overwritten`);else u5(`"${V}" is already defined and was NOT overwritten`)}else $[V]=J[V],G[V]=J[V];return G}var L6={configDotenv:na,_configVault:ra,_parseVault:da,config:pa,decrypt:aa,parse:ca,populate:oa};IF$.configDotenv=L6.configDotenv;IF$._configVault=L6._configVault;IF$._parseVault=L6._parseVault;IF$.config=L6.config;IF$.decrypt=L6.decrypt;IF$.parse=L6.parse;IF$.populate=L6.populate;J2.exports=L6});var Kf=J$((SF$,Zf)=>{var N8={};if(process.env.DOTENV_CONFIG_ENCODING!=null)N8.encoding=process.env.DOTENV_CONFIG_ENCODING;if(process.env.DOTENV_CONFIG_PATH!=null)N8.path=process.env.DOTENV_CONFIG_PATH;if(process.env.DOTENV_CONFIG_QUIET!=null)N8.quiet=process.env.DOTENV_CONFIG_QUIET;if(process.env.DOTENV_CONFIG_DEBUG!=null)N8.debug=process.env.DOTENV_CONFIG_DEBUG;if(process.env.DOTENV_CONFIG_OVERRIDE!=null)N8.override=process.env.DOTENV_CONFIG_OVERRIDE;if(process.env.DOTENV_CONFIG_DOTENV_KEY!=null)N8.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY;Zf.exports=N8});var Ff=J$((TF$,Nf)=>{var Qo=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;Nf.exports=function(J){let U=J.reduce(function(Q,_){let G=_.match(Qo);if(G)Q[G[1]]=G[2];return Q},{});if(!("quiet"in U))U.quiet="true";return U}});var Wf=J$(()=>{(function(){Yf().config(Object.assign({},Kf(),Ff()(process.argv)))})()});var c5={};O0(c5,{settingsToEnvVars:()=>Po,saveGoatChainUserCache:()=>Do,normalizeStr:()=>OB,normalizeNum:()=>jo,loadUserSettings:()=>Eo,loadGoatChainUserCache:()=>zf,getGoatChainUserDir:()=>Lf,STATE_DIR_NAME:()=>m5,CONFIG_DIR_NAME:()=>F8,APP_DIR_NAME:()=>U2});function OB($){return String($??"").trim()||void 0}function jo($){if(typeof $==="number"&&Number.isFinite($))return $;let J=String($??"").trim();if(!J)return;let U=Number(J);return Number.isFinite(U)?U:void 0}async function Lf(){let J=globalThis.process?.env??{},[{homedir:U},Q]=await Promise.all([import("node:os"),import("node:path")]),_=OB(J.GOATCHAIN_HOME);if(_)return Q.resolve(_,"goatchain");let G=OB(J.XDG_CONFIG_HOME);if(G)return Q.resolve(G,".goatchain","goatchain");return Q.resolve(U(),".goatchain","goatchain")}async function zf(){let $=await Lf(),[{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 Do($,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 Eo(){let{cache:$}=await zf();return $.settings??{}}function Po($){let J={};if($.model)J.MODEL_ID=$.model;if($.baseUrl)J.OPENAI_API_BASE_URL=$.baseUrl;if($.apiKey)J.OPENAI_API_KEY=$.apiKey;if(typeof $.contextWindow==="number")J.GOATCHAIN_CONTEXT_WINDOW=String($.contextWindow);if(typeof $.temperature==="number")J.GOATCHAIN_TEMPERATURE=String($.temperature);return J}var F8=".goatchain",U2="goatchain",m5="state";var d5={};O0(d5,{setOAuthTokens:()=>EB,removeOAuthTokens:()=>zo,loadAuthData:()=>xG,getOAuthTokens:()=>hG,OAUTH_DUMMY_KEY:()=>Lo});import{chmod as Rf,mkdir as Af,readFile as Mo,writeFile as wf}from"node:fs/promises";import jB from"node:path";async function DB(){let{getGoatChainUserDir:$}=await Promise.resolve().then(() => c5),J=await $();return jB.join(J,"auth.json")}async function xG(){try{let $=await DB(),J=await Mo($,"utf8"),U=JSON.parse(J);return U&&typeof U==="object"?U:{}}catch{return{}}}async function hG($){return(await xG())[$]}async function EB($,J){let U=await DB(),Q=await xG();Q[$]=J;let _=jB.dirname(U);await Af(_,{recursive:!0});let G=`${U}.tmp.${Date.now()}`,V=`${JSON.stringify(Q,null,2)}
|
|
31
|
-
`;await wf(G,V,{encoding:"utf8",mode:384});let{rename:X}=await import("node:fs/promises");await X(G,U);try{await Rf(U,384)}catch{}}async function zo($){let J=await DB(),U=await xG();delete U[$];let Q=jB.dirname(J);await Af(Q,{recursive:!0});let _=`${J}.tmp.${Date.now()}`,G=`${JSON.stringify(U,null,2)}
|
|
32
|
-
`;await wf(_,G,{encoding:"utf8",mode:384});let{rename:V}=await import("node:fs/promises");await V(_,J);try{await Rf(J,384)}catch{}}var Lo="goatchain-oauth-dummy-key";var $U=()=>{};var _2={};O0(_2,{waitForOAuthCallback:()=>xo,stopOAuthServer:()=>go,startOAuthServer:()=>yo,refreshAccessToken:()=>LB,parseJwtClaims:()=>l5,generateState:()=>vo,generatePKCE:()=>So,extractEmail:()=>RB,extractAccountIdFromClaims:()=>MB,extractAccountId:()=>zB,exchangeCodeForTokens:()=>If,buildAuthorizeUrl:()=>Co,OAUTH_PORT:()=>ko,ISSUER:()=>Ao,CODEX_MODELS:()=>Io,CODEX_BASE_URL:()=>fo,CODEX_API_ENDPOINT:()=>wo,CLIENT_ID:()=>Ro});async function So(){let $=To(43),U=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",U),_=kf(Q);return{verifier:$,challenge:_}}function To($){let U=crypto.getRandomValues(new Uint8Array($));return Array.from(U).map((Q)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[Q%66]).join("")}function kf($){let J=new Uint8Array($),U=String.fromCharCode(...J);return btoa(U).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function vo(){return kf(crypto.getRandomValues(new Uint8Array(32)).buffer)}function Co($,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 If($,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 LB($){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 l5($){let J=$.split(".");if(J.length!==3)return;try{return JSON.parse(Buffer.from(J[1],"base64url").toString())}catch{return}}function MB($){return $.chatgpt_account_id||$["https://api.openai.com/auth"]?.chatgpt_account_id||$.organizations?.[0]?.id}function zB($){if($.id_token){let J=l5($.id_token),U=J&&MB(J);if(U)return U}if($.access_token){let J=l5($.access_token);return J?MB(J):void 0}return}function RB($){if($.id_token){let J=l5($.id_token);if(J?.email)return J.email}if($.access_token)return l5($.access_token)?.email;return}function PB($){return`<!doctype html>
|
|
33
|
-
<html>
|
|
34
|
-
<head>
|
|
35
|
-
<title>GoatChain - Codex Authorization Failed</title>
|
|
36
|
-
<style>
|
|
37
|
-
body {
|
|
38
|
-
font-family:
|
|
39
|
-
system-ui,
|
|
40
|
-
-apple-system,
|
|
41
|
-
sans-serif;
|
|
42
|
-
display: flex;
|
|
43
|
-
justify-content: center;
|
|
44
|
-
align-items: center;
|
|
45
|
-
height: 100vh;
|
|
46
|
-
margin: 0;
|
|
47
|
-
background: #131010;
|
|
48
|
-
color: #f1ecec;
|
|
49
|
-
}
|
|
50
|
-
.container {
|
|
51
|
-
text-align: center;
|
|
52
|
-
padding: 2rem;
|
|
53
|
-
}
|
|
54
|
-
h1 {
|
|
55
|
-
color: #fc533a;
|
|
56
|
-
margin-bottom: 1rem;
|
|
57
|
-
}
|
|
58
|
-
p {
|
|
59
|
-
color: #b7b1b1;
|
|
60
|
-
}
|
|
61
|
-
.error {
|
|
62
|
-
color: #ff917b;
|
|
63
|
-
font-family: monospace;
|
|
64
|
-
margin-top: 1rem;
|
|
65
|
-
padding: 1rem;
|
|
66
|
-
background: #3c140d;
|
|
67
|
-
border-radius: 0.5rem;
|
|
68
|
-
}
|
|
69
|
-
</style>
|
|
70
|
-
</head>
|
|
71
|
-
<body>
|
|
72
|
-
<div class="container">
|
|
73
|
-
<h1>Authorization Failed</h1>
|
|
74
|
-
<p>An error occurred during authorization.</p>
|
|
75
|
-
<div class="error">${$}</div>
|
|
76
|
-
</div>
|
|
77
|
-
</body>
|
|
78
|
-
</html>`}async function yo(){if($1)return{port:1455,redirectUri:"http://localhost:1455/auth/callback"};if(typeof globalThis.Bun<"u"){let J=globalThis.Bun;try{$1=J.serve({port:1455,fetch(U){let Q=new URL(U.url);return ff(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 $1=(await import("node:http")).createServer(async(U,Q)=>{try{let _=new URL(U.url||"/","http://localhost:1455"),G=ff(_);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)=>{$1.listen(1455,()=>U()),$1.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 ff($){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(PB(V),{headers:{"Content-Type":"text/html"}})}if(!J)return r6?.reject(Error("Missing authorization code")),r6=void 0,new Response(PB("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(PB("Invalid state - potential CSRF attack"),{status:400,headers:{"Content-Type":"text/html"}});let G=r6;return r6=void 0,If(J,"http://localhost:1455/auth/callback",G.pkce).then((V)=>G.resolve(V)).catch((V)=>G.reject(V)),new Response(bo,{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 go(){if($1){if(typeof $1.stop==="function")$1.stop();else if(typeof $1.close==="function")$1.close();$1=void 0}}function xo($,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)}}})}var Ro="app_EMoamEEZ73f0CkXaXp7hrann",Ao="https://auth.openai.com",wo="https://chatgpt.com/backend-api/codex/responses",fo="https://chatgpt.com/backend-api",ko=1455,Io,bo=`<!doctype html>
|
|
79
|
-
<html>
|
|
80
|
-
<head>
|
|
81
|
-
<title>GoatChain - Codex Authorization Successful</title>
|
|
82
|
-
<style>
|
|
83
|
-
body {
|
|
84
|
-
font-family:
|
|
85
|
-
system-ui,
|
|
86
|
-
-apple-system,
|
|
87
|
-
sans-serif;
|
|
88
|
-
display: flex;
|
|
89
|
-
justify-content: center;
|
|
90
|
-
align-items: center;
|
|
91
|
-
height: 100vh;
|
|
92
|
-
margin: 0;
|
|
93
|
-
background: #131010;
|
|
94
|
-
color: #f1ecec;
|
|
95
|
-
}
|
|
96
|
-
.container {
|
|
97
|
-
text-align: center;
|
|
98
|
-
padding: 2rem;
|
|
99
|
-
}
|
|
100
|
-
h1 {
|
|
101
|
-
color: #f1ecec;
|
|
102
|
-
margin-bottom: 1rem;
|
|
103
|
-
}
|
|
104
|
-
p {
|
|
105
|
-
color: #b7b1b1;
|
|
106
|
-
}
|
|
107
|
-
</style>
|
|
108
|
-
</head>
|
|
109
|
-
<body>
|
|
110
|
-
<div class="container">
|
|
111
|
-
<h1>Authorization Successful</h1>
|
|
112
|
-
<p>You can close this window and return to GoatChain.</p>
|
|
113
|
-
</div>
|
|
114
|
-
<script>
|
|
115
|
-
setTimeout(() => window.close(), 2000)
|
|
116
|
-
</script>
|
|
117
|
-
</body>
|
|
118
|
-
</html>`,$1,r6;var f1=CX(()=>{Io=[{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"}]});var mG={};O0(mG,{toPlainJson:()=>ro,saveGoatChainUserCache:()=>kB,normalizeStr:()=>Z6,normalizeNum:()=>W8,loadGoatChainUserCache:()=>fB,getGoatChainUserDir:()=>hf});function Z6($){return String($??"").trim()||void 0}function W8($){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 ro($){return JSON.parse(JSON.stringify($))}async function hf($){let[{homedir:J},U]=await Promise.all([import("node:os"),import("node:path")]),Q=Z6($.GOATCHAIN_HOME);if(Q)return U.resolve(Q,U2);let _=Z6($.XDG_CONFIG_HOME);if(_)return U.resolve(_,F8,U2);return U.resolve(J(),F8,U2)}async function fB($){let J=await hf($),[{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 kB($,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)}
|
|
119
|
-
`;await Q(K,F,{encoding:"utf8",mode:384}),await _(K,$);try{await G($,384)}catch{}}var Q2=()=>{};var K7=J$((ZD$,TI)=>{var X$$=Number.MAX_SAFE_INTEGER||9007199254740991,Y$$=["major","premajor","minor","preminor","patch","prepatch","prerelease"];TI.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:X$$,RELEASE_TYPES:Y$$,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var N7=J$((KD$,vI)=>{var Z$$=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...$)=>console.error("SEMVER",...$):()=>{};vI.exports=Z$$});var zU=J$((k1,CI)=>{var{MAX_SAFE_COMPONENT_LENGTH:SO,MAX_SAFE_BUILD_LENGTH:K$$,MAX_LENGTH:N$$}=K7(),F$$=N7();k1=CI.exports={};var W$$=k1.re=[],q$$=k1.safeRe=[],I$=k1.src=[],H$$=k1.safeSrc=[],S$=k1.t={},B$$=0,TO="[a-zA-Z0-9-]",O$$=[["\\s",1],["\\d",N$$],[TO,K$$]],j$$=($)=>{for(let[J,U]of O$$)$=$.split(`${J}*`).join(`${J}{0,${U}}`).split(`${J}+`).join(`${J}{1,${U}}`);return $},K4=($,J,U)=>{let Q=j$$(J),_=B$$++;F$$($,_,J),S$[$]=_,I$[_]=J,H$$[_]=Q,W$$[_]=new RegExp(J,U?"g":void 0),q$$[_]=new RegExp(Q,U?"g":void 0)};K4("NUMERICIDENTIFIER","0|[1-9]\\d*");K4("NUMERICIDENTIFIERLOOSE","\\d+");K4("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${TO}*`);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",`${TO}+`);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,${SO}})(?:\\.(\\d{1,${SO}}))?(?:\\.(\\d{1,${SO}}))?`);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);k1.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);k1.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);k1.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 zV=J$((ND$,bI)=>{var D$$=Object.freeze({loose:!0}),E$$=Object.freeze({}),P$$=($)=>{if(!$)return E$$;if(typeof $!=="object")return D$$;return $};bI.exports=P$$});var vO=J$((FD$,xI)=>{var yI=/^[0-9]+$/,gI=($,J)=>{if(typeof $==="number"&&typeof J==="number")return $===J?0:$<J?-1:1;let U=yI.test($),Q=yI.test(J);if(U&&Q)$=+$,J=+J;return $===J?0:U&&!Q?-1:Q&&!U?1:$<J?-1:1},M$$=($,J)=>gI(J,$);xI.exports={compareIdentifiers:gI,rcompareIdentifiers:M$$}});var u6=J$((WD$,uI)=>{var RV=N7(),{MAX_LENGTH:hI,MAX_SAFE_INTEGER:AV}=K7(),{safeRe:wV,t:fV}=zU(),L$$=zV(),{compareIdentifiers:CO}=vO();class G1{constructor($,J){if(J=L$$(J),$ instanceof G1)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>hI)throw TypeError(`version is longer than ${hI} characters`);RV("SemVer",$,J),this.options=J,this.loose=!!J.loose,this.includePrerelease=!!J.includePrerelease;let U=$.trim().match(J.loose?wV[fV.LOOSE]:wV[fV.FULL]);if(!U)throw TypeError(`Invalid Version: ${$}`);if(this.raw=$,this.major=+U[1],this.minor=+U[2],this.patch=+U[3],this.major>AV||this.major<0)throw TypeError("Invalid major version");if(this.minor>AV||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>AV||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&&_<AV)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(RV("SemVer.compare",this.version,this.options,$),!($ instanceof G1)){if(typeof $==="string"&&$===this.version)return 0;$=new G1($,this.options)}if($.version===this.version)return 0;return this.compareMain($)||this.comparePre($)}compareMain($){if(!($ instanceof G1))$=new G1($,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 G1))$=new G1($,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(RV("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 CO(U,Q)}while(++J)}compareBuild($){if(!($ instanceof G1))$=new G1($,this.options);let J=0;do{let U=this.build[J],Q=$.build[J];if(RV("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 CO(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?wV[fV.PRERELEASELOOSE]:wV[fV.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(CO(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}}uI.exports=G1});var E8=J$((qD$,cI)=>{var mI=u6(),z$$=($,J,U=!1)=>{if($ instanceof mI)return $;try{return new mI($,J)}catch(Q){if(!U)return null;throw Q}};cI.exports=z$$});var lI=J$((HD$,dI)=>{var R$$=E8(),A$$=($,J)=>{let U=R$$($,J);return U?U.version:null};dI.exports=A$$});var rI=J$((BD$,iI)=>{var w$$=E8(),f$$=($,J)=>{let U=w$$($.trim().replace(/^[=v]+/,""),J);return U?U.version:null};iI.exports=f$$});var aI=J$((OD$,pI)=>{var nI=u6(),k$$=($,J,U,Q,_)=>{if(typeof U==="string")_=Q,Q=U,U=void 0;try{return new nI($ instanceof nI?$.version:$,U).inc(J,Q,_).version}catch(G){return null}};pI.exports=k$$});var sI=J$((jD$,tI)=>{var oI=E8(),I$$=($,J)=>{let U=oI($,null,!0),Q=oI(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"};tI.exports=I$$});var $S=J$((DD$,eI)=>{var S$$=u6(),T$$=($,J)=>new S$$($,J).major;eI.exports=T$$});var US=J$((ED$,JS)=>{var v$$=u6(),C$$=($,J)=>new v$$($,J).minor;JS.exports=C$$});var QS=J$((PD$,_S)=>{var b$$=u6(),y$$=($,J)=>new b$$($,J).patch;_S.exports=y$$});var VS=J$((MD$,GS)=>{var g$$=E8(),x$$=($,J)=>{let U=g$$($,J);return U&&U.prerelease.length?U.prerelease:null};GS.exports=x$$});var c0=J$((LD$,YS)=>{var XS=u6(),h$$=($,J,U)=>new XS($,U).compare(new XS(J,U));YS.exports=h$$});var KS=J$((zD$,ZS)=>{var u$$=c0(),m$$=($,J,U)=>u$$(J,$,U);ZS.exports=m$$});var FS=J$((RD$,NS)=>{var c$$=c0(),d$$=($,J)=>c$$($,J,!0);NS.exports=d$$});var kV=J$((AD$,qS)=>{var WS=u6(),l$$=($,J,U)=>{let Q=new WS($,U),_=new WS(J,U);return Q.compare(_)||Q.compareBuild(_)};qS.exports=l$$});var BS=J$((wD$,HS)=>{var i$$=kV(),r$$=($,J)=>$.sort((U,Q)=>i$$(U,Q,J));HS.exports=r$$});var jS=J$((fD$,OS)=>{var n$$=kV(),p$$=($,J)=>$.sort((U,Q)=>n$$(Q,U,J));OS.exports=p$$});var F7=J$((kD$,DS)=>{var a$$=c0(),o$$=($,J,U)=>a$$($,J,U)>0;DS.exports=o$$});var IV=J$((ID$,ES)=>{var t$$=c0(),s$$=($,J,U)=>t$$($,J,U)<0;ES.exports=s$$});var bO=J$((SD$,PS)=>{var e$$=c0(),$4$=($,J,U)=>e$$($,J,U)===0;PS.exports=$4$});var yO=J$((TD$,MS)=>{var J4$=c0(),U4$=($,J,U)=>J4$($,J,U)!==0;MS.exports=U4$});var SV=J$((vD$,LS)=>{var _4$=c0(),Q4$=($,J,U)=>_4$($,J,U)>=0;LS.exports=Q4$});var TV=J$((CD$,zS)=>{var G4$=c0(),V4$=($,J,U)=>G4$($,J,U)<=0;zS.exports=V4$});var gO=J$((bD$,RS)=>{var X4$=bO(),Y4$=yO(),Z4$=F7(),K4$=SV(),N4$=IV(),F4$=TV(),W4$=($,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 X4$($,U,Q);case"!=":return Y4$($,U,Q);case">":return Z4$($,U,Q);case">=":return K4$($,U,Q);case"<":return N4$($,U,Q);case"<=":return F4$($,U,Q);default:throw TypeError(`Invalid operator: ${J}`)}};RS.exports=W4$});var wS=J$((yD$,AS)=>{var q4$=u6(),H4$=E8(),{safeRe:vV,t:CV}=zU(),B4$=($,J)=>{if($ instanceof q4$)return $;if(typeof $==="number")$=String($);if(typeof $!=="string")return null;J=J||{};let U=null;if(!J.rtl)U=$.match(J.includePrerelease?vV[CV.COERCEFULL]:vV[CV.COERCE]);else{let Z=J.includePrerelease?vV[CV.COERCERTLFULL]:vV[CV.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 H4$(`${Q}.${_}.${G}${V}${X}`,J)};AS.exports=B4$});var IS=J$((gD$,kS)=>{class fS{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}}kS.exports=fS});var d0=J$((xD$,CS)=>{var O4$=/\s+/g;class W7{constructor($,J){if(J=D4$(J),$ instanceof W7)if($.loose===!!J.loose&&$.includePrerelease===!!J.includePrerelease)return $;else return new W7($.raw,J);if($ instanceof xO)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(O4$," "),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)=>!TS(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&&A4$(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&&z4$)|(this.options.loose&&R4$))+":"+$,Q=SS.get(U);if(Q)return Q;let _=this.options.loose,G=_?s6[m6.HYPHENRANGELOOSE]:s6[m6.HYPHENRANGE];$=$.replace(G,y4$(this.options.includePrerelease)),i4("hyphen replace",$),$=$.replace(s6[m6.COMPARATORTRIM],P4$),i4("comparator trim",$),$=$.replace(s6[m6.TILDETRIM],M4$),i4("tilde trim",$),$=$.replace(s6[m6.CARETTRIM],L4$),i4("caret trim",$);let V=$.split(" ").map((K)=>w4$(K,this.options)).join(" ").split(/\s+/).map((K)=>b4$(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 xO(K,this.options));for(let K of Z){if(TS(K))return[K];X.set(K.value,K)}if(X.size>1&&X.has(""))X.delete("");let Y=[...X.values()];return SS.set(U,Y),Y}intersects($,J){if(!($ instanceof W7))throw TypeError("a Range is required");return this.set.some((U)=>{return vS(U,J)&&$.set.some((Q)=>{return vS(Q,J)&&U.every((_)=>{return Q.every((G)=>{return _.intersects(G,J)})})})})}test($){if(!$)return!1;if(typeof $==="string")try{$=new E4$($,this.options)}catch(J){return!1}for(let J=0;J<this.set.length;J++)if(g4$(this.set[J],$,this.options))return!0;return!1}}CS.exports=W7;var j4$=IS(),SS=new j4$,D4$=zV(),xO=q7(),i4=N7(),E4$=u6(),{safeRe:s6,t:m6,comparatorTrimReplace:P4$,tildeTrimReplace:M4$,caretTrimReplace:L4$}=zU(),{FLAG_INCLUDE_PRERELEASE:z4$,FLAG_LOOSE:R4$}=K7(),TS=($)=>$.value==="<0.0.0-0",A4$=($)=>$.value==="",vS=($,J)=>{let U=!0,Q=$.slice(),_=Q.pop();while(U&&Q.length)U=Q.every((G)=>{return _.intersects(G,J)}),_=Q.pop();return U},w4$=($,J)=>{return $=$.replace(s6[m6.BUILD],""),i4("comp",$,J),$=I4$($,J),i4("caret",$),$=f4$($,J),i4("tildes",$),$=T4$($,J),i4("xrange",$),$=C4$($,J),i4("stars",$),$},e6=($)=>!$||$.toLowerCase()==="x"||$==="*",f4$=($,J)=>{return $.trim().split(/\s+/).map((U)=>k4$(U,J)).join(" ")},k4$=($,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})},I4$=($,J)=>{return $.trim().split(/\s+/).map((U)=>S4$(U,J)).join(" ")},S4$=($,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})},T4$=($,J)=>{return i4("replaceXRanges",$,J),$.split(/\s+/).map((U)=>v4$(U,J)).join(" ")},v4$=($,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})},C4$=($,J)=>{return i4("replaceStars",$,J),$.trim().replace(s6[m6.STAR],"")},b4$=($,J)=>{return i4("replaceGTE0",$,J),$.trim().replace(s6[J.includePrerelease?m6.GTE0PRE:m6.GTE0],"")},y4$=($)=>(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()},g4$=($,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===xO.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 q7=J$((hD$,uS)=>{var H7=Symbol("SemVer ANY");class bV{static get ANY(){return H7}constructor($,J){if(J=bS(J),$ instanceof bV)if($.loose===!!J.loose)return $;else $=$.value;if($=$.trim().split(/\s+/).join(" "),uO("comparator",$,J),this.options=J,this.loose=!!J.loose,this.parse($),this.semver===H7)this.value="";else this.value=this.operator+this.semver.version;uO("comp",this)}parse($){let J=this.options.loose?yS[gS.COMPARATORLOOSE]:yS[gS.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=H7;else this.semver=new xS(U[2],this.options.loose)}toString(){return this.value}test($){if(uO("Comparator.test",$,this.options.loose),this.semver===H7||$===H7)return!0;if(typeof $==="string")try{$=new xS($,this.options)}catch(J){return!1}return hO($,this.operator,this.semver,this.options)}intersects($,J){if(!($ instanceof bV))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new hS($.value,J).test(this.value)}else if($.operator===""){if($.value==="")return!0;return new hS(this.value,J).test($.semver)}if(J=bS(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(hO(this.semver,"<",$.semver,J)&&this.operator.startsWith(">")&&$.operator.startsWith("<"))return!0;if(hO(this.semver,">",$.semver,J)&&this.operator.startsWith("<")&&$.operator.startsWith(">"))return!0;return!1}}uS.exports=bV;var bS=zV(),{safeRe:yS,t:gS}=zU(),hO=gO(),uO=N7(),xS=u6(),hS=d0()});var B7=J$((uD$,mS)=>{var x4$=d0(),h4$=($,J,U)=>{try{J=new x4$(J,U)}catch(Q){return!1}return J.test($)};mS.exports=h4$});var dS=J$((mD$,cS)=>{var u4$=d0(),m4$=($,J)=>new u4$($,J).set.map((U)=>U.map((Q)=>Q.value).join(" ").trim().split(" "));cS.exports=m4$});var iS=J$((cD$,lS)=>{var c4$=u6(),d4$=d0(),l4$=($,J,U)=>{let Q=null,_=null,G=null;try{G=new d4$(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};lS.exports=l4$});var nS=J$((dD$,rS)=>{var i4$=u6(),r4$=d0(),n4$=($,J,U)=>{let Q=null,_=null,G=null;try{G=new r4$(J,U)}catch(V){return null}return $.forEach((V)=>{if(G.test(V)){if(!Q||_.compare(V)===1)Q=V,_=new i4$(Q,U)}}),Q};rS.exports=n4$});var oS=J$((lD$,aS)=>{var mO=u6(),p4$=d0(),pS=F7(),a4$=($,J)=>{$=new p4$($,J);let U=new mO("0.0.0");if($.test(U))return U;if(U=new mO("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 mO(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||pS(X,G))G=X;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${V.operator}`)}}),G&&(!U||pS(U,G)))U=G}if(U&&$.test(U))return U;return null};aS.exports=a4$});var sS=J$((iD$,tS)=>{var o4$=d0(),t4$=($,J)=>{try{return new o4$($,J).range||"*"}catch(U){return null}};tS.exports=t4$});var yV=J$((rD$,UT)=>{var s4$=u6(),JT=q7(),{ANY:e4$}=JT,$6$=d0(),J6$=B7(),eS=F7(),$T=IV(),U6$=TV(),_6$=SV(),Q6$=($,J,U,Q)=>{$=new s4$($,Q),J=new $6$(J,Q);let _,G,V,X,Z;switch(U){case">":_=eS,G=U6$,V=$T,X=">",Z=">=";break;case"<":_=$T,G=_6$,V=eS,X="<",Z="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(J6$($,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===e4$)q=new JT(">=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};UT.exports=Q6$});var QT=J$((nD$,_T)=>{var G6$=yV(),V6$=($,J,U)=>G6$($,J,">",U);_T.exports=V6$});var VT=J$((pD$,GT)=>{var X6$=yV(),Y6$=($,J,U)=>X6$($,J,"<",U);GT.exports=Y6$});var ZT=J$((aD$,YT)=>{var XT=d0(),Z6$=($,J,U)=>{return $=new XT($,U),J=new XT(J,U),$.intersects(J,U)};YT.exports=Z6$});var NT=J$((oD$,KT)=>{var K6$=B7(),N6$=c0();KT.exports=($,J,U)=>{let Q=[],_=null,G=null,V=$.sort((K,F)=>N6$(K,F,U));for(let K of V)if(K6$(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 OT=J$((tD$,BT)=>{var FT=d0(),dO=q7(),{ANY:cO}=dO,O7=B7(),lO=c0(),F6$=($,J,U={})=>{if($===J)return!0;$=new FT($,U),J=new FT(J,U);let Q=!1;$:for(let _ of $.set){for(let G of J.set){let V=q6$(_,G,U);if(Q=Q||V!==null,V)continue $}if(Q)return!1}return!0},W6$=[new dO(">=0.0.0-0")],WT=[new dO(">=0.0.0")],q6$=($,J,U)=>{if($===J)return!0;if($.length===1&&$[0].semver===cO)if(J.length===1&&J[0].semver===cO)return!0;else if(U.includePrerelease)$=W6$;else $=WT;if(J.length===1&&J[0].semver===cO)if(U.includePrerelease)return!0;else J=WT;let Q=new Set,_,G;for(let q of $)if(q.operator===">"||q.operator===">=")_=qT(_,q,U);else if(q.operator==="<"||q.operator==="<=")G=HT(G,q,U);else Q.add(q.semver);if(Q.size>1)return null;let V;if(_&&G){if(V=lO(_.semver,G.semver,U),V>0)return null;else if(V===0&&(_.operator!==">="||G.operator!=="<="))return null}for(let q of Q){if(_&&!O7(q,String(_),U))return null;if(G&&!O7(q,String(G),U))return null;for(let H of J)if(!O7(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=qT(_,q,U),X===q&&X!==_)return!1}else if(_.operator===">="&&!O7(_.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=HT(G,q,U),Z===q&&Z!==G)return!1}else if(G.operator==="<="&&!O7(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},qT=($,J,U)=>{if(!$)return J;let Q=lO($.semver,J.semver,U);return Q>0?$:Q<0?J:J.operator===">"&&$.operator===">="?J:$},HT=($,J,U)=>{if(!$)return J;let Q=lO($.semver,J.semver,U);return Q<0?$:Q>0?J:J.operator==="<"&&$.operator==="<="?J:$};BT.exports=F6$});var PT=J$((sD$,ET)=>{var iO=zU(),jT=K7(),H6$=u6(),DT=vO(),B6$=E8(),O6$=lI(),j6$=rI(),D6$=aI(),E6$=sI(),P6$=$S(),M6$=US(),L6$=QS(),z6$=VS(),R6$=c0(),A6$=KS(),w6$=FS(),f6$=kV(),k6$=BS(),I6$=jS(),S6$=F7(),T6$=IV(),v6$=bO(),C6$=yO(),b6$=SV(),y6$=TV(),g6$=gO(),x6$=wS(),h6$=q7(),u6$=d0(),m6$=B7(),c6$=dS(),d6$=iS(),l6$=nS(),i6$=oS(),r6$=sS(),n6$=yV(),p6$=QT(),a6$=VT(),o6$=ZT(),t6$=NT(),s6$=OT();ET.exports={parse:B6$,valid:O6$,clean:j6$,inc:D6$,diff:E6$,major:P6$,minor:M6$,patch:L6$,prerelease:z6$,compare:R6$,rcompare:A6$,compareLoose:w6$,compareBuild:f6$,sort:k6$,rsort:I6$,gt:S6$,lt:T6$,eq:v6$,neq:C6$,gte:b6$,lte:y6$,cmp:g6$,coerce:x6$,Comparator:h6$,Range:u6$,satisfies:m6$,toComparators:c6$,maxSatisfying:d6$,minSatisfying:l6$,minVersion:i6$,validRange:r6$,outside:n6$,gtr:p6$,ltr:a6$,intersects:o6$,simplifyRange:t6$,subset:s6$,SemVer:H6$,re:iO.re,src:iO.src,tokens:iO.t,SEMVER_SPEC_VERSION:jT.SEMVER_SPEC_VERSION,RELEASE_TYPES:jT.RELEASE_TYPES,compareIdentifiers:DT.compareIdentifiers,rcompareIdentifiers:DT.rcompareIdentifiers}});import{appendFileSync as h2$,writeFileSync as u2$}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 bj($,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,j=null,B=!1;for(let D=0;D<$.length;D++){let w=$[D];if(w==="--cols")G=Number.parseInt($[++D]??"",10),X=!0;else if(w==="--rows")V=Number.parseInt($[++D]??"",10),Z=!0;else if(w==="--app"||w==="--example")Y=String($[++D]??Y);else if(w==="--route"||w==="--initial-route")K=String($[++D]??K);else if(w==="--approvals"||w==="--approval"){let A=String($[++D]??"").trim().toLowerCase();if(A==="auto")j="auto";else if(A==="all"||A==="on"||A==="yes"||A==="true"||A==="1")j="all"}else if(w==="--auto-approve"||w==="--yes"||w==="-y")j="all";else if(w==="--record")F=$[++D]??null;else if(w==="--replay")N=$[++D]??null;else if(w==="--snapshot")q=$[++D]??null;else if(w==="--no-mouse")H=!1;else if(w==="--no-alt-screen")E=!1;else if(w==="--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:j,debug:B}}import*as Jk from"node:path";function yj($){let U=["# GoatChain error","","```text",$ instanceof Error?$.stack||$.message:String($),"```"].join(`
|
|
120
|
-
`);return{async*receiveMessage(Q){yield{role:"assistant",content:U,metadata:{done:!0,error:!0,stopReason:"error",originalEventType:"done"}}}}}import{randomUUID as ho}from"node:crypto";import{encoding_for_model as Ub,get_encoding as _b}from"tiktoken";var Qb="gpt-4o";function h1($,J){if(!$)return 0;let U=null;try{return U=Ub(J??Qb),U.encode($).length}catch(Q){console.error("Error encoding text:",Q);try{return U=_b("cl100k_base"),U.encode($).length}catch{return Math.ceil($.length/4)}}finally{U?.free()}}function gj($,J){if(typeof $==="string")return h1($,J);if(Array.isArray($))return $.reduce((U,Q)=>{if(typeof Q==="object"&&Q!==null&&"text"in Q)return U+h1(String(Q.text),J);return U},0);return 0}function xj($,J){try{let U=JSON.stringify($);return h1(U,J)}catch{return Gb($,J)}}function Gb($,J){let Q=4;if(Q+=gj($.content,J),$.role==="assistant"&&$.tool_calls)for(let _ of $.tool_calls){Q+=h1(_.function.name,J);let G=typeof _.function.arguments==="string"?_.function.arguments:JSON.stringify(_.function.arguments);Q+=h1(G,J),Q+=10}if($.role==="tool"&&$.name)Q+=h1($.name,J);if($.role==="assistant"&&$.reasoning_content)Q+=h1($.reasoning_content,J);return Q}function g8($,J){if(!$||$.length===0)return 0;try{let U=JSON.stringify($);return h1(U,J)}catch{return $.reduce((Q,_)=>Q+xj(_,J),3)}}var I6={CHECKPOINT:"checkpoint",COMPRESSION:"compression",SESSION:"session",COMPRESSION_SNAPSHOT:"compression-snapshot"};function u1($,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}
|
|
121
|
-
|
|
122
|
-
${J}`},K=[...Vb(V,U),Z],F={...G,content:K};return Q[_]=F,Q}function Vb($,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 hj="[Old tool result content cleared]",Xb=`
|
|
123
|
-
Summarize the conversation context for future continuation.
|
|
124
|
-
|
|
125
|
-
Rules:
|
|
126
|
-
- Be concise and factual
|
|
127
|
-
- Use bullet points (6-12 bullets)
|
|
128
|
-
- Include: user goals, key decisions, files/paths touched, unresolved issues, next steps
|
|
129
|
-
- Keep under 1200 characters
|
|
130
|
-
- If existing summary provided, merge old + new into one consolidated summary
|
|
131
|
-
- Remove redundancy and repeated facts
|
|
132
|
-
|
|
133
|
-
Existing summary (if any):
|
|
134
|
-
{{existingSummary}}
|
|
135
|
-
|
|
136
|
-
Content to summarize:
|
|
137
|
-
{{content}}
|
|
138
|
-
`;function RJ($){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=u1(q,N.summary);let H=g8(q),E=0,j=0,B=N?.summary,D=!1;if(H>Z){let S=Wb(q),O=qb(q,U),M=await Zb(q,Q,N?.summary,S,O);if(M.summaryApplied)q=M.compressedMessages,B=M.newSummary,j=M.removedCount,D=!0,q=u1(q,B)}if((D?g8(q):H)>X){let S=Math.floor(J*G),O=Yb(q,S,V);q=O.compressedMessages,E=O.clearedCount}let A=D||E>0,I=A?g8(q):H,f=A?Date.now():0;if(D){let S={tokensBefore:H,tokensAfter:I,clearedToolOutputs:E,removedMessages:j,summaryGenerated:!0,timestamp:f},O={lastStats:S,history:[...N?.history??[],S],summary:B,updatedAt:f};await _.save(K.sessionId,I6.COMPRESSION,O)}let z={...K,messages:q,metadata:A?{...K.metadata,lastCompression:{tokensBefore:H,tokensAfter:I,clearedToolOutputs:E,removedMessages:j,summaryGenerated:D,timestamp:f}}:K.metadata};return F(z)};return Y.__middlewareName="context-compression",Y}function Yb($,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===hj)continue;if(V=V.map((F,N)=>{if(N===Z)return{...Y,content:hj};return F}),X++,g8(V)<=J)break}return{compressedMessages:V,clearedCount:X}}async function Zb($,J,U,Q,_){let G=$.slice(Q,_);if(G.length===0)return{compressedMessages:$,newSummary:U??"",removedCount:0,summaryApplied:!1};let V=Kb(G),X=await Nb(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 Kb($){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
|
|
139
|
-
${Q}`)}else if(U.role==="assistant"){let Q=typeof U.content==="string"?U.content:JSON.stringify(U.content);J.push(`## Assistant
|
|
140
|
-
${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"}
|
|
141
|
-
${G}`)}return J.join(`
|
|
142
|
-
|
|
143
|
-
---
|
|
144
|
-
|
|
145
|
-
`)}async function Nb($,J,U,Q){let _=Fb(Q??Xb,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 Fb($,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):
|
|
146
|
-
${J??"(none)"}`);if(!_)V.push(`Content to summarize:
|
|
147
|
-
${U}`);return`${G.trim()}
|
|
148
|
-
|
|
149
|
-
${V.join(`
|
|
150
|
-
|
|
151
|
-
`)}
|
|
152
|
-
`}function Wb($){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 qb($,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 Hb=["planMode","planModeMiddleware","parallelMode","parallelSubagentMiddleware","blockedTools","commitProcessed","_pendingUserInput"];function xX($){let J={};for(let[U,Q]of Object.entries($))if(!Hb.includes(U))J[U]=Q;return J}var Bb=1;function y7($,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:Bb,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 cy}from"node:events";class H2 extends Error{constructor($="Agent execution aborted"){super($);this.name="AgentAbortError"}}class AJ extends Error{constructor($="Agent execution paused"){super($);this.name="AgentPauseError"}}function m1($,J){if(!$?.aborted)return;let U=$?.reason;if(U instanceof Error)throw U;throw new H2(typeof U==="string"?U:J?`${J} aborted`:"Agent execution aborted")}function g7($){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 x7($,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 wJ{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 fJ{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 fJ;static aggressive=new fJ({maxAttempts:5,baseDelayMs:1000,maxDelayMs:60000});static gentle=new fJ({maxAttempts:3,baseDelayMs:2000,maxDelayMs:30000,jitter:"full"})}function x8($){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 fJ({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,j=X.signal,B=setTimeout(()=>E.abort(),N),D=()=>E.abort();if(j)if(j.aborted)E.abort();else j.addEventListener("abort",D);let w={...K,requestId:Z,model:F,stream:X.stream??!0,signal:E.signal,timeoutMs:N};try{for(let A=1;A<=Q.maxAttempts;A++){H=A;try{for await(let I of J.stream({request:w})){if(I.type==="delta")q=!0;yield I}return}catch(I){let f=uj(I),T=f.retryable;if(q||!T||!Q.canRetry(A))throw f;let z=Q.getDelay(A);$.retry?.onRetry?.({attempt:A,maxAttempts:Q.maxAttempts,delayMs:z,error:{code:f.code,message:f.message,retryable:f.retryable},model:F,request:w}),await wJ.sleep(z,E.signal)}}}catch(A){let I=uj(A);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),j)j.removeEventListener("abort",D)}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 uj($){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?wJ.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 kJ({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 kJ extends q6{constructor({message:$,cause:J}){super(void 0,void 0,$||"Connection error.",void 0);if(J)this.cause=J}}class IJ extends kJ{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 c1 extends Error{constructor($){super($)}}var Db=/^[a-z][a-z0-9+.-]*:/i,mj=($)=>{return Db.test($)},g6=($)=>(g6=Array.isArray,g6($)),mX=g6;function cX($){if(typeof $!=="object")return{};return $??{}}function cj($){if(!$)return!0;for(let J in $)return!1;return!0}function dj($,J){return Object.prototype.hasOwnProperty.call($,J)}function $_($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var lj=($,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 ij=($)=>{try{return JSON.parse($)}catch(J){return}};var W1=($)=>new Promise((J)=>setTimeout(J,$));var B2="6.16.0";var aj=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function Eb(){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 Pb=()=>{let $=Eb();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B2,"X-Stainless-OS":nj(Deno.build.os),"X-Stainless-Arch":rj(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":B2,"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":B2,"X-Stainless-OS":nj(globalThis.process.platform??"unknown"),"X-Stainless-Arch":rj(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let J=Mb();if(J)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B2,"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":B2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Mb(){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 rj=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},nj=($)=>{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"},pj,oj=()=>{return pj??(pj=Pb())};function tj(){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 h7($){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 sj($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let J=$.getReader(),U=J.cancel();J.releaseLock(),await U}var ej=({headers:$,body:J})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(J)}};var u7="RFC3986",iX=($)=>String($),m7={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:iX},rX="RFC1738";var c7=($,J)=>(c7=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),c7($,J)),q1=(()=>{let $=[];for(let J=0;J<256;++J)$.push("%"+((J<16?"0":"")+J.toString(16)).toUpperCase());return $})();var nX=1024,$D=($,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 JD($){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 _D={brackets($){return String($)+"[]"},comma:"comma",indices($,J){return String($)+"["+J+"]"},repeat($){return String($)}},QD=function($,J){Array.prototype.push.apply($,g6(J)?J:[J])},UD,E6={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:$D,encodeValuesOnly:!1,format:u7,formatter:iX,indices:!1,serializeDate($){return(UD??(UD=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function Rb($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var aX={};function GD($,J,U,Q,_,G,V,X,Z,Y,K,F,N,q,H,E,j,B){let D=$,w=B,A=0,I=!1;while((w=w.get(aX))!==void 0&&!I){let O=w.get($);if(A+=1,typeof O<"u")if(O===A)throw RangeError("Cyclic object value");else I=!0;if(typeof w.get(aX)>"u")A=0}if(typeof Y==="function")D=Y(J,D);else if(D instanceof Date)D=N?.(D);else if(U==="comma"&&g6(D))D=pX(D,function(O){if(O instanceof Date)return N?.(O);return O});if(D===null){if(G)return Z&&!E?Z(J,E6.encoder,j,"key",q):J;D=""}if(Rb(D)||JD(D)){if(Z){let O=E?J:Z(J,E6.encoder,j,"key",q);return[H?.(O)+"="+H?.(Z(D,E6.encoder,j,"value",q))]}return[H?.(J)+"="+H?.(String(D))]}let f=[];if(typeof D>"u")return f;let T;if(U==="comma"&&g6(D)){if(E&&Z)D=pX(D,Z);T=[{value:D.length>0?D.join(",")||null:void 0}]}else if(g6(Y))T=Y;else{let O=Object.keys(D);T=K?O.sort(K):O}let z=X?String(J).replace(/\./g,"%2E"):String(J),S=Q&&g6(D)&&D.length===1?z+"[]":z;if(_&&g6(D)&&D.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:D[M];if(V&&P===null)continue;let R=F&&X?M.replace(/\./g,"%2E"):M,k=g6(D)?typeof U==="function"?U(S,R):S:S+(F?"."+R:"["+R+"]");B.set($,A);let L=new WeakMap;L.set(aX,B),QD(f,GD(P,k,U,Q,_,G,V,X,U==="comma"&&E&&g6(D)?null:Z,Y,K,F,N,q,H,E,j,L))}return f}function Ab($=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=u7;if(typeof $.format<"u"){if(!c7(m7,$.format))throw TypeError("Unknown format option provided.");U=$.format}let Q=m7[U],_=E6.filter;if(typeof $.filter==="function"||g6($.filter))_=$.filter;let G;if($.arrayFormat&&$.arrayFormat in _D)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=Ab(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=_D[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;QD(V,GD(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 YD($){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 VD;function h8($){let J;return(VD??(J=new globalThis.TextEncoder,VD=J.encode.bind(J)))($)}var XD;function tX($){let J;return(XD??(J=new globalThis.TextDecoder,XD=J.decode.bind(J)))($)}var j0,D0;class u8{constructor(){j0.set(this,void 0),D0.set(this,void 0),m$(this,j0,new Uint8Array,"f"),m$(this,D0,null,"f")}decode($){if($==null)return[];let J=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?h8($):$;m$(this,j0,YD([d(this,j0,"f"),J]),"f");let U=[],Q;while((Q=fb(d(this,j0,"f"),d(this,D0,"f")))!=null){if(Q.carriage&&d(this,D0,"f")==null){m$(this,D0,Q.index,"f");continue}if(d(this,D0,"f")!=null&&(Q.index!==d(this,D0,"f")+1||Q.carriage)){U.push(tX(d(this,j0,"f").subarray(0,d(this,D0,"f")-1))),m$(this,j0,d(this,j0,"f").subarray(d(this,D0,"f")),"f"),m$(this,D0,null,"f");continue}let _=d(this,D0,"f")!==null?Q.preceding-1:Q.preceding,G=tX(d(this,j0,"f").subarray(0,_));U.push(G),m$(this,j0,d(this,j0,"f").subarray(Q.index),"f"),m$(this,D0,null,"f")}return U}flush(){if(!d(this,j0,"f").length)return[];return this.decode(`
|
|
153
|
-
`)}}j0=new WeakMap,D0=new WeakMap;u8.NEWLINE_CHARS=new Set([`
|
|
154
|
-
`,"\r"]);u8.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function fb($,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 ZD($){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 l7={off:0,error:200,warn:300,info:400,debug:500},sX=($,J,U)=>{if(!$)return;if(dj(l7,$))return $;G6(U).warn(`${J} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(l7))}`);return};function J_(){}function d7($,J,U){if(!J||l7[$]>l7[U])return J_;else return J[$].bind(J)}var kb={error:J_,warn:J_,info:J_,debug:J_},KD=new WeakMap;function G6($){let J=$.logger,U=$.logLevel??"off";if(!J)return kb;let Q=KD.get(J);if(Q&&Q[0]===U)return Q[1];let _={error:d7("error",J,U),warn:d7("warn",J,U),info:d7("info",J,U),debug:d7("debug",J,U)};return KD.set(J,[U,_]),_}var d1=($)=>{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 U_;class E0{constructor($,J,U){this.iterator=$,U_.set(this,void 0),this.controller=J,m$(this,U_,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 Ib($,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 E0(G,J,U)}static fromReadableStream($,J,U){let Q=!1;async function*_(){let V=new u8,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 E0(G,J,U)}[(U_=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 E0(()=>Q($),this.controller,d(this,U_,"f")),new E0(()=>Q(J),this.controller,d(this,U_,"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=h8(JSON.stringify(Q)+`
|
|
155
|
-
`);U.enqueue(G)}catch(Q){U.error(Q)}},async cancel(){await J.return?.()}})}}async function*Ib($,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 ND,Q=new u8,_=lX($.body);for await(let G of Sb(_))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*Sb($){let J=new Uint8Array;for await(let U of $){if(U==null)continue;let Q=U instanceof ArrayBuffer?new Uint8Array(U):typeof U==="string"?h8(U):U,_=new Uint8Array(J.length+Q.length);_.set(J),_.set(Q,J.length),J=_;let G;while((G=ZD(J))!==-1)yield J.slice(0,G),J=J.slice(G)}if(J.length>0)yield J}class ND{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(`
|
|
156
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],_}if(this.chunks.push($),$.startsWith(":"))return null;let[J,U,Q]=Tb($,":");if(Q.startsWith(" "))Q=Q.substring(1);if(J==="event")this.event=Q;else if(J==="data")this.data.push(Q);return null}}function Tb($,J){let U=$.indexOf(J);if(U!==-1)return[$.substring(0,U),J,$.substring(U+J.length)];return[$,"",""]}async function i7($,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 E0.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`,d1({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 __;class SJ extends Promise{constructor($,J,U=i7){super((Q)=>{Q(null)});this.responsePromise=J,this.parseResponse=U,__.set(this,void 0),m$(this,__,$,"f")}_thenUnwrap($){return new SJ(d(this,__,"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,__,"f"),$));return this.parsedPromise}then($,J){return this.parse().then($,J)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}__=new WeakMap;var r7;class n7{constructor($,J,U,Q){r7.set(this,void 0),m$(this,r7,$,"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,r7,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(r7=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let J of $.getPaginatedItems())yield J}}class p7 extends SJ{constructor($,J,U){super($,J,async(Q,_)=>new U(Q,_.response,await i7(Q,_),_.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let J of $)yield J}}class l1 extends n7{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 n7{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 O2 extends n7{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 m8($,J,U){return UY(),new File($,J??"unknown_file",U)}function Q_($){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 a7=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",_Y=async($,J)=>{if(!$Y($.body))return $;return{...$,body:await WD($.body,J)}},P0=async($,J)=>{return{...$,body:await WD($.body,J)}},FD=new WeakMap;function Cb($){let J=typeof $==="function"?$:$.fetch,U=FD.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 FD.set(J,Q),Q}var WD=async($,J)=>{if(!await Cb(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},qD=($)=>$ instanceof Blob&&("name"in $),bb=($)=>typeof $==="object"&&$!==null&&($ instanceof Response||a7($)||qD($)),$Y=($)=>{if(bb($))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,m8([await U.blob()],Q_(U)));else if(a7(U))$.append(J,m8([await new Response(h7(U)).blob()],Q_(U)));else if(qD(U))$.append(J,U,Q_(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 HD=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",yb=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&HD($),gb=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function o7($,J,U){if(UY(),$=await $,yb($)){if($ instanceof File)return $;return m8([await $.arrayBuffer()],$.name)}if(gb($)){let _=await $.blob();return J||(J=new URL($.url).pathname.split(/[\\/]/).pop()),m8(await QY(_),J,U)}let Q=await QY($);if(J||(J=Q_($)),!U?.type){let _=Q.find((G)=>typeof G==="object"&&("type"in G)&&G.type);if(typeof _==="string")U={...U,type:_}}return m8(Q,J,U)}async function QY($){let J=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)J.push($);else if(HD($))J.push($ instanceof Blob?$:await $.arrayBuffer());else if(a7($))for await(let U of $)J.push(...await QY(U));else{let U=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${U?`; constructor: ${U}`:""}${xb($)}`)}return J}function xb($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((U)=>`"${U}"`).join(", ")}]`}class X${constructor($){this._client=$}}function OD($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var BD=Object.freeze(Object.create(null)),ub=($=OD)=>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??BD)??BD)?.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:
|
|
157
|
-
${G.map((N)=>N.error).join(`
|
|
158
|
-
`)}
|
|
159
|
-
${V}
|
|
160
|
-
${F}`)}return V},U$=ub(OD);class c8 extends X${list($,J={},U){return this._client.getAPIList(U$`/chat/completions/${$}/messages`,H4,{query:J,...U})}}function G_($){return $!==void 0&&"function"in $&&$.function!==void 0}function V_($){return $?.$brand==="auto-parseable-response-format"}function TJ($){return $?.$brand==="auto-parseable-tool"}function jD($,J){if(!J||!GY(J))return{...$,choices:$.choices.map((U)=>{return ED(U.message.tool_calls),{...U,message:{...U.message,parsed:null,...U.message.tool_calls?{tool_calls:U.message.tool_calls}:void 0}}})};return X_($,J)}function X_($,J){let U=$.choices.map((Q)=>{if(Q.finish_reason==="length")throw new sU;if(Q.finish_reason==="content_filter")throw new eU;return ED(Q.message.tool_calls),{...Q,message:{...Q.message,...Q.message.tool_calls?{tool_calls:Q.message.tool_calls?.map((_)=>lb(J,_))??void 0}:void 0,parsed:Q.message.content&&!Q.message.refusal?db(J,Q.message.content):null}}});return{...$,choices:U}}function db($,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 lb($,J){let U=$.tools?.find((Q)=>G_(Q)&&Q.function?.name===J.function.name);return{...J,function:{...J.function,parsed_arguments:TJ(U)?U.$parseRaw(J.function.arguments):U?.function.strict?JSON.parse(J.function.arguments):null}}}function DD($,J){if(!$||!("tools"in $)||!$.tools)return!1;let U=$.tools?.find((Q)=>G_(Q)&&Q.function?.name===J.function.name);return G_(U)&&(TJ(U)||U?.function.strict||!1)}function GY($){if(V_($.response_format))return!0;return $.tools?.some((J)=>TJ(J)||J.type==="function"&&J.function.strict===!0)??!1}function ED($){for(let J of $||[])if(J.type!=="function")throw new w$(`Currently only \`function\` tool calls are supported; Received \`${J.type}\``)}function PD($){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 d8=($)=>{return $?.role==="assistant"},VY=($)=>{return $?.role==="tool"};var XY,t7,s7,Y_,Z_,e7,K_,i1,N_,$Q,JQ,l8,MD;class vJ{constructor(){XY.add(this),this.controller=new AbortController,t7.set(this,void 0),s7.set(this,()=>{}),Y_.set(this,()=>{}),Z_.set(this,void 0),e7.set(this,()=>{}),K_.set(this,()=>{}),i1.set(this,{}),N_.set(this,!1),$Q.set(this,!1),JQ.set(this,!1),l8.set(this,!1),m$(this,t7,new Promise(($,J)=>{m$(this,s7,$,"f"),m$(this,Y_,J,"f")}),"f"),m$(this,Z_,new Promise(($,J)=>{m$(this,e7,$,"f"),m$(this,K_,J,"f")}),"f"),d(this,t7,"f").catch(()=>{}),d(this,Z_,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},d(this,XY,"m",MD).bind(this))},0)}_connected(){if(this.ended)return;d(this,s7,"f").call(this),this._emit("connect")}get ended(){return d(this,N_,"f")}get errored(){return d(this,$Q,"f")}get aborted(){return d(this,JQ,"f")}abort(){this.controller.abort()}on($,J){return(d(this,i1,"f")[$]||(d(this,i1,"f")[$]=[])).push({listener:J}),this}off($,J){let U=d(this,i1,"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,i1,"f")[$]||(d(this,i1,"f")[$]=[])).push({listener:J,once:!0}),this}emitted($){return new Promise((J,U)=>{if(m$(this,l8,!0,"f"),$!=="error")this.once("error",U);this.once($,J)})}async done(){m$(this,l8,!0,"f"),await d(this,Z_,"f")}_emit($,...J){if(d(this,N_,"f"))return;if($==="end")m$(this,N_,!0,"f"),d(this,e7,"f").call(this);let U=d(this,i1,"f")[$];if(U)d(this,i1,"f")[$]=U.filter((Q)=>!Q.once),U.forEach(({listener:Q})=>Q(...J));if($==="abort"){let Q=J[0];if(!d(this,l8,"f")&&!U?.length)Promise.reject(Q);d(this,Y_,"f").call(this,Q),d(this,K_,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=J[0];if(!d(this,l8,"f")&&!U?.length)Promise.reject(Q);d(this,Y_,"f").call(this,Q),d(this,K_,"f").call(this,Q),this._emit("end")}}_emitFinal(){}}t7=new WeakMap,s7=new WeakMap,Y_=new WeakMap,Z_=new WeakMap,e7=new WeakMap,K_=new WeakMap,i1=new WeakMap,N_=new WeakMap,$Q=new WeakMap,JQ=new WeakMap,l8=new WeakMap,XY=new WeakSet,MD=function(J){if(m$(this,$Q,!0,"f"),J instanceof Error&&J.name==="AbortError")J=new D6;if(J instanceof D6)return m$(this,JQ,!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 LD($){return typeof $.parse==="function"}var c6,YY,UQ,ZY,KY,NY,zD,RD,ib=10;class F_ extends vJ{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(d8($)&&$.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",UQ).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",UQ).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",zD).call(this,J);let _=await $.chat.completions.create({...J,stream:!1},{...U,signal:this.controller.signal});return this._connected(),this._addChatCompletion(X_(_,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=ib}=U||{},Y=J.tools.map((N)=>{if(TJ(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 j=E.id,{name:B,arguments:D}=E.function,w=K[B];if(!w){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:j,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:j,content:T});continue}let A;try{A=LD(w)?await w.parse(D):D}catch(T){let z=T instanceof Error?T.message:String(T);this._addMessage({role:"tool",tool_call_id:j,content:z});continue}let I=await w.function(A,this),f=d(this,c6,"m",RD).call(this,I);if(this._addMessage({role:"tool",tool_call_id:j,content:f}),X)return}}return}}c6=new WeakSet,YY=function(){return d(this,c6,"m",UQ).call(this).content??null},UQ=function(){let J=this.messages.length;while(J-- >0){let U=this.messages[J];if(d8(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(d8(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},zD=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.")},RD=function(J){return typeof J==="string"?J:J===void 0?"undefined":JSON.stringify(J)};class W_ extends F_{static runTools($,J,U){let Q=new W_,_={...U,headers:{...U?.headers,"X-Stainless-Helper-Method":"runTools"}};return Q._run(()=>Q._runTools($,J,_)),Q}_addMessage($,J=!0){if(super._addMessage($,J),d8($)&&$.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 AD extends Error{}class wD extends Error{}function rb($,J=w6.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return nb($.trim(),J)}var nb=($,J)=>{let U=$.length,Q=0,_=(N)=>{throw new AD(`${N} at position ${Q}`)},G=(N)=>{throw new wD(`${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&&`
|
|
161
|
-
\r `.includes($[Q]))Q++};return V()},FY=($)=>rb($,w6.ALL^w6.NUM);var P6,r1,i8,j2,WY,_Q,qY,HY,BY,QQ,OY,fD;class D2 extends F_{constructor($){super();P6.add(this),r1.set(this,void 0),i8.set(this,void 0),j2.set(this,void 0),m$(this,r1,$,"f"),m$(this,i8,[],"f")}get currentChatCompletionSnapshot(){return d(this,j2,"f")}static fromReadableStream($){let J=new D2(null);return J._run(()=>J._fromReadableStream($)),J}static createChatCompletion($,J,U){let Q=new D2(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",QQ).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=E0.fromReadableStream($,this.controller),_;for await(let G of Q){if(_&&_!==G.id)this._addChatCompletion(d(this,P6,"m",QQ).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",QQ).call(this))}[(r1=new WeakMap,i8=new WeakMap,j2=new WeakMap,P6=new WeakSet,WY=function(){if(this.ended)return;m$(this,j2,void 0,"f")},_Q=function(J){let U=d(this,i8,"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,i8,"f")[J.index]=U,U},qY=function(J){if(this.ended)return;let U=d(this,P6,"m",fD).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",_Q).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 ID(X?.type)}}},HY=function(J,U){if(d(this,P6,"m",_Q).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,r1,"f")?.tools?.find((V)=>G_(V)&&V.function.name===_.function.name);this._emit("tool_calls.function.arguments.done",{name:_.function.name,index:U,arguments:_.function.arguments,parsed_arguments:TJ(G)?G.$parseRaw(_.function.arguments):G?.function.strict?JSON.parse(_.function.arguments):null})}else ID(_.type)},BY=function(J){let U=d(this,P6,"m",_Q).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})},QQ=function(){if(this.ended)throw new w$("stream has ended, this shouldn't happen");let J=d(this,j2,"f");if(!J)throw new w$("request ended without sending any chunks");return m$(this,j2,void 0,"f"),m$(this,i8,[],"f"),pb(J,d(this,r1,"f"))},OY=function(){let J=d(this,r1,"f")?.response_format;if(V_(J))return J;return null},fD=function(J){var U,Q,_,G;let V=d(this,j2,"f"),{choices:X,...Z}=J;if(!V)V=m$(this,j2,{...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:f,...T}=N;if(kD(T),Object.assign(H.logprobs,T),I)(U=H.logprobs).content??(U.content=[]),H.logprobs.content.push(...I);if(f)(Q=H.logprobs).refusal??(Q.refusal=[]),H.logprobs.refusal.push(...f)}if(K){if(H.finish_reason=K,d(this,r1,"f")&&GY(d(this,r1,"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:j,function_call:B,role:D,tool_calls:w,...A}=Y;if(kD(A),Object.assign(H.message,A),j)H.message.refusal=(H.message.refusal||"")+j;if(D)H.message.role=D;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(w){if(!H.message.tool_calls)H.message.tool_calls=[];for(let{index:I,id:f,type:T,function:z,...S}of w){let O=(G=H.message.tool_calls)[I]??(G[I]={});if(Object.assign(O,S),f)O.id=f;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,DD(d(this,r1,"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 E0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function pb($,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:j,...B}=Y,D=Y.role;if(!D)throw new w$(`missing role for choice ${F}`);if(E){let{arguments:w,name:A}=E;if(w==null)throw new w$(`missing function_call.arguments for choice ${F}`);if(!A)throw new w$(`missing function_call.name for choice ${F}`);return{...q,message:{content:H,function_call:{arguments:w,name:A},role:D,refusal:Y.refusal??null},finish_reason:K,index:F,logprobs:N}}if(j)return{...q,index:F,finish_reason:K,logprobs:N,message:{...B,role:D,content:H,refusal:Y.refusal??null,tool_calls:j.map((w,A)=>{let{function:I,type:f,id:T,...z}=w,{arguments:S,name:O,...M}=I||{};if(T==null)throw new w$(`missing choices[${F}].tool_calls[${A}].id
|
|
162
|
-
${GQ($)}`);if(f==null)throw new w$(`missing choices[${F}].tool_calls[${A}].type
|
|
163
|
-
${GQ($)}`);if(O==null)throw new w$(`missing choices[${F}].tool_calls[${A}].function.name
|
|
164
|
-
${GQ($)}`);if(S==null)throw new w$(`missing choices[${F}].tool_calls[${A}].function.arguments
|
|
165
|
-
${GQ($)}`);return{...z,id:T,type:f,function:{...M,name:O,arguments:S}}})}};return{...q,message:{...B,content:H,role:D,refusal:Y.refusal??null},finish_reason:K,index:F,logprobs:N}}),created:_,model:G,object:"chat.completion",...V?{system_fingerprint:V}:{}};return jD(Z,J)}function GQ($){return JSON.stringify($)}function kD($){return}function ID($){}class r8 extends D2{static fromReadableStream($){let J=new r8(null);return J._run(()=>J._fromReadableStream($)),J}static runTools($,J,U){let Q=new r8(J),_={...U,headers:{...U?.headers,"X-Stainless-Helper-Method":"runTools"}};return Q._run(()=>Q._runTools($,J,_)),Q}}class E2 extends X${constructor(){super(...arguments);this.messages=new c8(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 PD($.tools),this._client.chat.completions.create($,{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((U)=>X_(U,$))}runTools($,J){if($.stream)return r8.runTools(this._client,$,J);return W_.runTools(this._client,$,J)}stream($,J){return D2.createChatCompletion(this._client,$,J)}}E2.Messages=c8;class CJ extends X${constructor(){super(...arguments);this.completions=new E2(this._client)}}CJ.Completions=E2;var SD=Symbol("brand.privateNullableHeaders");function*ob($){if(!$)return;if(SD 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 ob(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{[SD]:!0,values:J,nulls:U}};class q_ extends X${create($,J){return this._client.post("/audio/speech",{body:$,...J,headers:j$([{Accept:"application/octet-stream"},J?.headers]),__binaryResponse:!0})}}class H_ extends X${create($,J){return this._client.post("/audio/transcriptions",P0({body:$,...J,stream:$.stream??!1,__metadata:{model:$.model}},this._client))}}class B_ extends X${create($,J){return this._client.post("/audio/translations",P0({body:$,...J,__metadata:{model:$.model}},this._client))}}class n1 extends X${constructor(){super(...arguments);this.transcriptions=new H_(this._client),this.translations=new B_(this._client),this.speech=new q_(this._client)}}n1.Transcriptions=H_;n1.Translations=B_;n1.Speech=q_;class n8 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 O_ 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 j_ extends X${create($,J){return this._client.post("/realtime/sessions",{body:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}}class D_ extends X${create($,J){return this._client.post("/realtime/transcription_sessions",{body:$,...J,headers:j$([{"OpenAI-Beta":"assistants=v2"},J?.headers])})}}class bJ extends X${constructor(){super(...arguments);this.sessions=new j_(this._client),this.transcriptionSessions=new D_(this._client)}}bJ.Sessions=j_;bJ.TranscriptionSessions=D_;class E_ 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 P_ 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",O2,{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`,O2,{query:J,...U,headers:j$([{"OpenAI-Beta":"chatkit_beta=v1"},U?.headers])})}}class yJ extends X${constructor(){super(...arguments);this.sessions=new E_(this._client),this.threads=new P_(this._client)}}yJ.Sessions=E_;yJ.Threads=P_;class M_ 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 L_ 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 TD=($)=>{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 P2=($)=>{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,xJ,jY,H1,VQ,a0,hJ,p8,gJ,ZQ,M0,XQ,YQ,A_,z_,R_,vD,CD,bD,yD,gD,xD,hD;class M2 extends vJ{constructor(){super(...arguments);S6.add(this),jY.set(this,[]),H1.set(this,{}),VQ.set(this,{}),a0.set(this,void 0),hJ.set(this,void 0),p8.set(this,void 0),gJ.set(this,void 0),ZQ.set(this,void 0),M0.set(this,void 0),XQ.set(this,void 0),YQ.set(this,void 0),A_.set(this,void 0)}[(jY=new WeakMap,H1=new WeakMap,VQ=new WeakMap,a0=new WeakMap,hJ=new WeakMap,p8=new WeakMap,gJ=new WeakMap,ZQ=new WeakMap,M0=new WeakMap,XQ=new WeakMap,YQ=new WeakMap,A_=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 xJ;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=E0.fromReadableStream($,this.controller);for await(let _ of Q)d(this,S6,"m",z_).call(this,_);if(Q.controller.signal?.aborted)throw new D6;return this._addRun(d(this,S6,"m",R_).call(this))}toReadableStream(){return new E0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,J,U,Q){let _=new xJ;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",z_).call(this,X);if(V.controller.signal?.aborted)throw new D6;return this._addRun(d(this,S6,"m",R_).call(this))}static createThreadAssistantStream($,J,U){let Q=new xJ;return Q._run(()=>Q._threadAssistantStream($,J,{...U,headers:{...U?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}static createAssistantStream($,J,U,Q){let _=new xJ;return _._run(()=>_._runAssistantStream($,J,U,{...Q,headers:{...Q?.headers,"X-Stainless-Helper-Method":"stream"}})),_}currentEvent(){return d(this,XQ,"f")}currentRun(){return d(this,YQ,"f")}currentMessageSnapshot(){return d(this,a0,"f")}currentRunStepSnapshot(){return d(this,A_,"f")}async finalRunSteps(){return await this.done(),Object.values(d(this,H1,"f"))}async finalMessages(){return await this.done(),Object.values(d(this,VQ,"f"))}async finalRun(){if(await this.done(),!d(this,hJ,"f"))throw Error("Final run was not received.");return d(this,hJ,"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",z_).call(this,V);if(G.controller.signal?.aborted)throw new D6;return this._addRun(d(this,S6,"m",R_).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",z_).call(this,X);if(V.controller.signal?.aborted)throw new D6;return this._addRun(d(this,S6,"m",R_).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($_(_)&&$_(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(!$_(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)}}xJ=M2,z_=function(J){if(this.ended)return;switch(m$(this,XQ,J,"f"),d(this,S6,"m",bD).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",hD).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",CD).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",vD).call(this,J);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:Zy(J)}},R_=function(){if(this.ended)throw new w$("stream has ended, this shouldn't happen");if(!d(this,hJ,"f"))throw Error("Final run has not been received");return d(this,hJ,"f")},vD=function(J){let[U,Q]=d(this,S6,"m",gD).call(this,J,d(this,a0,"f"));m$(this,a0,U,"f"),d(this,VQ,"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,p8,"f")){if(d(this,gJ,"f"))switch(d(this,gJ,"f").type){case"text":this._emit("textDone",d(this,gJ,"f").text,d(this,a0,"f"));break;case"image_file":this._emit("imageFileDone",d(this,gJ,"f").image_file,d(this,a0,"f"));break}m$(this,p8,_.index,"f")}m$(this,gJ,U.content[_.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(d(this,p8,"f")!==void 0){let _=J.data.content[d(this,p8,"f")];if(_)switch(_.type){case"image_file":this._emit("imageFileDone",_.image_file,d(this,a0,"f"));break;case"text":this._emit("textDone",_.text,d(this,a0,"f"));break}}if(d(this,a0,"f"))this._emit("messageDone",J.data);m$(this,a0,void 0,"f")}},CD=function(J){let U=d(this,S6,"m",yD).call(this,J);switch(m$(this,A_,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,ZQ,"f"))this._emit("toolCallDelta",G,U.step_details.tool_calls[G.index]);else{if(d(this,M0,"f"))this._emit("toolCallDone",d(this,M0,"f"));if(m$(this,ZQ,G.index,"f"),m$(this,M0,U.step_details.tool_calls[G.index],"f"),d(this,M0,"f"))this._emit("toolCallCreated",d(this,M0,"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,A_,void 0,"f"),J.data.step_details.type=="tool_calls"){if(d(this,M0,"f"))this._emit("toolCallDone",d(this,M0,"f")),m$(this,M0,void 0,"f")}this._emit("runStepDone",J.data,U);break;case"thread.run.step.in_progress":break}},bD=function(J){d(this,jY,"f").push(J),this._emit("event",J)},yD=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 _=xJ.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")},gD=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",xD).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")},xD=function(J,U){return xJ.accumulateDelta(U,J)},hD=function(J){switch(m$(this,YQ,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,hJ,J.data,"f"),d(this,M0,"f"))this._emit("toolCallDone",d(this,M0,"f")),m$(this,M0,void 0,"f");break;case"thread.run.cancelling":break}};function Zy($){}class a8 extends X${constructor(){super(...arguments);this.steps=new L_(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 M2.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 M2.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 M2.createToolAssistantStream($,this._client.beta.threads.runs,J,U)}}a8.Steps=L_;class uJ extends X${constructor(){super(...arguments);this.runs=new a8(this._client),this.messages=new M_(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 M2.createThreadAssistantStream($,this._client.beta.threads,J)}}uJ.Runs=a8;uJ.Messages=M_;class B1 extends X${constructor(){super(...arguments);this.realtime=new bJ(this._client),this.chatkit=new yJ(this._client),this.assistants=new O_(this._client),this.threads=new uJ(this._client)}}B1.Realtime=bJ;B1.ChatKit=yJ;B1.Assistants=O_;B1.Threads=uJ;class o8 extends X${create($,J){return this._client.post("/completions",{body:$,...J,stream:$.stream??!1})}}class w_ 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 t8 extends X${constructor(){super(...arguments);this.content=new w_(this._client)}create($,J,U){return this._client.post(U$`/containers/${$}/files`,P0({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])})}}t8.Content=w_;class mJ extends X${constructor(){super(...arguments);this.files=new t8(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])})}}mJ.Files=t8;class f_ 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`,O2,{query:J,...U})}delete($,J,U){let{conversation_id:Q}=J;return this._client.delete(U$`/conversations/${Q}/items/${$}`,U)}}class cJ extends X${constructor(){super(...arguments);this.items=new f_(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)}}cJ.Items=f_;class s8 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=TD(X)});return G})}}class k_ 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 e8 extends X${constructor(){super(...arguments);this.outputItems=new k_(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)}}e8.OutputItems=k_;class dJ extends X${constructor(){super(...arguments);this.runs=new e8(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)}}dJ.Runs=e8;class $9 extends X${create($,J){return this._client.post("/files",P0({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 IJ({message:`Giving up on waiting for file ${$} to finish processing after ${U} milliseconds.`});return G}}class I_ extends X${}class S_ 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 J9 extends X${constructor(){super(...arguments);this.graders=new S_(this._client)}}J9.Graders=S_;class T_ extends X${create($,J,U){return this._client.getAPIList(U$`/fine_tuning/checkpoints/${$}/permissions`,l1,{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 U9 extends X${constructor(){super(...arguments);this.permissions=new T_(this._client)}}U9.Permissions=T_;class v_ extends X${list($,J={},U){return this._client.getAPIList(U$`/fine_tuning/jobs/${$}/checkpoints`,H4,{query:J,...U})}}class _9 extends X${constructor(){super(...arguments);this.checkpoints=new v_(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)}}_9.Checkpoints=v_;class O1 extends X${constructor(){super(...arguments);this.methods=new I_(this._client),this.jobs=new _9(this._client),this.checkpoints=new U9(this._client),this.alpha=new J9(this._client)}}O1.Methods=I_;O1.Jobs=_9;O1.Checkpoints=U9;O1.Alpha=J9;class C_ extends X${}class lJ extends X${constructor(){super(...arguments);this.graderModels=new C_(this._client)}}lJ.GraderModels=C_;class Q9 extends X${createVariation($,J){return this._client.post("/images/variations",P0({body:$,...J},this._client))}edit($,J){return this._client.post("/images/edits",P0({body:$,...J,stream:$.stream??!1},this._client))}generate($,J){return this._client.post("/images/generations",{body:$,...J,stream:$.stream??!1})}}class G9 extends X${retrieve($,J){return this._client.get(U$`/models/${$}`,J)}list($){return this._client.getAPIList("/models",l1,$)}delete($,J){return this._client.delete(U$`/models/${$}`,J)}}class V9 extends X${create($,J){return this._client.post("/moderations",{body:$,...J})}}class b_ 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 y_ extends X${create($,J){return this._client.post("/realtime/client_secrets",{body:$,...J})}}class L2 extends X${constructor(){super(...arguments);this.clientSecrets=new y_(this._client),this.calls=new b_(this._client)}}L2.ClientSecrets=y_;L2.Calls=b_;function uD($,J){if(!J||!fy(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:Sy(J,_)};if(_.type==="message"){let G=_.content.map((V)=>{if(V.type==="output_text")return{...V,parsed:wy(J,V.text)};return V});return{..._,content:G}}return _}),Q=Object.assign({},$,{output:U});if(!Object.getOwnPropertyDescriptor($,"output_text"))KQ(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 wy($,J){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(J);return JSON.parse(J)}function fy($){if(V_($.text?.format))return!0;return!1}function ky($){return $?.$brand==="auto-parseable-tool"}function Iy($,J){return $.find((U)=>U.type==="function"&&U.name===J)}function Sy($,J){let U=Iy($.tools??[],J.name);return{...J,...J,parsed_arguments:ky(U)?U.$parseRaw(J.arguments):U?.strict?JSON.parse(J.arguments):null}}function KQ($){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 X9,NQ,z2,FQ,mD,cD,dD,lD;class WQ extends vJ{constructor($){super();X9.add(this),NQ.set(this,void 0),z2.set(this,void 0),FQ.set(this,void 0),m$(this,NQ,$,"f")}static createResponse($,J,U){let Q=new WQ(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,X9,"m",mD).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,X9,"m",cD).call(this,V,G);if(_.controller.signal?.aborted)throw new D6;return d(this,X9,"m",dD).call(this)}[(NQ=new WeakMap,z2=new WeakMap,FQ=new WeakMap,X9=new WeakSet,mD=function(){if(this.ended)return;m$(this,z2,void 0,"f")},cD=function(J,U){if(this.ended)return;let Q=(G,V)=>{if(U==null||V.sequence_number>U)this._emit(G,V)},_=d(this,X9,"m",lD).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}},dD=function(){if(this.ended)throw new w$("stream has ended, this shouldn't happen");let J=d(this,z2,"f");if(!J)throw new w$("request ended without sending any events");m$(this,z2,void 0,"f");let U=Ty(J,d(this,NQ,"f"));return m$(this,FQ,U,"f"),U},lD=function(J){let U=d(this,z2,"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,z2,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,z2,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,FQ,"f");if(!$)throw new w$("stream ended without producing a ChatCompletion");return $}}function Ty($,J){return uD($,J)}class g_ extends X${list($,J={},U){return this._client.getAPIList(U$`/responses/${$}/input_items`,H4,{query:J,...U})}}class x_ extends X${count($={},J){return this._client.post("/responses/input_tokens",{body:$,...J})}}class R2 extends X${constructor(){super(...arguments);this.inputItems=new g_(this._client),this.inputTokens=new x_(this._client)}create($,J){return this._client.post("/responses",{body:$,...J,stream:$.stream??!1})._thenUnwrap((U)=>{if("object"in U&&U.object==="response")KQ(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")KQ(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 WQ.createResponse(this._client,$,J)}cancel($,J){return this._client.post(U$`/responses/${$}/cancel`,J)}compact($,J){return this._client.post("/responses/compact",{body:$,...J})}}R2.InputItems=g_;R2.InputTokens=x_;class h_ extends X${create($,J,U){return this._client.post(U$`/uploads/${$}/parts`,P0({body:J,...U},this._client))}}class iJ extends X${constructor(){super(...arguments);this.parts=new h_(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})}}iJ.Parts=h_;var iD=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 u_ 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 iD(K),await this.createAndPoll($,{file_ids:Z})}}class m_ 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`,l1,{...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}}class A2 extends X${constructor(){super(...arguments);this.files=new m_(this._client),this.fileBatches=new u_(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`,l1,{body:J,method:"post",...U,headers:j$([{"OpenAI-Beta":"assistants=v2"},U?.headers])})}}A2.Files=m_;A2.FileBatches=u_;class Y9 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",O2,{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 Z9,rD,qQ;class K9 extends X${constructor(){super(...arguments);Z9.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,Z9,"m",rD).call(this,U);let _=j$([J]).values,G=d(this,Z9,"m",qQ).call(this,_,"webhook-signature"),V=d(this,Z9,"m",qQ).call(this,_,"webhook-timestamp"),X=d(this,Z9,"m",qQ).call(this,_,"webhook-id"),Z=parseInt(V,10);if(isNaN(Z))throw new c1("Invalid webhook timestamp format");let Y=Math.floor(Date.now()/1000);if(Y-Z>Q)throw new c1("Webhook timestamp is too old");if(Z>Y+Q)throw new c1("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 c1("The given webhook signature does not match the expected signature")}}Z9=new WeakSet,rD=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")},qQ=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,HQ,nD;class s${constructor({baseURL:$=P2("OPENAI_BASE_URL"),apiKey:J=P2("OPENAI_API_KEY"),organization:U=P2("OPENAI_ORG_ID")??null,project:Q=P2("OPENAI_PROJECT_ID")??null,webhookSecret:_=P2("OPENAI_WEBHOOK_SECRET")??null,...G}={}){if(EY.add(this),HQ.set(this,void 0),this.completions=new o8(this),this.chat=new CJ(this),this.embeddings=new s8(this),this.files=new $9(this),this.images=new Q9(this),this.audio=new n1(this),this.moderations=new V9(this),this.models=new G9(this),this.fineTuning=new O1(this),this.graders=new lJ(this),this.vectorStores=new A2(this),this.webhooks=new K9(this),this.beta=new B1(this),this.batches=new n8(this),this.uploads=new iJ(this),this.responses=new R2(this),this.realtime=new L2(this),this.conversations=new cJ(this),this.evals=new dJ(this),this.containers=new mJ(this),this.videos=new Y9(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&&aj())throw new w$(`It looks like you're running in a browser-like environment.
|
|
166
|
-
|
|
167
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
168
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
169
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
170
|
-
|
|
171
|
-
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
172
|
-
|
|
173
|
-
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
174
|
-
`);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(P2("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??X,this.fetchOptions=V.fetchOptions,this.maxRetries=V.maxRetries??2,this.fetch=V.fetch??tj(),m$(this,HQ,ej,"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 ${B2}`}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",nD).call(this)&&U||this.baseURL,_=mj($)?new URL($):new URL(Q+(Q.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),G=this.defaultQuery();if(!cj(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 SJ(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`,d1({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 j=`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"} - ${j}`),G6(this).debug(`[${Z}] connection ${B?"timed out":"failed"} (${j})`,d1({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)`,d1({retryOfRequestLogID:U,url:V,durationMs:q-K,message:N.message})),B)throw new IJ;throw new kJ({cause:N})}let H=[...N.headers.entries()].filter(([j])=>j==="x-request-id").map(([j,B])=>", "+j+": "+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 j=await this.shouldRetry(N);if(J&&j){let f=`retrying, ${J} attempts remaining`;return await sj(N.body),G6(this).info(`${E} - ${f}`),G6(this).debug(`[${Z}] response error (${f})`,d1({retryOfRequestLogID:U,url:N.url,status:N.status,headers:N.headers,durationMs:q-K})),this.retryRequest(Q,J,U??Z,N.headers)}let B=j?"error; no more retries left":"error; not retryable";G6(this).info(`${E} - ${B}`);let D=await N.text().catch((f)=>dU(f).message),w=ij(D),A=w?void 0:D;throw G6(this).debug(`[${Z}] response error (${B})`,d1({retryOfRequestLogID:U,url:N.url,status:N.status,headers:N.headers,message:A,durationMs:Date.now()-K})),this.makeStatusError(N.status,w,A,N.headers)}return G6(this).info(E),G6(this).debug(`[${Z}] response start`,d1({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 p7(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)lj("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))}:{},...oj(),"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:h7($)};else return d(this,HQ,"f").call(this,{body:$,headers:U})}}PY=s$,HQ=new WeakMap,EY=new WeakSet,nD=function(){return this.baseURL!=="https://api.openai.com/v1"};s$.OpenAI=PY;s$.DEFAULT_TIMEOUT=600000;s$.OpenAIError=w$;s$.APIError=q6;s$.APIConnectionError=kJ;s$.APIConnectionTimeoutError=IJ;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=c1;s$.toFile=o7;s$.Completions=o8;s$.Chat=CJ;s$.Embeddings=s8;s$.Files=$9;s$.Images=Q9;s$.Audio=n1;s$.Moderations=V9;s$.Models=G9;s$.FineTuning=O1;s$.Graders=lJ;s$.VectorStores=A2;s$.Webhooks=K9;s$.Beta=B1;s$.Batches=n8;s$.Uploads=iJ;s$.Responses=R2;s$.Realtime=L2;s$.Conversations=cJ;s$.Evals=dJ;s$.Containers=mJ;s$.Videos=Y9;function hy($){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 uy($){return{...$,content:hy($.content)}}function my($,J){if(typeof J==="string"&&/deepseek/i.test(J))return!0;return/^deepseek-/i.test($)}function N9($={}){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?wJ.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:my(N,J),E=Y.stream!==!1,j=[];if(Y.messages&&Array.isArray(Y.messages)){let w=-1;for(let A=Y.messages.length-1;A>=0;A--)if(Y.messages[A].role==="user"){w=A;break}for(let A=0;A<Y.messages.length;A++){let I=Y.messages[A],f=uy(I),T=A<w;if(f&&typeof f==="object"&&f.role==="assistant"){if(T){if("reasoning_content"in f)delete f.reasoning_content}else if(!H){if("reasoning_content"in f)delete f.reasoning_content}else if(Array.isArray(f?.tool_calls)&&f.tool_calls.length>0){let z=f.reasoning_content;if(typeof z!=="string"||z.length===0)f.reasoning_content="."}}j.push(f)}}else{if(typeof Y.instructions==="string"&&Y.instructions.length>0)j.push({role:"system",content:Y.instructions});j.push({role:"user",content:Y.input})}let B=(()=>{let w=Y.reasoning?.effort;if(typeof w!=="string")return;if(w==="none"||w==="minimal"||w==="low"||w==="medium"||w==="high"||w==="xhigh")return w;return})(),D={model:N,messages:j,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)D.tools=Y.tools;try{let w=G(Y);if(yield{type:"response_start",requestId:K,model:w},!E){let O=await F.chat.completions.create({...D,stream:!1},{signal:Y.signal,timeout:Y.timeoutMs}),M=Array.isArray(O?.choices)?O.choices[0]:void 0,P=M?.message,R=typeof P?.reasoning_content==="string"?P.reasoning_content:"";if(R.length>0)yield{type:"delta",requestId:K,chunk:{kind:"thinking_start"}},yield{type:"delta",requestId:K,chunk:{kind:"thinking_delta",text:R}},yield{type:"delta",requestId:K,chunk:{kind:"thinking_end",text:R}};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=pD(M?.finish_reason);yield{type:"response_end",requestId:K,stopReason:v,usage:O?.usage};return}let A=await F.chat.completions.create({...D,stream:!0},{signal:Y.signal,timeout:Y.timeoutMs}),I=null,f,T=new Map,z=!1,S="";for await(let O of A){if(O?.usage!=null)f=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 R=P?.delta,k=R?.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=R?.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(R?.tool_calls)?R.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:pD(I),usage:f}}catch(w){if(w?.name==="AbortError")throw new r4("Aborted",{code:"aborted",retryable:!1});throw V(w)}}return{provider:"openai",defaultModelId:$.defaultModelId,stream:X}}function pD($){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 BQ{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 BQ;constructor($,J){this.tools=$;this.options=J}async*executeTasksInParallel($,J,U){this.eventQueue=new BQ;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 rJ{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,_){m1(U,`Tool execution: ${$.toolCall.function.name}`);let G=Q?new rJ(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((D)=>{if(!D||typeof D!=="object"||D.role!=="assistant")return!1;let w=D.tool_calls;return Array.isArray(w)&&w.some((A)=>A?.id===B)})},K=(B)=>{if(!Y(B))this.options.addAssistantMessageWithToolCalls($)},F=(B)=>{return $.messages.some((D)=>D&&typeof D==="object"&&D.role==="tool"&&D.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(D){let w=D instanceof Error?D.message:String(D);return{_raw:B.function.arguments,_parseError:w}}},H=(B)=>{let D=[];for(let w=B;w<$.pendingToolCalls.length;w++){let A=$.pendingToolCalls[w];if(F(A.toolCall.id))continue;if(N.has(A.toolCall.id))continue;if(X[A.toolCall.id])continue;let I=this.options.tools?.get(A.toolCall.function.name),f=I?.riskLevel??"safe";if(I&&this.options.isToolDisabled(A.toolCall.function.name))continue;if(I&&this.options.isToolBlocked($,A.toolCall.function.name))continue;if(!I||!Z(f))continue;N.add(A.toolCall.id),D.push({type:"tool_approval_requested",tool_call_id:A.toolCall.id,toolName:A.toolCall.function.name,riskLevel:f,args:q(A.toolCall),sessionId:$.sessionId})}return D};if($.metadata?.parallelMode===!0){let B=$.pendingToolCalls.filter((D)=>{let w=D.toolCall.function.name;return w==="Task"||w.endsWith("_Task")});if(B.length>1)yield*this.options.parallelTaskExecutor.executeTasksInParallel(B,$,J),$.pendingToolCalls=$.pendingToolCalls.filter((D)=>!B.includes(D))}let j=this.options.checkpointManager.hasStore();for(let B=0;B<$.pendingToolCalls.length;B++){let D=$.pendingToolCalls[B];if(F(D.toolCall.id)){$.pendingToolCalls.splice(B,1),B--;continue}let w=D.toolCall.function.name,A;if(U?.hooks?.preToolUse){let O=new rJ(U.hooks),M=(P)=>({sessionId:$.sessionId,toolCall:P,toolContext:J});if(A=await O.executePreToolUse(M(D.toolCall)),!A.allow){this._log(`Tool BLOCKED by preToolUse hook: ${w}`),D.result="Tool execution blocked by PreToolUse hook",D.isError=!0,K(D.toolCall.id),yield{type:"tool_result",tool_call_id:D.toolCall.id,result:D.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,D),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:`Tool blocked by preToolUse hook: ${w}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}}if(A?.modifiedToolCall)D.toolCall={...A.modifiedToolCall,id:D.toolCall.id,type:D.toolCall.type};let I=D.toolCall.function.name,f=this.options.tools?.get(I),T=f?.riskLevel??"safe";if(f&&this.options.isToolBlocked($,I)){let O=`Tool "${I}" is blocked by middleware`;this._log(`Tool BLOCKED: ${I} - ${O}`),D.result=`Tool execution skipped: ${O}`,D.isError=!0,K(D.toolCall.id),yield{type:"tool_skipped",tool_call_id:D.toolCall.id,toolName:I,reason:O,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:D.toolCall.id,result:D.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,D),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:`Tool blocked: ${I}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}if(f&&this.options.isToolDisabled(I)){let O=`Tool "${I}" is disabled for this session`;this._log(`Tool DISABLED: ${I}`),D.result=`Tool execution skipped: ${O}`,D.isError=!0,K(D.toolCall.id),yield{type:"tool_skipped",tool_call_id:D.toolCall.id,toolName:I,reason:O,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:D.toolCall.id,result:D.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,D),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:`Tool disabled: ${I}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}if(f&&Z(T)){let O=X[D.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:j?void 0:M,checkpointRef:j?{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 AJ}if(!O.approved){let M=O.reason??"User denied approval";this._log(`Tool approval REJECTED: ${I} - ${M}`),D.result=`Tool execution skipped: ${M}`,D.isError=!0,K(D.toolCall.id),yield{type:"tool_skipped",tool_call_id:D.toolCall.id,toolName:D.toolCall.function.name,reason:M,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:D.toolCall.id,result:D.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,D),$.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(D.toolCall.id),this._log(`Executing tool: ${I}`),this.toolEventQueue=[];let z=await this.executeToolCall(D,J,_,U?.hooks,A);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(f&&f.name==="AskUserQuestion"&&S){let O=G?.askUser?.rejected?.[D.toolCall.id];if(O!==void 0){let P=O||"User cancelled the question";this._log(`AskUser CANCELLED: ${P}`),D.result=`User cancelled the question: ${P}`,D.isError=!0,K(D.toolCall.id),yield{type:"tool_skipped",tool_call_id:D.toolCall.id,toolName:f.name,reason:P,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:D.toolCall.id,result:D.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,D),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:`AskUser cancelled: ${f.name}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}let M=G?.askUser?.answers?.[D.toolCall.id];if(!M){let R=(typeof D.toolCall.function.arguments==="string"?JSON.parse(D.toolCall.function.arguments):D.toolCall.function.arguments)?.questions||[];this._log(`AskUser waiting for answers (${R.length} questions)`),yield z,$.stopReason="approval_required";let k=await this.options.saveCheckpoint($,{phase:"approval_pending",status:`Waiting for user answers: ${f.name}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});throw await this.options.persistSessionState($),yield{type:"requires_action",kind:"ask_user",toolCallId:D.toolCall.id,questions:R,checkpoint:j?void 0:k,checkpointRef:j?{sessionId:k.sessionId}:void 0,sessionId:$.sessionId},yield{type:"done",finalResponse:$.currentResponse,stopReason:"approval_required",modelStopReason:$.lastModelStopReason,usage:{...$.usage},sessionId:$.sessionId},new AJ}else{let R={...typeof D.toolCall.function.arguments==="string"?JSON.parse(D.toolCall.function.arguments):D.toolCall.function.arguments,answers:M};D.toolCall.function.arguments=JSON.stringify(R),this.toolEventQueue=[];let k=await this.executeToolCall(D,J,_,U?.hooks,A);for(let L of this.toolEventQueue)yield L;this.toolEventQueue=[],yield k,this.options.addToolResultToHistory($,D),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:D.isError?`AskUser error: ${f.name}`:`AskUser completed: ${f.name}`,modelConfig:U?.checkpointModelConfig,requestParams:U?.requestParams});continue}}yield z,this.options.addToolResultToHistory($,D),$.pendingToolCalls.splice(B,1),B--,await this.options.saveCheckpoint($,{phase:"tool_execution",status:D.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 OQ{static APPROVAL_REQUIRED_LEVELS=new Set(["high","critical"]);requiresApproval($){return OQ.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 dy=1000;function ly($){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 oD($){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 aD($){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=oD(X);if(Z!==X)G=!0;return Z});if(!G)return Q;return J=!0,{...Q,tool_calls:V}});return J?U:$}class L0 extends cy{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 OQ,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 H2){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=x7({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 AJ)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=(D)=>{let w=X.get(D);if(w)return w;let A={argsText:"",started:!1};return X.set(D,A),A},F=(D,w)=>{let A=K(D);if(w&&!A.toolName)A.toolName=w;if(!A.started)A.started=!0,this._log(`Stream: tool_call_start - ${A.toolName} (${D.slice(0,8)})`),G.push({type:"tool_call_start",callId:D,toolName:A.toolName,sessionId:V})},N=(D,w,A)=>{let I=K(D);if(w&&!I.toolName)I.toolName=w;if(typeof A==="string"&&A.length>0)I.argsText+=A;F(D,I.toolName),G.push({type:"tool_call_delta",callId:D,toolName:I.toolName,argsTextDelta:A,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 D=$.currentResponse.slice(0,50)+($.currentResponse.length>50?"...":"");this._log(`Stream: text_end - "${D}"`),G.push({type:"text_end",content:$.currentResponse,sessionId:V})},E=()=>{for(let[D,w]of X){if(!w.toolName)continue;let A={id:D,type:"function",function:{name:w.toolName,arguments:w.argsText}};if(this._tools){$.pendingToolCalls.push({toolCall:A});let I=w.argsText.slice(0,100)+(w.argsText.length>100?"...":"");this._log(`Stream: tool_call_end - ${w.toolName} with args: ${I}`)}G.push({type:"tool_call_end",toolCall:A,sessionId:V})}X.clear()},j=(()=>{if(!_)return;let D={..._};if(typeof D.maxOutputTokens!=="number"&&typeof _.maxTokens==="number")D.maxOutputTokens=_.maxTokens;return delete D.maxTokens,D})(),B=Q?{model:Q,messages:aD($.messages),tools:U,signal:J,...j??{}}:{messages:aD($.messages),tools:U,signal:J,...j??{}};try{for await(let D of this._modelClient.stream(B))if(m1(J,"Session streaming"),D.type==="delta"){if(D.chunk.kind==="text")q(),$.currentResponse+=D.chunk.text,G.push({type:"text_delta",delta:D.chunk.text,sessionId:V});else if(D.chunk.kind==="thinking_start")this._log("Stream: thinking_start"),G.push({type:"thinking_start",sessionId:V});else if(D.chunk.kind==="thinking_delta")$.currentThinking=($.currentThinking??"")+D.chunk.text,G.push({type:"thinking_delta",delta:D.chunk.text,sessionId:V});else if(D.chunk.kind==="thinking_end"){let w=typeof D.chunk.text==="string"?D.chunk.text:"";if(w&&typeof $.currentThinking!=="string")$.currentThinking=w;let A=typeof $.currentThinking==="string"?$.currentThinking:w,I=A?A.slice(0,50)+(A.length>50?"...":""):"";this._log(`Stream: thinking_end - "${I}"`),G.push({type:"thinking_end",sessionId:V,...A?{content:A}:{}})}else if(D.chunk.kind==="tool_call_delta")N(D.chunk.callId,D.chunk.toolId,D.chunk.argsTextDelta)}else if(D.type==="response_end"){this._log(`Stream: response_end - stopReason: ${D.stopReason}`),H(),E(),$.lastModelStopReason=D.stopReason;let w=D.usage;if(w&&typeof w==="object"){let A=w;if(A.prompt_tokens||A.completion_tokens||A.total_tokens){let I={promptTokens:A.prompt_tokens??0,completionTokens:A.completion_tokens??0,totalTokens:A.total_tokens??0};$.usage.promptTokens=I.promptTokens,$.usage.completionTokens=I.completionTokens,$.usage.totalTokens+=I.totalTokens,this._recordUsage(I)}}}else if(D.type==="error"){if(D.terminal!==!1){let w=D.error?.code??"model_error",A=D.error?.message??"Model error",I=new r4(A,{code:w,retryable:D.error?.retryable});$.error=I,$.shouldContinue=!1,$.stopReason="error"}}}catch(D){if(D instanceof H2)throw D;if(J?.aborted)throw new H2(typeof J?.reason==="string"?J.reason:"Agent execution aborted");$.error=D instanceof Error?D:Error(String(D)),$.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=y7($,{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)=>oD(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??dy,Q=J.signal,_=g7(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(m1(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)=>{m1(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(m1(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:ly($.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 c_{}import{randomUUID as iy}from"node:crypto";class jQ extends c_{_stateStore;constructor($){super();this._stateStore=$}async create($){let J=$??iy(),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 L0(this._stateStore,J,_);return await G.save(),G}async get($){let J=await this._stateStore.load($,I6.SESSION);if(!J)return;return new L0(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 L0(this._stateStore,U,Q);J.push(_)}}return J}async destroy($){await this._stateStore.deleteSession($)}}import{existsSync as w2,mkdirSync as tD,readdirSync as RY,readFileSync as ry,rmSync as AY,writeFileSync as ny}from"node:fs";import pJ from"node:path";class nJ{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 f2 extends nJ{baseDir;constructor($){super($);this.baseDir=pJ.resolve($.dir),this.ensureDir(this.baseDir)}async _write($,J){let U=this.toFilePath($);this.ensureDir(pJ.dirname(U)),ny(U,J,"utf-8")}async _read($){let J=this.toFilePath($);try{if(!w2(J))return;return ry(J,"utf-8")}catch{return}}async _delete($){let J=this.toFilePath($);if(w2(J))AY(J);let U=pJ.dirname(J);if(w2(U))try{if(RY(U).length===0)AY(U,{recursive:!0})}catch{}}async _exists($){let J=this.toFilePath($);return w2(J)}async _list($){let J=[];if(!w2(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 _=pJ.join(this.baseDir,Q),G=this.listJsonFiles(_);for(let V of G){let X=pJ.basename(V,".json"),Z=`${Q}/${X}`;if(!$||Z.startsWith($))J.push(Z)}}return J}toFilePath($){return pJ.join(this.baseDir,`${$}.json`)}ensureDir($){if(!w2($))tD($,{recursive:!0})}listJsonFiles($){if(!w2($))return[];return RY($).filter((J)=>J.endsWith(".json")).map((J)=>pJ.join($,J))}getBaseDir(){return this.baseDir}clear(){if(w2(this.baseDir))AY(this.baseDir,{recursive:!0}),tD(this.baseDir,{recursive:!0})}}class k2 extends nJ{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 k2,this._enableLogging=$.enableLogging??!1,this._sessionManager=new jQ(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 L0(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 L0(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 ty}from"node:fs/promises";import sy from"node:path";import ey from"node:process";var $g=["AGENTS.md","CLAUDE.md"],Jg="[Project Agent Rules]";async function Ug($,J){let U=[];for(let Q of J)try{let _=sy.resolve($,Q),G=await ty(_,"utf-8");if(G.trim())U.push(G.trim())}catch{continue}return U.length>0?U.join(`
|
|
175
|
-
|
|
176
|
-
---
|
|
177
|
-
|
|
178
|
-
`):""}function DQ($){let{cwd:J,ruleFiles:U=$g,marker:Q=Jg}=$??{},_=async(G,V)=>{let X=typeof J==="function"?J():J??ey.cwd(),Z=await Ug(X,U),Y=G.messages;if(Z)Y=u1(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 _g,writeFileSync as Qg}from"node:fs";import{tmpdir as Gg}from"node:os";import{join as Vg}from"node:path";function wY($){try{return H6("git rev-parse --git-dir",{cwd:$,stdio:"pipe"}),!0}catch{return!1}}function sD($){try{return H6("git add --all",{cwd:$,encoding:"utf-8"}),H6("git diff --staged --name-only",{cwd:$,encoding:"utf-8"}).trim().split(`
|
|
179
|
-
`).filter(Boolean)}catch(J){throw Error(`Failed to stage files: ${J instanceof Error?J.message:String(J)}`)}}function eD($){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 $E($){try{let J=H6("git diff --staged --name-status",{cwd:$,encoding:"utf-8"});if(!J.trim())return[];return J.trim().split(`
|
|
180
|
-
`).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 JE($,J){try{let U=Vg(Gg(),`goatchain-commit-${Date.now()}.txt`);Qg(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{_g(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 Xg($,J="origin"){try{return H6("git remote",{cwd:$,encoding:"utf-8"}).split(`
|
|
181
|
-
`).map((Q)=>Q.trim()).includes(J)}catch{return!1}}function Yg($){try{return H6("git rev-parse --abbrev-ref --symbolic-full-name @{u}",{cwd:$,encoding:"utf-8"}).trim()||null}catch{return null}}function UE($,J="origin"){try{return H6(`git fetch ${J}`,{cwd:$,stdio:"pipe"}),!0}catch{return!1}}function Zg($){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 Kg($){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 Ng($){try{let J=H6("git status --porcelain",{cwd:$,encoding:"utf-8"}),U=[],Q=J.split(`
|
|
182
|
-
`);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 Fg($){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=Fg($);if(J.inMergeState=U.inMerge,J.mergeStateType=U.type,J.inMergeState)J.warnings.push(`Currently in ${J.mergeStateType} state`);if(J.hasConflicts=Kg($),J.hasConflicts)J.conflictFiles=Ng($),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=Xg($),J.hasRemote){let Q=Yg($);if(J.hasUpstream=!!Q,J.hasUpstream){let _=Zg($);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 Wg="You are a commit message generator. You print plain text without code blocks and don't talk.";function qg($,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}.
|
|
183
|
-
|
|
184
|
-
Staged Diffs:
|
|
185
|
-
\`\`\`diff
|
|
186
|
-
${$}
|
|
187
|
-
\`\`\`
|
|
188
|
-
|
|
189
|
-
Requirements:
|
|
190
|
-
- Title: Under 50 characters with appropriate type (feat/fix/docs/style/refactor/test/chore)
|
|
191
|
-
- Body: List changes in categories (Added/Changed/Fixed/Removed/etc.) with lines under 70 chars
|
|
192
|
-
- Format exactly as:
|
|
193
|
-
|
|
194
|
-
<type>[optional scope]: <title>
|
|
195
|
-
|
|
196
|
-
Added (if applicable):
|
|
197
|
-
- [New features/modules]
|
|
198
|
-
|
|
199
|
-
Changed (if applicable):
|
|
200
|
-
- [Modifications to existing functionality]
|
|
201
|
-
|
|
202
|
-
Fixed (if applicable):
|
|
203
|
-
- [Bug fixes]
|
|
204
|
-
|
|
205
|
-
Security (if applicable):
|
|
206
|
-
- [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(`
|
|
207
|
-
`)}function _E($){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 Hg($){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(` ${_E(_)}:`);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(` ${_E(_)}:`);for(let V of G)J.push(` • ${V.file}`);J.push("")}return J.push(` 共 ${$.length} 个文件 (Total: ${$.length} files)`),J.join(`
|
|
208
|
-
`)}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 仓库。
|
|
209
|
-
|
|
210
|
-
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(UE(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:`✗ 存在未解决的冲突,无法提交。
|
|
211
|
-
|
|
212
|
-
❌ Cannot commit: Unresolved conflicts detected.
|
|
213
|
-
|
|
214
|
-
${TY(N)}
|
|
215
|
-
|
|
216
|
-
请先解决以上冲突文件,然后再次尝试提交。
|
|
217
|
-
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},但没有暂存的更改。
|
|
218
|
-
|
|
219
|
-
❌ Currently in ${N.mergeStateType} state but no staged changes.
|
|
220
|
-
|
|
221
|
-
${TY(N)}
|
|
222
|
-
|
|
223
|
-
请先完成或取消当前的 ${N.mergeStateType} 操作。
|
|
224
|
-
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} 个提交。
|
|
225
|
-
|
|
226
|
-
⚠️ Local branch is ${N.behind} commit(s) behind remote.
|
|
227
|
-
|
|
228
|
-
${TY(N)}
|
|
229
|
-
|
|
230
|
-
建议先执行 git pull 拉取最新更改,解决可能的冲突后再提交。
|
|
231
|
-
Recommend running 'git pull' first to get latest changes and resolve any conflicts before committing.
|
|
232
|
-
|
|
233
|
-
如需强制提交,请使用 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))sD(X);else if(!fY(X)&&!N.inMergeState){let O={role:"assistant",content:`✗ 没有需要提交的更改。
|
|
234
|
-
|
|
235
|
-
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=$E(X),E=eD(X);if(!E||E.trim().length===0){let O={role:"assistant",content:`✗ 没有暂存的更改。
|
|
236
|
-
|
|
237
|
-
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 j=qg(E,Q,Z),B=[{role:"system",content:Wg},{role:"user",content:j}],w=(await U.run({messages:B})).text.trim();if(!w)throw Error("LLM returned empty commit message");let A=JE(w,X),I=Hg(H),f=q.fetched?`
|
|
238
|
-
|
|
239
|
-
\uD83D\uDCE1 ${q.message}`:"",T=N.warnings.length>0?`
|
|
240
|
-
|
|
241
|
-
⚠️ 注意事项:
|
|
242
|
-
${N.warnings.map((O)=>` • ${O}`).join(`
|
|
243
|
-
`)}`:"",z=N.currentBranch?`
|
|
244
|
-
分支: ${N.currentBranch}`:"",S={role:"assistant",content:`✓ 成功创建 commit
|
|
245
|
-
|
|
246
|
-
Commit Hash: ${A}${z}${f}${T}
|
|
247
|
-
|
|
248
|
-
${I}
|
|
249
|
-
|
|
250
|
-
Commit Message:
|
|
251
|
-
${w}`};return{...K,messages:[...K.messages,S],currentResponse:S.content,shouldContinue:!1,stopReason:"final_response",metadata:{...K.metadata,commitProcessed:!0,commitHash:A,commitMessage:w,preCommitCheck:N}}}catch(N){let q={role:"assistant",content:`✗ 创建 commit 失败
|
|
252
|
-
|
|
253
|
-
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 QE,readFile as Bg}from"node:fs/promises";import p1 from"node:path";import GE from"node:process";var Og="[Environment Information]";async function jg($){try{let J=p1.join($,".gitignore"),U=await Bg(J,"utf-8"),Q=new Set;for(let _ of U.split(`
|
|
254
|
-
`)){let G=_.trim();if(G&&!G.startsWith("#"))Q.add(G)}return Q}catch{return new Set}}function VE($,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 XE($){return p1.extname($)||$}async function YE($,J,U,Q,_){try{let G=await QE($,{withFileTypes:!0}),V=p1.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=p1.join($,N.name),H=p1.relative(Q.cwd,q);if(Q.respectGitignore&&VE(H,N.name,_))continue;if(N.isDirectory())if(U<Q.maxDepth){let E=await YE(q,J,U+1,Q,_);if(E){X.push(E),Y+=E.totalFiles;for(let[j,B]of Object.entries(E.fileStats))Z[j]=(Z[j]||0)+B}}else{let E=await ZE(q,_,Q);X.push({name:N.name,path:H,children:[],fileStats:E.stats,totalFiles:E.total}),Y+=E.total;for(let[j,B]of Object.entries(E.stats))Z[j]=(Z[j]||0)+B}else{X.push({name:N.name,path:H});let E=XE(N.name);Z[E]=(Z[E]||0)+1,Y+=1}F++}return{name:p1.basename($),path:V||".",children:X,fileStats:Z,totalFiles:Y}}catch{return null}}async function ZE($,J,U){let Q={},_=0;try{let G=await QE($,{withFileTypes:!0});for(let V of G){let X=p1.join($,V.name),Z=p1.relative(U.cwd,X);if(U.respectGitignore&&VE(Z,V.name,J))continue;if(V.isDirectory()){let Y=await ZE(X,J,U);_+=Y.total;for(let[K,F]of Object.entries(Y.stats))Q[K]=(Q[K]||0)+F}else{let Y=XE(V.name);Q[Y]=(Q[Y]||0)+1,_+=1}}}catch{}return{total:_,stats:Q}}function Dg($,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 KE($,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=Dg(V.fileStats,V.totalFiles);if(X)Q.push(`${J} ${X}`)}else if(V.children.length>0){let X=KE(V,`${J} `,!1);Q.push(X)}}else{let V=G;Q.push(`${J}${V.name}`)}}return Q.join(`
|
|
255
|
-
`)}async function Eg($){try{let J=$.respectGitignore?await jg($.cwd):new Set,U=await YE($.cwd,$.cwd,0,$,J);if(!U)return"Unable to read directory structure";return KE(U)}catch(J){return`Error generating file tree: ${J instanceof Error?J.message:String(J)}`}}function Pg($){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 Mg($,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: ${GE.platform}`),_.push(`Today's date: ${Pg(new Date)}`),Q.push(`<env>
|
|
256
|
-
${_.join(`
|
|
257
|
-
`)}
|
|
258
|
-
</env>`),J&&G&&U){let V=await Eg(U);Q.push(`<files>
|
|
259
|
-
${V}
|
|
260
|
-
</files>`)}return Q.join(`
|
|
261
|
-
|
|
262
|
-
`)}function EQ($){let{cwd:J,marker:U=Og,includeFileTree:Q=!0,maxDepth:_=3,maxEntriesPerDir:G=50,respectGitignore:V=!0}=$??{},X=async(Z,Y)=>{let K=typeof J==="function"?J():J??GE.cwd(),N=await Mg(K,Q,{cwd:K,maxDepth:_,maxEntriesPerDir:G,respectGitignore:V}),q=Z.messages;if(N)q=u1(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 I2 extends P4{name="AskUserQuestion";riskLevel="safe";description=`Use this tool when you need to ask the user questions during execution. This allows you to:
|
|
263
|
-
1. Gather user preferences or requirements
|
|
264
|
-
2. Clarify ambiguous instructions
|
|
265
|
-
3. Get decisions on implementation choices as you work
|
|
266
|
-
4. Offer choices to the user about what direction to take
|
|
267
|
-
|
|
268
|
-
Usage notes:
|
|
269
|
-
- Users will always be able to select "Other" to provide custom text input
|
|
270
|
-
- Use multiSelect: true to allow multiple answers to be selected for a question
|
|
271
|
-
- 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:
|
|
272
|
-
|
|
273
|
-
${U.join(`
|
|
274
|
-
`)}`}formatAnswerText($){if(Array.isArray($)){if($.length===0)return{inline:"(no response)"};if($.length===1){let U=String($[0]);if(U.includes(`
|
|
275
|
-
`))return{lines:U.split(`
|
|
276
|
-
`)};return{inline:U}}return{lines:this.formatArrayAnswer($.map((U)=>String(U)))}}let J=String($);if(J.includes(`
|
|
277
|
-
`))return{lines:J.split(`
|
|
278
|
-
`)};return{inline:J}}formatArrayAnswer($){let J=[];for(let U of $){let Q=U.split(`
|
|
279
|
-
`);J.push(`- ${Q[0]??""}`);for(let _=1;_<Q.length;_++)J.push(` ${Q[_]}`)}return J}}import lg from"node:process";import{spawn as qE}from"node:child_process";import{chmodSync as Lg,existsSync as o0,mkdirSync as zg,statSync as Rg,unlinkSync as Ag}from"node:fs";import{writeFile as wg}from"node:fs/promises";import{createRequire as CY}from"node:module";import{homedir as NE}from"node:os";import z0 from"node:path";import B6 from"node:process";var fg="ast-grep/ast-grep",HE="0.40.0",S2=["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"],kg=300000,d_=1048576,FE=500,Ig={"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 l_($){try{return Rg($).size>1e4}catch{return!1}}function Sg(){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 Tg(){try{return CY(import.meta.url)("@ast-grep/cli/package.json").version}catch{return HE}}function i_(){if(B6.platform==="win32"){let Q=B6.env.LOCALAPPDATA||B6.env.APPDATA||z0.join(NE(),"AppData","Local");return z0.join(Q,"goat-chain","bin")}let J=B6.env.XDG_CACHE_HOME||z0.join(NE(),".cache");return z0.join(J,"goat-chain","bin")}function bY(){return B6.platform==="win32"?"ast-grep.exe":"ast-grep"}function vg(){return B6.platform==="win32"?"sg.exe":"sg"}function Cg(){let $=[bY(),vg()];return Array.from(new Set($))}function BE(){let $=i_();for(let J of Cg()){let U=z0.join($,J);if(o0(U)&&l_(U))return U}return null}async function bg($,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 hg(Q,_);if(G!==0)throw Error(`zip extraction failed (exit ${G}): ${V}
|
|
280
|
-
|
|
281
|
-
${U?"Ensure PowerShell is available on your system.":"Please install 'unzip' (e.g., apt install unzip, brew install unzip)."}`)}async function yg($=HE){let J=`${B6.platform}-${B6.arch}`,U=Ig[J];if(!U)return console.error(`[goat-chain] Unsupported platform for ast-grep: ${J}`),null;let Q=i_(),_=bY(),G=z0.join(Q,_);if(o0(G))return G;let{arch:V,os:X}=U,Z=`app-${V}-${X}.zip`,Y=`https://github.com/${fg}/releases/download/${$}/${Z}`;console.log("[goat-chain] Downloading ast-grep binary...");try{if(!o0(Q))zg(Q,{recursive:!0});let K=await fetch(Y,{redirect:"follow"});if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let F=z0.join(Q,Z),N=await K.arrayBuffer();if(await wg(F,Buffer.from(N)),await bg(F,Q),o0(F))Ag(F);if(B6.platform!=="win32"&&o0(G))Lg(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 OE(){let $=Tg(),J=await yg($);if(J)a1=J,DE(J);return J}async function WE(){let $=BE();if($)return $;if(D1)return D1;return D1=(async()=>{try{return await OE()}finally{D1=null}})(),D1}function jE(){let $=bY(),J=BE();if(J&&l_(J))return J;try{let _=CY(import.meta.url).resolve("@ast-grep/cli/package.json"),G=z0.dirname(_),V=z0.join(G,$);if(o0(V)&&l_(V))return V}catch{}let U=Sg();if(U)try{let _=CY(import.meta.url).resolve(`${U}/package.json`),G=z0.dirname(_),V=B6.platform==="win32"?"ast-grep.exe":"ast-grep",X=z0.join(G,V);if(o0(X)&&l_(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(o0(_)&&l_(_))return _}return null}var a1=null,D1=null;function gg(){if(a1!==null)return a1;let $=jE();if($)return a1=$,$;return"sg"}function DE($){a1=$}async function xg(){if(a1!==null&&o0(a1))return a1;if(D1)return D1;return D1=(async()=>{try{let $=jE();if($&&o0($))return a1=$,DE($),$;return await OE()}finally{D1=null}})(),D1}function hg($,J){return new Promise((U,Q)=>{let _=qE($,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 ug($,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=qE($,J,{cwd:Q,stdio:["ignore","pipe","pipe"]}),q=setTimeout(()=>{V=!0,N.kill()},U);N.stdout?.on("data",(H)=>{if(Y>=d_){X=!0;return}let E=d_-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>=d_)return;let E=d_-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 mg($){return $.code==="ENOENT"||$.message?.includes("ENOENT")||$.message?.includes("not found")||$.message?.includes("cannot execute")||$.message?.includes("Exec format error")||$.code==="EACCES"}function cg($,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 aJ($){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 _=kg,G=Boolean($.binaryPath),V=$.binaryPath??gg();if(!G&&!o0(V)&&V!=="sg"){let q=await xg();if(q)V=q}let X;try{X=await ug(V,U,_,$.cwd)}catch(q){let H=q;if(!G&&mg(H)){if(await WE())return aJ($);return{matches:[],totalMatches:0,truncated:!1,error:`ast-grep CLI binary not found or invalid.
|
|
282
|
-
|
|
283
|
-
Auto-download failed. Manual install options:
|
|
284
|
-
pnpm install --force # Re-run postinstall scripts
|
|
285
|
-
bun add -D @ast-grep/cli
|
|
286
|
-
cargo install ast-grep --locked
|
|
287
|
-
brew install ast-grep
|
|
288
|
-
|
|
289
|
-
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 WE())return aJ($)}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)>=d_,Y=cg(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>FE;return{matches:F?Y.slice(0,FE):Y,totalMatches:K,truncated:Z||F,truncatedReason:Z?"max_output_bytes":F?"max_matches":void 0,exitCode:X.exitCode,stderr:X.stderr}}import EE from"node:path";function PE($,J){if(!$||!J)return $;let U=EE.relative(J,$);if(U&&!U.startsWith("..")&&!EE.isAbsolute(U))return U;return $}function ME($){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 dg($){let J=($.lines??$.text??"").trim();return J?` ${J}`:""}function LE($,J){if($.error)return`Error: ${$.error}`;if($.matches.length===0)return"No matches found";let U=[];if($.truncated)U.push(`Results truncated (${ME($)})
|
|
290
|
-
`);U.push(`Found ${$.matches.length} match(es)${$.truncated?` (truncated from ${$.totalMatches})`:""}:
|
|
291
|
-
`);for(let Q of $.matches){let _=(Q.range?.start?.line??0)+1,G=(Q.range?.start?.column??0)+1,V=`${PE(Q.file,J)}:${_}:${G}`;U.push(V);let X=dg(Q);if(X)U.push(X);U.push("")}return U.join(`
|
|
292
|
-
`)}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 (${ME($)})
|
|
293
|
-
`);_.push(`${Q}${$.matches.length} replacement(s):
|
|
294
|
-
`);for(let G of $.matches){let V=(G.range?.start?.line??0)+1,X=(G.range?.start?.column??0)+1,Z=`${PE(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(`
|
|
295
|
-
`)}function zE($,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 T2 extends P4{name="ast_grep_replace";riskLevel="high";description=`Replace code patterns across filesystem with AST-aware rewriting. Dry-run by default.
|
|
296
|
-
|
|
297
|
-
Usage notes:
|
|
298
|
-
- Use meta-variables in rewrite to preserve matched content
|
|
299
|
-
- Example: pattern='console.log($MSG)' rewrite='logger.info($MSG)'
|
|
300
|
-
- 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:[...S2],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??lg.cwd(),this.astGrepPath=$?.astGrepPath}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($,J){let U=this.validateArgs($),Q=U.dryRun!==!1,_=await aJ({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 aJ({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(!S2.includes(Q))throw Error(`lang must be one of: ${S2.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 ig from"node:process";var RE=5000;class v2 extends P4{name="ast_grep_search";description=`Search code patterns across filesystem using AST-aware matching. Supports 25 languages.
|
|
301
|
-
|
|
302
|
-
Usage notes:
|
|
303
|
-
- Use meta-variables: $VAR (single node), $$$ (multiple nodes)
|
|
304
|
-
- Patterns must be complete AST nodes (valid code)
|
|
305
|
-
- For functions, include params and body: 'export async function $NAME($$$) { $$$ }' not 'export async function $NAME'
|
|
306
|
-
- 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:[...S2],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??ig.cwd(),this.astGrepPath=$?.astGrepPath}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($,J){let U=this.validateArgs($),Q=await aJ({pattern:U.pattern,lang:U.lang,paths:U.paths,globs:U.globs,context:U.context,cwd:this.cwd,binaryPath:this.astGrepPath}),_=LE(Q,this.cwd);if(Q.matches.length===0&&!Q.error){let Z=zE(U.pattern,U.lang);if(Z)_+=`
|
|
307
|
-
|
|
308
|
-
${Z}`}let{truncated:G,truncatedReason:V}=Q;if(_.length>RE){if(_=_.slice(0,RE)+`
|
|
309
|
-
|
|
310
|
-
... [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(!S2.includes(U))throw Error(`lang must be one of: ${S2.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 AE}from"node:child_process";import Q0 from"node:process";var PQ=30000,wE=120000,rg=600000,E1=new Map;async function F9($){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 r_($){try{return Q0.kill($,0),!0}catch{return!1}}function gY(){for(let[$]of E1)if(!r_($))E1.delete($);return Array.from(E1.values())}async function xY($){let J=[];for(let[U,Q]of E1)if(Q.category===$&&r_(U)){if(await F9(U))J.push(U),E1.delete(U)}return J}async function hY(){let $=[];for(let[J]of E1){if(r_(J)){if(await F9(J))$.push(J)}E1.delete(J)}return $}function fE($){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 C2 extends P4{name="Bash";riskLevel="critical";description=`Executes a given bash command in a persistent shell session with optional timeout.
|
|
311
|
-
|
|
312
|
-
Usage notes:
|
|
313
|
-
- The command argument is required.
|
|
314
|
-
- Use 'run_in_background: true' for long-running processes such as:
|
|
315
|
-
* Development servers: npm run dev, yarn dev, pnpm dev, npm start
|
|
316
|
-
* Server processes: node server.js, python -m http.server
|
|
317
|
-
* Watch modes: npm run watch, yarn watch
|
|
318
|
-
* Database/service daemons: redis-server, mongod
|
|
319
|
-
* Any command that runs indefinitely until manually stopped
|
|
320
|
-
- If not specified, commands will timeout after 120000ms (2 minutes).
|
|
321
|
-
- Standard timeout is suitable for short-lived commands like builds, tests, and file operations.
|
|
322
|
-
- If the output exceeds 30000 characters, it will be truncated.
|
|
323
|
-
|
|
324
|
-
Examples:
|
|
325
|
-
- Background: { command: "npm run dev", run_in_background: true, description: "Start dev server" }
|
|
326
|
-
- Foreground: { command: "npm test", timeout: 60000, description: "Run tests" }
|
|
327
|
-
- 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=wE,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=fE(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]:
|
|
328
|
-
${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(`
|
|
329
|
-
`)||"[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=wE;if($.timeout!==void 0){if(typeof $.timeout!=="number")throw TypeError("Timeout must be a number");U=Math.min(Math.max(0,$.timeout),rg)}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=AE(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"})},j=(f,T)=>{if(Q?.emitEvent&&Q.toolCallId)E(),Q.emitEvent({type:"tool_output_delta",tool_call_id:Q.toolCallId,delta:f,isStderr:T})},B=async()=>{if(H&&!K)await F9(H)},D=()=>{Y=!0,B()},w=Q?.signal;if(w)if(w.aborted)Y=!0,B();else w.addEventListener("abort",D,{once:!0});let A=setTimeout(()=>{X=!0,B()},J),I=()=>{if(clearTimeout(A),w)w.removeEventListener("abort",D)};q.stdout?.on("data",(f)=>{let T=f.toString();if(G.length+T.length>PQ)G+=T.slice(0,PQ-G.length),Z=!0;else G+=T;j(T,!1)}),q.stderr?.on("data",(f)=>{let T=f.toString();if(V.length+T.length>PQ)V+=T.slice(0,PQ-V.length),Z=!0;else V+=T;j(T,!0)}),q.on("close",(f)=>{K=!0,I();let T=Z?`${G}
|
|
330
|
-
... [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?`
|
|
331
|
-
|
|
332
|
-
`:"")+`<bash_metadata>
|
|
333
|
-
`+S.join(`
|
|
334
|
-
`)+`
|
|
335
|
-
</bash_metadata>`;_({exitCode:f,stdout:T,stderr:z,truncated:Z,timedOut:X,background:!1})}),q.on("error",(f)=>{K=!0,I(),_({exitCode:1,stdout:"",stderr:`Failed to execute command: ${f.message}`,truncated:!1,timedOut:!1,background:!1})})})}executeBackground($,J,U){return new Promise((Q)=>{let _=Q0.platform==="win32"?["/c",$]:["-c",$],G=AE(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=fE($);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(`
|
|
336
|
-
[Initial output]:
|
|
337
|
-
${K.trim()}`);if(F.trim())q.push(`
|
|
338
|
-
[Initial stderr]:
|
|
339
|
-
${F.trim()}`);Q({exitCode:null,stdout:q.join(""),stderr:"",truncated:!1,timedOut:!1,background:!0,pid:V})},N)})}async killProcess($){let J=await F9($);if(J)E1.delete($);return J}getRunningProcesses(){return gY()}async killAllProcesses(){return hY()}}import{readFile as ng,stat as pg,writeFile as ag}from"node:fs/promises";import uY from"node:path";import og from"node:process";var kE=0,tg=0.3;function IE($,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 sg=function*($,J){yield J},eg=function*($,J){let U=$.split(`
|
|
340
|
-
`),Q=J.split(`
|
|
341
|
-
`);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)}}},$x=function*($,J){let U=$.split(`
|
|
342
|
-
`),Q=J.split(`
|
|
343
|
-
`);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 j=U[K+E].trim(),B=Q[E].trim(),D=Math.max(j.length,B.length);if(D===0)continue;let w=IE(j,B);if(q+=(1-w/D)/H,q>=kE)break}else q=1;if(q>=kE){let E=0;for(let B=0;B<K;B++)E+=U[B].length+1;let j=E;for(let B=K;B<=F;B++)if(j+=U[B].length,B<F)j+=1;yield $.substring(E,j)}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 j=1;j<V-1&&j<q-1;j++){let B=U[F+j].trim(),D=Q[j].trim(),w=Math.max(B.length,D.length);if(w===0)continue;let A=IE(B,D);H+=1-A/w}H/=E}else H=1;if(H>Y)Y=H,Z=K}if(Y>=tg&&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)}},Jx=function*($,J){let U=(V)=>V.replace(/\s+/g," ").trim(),Q=U(J),_=$.split(`
|
|
344
|
-
`);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(`
|
|
345
|
-
`);if(G.length>1)for(let V=0;V<=_.length-G.length;V++){let X=_.slice(V,V+G.length);if(U(X.join(`
|
|
346
|
-
`))===Q)yield X.join(`
|
|
347
|
-
`)}},Ux=function*($,J){let U=(V)=>{let X=V.split(`
|
|
348
|
-
`),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(`
|
|
349
|
-
`)},Q=U(J),_=$.split(`
|
|
350
|
-
`),G=J.split(`
|
|
351
|
-
`);for(let V=0;V<=_.length-G.length;V++){let X=_.slice(V,V+G.length).join(`
|
|
352
|
-
`);if(U(X)===Q)yield X}},_x=function*($,J){let U=(V)=>{return V.replace(/\\([ntr'"`\\\n$])/g,(X,Z)=>{switch(Z){case"n":return`
|
|
353
|
-
`;case"t":return"\t";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case`
|
|
354
|
-
`:return`
|
|
355
|
-
`;case"$":return"$";default:return X}})},Q=U(J);if($.includes(Q))yield Q;let _=$.split(`
|
|
356
|
-
`),G=Q.split(`
|
|
357
|
-
`);for(let V=0;V<=_.length-G.length;V++){let X=_.slice(V,V+G.length).join(`
|
|
358
|
-
`);if(U(X)===Q)yield X}},Qx=function*($,J){let U=J.trim();if(U===J)return;if($.includes(U))yield U;let Q=$.split(`
|
|
359
|
-
`),_=J.split(`
|
|
360
|
-
`);for(let G=0;G<=Q.length-_.length;G++){let V=Q.slice(G,G+_.length).join(`
|
|
361
|
-
`);if(V.trim()===U)yield V}},Gx=function*($,J){let U=J.split(`
|
|
362
|
-
`);if(U.length<3)return;if(U[U.length-1]==="")U.pop();let Q=$.split(`
|
|
363
|
-
`),_=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(`
|
|
364
|
-
`);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 b2 extends P4{name="Edit";riskLevel="high";description=`Performs exact string replacements in files.
|
|
365
|
-
|
|
366
|
-
Usage notes:
|
|
367
|
-
- When editing, preserve the exact indentation (tabs/spaces) from the original file
|
|
368
|
-
- The edit will FAIL if old_string is not unique in the file unless replace_all is true
|
|
369
|
-
- Use replace_all for replacing/renaming strings across the entire file
|
|
370
|
-
- old_string and new_string must be different
|
|
371
|
-
- If exact matching fails, the tool tries normalized variants (trimmed lines, whitespace, indentation, escapes)
|
|
372
|
-
- 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??og.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 pg(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 ng(V,"utf-8"),Z=this.replaceWithFallback(X,Q,_,G??!1);if(Z.kind==="not_found")return S4(`old_string not found in file: ${V}
|
|
373
|
-
|
|
374
|
-
Searched for (including normalized variants):
|
|
375
|
-
${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 ag(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=[sg,eg,$x,Jx,Ux,_x,Qx,Gx];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 Vx,stat as SE}from"node:fs/promises";import MQ from"node:path";import Xx from"node:process";var mY=1000,Yx=20;function Zx($){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)=>Kx(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 Kx($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}class y2 extends P4{name="Glob";description=`Fast file pattern matching tool that works with any codebase size.
|
|
376
|
-
|
|
377
|
-
Usage notes:
|
|
378
|
-
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
|
|
379
|
-
- Returns matching file paths sorted by modification time (newest first)
|
|
380
|
-
- Use this tool when you need to find files by name patterns
|
|
381
|
-
- You can call multiple tools in a single response for parallel searches
|
|
382
|
-
|
|
383
|
-
Supported patterns:
|
|
384
|
-
- \`*\` matches any sequence of characters except path separator
|
|
385
|
-
- \`**\` matches any sequence of characters including path separator
|
|
386
|
-
- \`?\` matches any single character
|
|
387
|
-
- \`{a,b}\` matches either a or b
|
|
388
|
-
- \`[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??Xx.cwd()}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($,J){let{pattern:U,path:Q}=this.validateArgs($),_=Q?MQ.isAbsolute(Q)?Q:MQ.resolve(this.cwd,Q):this.cwd;try{if(!(await SE(_)).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=Zx(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})`:""}:
|
|
389
|
-
${Y.join(`
|
|
390
|
-
`)}`:`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(_>Yx)return;let G=J?MQ.join($,J):$,V;try{V=await Vx(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=MQ.join(G,X.name),K=await SE(Y);Q.push({path:Z,mtime:K.mtimeMs})}catch{}}}}}var mZ=U4(VR(),1),IR=U4(fR(),1);import{Buffer as Tl}from"node:buffer";import{spawn as uZ}from"node:child_process";import{chmodSync as vl,existsSync as U5,mkdirSync as Cl,statSync as bl}from"node:fs";import{copyFile as yl,mkdtemp as gl,readdir as xl,readFile as hl,rm as kR,stat as ul,writeFile as ml}from"node:fs/promises";import V0 from"node:path";import h2 from"node:process";var x2=5000,hZ=60000,cl="BurntSushi/ripgrep",SR="latest",dl={"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 bl($).size>1e4}catch{return!1}}function TR(){return h2.platform==="win32"?"rg.exe":"rg"}function dZ(){let $=V0.join(i_(),TR());return U5($)&&cZ($)?$:null}function ll($){return $.code==="ENOENT"||$.message?.includes("ENOENT")||$.message?.includes("not found")}function vR($,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 il($,J){let Q=["-command",`Expand-Archive -Path '${$}' -DestinationPath '${J}' -Force`],{exitCode:_,stderr:G}=await vR("powershell",Q);if(_!==0)throw Error(`zip extraction failed (exit ${_}): ${G}
|
|
391
|
-
|
|
392
|
-
Ensure PowerShell is available on your system.`)}async function rl($,J){let{exitCode:U,stderr:Q}=await vR("tar",["-xzf",$,"-C",J]);if(U!==0)throw Error(`tar extraction failed (exit ${U}): ${Q}
|
|
393
|
-
|
|
394
|
-
Please install 'tar' (e.g., apt install tar, brew install gnu-tar).`)}async function CR($,J){let U=await xl($,{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 CR(_,J);if(G)return G}}return null}var J5=null,lQ=null,iQ=null;async function nl($){if($!=="latest")return $;if(iQ)return iQ;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 iQ=G.startsWith("v")?G.slice(1):G,iQ}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 pl($=SR){let J=`${h2.platform}-${h2.arch}`,U=dl[J];if(!U)return console.error(`[goat-chain] Unsupported platform for ripgrep: ${J}`),null;let Q=i_(),_=TR(),G=V0.join(Q,_);if(U5(G)&&cZ(G))return G;let V=await nl($);if(!V)return null;let{arch:X,os:Z}=U,Y=h2.platform==="win32"?"zip":"tar.gz",K=`ripgrep-${V}-${X}-${Z}.${Y}`,F=`https://github.com/${cl}/releases/download/${V}/${K}`;console.log("[goat-chain] Downloading ripgrep binary...");let N=null,q=V0.join(Q,K);try{if(!U5(Q))Cl(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 D=await B.arrayBuffer();await ml(q,Tl.from(D))}finally{clearTimeout(E)}if(N=await gl(V0.join(Q,"ripgrep-")),Y==="zip")await il(q,N);else await rl(q,N);let j=await CR(N,_);if(!j)throw Error("ripgrep binary not found in extracted archive.");if(await yl(j,G),h2.platform!=="win32"&&U5(G))vl(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 kR(q,{force:!0}).catch(()=>{}),N)await kR(N,{recursive:!0,force:!0}).catch(()=>{})}}async function al($=SR){let J=dZ();if(J)return J;return pl($)}async function ol(){if(J5!==null&&U5(J5))return J5;if(lQ)return lQ;return lQ=(async()=>{let $=dZ();if($)return J5=$,$;let J=await al();if(J)return J5=J,J;return null})(),lQ}class u2 extends P4{name="Grep";description=`A powerful search tool built on ripgrep.
|
|
395
|
-
|
|
396
|
-
Usage notes:
|
|
397
|
-
- Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
|
|
398
|
-
- Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
|
|
399
|
-
- Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
|
|
400
|
-
- Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
|
|
401
|
-
- Multiline matching: By default patterns match within single lines only. For cross-line patterns, use multiline: true
|
|
402
|
-
- 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??h2.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+=`
|
|
403
|
-
[Search timed out]`;if(_.matchCount!==void 0)G=`Found ${_.matchCount} match${_.matchCount!==1?"es":""}
|
|
404
|
-
${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:h2.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>x2)_+=H.slice(0,x2-_.length),V=!0,clearTimeout(N),K.kill("SIGTERM");else _+=H}),K.stderr?.on("data",(q)=>{let H=q.toString();if(H.includes("error:"))_+=`
|
|
405
|
-
[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 j=_.split(`
|
|
406
|
-
`).filter((A)=>A.trim()),B=J.offset??0,D=J.head_limit??j.length;H=j.slice(B,B+D).join(`
|
|
407
|
-
`)}let E;if(J.output_mode==="count")E=H.split(`
|
|
408
|
-
`).filter((j)=>j.trim()).reduce((j,B)=>{let D=B.match(/:(\d+)$/);return j+(D?Number.parseInt(D[1],10):0)},0);F({exitCode:q,output:V?`${H}
|
|
409
|
-
... [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&&ll(H)){(async()=>{try{let j=await ol();if(j){this.rgPath=j;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),j;try{j=await ul(H)}catch{return clearTimeout(Q),{exitCode:2,engine:"js",output:`Search path not found: ${q}`,truncated:!1,timedOut:!1}}let B=[],D=mZ.default.default??mZ.default;if(typeof D!=="function")return clearTimeout(Q),this.runSystemGrep($);let w=H;if(j.isFile())B=[H],w=V0.dirname(H);else if(j.isDirectory()){w=H;try{B=await D("**/*",{cwd:w,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 A=[],I=!1,f=0,T=(C)=>{let b=C.length+1;if(f+b>x2)return U=!0,!1;return A.push(C),f+=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=IR.default.isMatch,R=_==="content"?$["-n"]!==!1:!1;for(let C of B){if(J)break;if(f>=x2){U=!0;break}if(!S(C))continue;if(M&&P&&!P(V0.basename(C),M))continue;let b="";try{b=await hl(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$=R?`${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$]===`
|
|
410
|
-
`)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=R?`${y}:${u$}:${_$}`:`${y}:${_$}`;if(!T(n)){Y$=!0;break}}if(Y$)break}clearTimeout(Q);let k=A;if($.offset||$.head_limit){let C=A.filter((x)=>x.trim()),b=$.offset??0,y=$.head_limit??C.length;k=C.slice(b,b+y)}let L=k.join(`
|
|
411
|
-
`);if(L.length>x2)L=L.slice(0,x2),U=!0;let v;if(_==="count")v=L.split(`
|
|
412
|
-
`).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}
|
|
413
|
-
... [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:h2.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>x2)U+=K.slice(0,x2-U.length),_=!0,clearTimeout(Z),X.kill("SIGTERM");else U+=K}),X.stderr?.on("data",(Y)=>{let K=Y.toString();if(K.trim())U+=`
|
|
414
|
-
[stderr]: ${K}`}),X.on("close",(Y)=>{clearTimeout(Z);let K=U;if($.offset||$.head_limit){let N=U.split(`
|
|
415
|
-
`).filter((E)=>E.trim()),q=$.offset??0,H=$.head_limit??N.length;K=N.slice(q,q+H).join(`
|
|
416
|
-
`)}let F;if(V==="count")F=K.split(`
|
|
417
|
-
`).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}
|
|
418
|
-
... [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 rQ,stat as tl}from"node:fs/promises";import eJ from"node:path";import sl from"node:process";var bR=2000,lZ=2000,el=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"]),$i={".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 m2 extends P4{name="Read";_cwd;_allowedDirectory;constructor($){super();this._cwd=$?.cwd??sl.cwd(),this._allowedDirectory=$?.allowedDirectory}get description(){let $=`Reads a file from the local filesystem. You can access any file directly by using this tool.
|
|
419
|
-
|
|
420
|
-
Usage notes:
|
|
421
|
-
- Current working directory: ${this._cwd}
|
|
422
|
-
- Supports both absolute paths and relative paths (relative to cwd)
|
|
423
|
-
- IMPORTANT: Do NOT guess file paths. Use Glob to search for files first if unsure.
|
|
424
|
-
- By default, it reads up to ${bR} lines starting from the beginning
|
|
425
|
-
- You can optionally specify a line offset and limit for large files
|
|
426
|
-
- Any lines longer than ${lZ} characters will be truncated
|
|
427
|
-
- Results are returned with line numbers (like cat -n format)
|
|
428
|
-
- Can read images (PNG, JPG, etc.), PDFs, and Jupyter notebooks
|
|
429
|
-
- You can call multiple tools in parallel to read multiple files at once`;if(this._allowedDirectory)return`${$}
|
|
430
|
-
- IMPORTANT: Files can ONLY be read from within: ${this._allowedDirectory}
|
|
431
|
-
- 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=eJ.isAbsolute(U)?U:eJ.resolve(this._cwd,U);if(this._allowedDirectory){let F=eJ.resolve(this._allowedDirectory),N=eJ.resolve(G);if(!N.startsWith(F+eJ.sep)&&N!==F)return S4(`Access denied: ${U}
|
|
432
|
-
Files can only be read from within: ${this._allowedDirectory}
|
|
433
|
-
Please use a path like: ${this._allowedDirectory}/<filename>`)}let V;try{V=await tl(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=eJ.extname(G).toLowerCase(),Z=el.has(X),Y=$i[X],K;if(Z){if(K=await this.handleBinaryFile(G,V.size,Y),Y?.startsWith("image/"))return{content:[{type:"image",data:(await rQ(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 rQ($)).toString("base64");return{content:`[Binary file: ${eJ.basename($)}]
|
|
434
|
-
Size: ${this.formatSize(J)}
|
|
435
|
-
MIME type: ${U??"unknown"}
|
|
436
|
-
Base64 encoded content:
|
|
437
|
-
${_}`,totalLines:1,linesReturned:1,startLine:1,truncated:!1,fileSize:J,isBinary:!0,mimeType:U}}async handleJupyterNotebook($,J,U,Q){let _=await rQ($,"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(`
|
|
438
|
-
`)),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(`
|
|
439
|
-
`))}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(`
|
|
440
|
-
`))}}}X.push("")}return this.formatOutput(X,J,U,Q)}async handleTextFile($,J,U,Q){let _=await rQ($,"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(`
|
|
441
|
-
`);return this.formatOutput(G,J,U,Q)}formatOutput($,J,U,Q){let _=$.length,G=U??1,V=Q??bR,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," "),j=N;if(N.length>lZ)j=`${N.slice(0,lZ)}... [truncated]`,K=!0;return`${E}|${j}`}).join(`
|
|
442
|
-
`),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 _5 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}
|
|
443
|
-
|
|
444
|
-
${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.
|
|
445
|
-
|
|
446
|
-
<available_agents>
|
|
447
|
-
${this.buildAgentsList()||"No subagent types registered."}
|
|
448
|
-
</available_agents>
|
|
449
|
-
|
|
450
|
-
When to use the Task tool:
|
|
451
|
-
- When you are instructed to execute custom slash commands. Use the Task tool with the slash command invocation as the entire prompt
|
|
452
|
-
- For complex multi-step tasks requiring autonomous exploration across many files
|
|
453
|
-
- When you need to research or analyze code that spans multiple directories
|
|
454
|
-
|
|
455
|
-
When NOT to use the Task tool:
|
|
456
|
-
- 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
|
|
457
|
-
- If you are searching for a specific class definition like "class Foo", use the Glob tool instead, to find the match more quickly
|
|
458
|
-
- 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
|
|
459
|
-
- For simple tasks that can be completed with 1-2 tool calls
|
|
460
|
-
|
|
461
|
-
Usage notes:
|
|
462
|
-
1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
|
|
463
|
-
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.
|
|
464
|
-
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.
|
|
465
|
-
4. The agent's outputs should generally be trusted
|
|
466
|
-
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
|
|
467
|
-
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.
|
|
468
|
-
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(`
|
|
469
|
-
`)}}class j9 extends P4{name="TodoPlan";riskLevel="safe";description=`Use this tool to draft a structured task list in plan mode.
|
|
470
|
-
|
|
471
|
-
This tool only generates a plan for review and does NOT update any execution state.
|
|
472
|
-
Use TodoWrite in agent mode when you are actively executing tasks.
|
|
473
|
-
|
|
474
|
-
When to use:
|
|
475
|
-
- Plan mode task breakdowns (3+ steps)
|
|
476
|
-
- Presenting a proposed plan for review
|
|
477
|
-
- After clarifying requirements in plan mode
|
|
478
|
-
|
|
479
|
-
When NOT to use:
|
|
480
|
-
- Active execution tracking (use TodoWrite)
|
|
481
|
-
- Single, straightforward task
|
|
482
|
-
- Purely conversational/informational requests
|
|
483
|
-
|
|
484
|
-
Task States:
|
|
485
|
-
- pending: Task not yet started
|
|
486
|
-
- in_progress: Currently working on (limit to ONE at a time)
|
|
487
|
-
- completed: Task finished successfully
|
|
488
|
-
|
|
489
|
-
Task descriptions have two forms:
|
|
490
|
-
- content: Imperative form (e.g., "Run tests")
|
|
491
|
-
- 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(`
|
|
492
|
-
`)}}class c2 extends P4{name="TodoWrite";riskLevel="low";description=`Use this tool to create and manage a structured task list for your current coding session.
|
|
493
|
-
|
|
494
|
-
When to use:
|
|
495
|
-
- Complex multi-step tasks (3+ steps)
|
|
496
|
-
- Non-trivial tasks requiring careful planning
|
|
497
|
-
- User explicitly requests todo list
|
|
498
|
-
- User provides multiple tasks
|
|
499
|
-
- After receiving new instructions
|
|
500
|
-
|
|
501
|
-
When NOT to use:
|
|
502
|
-
- Single, straightforward task
|
|
503
|
-
- Trivial tasks (< 3 steps)
|
|
504
|
-
- Purely conversational/informational requests
|
|
505
|
-
|
|
506
|
-
Task States:
|
|
507
|
-
- pending: Task not yet started
|
|
508
|
-
- in_progress: Currently working on (limit to ONE at a time)
|
|
509
|
-
- completed: Task finished successfully
|
|
510
|
-
|
|
511
|
-
Task descriptions have two forms:
|
|
512
|
-
- content: Imperative form (e.g., "Run tests")
|
|
513
|
-
- 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(`
|
|
514
|
-
`)}}import Ji from"node:process";class d2 extends P4{name="WebSearch";riskLevel="medium";description=`Allows the agent to search the web and use the results to inform responses.
|
|
515
|
-
|
|
516
|
-
Usage notes:
|
|
517
|
-
- Provides up-to-date information for current events and recent data
|
|
518
|
-
- Returns search results with titles, links, and snippets
|
|
519
|
-
- Use this tool for accessing information beyond the knowledge cutoff
|
|
520
|
-
- 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??Ji.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(`
|
|
521
|
-
`)}}import{mkdir as Ui,stat as _i,writeFile as Qi}from"node:fs/promises";import l2 from"node:path";import Gi from"node:process";class i2 extends P4{name="Write";riskLevel="high";_cwd;_allowedDirectory;constructor($){super();this._cwd=$?.cwd??Gi.cwd(),this._allowedDirectory=$?.allowedDirectory}get description(){let $=`Writes a file to the local filesystem.
|
|
522
|
-
|
|
523
|
-
Usage notes:
|
|
524
|
-
- Current working directory: ${this._cwd}
|
|
525
|
-
- Supports both absolute paths and relative paths (relative to cwd)
|
|
526
|
-
- IMPORTANT: When editing existing files, verify the path first using Glob or Read
|
|
527
|
-
- This tool will overwrite the existing file if there is one at the provided path
|
|
528
|
-
- Parent directories will be created automatically if they don't exist
|
|
529
|
-
- ALWAYS prefer editing existing files over writing new ones
|
|
530
|
-
- NEVER proactively create documentation files (*.md) or README files unless explicitly requested`;if(this._allowedDirectory)return`${$}
|
|
531
|
-
- IMPORTANT: Files can ONLY be written within: ${this._allowedDirectory}
|
|
532
|
-
- 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($),_=l2.isAbsolute(U)?U:l2.resolve(this._cwd,U);if(this._allowedDirectory){let Y=l2.resolve(this._allowedDirectory),K=l2.resolve(_);if(!K.startsWith(Y+l2.sep)&&K!==Y)return S4(`Access denied: ${U}
|
|
533
|
-
Files can only be written within: ${this._allowedDirectory}
|
|
534
|
-
Please use a path like: ${this._allowedDirectory}/<filename>`)}let G=!1;try{if((await _i(_)).isDirectory())return S4(`Path is a directory, not a file: ${_}`);G=!0}catch(Y){if(Y.code!=="ENOENT")throw Y}let V=l2.dirname(_);await Ui(V,{recursive:!0}),await Qi(_,Q,"utf-8");let X=Buffer.byteLength(Q,"utf-8"),Z={success:!0,filePath:_,bytesWritten:X,overwritten:G,message:G?`Successfully overwrote ${l2.basename(_)} (${this.formatSize(X)})`:`Successfully created ${l2.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 Yi=["Bash","Edit","Write","ast_grep_replace","TodoWrite"],Zi=["<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(`
|
|
535
|
-
`);function Ki($){if($?.instruction)return $.instruction;let J=$?.maxParallelAgents??3,U=$?.encourageEarlyQuestions??!0,Q=$?.requireSynthesisPhase??!1,_=Zi,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.
|
|
536
|
-
|
|
537
|
-
`,""),_=_.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.
|
|
538
|
-
|
|
539
|
-
`,"");return _}function D9($){let J=Ki($),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 j9],_.__getBlockedTools=(G)=>{return G.metadata?.planMode?[...Yi]:[]},_}function E9($){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 D=Q.get(B);if(!D)continue;if(D instanceof _5){if($.debug)console.warn(`[${G}] Skipping TaskTool "${B}" for subagent "${Y.subagent_type}" to prevent infinite recursion`);continue}q.register(D)}let H=new j1({name:Y.subagent_type,systemPrompt:`${F.systemPrompt||""}
|
|
540
|
-
|
|
541
|
-
Your task: ${Y.prompt}
|
|
542
|
-
|
|
543
|
-
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 j="";for await(let B of E.receive()){if(K?.emitEvent&&V.has(B.type)){let{sessionId:D,...w}=B;K.emitEvent({type:"subagent_event",subagentId:H.id,subagentType:Y.subagent_type,taskDescription:Y.description,nestedEvent:w})}if(B.type==="done")j=B.finalResponse||""}return{subagentId:H.id,data:j}}),Z=async(Y,K)=>{return K({...Y,metadata:{...Y.metadata,parallelMode:!0,parallelSubagentMiddleware:G}})};return Z.__middlewareName=G,Z.__createTools=()=>{return[new _5({subagents:J,executor:X})]},Z}import{existsSync as Ni}from"node:fs";import{appendFile as Fi,mkdir as Wi,readdir as qi,readFile as Hi}from"node:fs/promises";import{homedir as Bi}from"node:os";import $8 from"node:path";import nQ 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.
|
|
544
|
-
Skills provide specialized knowledge and step-by-step guidance.
|
|
545
|
-
Use this when a task matches an available skill's description.
|
|
546
|
-
|
|
547
|
-
How to use:
|
|
548
|
-
- Activate a skill to load its instructions into the conversation
|
|
549
|
-
- Deactivate a skill to remove its instructions
|
|
550
|
-
- Examples:
|
|
551
|
-
- action: "activate", skill_name: "pdf" - load the PDF skill instructions
|
|
552
|
-
- action: "deactivate", skill_name: "pdf" - unload the PDF skill
|
|
553
|
-
|
|
554
|
-
<available_skills>
|
|
555
|
-
No skills registered.
|
|
556
|
-
</available_skills>`;return`Load a skill to get detailed instructions for a specific task.
|
|
557
|
-
Skills provide specialized knowledge and step-by-step guidance.
|
|
558
|
-
Use this when a task matches an available skill's description.
|
|
559
|
-
|
|
560
|
-
How to use:
|
|
561
|
-
- Activate a skill to load its instructions into the conversation
|
|
562
|
-
- Deactivate a skill to remove its instructions
|
|
563
|
-
- Examples:
|
|
564
|
-
- action: "activate", skill_name: "pdf" - load the PDF skill instructions
|
|
565
|
-
- action: "deactivate", skill_name: "pdf" - unload the PDF skill
|
|
566
|
-
|
|
567
|
-
<available_skills>
|
|
568
|
-
${Array.from(this.skills.values()).map((U)=>`<skill>
|
|
569
|
-
<name>${U.name}</name>
|
|
570
|
-
<description>${U.description}</description>
|
|
571
|
-
</skill>`).join(`
|
|
572
|
-
`)}
|
|
573
|
-
</available_skills>`}}var yR=$8.join(nQ.cwd(),".goatchain","skills-debug.log"),Oi=nQ.env.GOATCHAIN_SKILLS_DEBUG==="1";async function h$($,J){try{if(!Oi)return;let U=new Date().toISOString(),Q=J?`[${U}] ${$}
|
|
574
|
-
${JSON.stringify(J,null,2)}
|
|
575
|
-
|
|
576
|
-
`:`[${U}] ${$}
|
|
577
|
-
|
|
578
|
-
`,_=$8.dirname(yR);if(!Ni(_))await Wi(_,{recursive:!0});await Fi(yR,Q,"utf-8")}catch(U){console.error("Failed to write skills debug log:",U)}}var ji="[Active Skills]";async function rZ($){try{await h$(`Attempting to parse skill file: ${$}`);let J=await Hi($,"utf-8");if(await h$(`Successfully read file: ${$} (${J.length} chars)`),!J.startsWith(`---
|
|
579
|
-
`)&&!J.startsWith(`---\r
|
|
580
|
-
`))return await h$(`File ${$} does not start with frontmatter delimiter`),null;let U=J.split(`
|
|
581
|
-
`),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(`
|
|
582
|
-
`).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 gR($){let J=[];try{await h$(`Scanning skills directory: ${$}`);let U=await qi($,{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 _=$8.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 xR($){await h$(`Scanning ${$.length} skill directories`,$);let J=new Map;for(let Q of $){await h$(`Scanning directory: ${Q}`);let _=await gR(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 Di($){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 Ei($,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=$8.join(V,_,"SKILL.md");await h$(`Trying path: ${X}`);let Z=await rZ(X);if(Z){U.push(`## Skill: ${Z.name}
|
|
583
|
-
|
|
584
|
-
${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(`
|
|
585
|
-
|
|
586
|
-
`);return await h$(`Loaded ${U.length} skills, total content length: ${Q.length}`),Q}function pQ($){let J=$?.cwd,U=$?.globalSkillsDirectory===null?null:$?.globalSkillsDirectory??$8.join(Bi(),".claude","skills"),Q=$?.projectSkillsDirectory,_=$?.marker??ji,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) ===
|
|
587
|
-
`),await K(Y);let F=typeof J==="function"?J():J??nQ.cwd();await h$(`Resolved cwd: ${F}`);let N=Q===null?null:Q??$8.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=Di(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 D=await Ei(H,q);if(D)await h$(`Injecting ${D.length} chars of skills content with marker: "${_}"`),E=u1(E,D,_),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 j={...Y,messages:E};await h$("Calling next middleware...");let B=await K(j);return await h$(`=== Skills Middleware Execution End ===
|
|
588
|
-
`),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??nQ.cwd();await h$(`Initial cwd: ${Y}`);let K=Q===null?null:Q??$8.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 xR(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 ===
|
|
589
|
-
`)}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.
|
|
590
|
-
|
|
591
|
-
Your strengths:
|
|
592
|
-
- Rapidly finding files using glob patterns
|
|
593
|
-
- Searching code and text with powerful regex patterns
|
|
594
|
-
- Reading and analyzing file contents
|
|
595
|
-
|
|
596
|
-
Guidelines:
|
|
597
|
-
- Use Glob for broad file pattern matching
|
|
598
|
-
- Use Grep for searching file contents with regex
|
|
599
|
-
- Use Read when you know the specific file path you need to read
|
|
600
|
-
- Do not use AskUserQuestion; report any questions in your final response
|
|
601
|
-
- Adapt your search approach based on the thoroughness level specified by the caller
|
|
602
|
-
- Return file paths as absolute paths in your final response
|
|
603
|
-
- For clear communication, avoid using emojis
|
|
604
|
-
- Do not create any files, or run bash commands that modify the user's system state in any way
|
|
605
|
-
|
|
606
|
-
Complete the user's search request efficiently and report your findings clearly.
|
|
607
|
-
|
|
608
|
-
Here is some useful information about the environment you are running in:
|
|
609
|
-
<env>
|
|
610
|
-
Working directory: ${$}
|
|
611
|
-
Platform: ${process.platform}
|
|
612
|
-
Today's date: ${J.toDateString()}
|
|
613
|
-
</env>`}var Pi=nZ(process.cwd()),r2={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:Pi};class aQ{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}
|
|
614
|
-
|
|
615
|
-
`,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}
|
|
616
|
-
|
|
617
|
-
`,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(`
|
|
618
|
-
`);return JSON.stringify($,null,2)}}class oQ{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 tQ{agent;router;converter;debug;constructor($,J){if(this.agent=$,this.debug=J?.debug??!1,this.router=new oQ({sessionTimeout:J?.sessionTimeout,maxConcurrentSessions:J?.maxConcurrentSessions,maxIterations:J?.maxIterations}),this.converter=new aQ({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 Go,Writable as Vo}from"node:stream";var W={};O0(W,{xor:()=>Nw,xid:()=>CA,void:()=>Gw,uuidv7:()=>AA,uuidv6:()=>RA,uuidv4:()=>zA,uuid:()=>LA,util:()=>B$,url:()=>wA,uppercase:()=>T9,unknown:()=>Y8,union:()=>RG,undefined:()=>_w,ulid:()=>vA,uint64:()=>Jw,uint32:()=>sA,tuple:()=>KH,trim:()=>x9,treeifyError:()=>GK,transform:()=>wG,toUpperCase:()=>u9,toLowerCase:()=>h9,toJSONSchema:()=>s3,templateLiteral:()=>zw,symbol:()=>Uw,superRefine:()=>gH,success:()=>Pw,stringbool:()=>Tw,stringFormat:()=>iA,string:()=>QG,strictObject:()=>Zw,startsWith:()=>C9,slugify:()=>m9,size:()=>G8,setErrorMap:()=>en,set:()=>Bw,safeParseAsync:()=>xq,safeParse:()=>gq,safeEncodeAsync:()=>iq,safeEncode:()=>dq,safeDecodeAsync:()=>rq,safeDecode:()=>lq,registry:()=>L3,regexes:()=>h0,regex:()=>I9,refine:()=>yH,record:()=>NH,readonly:()=>IH,property:()=>p3,promise:()=>Rw,prettifyError:()=>VK,preprocess:()=>Cw,prefault:()=>LH,positive:()=>l3,pipe:()=>S5,partialRecord:()=>Ww,parseAsync:()=>yq,parse:()=>bq,overwrite:()=>e0,optional:()=>k5,object:()=>Yw,number:()=>pq,nullish:()=>Ew,nullable:()=>I5,null:()=>eq,normalize:()=>g9,nonpositive:()=>r3,nonoptional:()=>zH,nonnegative:()=>n3,never:()=>zG,negative:()=>i3,nativeEnum:()=>Ow,nanoid:()=>IA,nan:()=>Mw,multipleOf:()=>t2,minSize:()=>A1,minLength:()=>s1,mime:()=>y9,meta:()=>Iw,maxSize:()=>s2,maxLength:()=>V8,map:()=>Hw,mac:()=>gA,lte:()=>f0,lt:()=>z1,lowercase:()=>S9,looseRecord:()=>qw,looseObject:()=>Kw,locales:()=>z5,literal:()=>jw,length:()=>X8,lazy:()=>vH,ksuid:()=>bA,keyof:()=>Xw,jwt:()=>lA,json:()=>vw,iso:()=>l9,ipv6:()=>xA,ipv4:()=>yA,intersection:()=>YH,int64:()=>$w,int32:()=>tA,int:()=>GG,instanceof:()=>Sw,includes:()=>v9,httpUrl:()=>fA,hostname:()=>rA,hex:()=>nA,hash:()=>pA,guid:()=>MA,gte:()=>l6,gt:()=>R1,globalRegistry:()=>T6,getErrorMap:()=>$p,function:()=>Aw,fromJSONSchema:()=>yw,formatError:()=>W5,float64:()=>oA,float32:()=>aA,flattenError:()=>F5,file:()=>Dw,exactOptional:()=>jH,enum:()=>AG,endsWith:()=>b9,encodeAsync:()=>mq,encode:()=>hq,emoji:()=>kA,email:()=>PA,e164:()=>dA,discriminatedUnion:()=>Fw,describe:()=>kw,decodeAsync:()=>cq,decode:()=>uq,date:()=>Vw,custom:()=>fw,cuid2:()=>TA,cuid:()=>SA,core:()=>e1,config:()=>Y6,coerce:()=>hH,codec:()=>Lw,clone:()=>d6,cidrv6:()=>uA,cidrv4:()=>hA,check:()=>ww,catch:()=>wH,boolean:()=>aq,bigint:()=>eA,base64url:()=>cA,base64:()=>mA,array:()=>C5,any:()=>Qw,_function:()=>Aw,_default:()=>PH,_ZodString:()=>VG,ZodXor:()=>GH,ZodXID:()=>WG,ZodVoid:()=>_H,ZodUnknown:()=>JH,ZodUnion:()=>y5,ZodUndefined:()=>tq,ZodUUID:()=>w1,ZodURL:()=>T5,ZodULID:()=>FG,ZodType:()=>N4,ZodTuple:()=>ZH,ZodTransform:()=>BH,ZodTemplateLiteral:()=>SH,ZodSymbol:()=>oq,ZodSuccess:()=>RH,ZodStringFormat:()=>v4,ZodString:()=>r9,ZodSet:()=>WH,ZodRecord:()=>g5,ZodRealError:()=>Z0,ZodReadonly:()=>kH,ZodPromise:()=>CH,ZodPrefault:()=>MH,ZodPipe:()=>IG,ZodOptional:()=>fG,ZodObject:()=>b5,ZodNumberFormat:()=>Z8,ZodNumber:()=>p9,ZodNullable:()=>DH,ZodNull:()=>sq,ZodNonOptional:()=>kG,ZodNever:()=>UH,ZodNanoID:()=>ZG,ZodNaN:()=>fH,ZodMap:()=>FH,ZodMAC:()=>nq,ZodLiteral:()=>qH,ZodLazy:()=>TH,ZodKSUID:()=>qG,ZodJWT:()=>MG,ZodIssueCode:()=>sn,ZodIntersection:()=>XH,ZodISOTime:()=>UG,ZodISODuration:()=>_G,ZodISODateTime:()=>$G,ZodISODate:()=>JG,ZodIPv6:()=>BG,ZodIPv4:()=>HG,ZodGUID:()=>f5,ZodFunction:()=>bH,ZodFirstPartyTypeKind:()=>xH,ZodFile:()=>HH,ZodExactOptional:()=>OH,ZodError:()=>on,ZodEnum:()=>i9,ZodEmoji:()=>YG,ZodEmail:()=>XG,ZodE164:()=>PG,ZodDiscriminatedUnion:()=>VH,ZodDefault:()=>EH,ZodDate:()=>v5,ZodCustomStringFormat:()=>n9,ZodCustom:()=>x5,ZodCodec:()=>SG,ZodCatch:()=>AH,ZodCUID2:()=>NG,ZodCUID:()=>KG,ZodCIDRv6:()=>jG,ZodCIDRv4:()=>OG,ZodBoolean:()=>a9,ZodBigIntFormat:()=>LG,ZodBigInt:()=>o9,ZodBase64URL:()=>EG,ZodBase64:()=>DG,ZodArray:()=>QH,ZodAny:()=>$H,TimePrecision:()=>KW,NEVER:()=>pZ,$output:()=>QW,$input:()=>GW,$brand:()=>aZ});var e1={};O0(e1,{version:()=>JN,util:()=>B$,treeifyError:()=>GK,toJSONSchema:()=>s3,toDotPath:()=>lR,safeParseAsync:()=>YK,safeParse:()=>XK,safeEncodeAsync:()=>$r,safeEncode:()=>si,safeDecodeAsync:()=>Jr,safeDecode:()=>ei,registry:()=>L3,regexes:()=>h0,process:()=>k4,prettifyError:()=>VK,parseAsync:()=>J3,parse:()=>$3,meta:()=>lW,locales:()=>z5,isValidJWT:()=>ZA,isValidBase64URL:()=>YA,isValidBase64:()=>LN,initializeContext:()=>e2,globalRegistry:()=>T6,globalConfig:()=>Q5,formatError:()=>W5,flattenError:()=>F5,finalize:()=>JJ,extractDefs:()=>$J,encodeAsync:()=>oi,encode:()=>pi,describe:()=>dW,decodeAsync:()=>ti,decode:()=>ai,createToJSONSchemaMethod:()=>rW,createStandardJSONSchemaMethod:()=>d9,config:()=>Y6,clone:()=>d6,_xor:()=>Rn,_xid:()=>C3,_void:()=>CW,_uuidv7:()=>f3,_uuidv6:()=>w3,_uuidv4:()=>A3,_uuid:()=>R3,_url:()=>A5,_uppercase:()=>T9,_unknown:()=>TW,_union:()=>zn,_undefined:()=>kW,_ulid:()=>v3,_uint64:()=>wW,_uint32:()=>PW,_tuple:()=>fn,_trim:()=>x9,_transform:()=>bn,_toUpperCase:()=>u9,_toLowerCase:()=>h9,_templateLiteral:()=>ln,_symbol:()=>fW,_superRefine:()=>cW,_success:()=>un,_stringbool:()=>iW,_stringFormat:()=>c9,_string:()=>XW,_startsWith:()=>C9,_slugify:()=>m9,_size:()=>G8,_set:()=>Sn,_safeParseAsync:()=>w9,_safeParse:()=>A9,_safeEncodeAsync:()=>Y3,_safeEncode:()=>V3,_safeDecodeAsync:()=>Z3,_safeDecode:()=>X3,_regex:()=>I9,_refine:()=>mW,_record:()=>kn,_readonly:()=>dn,_property:()=>p3,_promise:()=>nn,_positive:()=>l3,_pipe:()=>cn,_parseAsync:()=>R9,_parse:()=>z9,_overwrite:()=>e0,_optional:()=>yn,_number:()=>HW,_nullable:()=>gn,_null:()=>IW,_normalize:()=>g9,_nonpositive:()=>r3,_nonoptional:()=>hn,_nonnegative:()=>n3,_never:()=>vW,_negative:()=>i3,_nativeEnum:()=>vn,_nanoid:()=>I3,_nan:()=>gW,_multipleOf:()=>t2,_minSize:()=>A1,_minLength:()=>s1,_min:()=>l6,_mime:()=>y9,_maxSize:()=>s2,_maxLength:()=>V8,_max:()=>f0,_map:()=>In,_mac:()=>ZW,_lte:()=>f0,_lt:()=>z1,_lowercase:()=>S9,_literal:()=>Cn,_length:()=>X8,_lazy:()=>rn,_ksuid:()=>b3,_jwt:()=>d3,_isoTime:()=>WW,_isoDuration:()=>qW,_isoDateTime:()=>NW,_isoDate:()=>FW,_ipv6:()=>g3,_ipv4:()=>y3,_intersection:()=>wn,_int64:()=>AW,_int32:()=>EW,_int:()=>OW,_includes:()=>v9,_guid:()=>R5,_gte:()=>l6,_gt:()=>R1,_float64:()=>DW,_float32:()=>jW,_file:()=>hW,_enum:()=>Tn,_endsWith:()=>b9,_encodeAsync:()=>Q3,_encode:()=>U3,_emoji:()=>k3,_email:()=>z3,_e164:()=>c3,_discriminatedUnion:()=>An,_default:()=>xn,_decodeAsync:()=>G3,_decode:()=>_3,_date:()=>bW,_custom:()=>uW,_cuid2:()=>T3,_cuid:()=>S3,_coercedString:()=>YW,_coercedNumber:()=>BW,_coercedDate:()=>yW,_coercedBoolean:()=>LW,_coercedBigint:()=>RW,_cidrv6:()=>h3,_cidrv4:()=>x3,_check:()=>jA,_catch:()=>mn,_boolean:()=>MW,_bigint:()=>zW,_base64url:()=>m3,_base64:()=>u3,_array:()=>xW,_any:()=>SW,TimePrecision:()=>KW,NEVER:()=>pZ,JSONSchemaGenerator:()=>Iq,JSONSchema:()=>DA,Doc:()=>W3,$output:()=>QW,$input:()=>GW,$constructor:()=>u,$brand:()=>aZ,$ZodXor:()=>mN,$ZodXID:()=>FN,$ZodVoid:()=>gN,$ZodUnknown:()=>bN,$ZodUnion:()=>j5,$ZodUndefined:()=>TN,$ZodUUID:()=>QN,$ZodURL:()=>VN,$ZodULID:()=>NN,$ZodType:()=>e$,$ZodTuple:()=>P3,$ZodTransform:()=>oN,$ZodTemplateLiteral:()=>XF,$ZodSymbol:()=>SN,$ZodSuccess:()=>UF,$ZodStringFormat:()=>T4,$ZodString:()=>Q8,$ZodSet:()=>rN,$ZodRegistry:()=>VW,$ZodRecord:()=>lN,$ZodRealError:()=>Y0,$ZodReadonly:()=>VF,$ZodPromise:()=>ZF,$ZodPrefault:()=>$F,$ZodPipe:()=>GF,$ZodOptional:()=>M3,$ZodObjectJIT:()=>uN,$ZodObject:()=>FA,$ZodNumberFormat:()=>kN,$ZodNumber:()=>D3,$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:()=>N5,$ZodEnum:()=>nN,$ZodEncodeError:()=>J8,$ZodEmoji:()=>XN,$ZodEmail:()=>GN,$ZodE164:()=>AN,$ZodDiscriminatedUnion:()=>cN,$ZodDefault:()=>eN,$ZodDate:()=>xN,$ZodCustomStringFormat:()=>fN,$ZodCustom:()=>NF,$ZodCodec:()=>D5,$ZodCheckUpperCase:()=>pK,$ZodCheckStringFormat:()=>f9,$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:()=>N3,$ZodCheckLengthEquals:()=>iK,$ZodCheckIncludes:()=>aK,$ZodCheckGreaterThan:()=>F3,$ZodCheckEndsWith:()=>tK,$ZodCheckBigIntFormat:()=>hK,$ZodCheck:()=>x4,$ZodCatch:()=>_F,$ZodCUID2:()=>KN,$ZodCUID:()=>ZN,$ZodCIDRv6:()=>MN,$ZodCIDRv4:()=>PN,$ZodBoolean:()=>O5,$ZodBigIntFormat:()=>IN,$ZodBigInt:()=>E3,$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 J8 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}var Q5={};function Y6($){if($)Object.assign(Q5,$);return Q5}var B$={};O0(B$,{unwrapMessage:()=>G5,uint8ArrayToHex:()=>ri,uint8ArrayToBase64url:()=>li,uint8ArrayToBase64:()=>mR,stringifyPrimitive:()=>W$,slugify:()=>sZ,shallowClone:()=>$K,safeExtend:()=>xi,required:()=>mi,randomString:()=>Si,propertyKeyTypes:()=>Y5,promiseAllObject:()=>Ii,primitiveTypes:()=>JK,prefixIssues:()=>w0,pick:()=>bi,partial:()=>ui,parsedType:()=>H$,optionalKeys:()=>UK,omit:()=>yi,objectClone:()=>wi,numKeys:()=>Ti,nullish:()=>n2,normalizeParams:()=>O$,mergeDefs:()=>t1,merge:()=>hi,jsonStringifyReplacer:()=>P9,joinValues:()=>o,issue:()=>L9,isPlainObject:()=>a2,isObject:()=>U8,hexToUint8Array:()=>ii,getSizableOrigin:()=>Z5,getParsedType:()=>vi,getLengthableOrigin:()=>K5,getEnumValues:()=>V5,getElementAtPath:()=>ki,floatSafeRemainder:()=>tZ,finalizeIssue:()=>X0,extend:()=>gi,escapeRegex:()=>x0,esc:()=>sQ,defineLazy:()=>B4,createTransparentProxy:()=>Ci,cloneDef:()=>fi,clone:()=>d6,cleanRegex:()=>X5,cleanEnum:()=>ci,captureStackTrace:()=>eQ,cached:()=>M9,base64urlToUint8Array:()=>di,base64ToUint8Array:()=>uR,assignProp:()=>p2,assertNotEqual:()=>Li,assertNever:()=>Ri,assertIs:()=>zi,assertEqual:()=>Mi,assert:()=>Ai,allowsEval:()=>eZ,aborted:()=>o2,NUMBER_FORMAT_RANGES:()=>_K,Class:()=>cR,BIGINT_FORMAT_RANGES:()=>QK});function Mi($){return $}function Li($){return $}function zi($){}function Ri($){throw Error("Unexpected value in exhaustive check")}function Ai($){}function V5($){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 P9($,J){if(typeof J==="bigint")return J.toString();return J}function M9($){return{get value(){{let U=$();return Object.defineProperty(this,"value",{value:U}),U}throw Error("cached value already set")}}}function n2($){return $===null||$===void 0}function X5($){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 hR=Symbol("evaluating");function B4($,J,U){let Q=void 0;Object.defineProperty($,J,{get(){if(Q===hR)return;if(Q===void 0)Q=hR,Q=U();return Q},set(_){Object.defineProperty($,J,{value:_})},configurable:!0})}function wi($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function p2($,J,U){Object.defineProperty($,J,{value:U,writable:!0,enumerable:!0,configurable:!0})}function t1(...$){let J={};for(let U of $){let Q=Object.getOwnPropertyDescriptors(U);Object.assign(J,Q)}return Object.defineProperties({},J)}function fi($){return t1($._zod.def)}function ki($,J){if(!J)return $;return J.reduce((U,Q)=>U?.[Q],$)}function Ii($){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 Si($=10){let U="";for(let Q=0;Q<$;Q++)U+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return U}function sQ($){return JSON.stringify($)}function sZ($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var eQ="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function U8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var eZ=M9(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function a2($){if(U8($)===!1)return!1;let J=$.constructor;if(J===void 0)return!0;if(typeof J!=="function")return!0;let U=J.prototype;if(U8(U)===!1)return!1;if(Object.prototype.hasOwnProperty.call(U,"isPrototypeOf")===!1)return!1;return!0}function $K($){if(a2($))return{...$};if(Array.isArray($))return[...$];return $}function Ti($){let J=0;for(let U in $)if(Object.prototype.hasOwnProperty.call($,U))J++;return J}var vi=($)=>{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}`)}},Y5=new Set(["string","number","symbol"]),JK=new Set(["string","number","bigint","boolean","symbol","undefined"]);function x0($){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 Ci($){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 bi($,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=t1($._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 p2(this,"shape",V),V},checks:[]});return d6($,G)}function yi($,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=t1($._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 p2(this,"shape",V),V},checks:[]});return d6($,G)}function gi($,J){if(!a2(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 _=t1($._zod.def,{get shape(){let G={...$._zod.def.shape,...J};return p2(this,"shape",G),G}});return d6($,_)}function xi($,J){if(!a2(J))throw Error("Invalid input to safeExtend: expected a plain object");let U=t1($._zod.def,{get shape(){let Q={...$._zod.def.shape,...J};return p2(this,"shape",Q),Q}});return d6($,U)}function hi($,J){let U=t1($._zod.def,{get shape(){let Q={...$._zod.def.shape,...J._zod.def.shape};return p2(this,"shape",Q),Q},get catchall(){return J._zod.def.catchall},checks:[]});return d6($,U)}function ui($,J,U){let _=J._zod.def.checks;if(_&&_.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let V=t1(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 p2(this,"shape",Z),Z},checks:[]});return d6(J,V)}function mi($,J,U){let Q=t1(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 p2(this,"shape",G),G}});return d6(J,Q)}function o2($,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 w0($,J){return J.map((U)=>{var Q;return(Q=U).path??(Q.path=[]),U.path.unshift($),U})}function G5($){return typeof $==="string"?$:$?.message}function X0($,J,U){let Q={...$,path:$.path??[]};if(!$.message){let _=G5($.inst?._zod.def?.error?.($))??G5(J?.error?.($))??G5(U.customError?.($))??G5(U.localeError?.($))??"Invalid input";Q.message=_}if(delete Q.inst,delete Q.continue,!J?.reportInput)delete Q.input;return Q}function Z5($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function K5($){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 L9(...$){let[J,U,Q]=$;if(typeof J==="string")return{message:J,code:"custom",input:U,inst:Q};return{...J}}function ci($){return Object.entries($).filter(([J,U])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function uR($){let J=atob($),U=new Uint8Array(J.length);for(let Q=0;Q<J.length;Q++)U[Q]=J.charCodeAt(Q);return U}function mR($){let J="";for(let U=0;U<$.length;U++)J+=String.fromCharCode($[U]);return btoa(J)}function di($){let J=$.replace(/-/g,"+").replace(/_/g,"/"),U="=".repeat((4-J.length%4)%4);return uR(J+U)}function li($){return mR($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ii($){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 ri($){return Array.from($).map((J)=>J.toString(16).padStart(2,"0")).join("")}class cR{constructor(...$){}}var dR=($,J)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:J,enumerable:!1}),$.message=JSON.stringify(J,P9,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},N5=u("$ZodError",dR),Y0=u("$ZodError",dR,{Parent:Error});function F5($,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 W5($,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 lR($){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 ${lR(Q.path)}`);return J.join(`
|
|
619
|
-
`)}var z9=($)=>(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 eQ(X,_?.callee),X}return V.value},$3=z9(Y0),R9=($)=>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 eQ(X,_?.callee),X}return V.value},J3=R9(Y0),A9=($)=>(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($??N5)(G.issues.map((V)=>X0(V,_,Y6())))}:{success:!0,data:G.value}},XK=A9(Y0),w9=($)=>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=w9(Y0),U3=($)=>(J,U,Q)=>{let _=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return z9($)(J,U,_)},pi=U3(Y0),_3=($)=>(J,U,Q)=>{return z9($)(J,U,Q)},ai=_3(Y0),Q3=($)=>async(J,U,Q)=>{let _=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return R9($)(J,U,_)},oi=Q3(Y0),G3=($)=>async(J,U,Q)=>{return R9($)(J,U,Q)},ti=G3(Y0),V3=($)=>(J,U,Q)=>{let _=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return A9($)(J,U,_)},si=V3(Y0),X3=($)=>(J,U,Q)=>{return A9($)(J,U,Q)},ei=X3(Y0),Y3=($)=>async(J,U,Q)=>{let _=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return w9($)(J,U,_)},$r=Y3(Y0),Z3=($)=>async(J,U,Q)=>{return w9($)(J,U,Q)},Jr=Z3(Y0);var h0={};O0(h0,{xid:()=>FK,uuid7:()=>Gr,uuid6:()=>Qr,uuid4:()=>_r,uuid:()=>_8,uppercase:()=>yK,unicodeEmail:()=>iR,undefined:()=>CK,ulid:()=>NK,time:()=>wK,string:()=>kK,sha512_hex:()=>Ar,sha512_base64url:()=>fr,sha512_base64:()=>wr,sha384_hex:()=>Lr,sha384_base64url:()=>Rr,sha384_base64:()=>zr,sha256_hex:()=>Er,sha256_base64url:()=>Mr,sha256_base64:()=>Pr,sha1_hex:()=>Or,sha1_base64url:()=>Dr,sha1_base64:()=>jr,rfc5322Email:()=>Xr,number:()=>q5,null:()=>vK,nanoid:()=>qK,md5_hex:()=>qr,md5_base64url:()=>Br,md5_base64:()=>Hr,mac:()=>PK,lowercase:()=>bK,ksuid:()=>WK,ipv6:()=>EK,ipv4:()=>DK,integer:()=>SK,idnEmail:()=>Yr,html5Email:()=>Vr,hostname:()=>Nr,hex:()=>Wr,guid:()=>BK,extendedDuration:()=>Ur,emoji:()=>jK,email:()=>OK,e164:()=>RK,duration:()=>HK,domain:()=>Fr,datetime:()=>fK,date:()=>AK,cuid2:()=>KK,cuid:()=>ZK,cidrv6:()=>LK,cidrv4:()=>MK,browserEmail:()=>Zr,boolean:()=>TK,bigint:()=>IK,base64url:()=>K3,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)?)?)$/,Ur=/^[-+]?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})$/,_8=($)=>{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})$`)},_r=_8(4),Qr=_8(6),Gr=_8(7),OK=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Vr=/^[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])?)*$/,Xr=/^(([^<>()\[\]\\.,;:\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,}))$/,iR=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Yr=iR,Zr=/^[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])?)*$/,Kr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jK(){return new RegExp(Kr,"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=x0($??":");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}=))?$/,K3=/^[A-Za-z0-9_-]*$/,Nr=/^(?=.{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])?)*\.?$/,Fr=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,RK=/^\+[1-9]\d{6,14}$/,rR="(?:(?:\\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(`^${rR}$`);function nR($){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(`^${nR($)}$`)}function fK($){let J=nR({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(`^${rR}T(?:${Q})$`)}var kK=($)=>{let J=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)},IK=/^-?\d+n?$/,SK=/^-?\d+$/,q5=/^-?\d+(?:\.\d+)?$/,TK=/^(?:true|false)$/i,vK=/^null$/i;var CK=/^undefined$/i;var bK=/^[^A-Z]*$/,yK=/^[^a-z]*$/,Wr=/^[0-9a-fA-F]*$/;function H5($,J){return new RegExp(`^[A-Za-z0-9+/]{${$}}${J}$`)}function B5($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var qr=/^[0-9a-fA-F]{32}$/,Hr=H5(22,"=="),Br=B5(22),Or=/^[0-9a-fA-F]{40}$/,jr=H5(27,"="),Dr=B5(27),Er=/^[0-9a-fA-F]{64}$/,Pr=H5(43,"="),Mr=B5(43),Lr=/^[0-9a-fA-F]{96}$/,zr=H5(64,""),Rr=B5(64),Ar=/^[0-9a-fA-F]{128}$/,wr=H5(86,"=="),fr=B5(86);var x4=u("$ZodCheck",($,J)=>{var U;$._zod??($._zod={}),$._zod.def=J,(U=$._zod).onattach??(U.onattach=[])}),aR={number:"number",bigint:"bigint",object:"date"},N3=u("$ZodCheckLessThan",($,J)=>{x4.init($,J);let U=aR[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})}}),F3=u("$ZodCheckGreaterThan",($,J)=>{x4.init($,J);let U=aR[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!n2(_)&&_.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:Z5(_),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!n2(_)&&_.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:Z5(_),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!n2(_)&&_.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:Z5(_),...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!n2(_)&&_.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=K5(_);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!n2(_)&&_.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=K5(_);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!n2(_)&&_.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=K5(_),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})}}),f9=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)=>{f9.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),f9.init($,J)}),pK=u("$ZodCheckUpperCase",($,J)=>{J.pattern??(J.pattern=yK),f9.init($,J)}),aK=u("$ZodCheckIncludes",($,J)=>{x4.init($,J);let U=x0(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(`^${x0(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(`.*${x0(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 pR($,J,U){if($.issues.length)J.issues.push(...w0(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((_)=>pR(_,U,J.property));pR(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 W3{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(`
|
|
620
|
-
`).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(`
|
|
621
|
-
`))}}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=o2(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=o2(V,N)});else{if(V.issues.length===N)continue;if(!Y)Y=o2(V,N)}}if(K)return K.then(()=>{return V});return V},G=(V,X,Z)=>{if(o2(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}))}),Q8=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)=>{f9.init($,J),Q8.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=_8(Q))}else J.pattern??(J.pattern=_8());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 YA($){if(!K3.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=K3),T4.init($,J),$._zod.bag.contentEncoding="base64url",$._zod.check=(U)=>{if(YA(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 ZA($,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(ZA(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})}}),D3=u("$ZodNumber",($,J)=>{e$.init($,J),$._zod.pattern=$._zod.bag.pattern??q5,$._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),D3.init($,J)}),O5=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}}),E3=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),E3.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 tR($,J,U){if($.issues.length)J.issues.push(...w0(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)=>tR(Y,U,V)));else tR(Z,U,V)}if(G.length)return Promise.all(G).then(()=>U);return U}});function j3($,J,U,Q,_){if($.issues.length){if(_&&!(U in Q))return;J.issues.push(...w0(U,$.issues))}if($.value===void 0){if(U in Q)J.value[U]=void 0}else J.value[U]=$.value}function KA($){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 NA($,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)=>j3(q,U,F,J,K)));else j3(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 FA=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=M9(()=>KA(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 _=U8,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((j)=>j3(j,X,N,Y,H)));else j3(E,X,N,Y,H)}if(!G)return K.length?Promise.all(K).then(()=>X):X;return NA(K,Y,X,Z,Q.value,$)}}),uN=u("$ZodObjectJIT",($,J)=>{FA.init($,J);let U=$._zod.parse,Q=M9(()=>KA(J)),_=(N)=>{let q=new W3(["shape","payload","ctx"]),H=Q.value,E=(w)=>{let A=sQ(w);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};q.write("const input = payload.value;");let j=Object.create(null),B=0;for(let w of H.keys)j[w]=`key_${B++}`;q.write("const newResult = {};");for(let w of H.keys){let A=j[w],I=sQ(w),T=N[w]?._zod?.optout==="optional";if(q.write(`const ${A} = ${E(w)};`),T)q.write(`
|
|
622
|
-
if (${A}.issues.length) {
|
|
623
|
-
if (${I} in input) {
|
|
624
|
-
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
|
|
625
|
-
...iss,
|
|
626
|
-
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
627
|
-
})));
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
if (${A}.value === undefined) {
|
|
632
|
-
if (${I} in input) {
|
|
633
|
-
newResult[${I}] = undefined;
|
|
634
|
-
}
|
|
635
|
-
} else {
|
|
636
|
-
newResult[${I}] = ${A}.value;
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
`);else q.write(`
|
|
640
|
-
if (${A}.issues.length) {
|
|
641
|
-
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
|
|
642
|
-
...iss,
|
|
643
|
-
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
644
|
-
})));
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
if (${A}.value === undefined) {
|
|
648
|
-
if (${I} in input) {
|
|
649
|
-
newResult[${I}] = undefined;
|
|
650
|
-
}
|
|
651
|
-
} else {
|
|
652
|
-
newResult[${I}] = ${A}.value;
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
`)}q.write("payload.value = newResult;"),q.write("return payload;");let D=q.compile();return(w,A)=>D(N,w,A)},G,V=U8,X=!Q5.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 NA([],H,N,q,F,$)}return U(N,q)}});function sR($,J,U,Q){for(let G of $)if(G.issues.length===0)return J.value=G.value,J;let _=$.filter((G)=>!o2(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 j5=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)=>X5(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 sR(X,_,$,G);return Promise.all(X).then((Z)=>{return sR(Z,_,$,G)})}});function eR($,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)=>{j5.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 eR(X,_,$,G);return Promise.all(X).then((Z)=>{return eR(Z,_,$,G)})}}),cN=u("$ZodDiscriminatedUnion",($,J)=>{J.inclusive=!1,j5.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=M9(()=>{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(!U8(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 $A(U,Z,Y)});return $A(U,G,V)}});function UN($,J){if($===J)return{valid:!0,data:$};if($ instanceof Date&&J instanceof Date&&+$===+J)return{valid:!0,data:$};if(a2($)&&a2(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 $A($,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(o2($))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 P3=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)=>q3(N,Q,Y)));else q3(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)=>q3(q,Q,Y)));else q3(N,Q,Y)}}if(V.length)return Promise.all(V).then(()=>Q);return Q}});function q3($,J,U){if($.issues.length)J.issues.push(...w0(U,$.issues));J.value[U]=$.value}var lN=u("$ZodRecord",($,J)=>{e$.init($,J),$._zod.parse=(U,Q)=>{let _=U.value;if(!a2(_))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(...w0(Y,F.issues));U.value[Y]=F.value}));else{if(K.issues.length)U.issues.push(...w0(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"&&q5.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(...w0(X,F.issues));U.value[Z.value]=F.value}));else{if(K.issues.length)U.issues.push(...w0(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])=>{JA(K,F,U,V,_,$,Q)}));else JA(Z,Y,U,V,_,$,Q)}if(G.length)return Promise.all(G).then(()=>U);return U}});function JA($,J,U,Q,_,G,V){if($.issues.length)if(Y5.has(typeof Q))U.issues.push(...w0(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(Y5.has(typeof Q))U.issues.push(...w0(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)=>UA(Z,U)));else UA(X,U)}if(G.length)return Promise.all(G).then(()=>U);return U}});function UA($,J){if($.issues.length)J.issues.push(...$.issues);J.value.add($.value)}var nN=u("$ZodEnum",($,J)=>{e$.init($,J);let U=V5(J.entries),Q=new Set(U);$._zod.values=Q,$._zod.pattern=new RegExp(`^(${U.filter((_)=>Y5.has(typeof _)).map((_)=>typeof _==="string"?x0(_):_.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"?x0(Q):Q?x0(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 J8($.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 _A($,J){if($.issues.length&&J===void 0)return{issues:[],value:void 0};return $}var M3=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(`^(${X5(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)=>_A(G,U.value));return _A(_,U.value)}if(U.value===void 0)return U;return J.innerType._zod.run(U,Q)}}),tN=u("$ZodExactOptional",($,J)=>{M3.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(`^(${X5(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)=>QA(G,J));return QA(_,J)}});function QA($,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)=>GA(G,$));return GA(_,$)}});function GA($,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 J8("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)=>H3(V,J.in,Q));return H3(G,J.in,Q)}let _=J.in._zod.run(U,Q);if(_ instanceof Promise)return _.then((G)=>H3(G,J.out,Q));return H3(_,J.out,Q)}});function H3($,J,U){if($.issues.length)return $.aborted=!0,$;return J._zod.run({value:$.value,issues:$.issues},U)}var D5=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)=>B3(V,J,Q));return B3(G,J,Q)}else{let G=J.out._zod.run(U,Q);if(G instanceof Promise)return G.then((V)=>B3(V,J,Q));return B3(G,J,Q)}}});function B3($,J,U){if($.issues.length)return $.aborted=!0,$;if((U.direction||"forward")==="forward"){let _=J.transform($.value,$);if(_ instanceof Promise)return _.then((G)=>O3($,G,J.out,U));return O3($,_,J.out,U)}else{let _=J.reverseTransform($.value,$);if(_ instanceof Promise)return _.then((G)=>O3($,G,J.in,U));return O3($,_,J.in,U)}}function O3($,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(VA);return VA(_)}});function VA($){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(x0(`${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?$3($._def.input,Q):Q,G=Reflect.apply(U,this,_);if($._def.output)return $3($._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 J3($._def.input,Q):Q,G=await Reflect.apply(U,this,_);if($._def.output)return await J3($._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 P3({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)=>XA(G,U,Q,$));XA(_,U,Q,$);return}});function XA($,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(L9(_))}}var z5={};O0(z5,{zhTW:()=>UW,zhCN:()=>JW,yo:()=>_W,vi:()=>$W,uz:()=>eF,ur:()=>sF,uk:()=>L5,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:()=>P5,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:()=>E5,de:()=>DF,da:()=>jF,cs:()=>OF,ca:()=>BF,bg:()=>HF,be:()=>qF,az:()=>WF,ar:()=>FF});var Ir=()=>{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:Ir()}}var Sr=()=>{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:Sr()}}function WA($,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 Tr=()=>{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=WA(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=WA(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:Tr()}}var vr=()=>{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:vr()}}var Cr=()=>{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:Cr()}}var br=()=>{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:br()}}var yr=()=>{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:yr()}}var gr=()=>{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:gr()}}var xr=()=>{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 E5(){return{localeError:xr()}}var hr=()=>{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:hr()}}var ur=()=>{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:ur()}}var mr=()=>{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:mr()}}var cr=()=>{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:cr()}}var dr=()=>{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:dr()}}var lr=()=>{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:lr()}}var ir=()=>{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 j=Y.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${F} ${H} להכיל ${j}`}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:ir()}}var rr=()=>{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:rr()}}function qA($,J,U){return Math.abs($)===1?J:U}function k9($){if(!$)return"";let J=["ա","ե","ը","ի","ո","ու","օ"],U=$[$.length-1];return $+(J.includes(U)?"ն":"ը")}var nr=()=>{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=qA(X,V.unit.one,V.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${k9(_.origin??"արժեք")} կունենա ${G}${_.maximum.toString()} ${Z}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${k9(_.origin??"արժեք")} լինի ${G}${_.maximum.toString()}`}case"too_small":{let G=_.inclusive?">=":">",V=J(_.origin);if(V){let X=Number(_.minimum),Z=qA(X,V.unit.one,V.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${k9(_.origin)} կունենա ${G}${_.minimum.toString()} ${Z}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${k9(_.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`Սխալ բանալի ${k9(_.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${k9(_.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function fF(){return{localeError:nr()}}var pr=()=>{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:pr()}}var ar=()=>{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:ar()}}var or=()=>{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:or()}}var tr=()=>{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:tr()}}var sr=()=>{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:sr()}}var er=()=>{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 P5(){return{localeError:er()}}function CF(){return P5()}var $n=()=>{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:$n()}}var M5=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function HA($){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 Jn=()=>{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,HA(Number(_.maximum)),_.inclusive??!1,"smaller");if(V?.verb)return`${M5(G??_.origin??"reikšmė")} ${V.verb} ${_.maximum.toString()} ${V.unit??"elementų"}`;let X=_.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${M5(G??_.origin??"reikšmė")} turi būti ${X} ${_.maximum.toString()} ${V?.unit}`}case"too_small":{let G=Q[_.origin]??_.origin,V=J(_.origin,HA(Number(_.minimum)),_.inclusive??!1,"bigger");if(V?.verb)return`${M5(G??_.origin??"reikšmė")} ${V.verb} ${_.minimum.toString()} ${V.unit??"elementų"}`;let X=_.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${M5(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`${M5(G??_.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function yF(){return{localeError:Jn()}}var Un=()=>{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:Un()}}var _n=()=>{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:_n()}}var Qn=()=>{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:Qn()}}var Gn=()=>{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:Gn()}}var Vn=()=>{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:Vn()}}var Xn=()=>{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:Xn()}}var Yn=()=>{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:Yn()}}var Zn=()=>{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:Zn()}}function BA($,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 Kn=()=>{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=BA(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=BA(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:Kn()}}var Nn=()=>{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:Nn()}}var Fn=()=>{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: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:"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:Wn()}}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:"วันที่เวลาแบบ 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:qn()}}var Hn=()=>{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:Hn()}}var Bn=()=>{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 L5(){return{localeError:Bn()}}function tF(){return L5()}var On=()=>{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:On()}}var jn=()=>{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:jn()}}var Dn=()=>{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: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:"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:En()}}var Pn=()=>{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:Pn()}}var Mn=()=>{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:Mn()}}var OA,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 L3(){return new VW}(OA=globalThis).__zod_globalRegistry??(OA.__zod_globalRegistry=L3());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 z3($,J){return new $({type:"string",format:"email",check:"string_format",abort:!1,...O$(J)})}function R5($,J){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...O$(J)})}function R3($,J){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...O$(J)})}function A3($,J){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...O$(J)})}function w3($,J){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...O$(J)})}function f3($,J){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...O$(J)})}function A5($,J){return new $({type:"string",format:"url",check:"string_format",abort:!1,...O$(J)})}function k3($,J){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...O$(J)})}function I3($,J){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...O$(J)})}function S3($,J){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...O$(J)})}function T3($,J){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...O$(J)})}function v3($,J){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...O$(J)})}function C3($,J){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...O$(J)})}function b3($,J){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...O$(J)})}function y3($,J){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...O$(J)})}function g3($,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 x3($,J){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...O$(J)})}function h3($,J){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...O$(J)})}function u3($,J){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...O$(J)})}function m3($,J){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...O$(J)})}function c3($,J){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...O$(J)})}function d3($,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 N3({check:"less_than",...O$(J),value:$,inclusive:!1})}function f0($,J){return new N3({check:"less_than",...O$(J),value:$,inclusive:!0})}function R1($,J){return new F3({check:"greater_than",...O$(J),value:$,inclusive:!1})}function l6($,J){return new F3({check:"greater_than",...O$(J),value:$,inclusive:!0})}function l3($){return R1(0,$)}function i3($){return z1(0,$)}function r3($){return f0(0,$)}function n3($){return l6(0,$)}function t2($,J){return new gK({check:"multiple_of",...O$(J),value:$})}function s2($,J){return new uK({check:"max_size",...O$(J),maximum:$})}function A1($,J){return new mK({check:"min_size",...O$(J),minimum:$})}function G8($,J){return new cK({check:"size_equals",...O$(J),size:$})}function V8($,J){return new dK({check:"max_length",...O$(J),maximum:$})}function s1($,J){return new lK({check:"min_length",...O$(J),minimum:$})}function X8($,J){return new iK({check:"length_equals",...O$(J),length:$})}function I9($,J){return new rK({check:"string_format",format:"regex",...O$(J),pattern:$})}function S9($){return new nK({check:"string_format",format:"lowercase",...O$($)})}function T9($){return new pK({check:"string_format",format:"uppercase",...O$($)})}function v9($,J){return new aK({check:"string_format",format:"includes",...O$(J),includes:$})}function C9($,J){return new oK({check:"string_format",format:"starts_with",...O$(J),prefix:$})}function b9($,J){return new tK({check:"string_format",format:"ends_with",...O$(J),suffix:$})}function p3($,J,U){return new sK({check:"property",property:$,schema:J,...O$(U)})}function y9($,J){return new eK({check:"mime_type",mime:$,...O$(J)})}function e0($){return new $N({check:"overwrite",tx:$})}function g9($){return e0((J)=>J.normalize($))}function x9(){return e0(($)=>$.trim())}function h9(){return e0(($)=>$.toLowerCase())}function u9(){return e0(($)=>$.toUpperCase())}function m9(){return e0(($)=>sZ($))}function xW($,J,U){return new $({type:"array",element:J,...O$(U)})}function zn($,J,U){return new $({type:"union",options:J,...O$(U)})}function Rn($,J,U){return new $({type:"union",options:J,inclusive:!1,...O$(U)})}function An($,J,U,Q){return new $({type:"union",options:U,discriminator:J,...O$(Q)})}function wn($,J,U){return new $({type:"intersection",left:J,right:U})}function fn($,J,U,Q){let _=U instanceof e$;return new $({type:"tuple",items:J,rest:_?U:null,...O$(_?Q:U)})}function kn($,J,U,Q){return new $({type:"record",keyType:J,valueType:U,...O$(Q)})}function In($,J,U,Q){return new $({type:"map",keyType:J,valueType:U,...O$(Q)})}function Sn($,J,U){return new $({type:"set",valueType:J,...O$(U)})}function Tn($,J,U){let Q=Array.isArray(J)?Object.fromEntries(J.map((_)=>[_,_])):J;return new $({type:"enum",entries:Q,...O$(U)})}function vn($,J,U){return new $({type:"enum",entries:J,...O$(U)})}function Cn($,J,U){return new $({type:"literal",values:Array.isArray(J)?J:[J],...O$(U)})}function hW($,J){return new $({type:"file",...O$(J)})}function bn($,J){return new $({type:"transform",transform:J})}function yn($,J){return new $({type:"optional",innerType:J})}function gn($,J){return new $({type:"nullable",innerType:J})}function xn($,J,U){return new $({type:"default",innerType:J,get defaultValue(){return typeof U==="function"?U():$K(U)}})}function hn($,J,U){return new $({type:"nonoptional",innerType:J,...O$(U)})}function un($,J){return new $({type:"success",innerType:J})}function mn($,J,U){return new $({type:"catch",innerType:J,catchValue:typeof U==="function"?U:()=>U})}function cn($,J,U){return new $({type:"pipe",in:J,out:U})}function dn($,J){return new $({type:"readonly",innerType:J})}function ln($,J,U){return new $({type:"template_literal",parts:J,...O$(U)})}function rn($,J){return new $({type:"lazy",getter:J})}function nn($,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=jA((U)=>{return U.addIssue=(Q)=>{if(typeof Q==="string")U.issues.push(L9(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(L9(_))}},$(U.value,U)});return J}function jA($,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??D5,Z=$.Boolean??O5,K=new($.String??Q8)({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 c9($,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 e2($){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 $J($,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>
|
|
656
|
-
|
|
657
|
-
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 JJ($,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:d9(J,"input",$.processors),output:d9(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=e2({...U,processors:J});return k4($,Q),$J(Q,$),JJ(Q,$)},d9=($,J,U={})=>(Q)=>{let{libraryOptions:_,target:G}=Q??{},V=e2({..._??{},target:G,io:J,processors:U});return k4($,V),$J(V,$),JJ(V,$)};var pn={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=pn[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=V5(_.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"]})},o3=($,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},t3=($,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=_},a3={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:o3,intersection:jq,tuple:Dq,record:Eq,nullable:Pq,nonoptional:Mq,default:Lq,prefault:zq,catch:Rq,pipe:Aq,readonly:wq,promise:fq,optional:t3,lazy:kq};function s3($,J){if("_idmap"in $){let Q=$,_=e2({...J,processors:a3}),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;$J(_,K),V[Y]=JJ(_,K)}if(Object.keys(G).length>0){let Z=_.target==="draft-2020-12"?"$defs":"definitions";V.__shared={[Z]:G}}return{schemas:V}}let U=e2({...J,processors:a3});return k4($,U),$J(U,$),JJ(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=e2({processors:a3,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}$J(this.ctx,$);let U=JJ(this.ctx,$),{"~standard":Q,..._}=U;return _}}var DA={};var w5={};O0(w5,{xor:()=>Nw,xid:()=>CA,void:()=>Gw,uuidv7:()=>AA,uuidv6:()=>RA,uuidv4:()=>zA,uuid:()=>LA,url:()=>wA,unknown:()=>Y8,union:()=>RG,undefined:()=>_w,ulid:()=>vA,uint64:()=>Jw,uint32:()=>sA,tuple:()=>KH,transform:()=>wG,templateLiteral:()=>zw,symbol:()=>Uw,superRefine:()=>gH,success:()=>Pw,stringbool:()=>Tw,stringFormat:()=>iA,string:()=>QG,strictObject:()=>Zw,set:()=>Bw,refine:()=>yH,record:()=>NH,readonly:()=>IH,promise:()=>Rw,preprocess:()=>Cw,prefault:()=>LH,pipe:()=>S5,partialRecord:()=>Ww,optional:()=>k5,object:()=>Yw,number:()=>pq,nullish:()=>Ew,nullable:()=>I5,null:()=>eq,nonoptional:()=>zH,never:()=>zG,nativeEnum:()=>Ow,nanoid:()=>IA,nan:()=>Mw,meta:()=>Iw,map:()=>Hw,mac:()=>gA,looseRecord:()=>qw,looseObject:()=>Kw,literal:()=>jw,lazy:()=>vH,ksuid:()=>bA,keyof:()=>Xw,jwt:()=>lA,json:()=>vw,ipv6:()=>xA,ipv4:()=>yA,intersection:()=>YH,int64:()=>$w,int32:()=>tA,int:()=>GG,instanceof:()=>Sw,httpUrl:()=>fA,hostname:()=>rA,hex:()=>nA,hash:()=>pA,guid:()=>MA,function:()=>Aw,float64:()=>oA,float32:()=>aA,file:()=>Dw,exactOptional:()=>jH,enum:()=>AG,emoji:()=>kA,email:()=>PA,e164:()=>dA,discriminatedUnion:()=>Fw,describe:()=>kw,date:()=>Vw,custom:()=>fw,cuid2:()=>TA,cuid:()=>SA,codec:()=>Lw,cidrv6:()=>uA,cidrv4:()=>hA,check:()=>ww,catch:()=>wH,boolean:()=>aq,bigint:()=>eA,base64url:()=>cA,base64:()=>mA,array:()=>C5,any:()=>Qw,_function:()=>Aw,_default:()=>PH,_ZodString:()=>VG,ZodXor:()=>GH,ZodXID:()=>WG,ZodVoid:()=>_H,ZodUnknown:()=>JH,ZodUnion:()=>y5,ZodUndefined:()=>tq,ZodUUID:()=>w1,ZodURL:()=>T5,ZodULID:()=>FG,ZodType:()=>N4,ZodTuple:()=>ZH,ZodTransform:()=>BH,ZodTemplateLiteral:()=>SH,ZodSymbol:()=>oq,ZodSuccess:()=>RH,ZodStringFormat:()=>v4,ZodString:()=>r9,ZodSet:()=>WH,ZodRecord:()=>g5,ZodReadonly:()=>kH,ZodPromise:()=>CH,ZodPrefault:()=>MH,ZodPipe:()=>IG,ZodOptional:()=>fG,ZodObject:()=>b5,ZodNumberFormat:()=>Z8,ZodNumber:()=>p9,ZodNullable:()=>DH,ZodNull:()=>sq,ZodNonOptional:()=>kG,ZodNever:()=>UH,ZodNanoID:()=>ZG,ZodNaN:()=>fH,ZodMap:()=>FH,ZodMAC:()=>nq,ZodLiteral:()=>qH,ZodLazy:()=>TH,ZodKSUID:()=>qG,ZodJWT:()=>MG,ZodIntersection:()=>XH,ZodIPv6:()=>BG,ZodIPv4:()=>HG,ZodGUID:()=>f5,ZodFunction:()=>bH,ZodFile:()=>HH,ZodExactOptional:()=>OH,ZodEnum:()=>i9,ZodEmoji:()=>YG,ZodEmail:()=>XG,ZodE164:()=>PG,ZodDiscriminatedUnion:()=>VH,ZodDefault:()=>EH,ZodDate:()=>v5,ZodCustomStringFormat:()=>n9,ZodCustom:()=>x5,ZodCodec:()=>SG,ZodCatch:()=>AH,ZodCUID2:()=>NG,ZodCUID:()=>KG,ZodCIDRv6:()=>jG,ZodCIDRv4:()=>OG,ZodBoolean:()=>a9,ZodBigIntFormat:()=>LG,ZodBigInt:()=>o9,ZodBase64URL:()=>EG,ZodBase64:()=>DG,ZodArray:()=>QH,ZodAny:()=>$H});var e3={};O0(e3,{uppercase:()=>T9,trim:()=>x9,toUpperCase:()=>u9,toLowerCase:()=>h9,startsWith:()=>C9,slugify:()=>m9,size:()=>G8,regex:()=>I9,property:()=>p3,positive:()=>l3,overwrite:()=>e0,normalize:()=>g9,nonpositive:()=>r3,nonnegative:()=>n3,negative:()=>i3,multipleOf:()=>t2,minSize:()=>A1,minLength:()=>s1,mime:()=>y9,maxSize:()=>s2,maxLength:()=>V8,lte:()=>f0,lt:()=>z1,lowercase:()=>S9,length:()=>X8,includes:()=>v9,gte:()=>l6,gt:()=>R1,endsWith:()=>b9});var l9={};O0(l9,{time:()=>vq,duration:()=>Cq,datetime:()=>Sq,date:()=>Tq,ZodISOTime:()=>UG,ZodISODuration:()=>_G,ZodISODateTime:()=>$G,ZodISODate:()=>JG});var $G=u("ZodISODateTime",($,J)=>{qN.init($,J),v4.init($,J)});function Sq($){return NW($G,$)}var JG=u("ZodISODate",($,J)=>{HN.init($,J),v4.init($,J)});function Tq($){return FW(JG,$)}var UG=u("ZodISOTime",($,J)=>{BN.init($,J),v4.init($,J)});function vq($){return WW(UG,$)}var _G=u("ZodISODuration",($,J)=>{ON.init($,J),v4.init($,J)});function Cq($){return qW(_G,$)}var EA=($,J)=>{N5.init($,J),$.name="ZodError",Object.defineProperties($,{format:{value:(U)=>W5($,U)},flatten:{value:(U)=>F5($,U)},addIssue:{value:(U)=>{$.issues.push(U),$.message=JSON.stringify($.issues,P9,2)}},addIssues:{value:(U)=>{$.issues.push(...U),$.message=JSON.stringify($.issues,P9,2)}},isEmpty:{get(){return $.issues.length===0}}})},on=u("ZodError",EA),Z0=u("ZodError",EA,{Parent:Error});var bq=z9(Z0),yq=R9(Z0),gq=A9(Z0),xq=w9(Z0),hq=U3(Z0),uq=_3(Z0),mq=Q3(Z0),cq=G3(Z0),dq=V3(Z0),lq=X3(Z0),iq=Y3(Z0),rq=Z3(Z0);var N4=u("ZodType",($,J)=>{return e$.init($,J),Object.assign($["~standard"],{jsonSchema:{input:d9($,"input"),output:d9($,"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(e0(U)),$.optional=()=>k5($),$.exactOptional=()=>jH($),$.nullable=()=>I5($),$.nullish=()=>k5(I5($)),$.nonoptional=(U)=>zH($,U),$.array=()=>C5($),$.or=(U)=>RG([$,U]),$.and=(U)=>YH($,U),$.transform=(U)=>S5($,wG(U)),$.default=(U)=>PH($,U),$.prefault=(U)=>LH($,U),$.catch=(U)=>wH($,U),$.pipe=(U)=>S5($,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($),$}),VG=u("_ZodString",($,J)=>{Q8.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(I9(...Q)),$.includes=(...Q)=>$.check(v9(...Q)),$.startsWith=(...Q)=>$.check(C9(...Q)),$.endsWith=(...Q)=>$.check(b9(...Q)),$.min=(...Q)=>$.check(s1(...Q)),$.max=(...Q)=>$.check(V8(...Q)),$.length=(...Q)=>$.check(X8(...Q)),$.nonempty=(...Q)=>$.check(s1(1,...Q)),$.lowercase=(Q)=>$.check(S9(Q)),$.uppercase=(Q)=>$.check(T9(Q)),$.trim=()=>$.check(x9()),$.normalize=(...Q)=>$.check(g9(...Q)),$.toLowerCase=()=>$.check(h9()),$.toUpperCase=()=>$.check(u9()),$.slugify=()=>$.check(m9())}),r9=u("ZodString",($,J)=>{Q8.init($,J),VG.init($,J),$.email=(U)=>$.check(z3(XG,U)),$.url=(U)=>$.check(A5(T5,U)),$.jwt=(U)=>$.check(d3(MG,U)),$.emoji=(U)=>$.check(k3(YG,U)),$.guid=(U)=>$.check(R5(f5,U)),$.uuid=(U)=>$.check(R3(w1,U)),$.uuidv4=(U)=>$.check(A3(w1,U)),$.uuidv6=(U)=>$.check(w3(w1,U)),$.uuidv7=(U)=>$.check(f3(w1,U)),$.nanoid=(U)=>$.check(I3(ZG,U)),$.guid=(U)=>$.check(R5(f5,U)),$.cuid=(U)=>$.check(S3(KG,U)),$.cuid2=(U)=>$.check(T3(NG,U)),$.ulid=(U)=>$.check(v3(FG,U)),$.base64=(U)=>$.check(u3(DG,U)),$.base64url=(U)=>$.check(m3(EG,U)),$.xid=(U)=>$.check(C3(WG,U)),$.ksuid=(U)=>$.check(b3(qG,U)),$.ipv4=(U)=>$.check(y3(HG,U)),$.ipv6=(U)=>$.check(g3(BG,U)),$.cidrv4=(U)=>$.check(x3(OG,U)),$.cidrv6=(U)=>$.check(h3(jG,U)),$.e164=(U)=>$.check(c3(PG,U)),$.datetime=(U)=>$.check(Sq(U)),$.date=(U)=>$.check(Tq(U)),$.time=(U)=>$.check(vq(U)),$.duration=(U)=>$.check(Cq(U))});function QG($){return XW(r9,$)}var v4=u("ZodStringFormat",($,J)=>{T4.init($,J),VG.init($,J)}),XG=u("ZodEmail",($,J)=>{GN.init($,J),v4.init($,J)});function PA($){return z3(XG,$)}var f5=u("ZodGUID",($,J)=>{_N.init($,J),v4.init($,J)});function MA($){return R5(f5,$)}var w1=u("ZodUUID",($,J)=>{QN.init($,J),v4.init($,J)});function LA($){return R3(w1,$)}function zA($){return A3(w1,$)}function RA($){return w3(w1,$)}function AA($){return f3(w1,$)}var T5=u("ZodURL",($,J)=>{VN.init($,J),v4.init($,J)});function wA($){return A5(T5,$)}function fA($){return A5(T5,{protocol:/^https?$/,hostname:h0.domain,...B$.normalizeParams($)})}var YG=u("ZodEmoji",($,J)=>{XN.init($,J),v4.init($,J)});function kA($){return k3(YG,$)}var ZG=u("ZodNanoID",($,J)=>{YN.init($,J),v4.init($,J)});function IA($){return I3(ZG,$)}var KG=u("ZodCUID",($,J)=>{ZN.init($,J),v4.init($,J)});function SA($){return S3(KG,$)}var NG=u("ZodCUID2",($,J)=>{KN.init($,J),v4.init($,J)});function TA($){return T3(NG,$)}var FG=u("ZodULID",($,J)=>{NN.init($,J),v4.init($,J)});function vA($){return v3(FG,$)}var WG=u("ZodXID",($,J)=>{FN.init($,J),v4.init($,J)});function CA($){return C3(WG,$)}var qG=u("ZodKSUID",($,J)=>{WN.init($,J),v4.init($,J)});function bA($){return b3(qG,$)}var HG=u("ZodIPv4",($,J)=>{jN.init($,J),v4.init($,J)});function yA($){return y3(HG,$)}var nq=u("ZodMAC",($,J)=>{EN.init($,J),v4.init($,J)});function gA($){return ZW(nq,$)}var BG=u("ZodIPv6",($,J)=>{DN.init($,J),v4.init($,J)});function xA($){return g3(BG,$)}var OG=u("ZodCIDRv4",($,J)=>{PN.init($,J),v4.init($,J)});function hA($){return x3(OG,$)}var jG=u("ZodCIDRv6",($,J)=>{MN.init($,J),v4.init($,J)});function uA($){return h3(jG,$)}var DG=u("ZodBase64",($,J)=>{zN.init($,J),v4.init($,J)});function mA($){return u3(DG,$)}var EG=u("ZodBase64URL",($,J)=>{RN.init($,J),v4.init($,J)});function cA($){return m3(EG,$)}var PG=u("ZodE164",($,J)=>{AN.init($,J),v4.init($,J)});function dA($){return c3(PG,$)}var MG=u("ZodJWT",($,J)=>{wN.init($,J),v4.init($,J)});function lA($){return d3(MG,$)}var n9=u("ZodCustomStringFormat",($,J)=>{fN.init($,J),v4.init($,J)});function iA($,J,U={}){return c9(n9,$,J,U)}function rA($){return c9(n9,"hostname",h0.hostname,$)}function nA($){return c9(n9,"hex",h0.hex,$)}function pA($,J){let U=J?.enc??"hex",Q=`${$}_${U}`,_=h0[Q];if(!_)throw Error(`Unrecognized hash format: ${Q}`);return c9(n9,Q,_,J)}var p9=u("ZodNumber",($,J)=>{D3.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(f0(Q,_)),$.max=(Q,_)=>$.check(f0(Q,_)),$.int=(Q)=>$.check(GG(Q)),$.safe=(Q)=>$.check(GG(Q)),$.positive=(Q)=>$.check(R1(0,Q)),$.nonnegative=(Q)=>$.check(l6(0,Q)),$.negative=(Q)=>$.check(z1(0,Q)),$.nonpositive=(Q)=>$.check(f0(0,Q)),$.multipleOf=(Q,_)=>$.check(t2(Q,_)),$.step=(Q,_)=>$.check(t2(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(p9,$)}var Z8=u("ZodNumberFormat",($,J)=>{kN.init($,J),p9.init($,J)});function GG($){return OW(Z8,$)}function aA($){return jW(Z8,$)}function oA($){return DW(Z8,$)}function tA($){return EW(Z8,$)}function sA($){return PW(Z8,$)}var a9=u("ZodBoolean",($,J)=>{O5.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>aW($,U,Q,_)});function aq($){return MW(a9,$)}var o9=u("ZodBigInt",($,J)=>{E3.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(f0(Q,_)),$.max=(Q,_)=>$.check(f0(Q,_)),$.positive=(Q)=>$.check(R1(BigInt(0),Q)),$.negative=(Q)=>$.check(z1(BigInt(0),Q)),$.nonpositive=(Q)=>$.check(f0(BigInt(0),Q)),$.nonnegative=(Q)=>$.check(l6(BigInt(0),Q)),$.multipleOf=(Q,_)=>$.check(t2(Q,_));let U=$._zod.bag;$.minValue=U.minimum??null,$.maxValue=U.maximum??null,$.format=U.format??null});function eA($){return zW(o9,$)}var LG=u("ZodBigIntFormat",($,J)=>{IN.init($,J),o9.init($,J)});function $w($){return AW(LG,$)}function Jw($){return wW(LG,$)}var oq=u("ZodSymbol",($,J)=>{SN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>tW($,U,Q,_)});function Uw($){return fW(oq,$)}var tq=u("ZodUndefined",($,J)=>{TN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>eW($,U,Q,_)});function _w($){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 Qw(){return SW($H)}var JH=u("ZodUnknown",($,J)=>{bN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>_q($,U,Q,_)});function Y8(){return TW(JH)}var UH=u("ZodNever",($,J)=>{yN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Jq($,U,Q,_)});function zG($){return vW(UH,$)}var _H=u("ZodVoid",($,J)=>{gN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>$q($,U,Q,_)});function Gw($){return CW(_H,$)}var v5=u("ZodDate",($,J)=>{xN.init($,J),N4.init($,J),$._zod.processJSONSchema=(Q,_,G)=>Qq($,Q,_,G),$.min=(Q,_)=>$.check(l6(Q,_)),$.max=(Q,_)=>$.check(f0(Q,_));let U=$._zod.bag;$.minDate=U.minimum?new Date(U.minimum):null,$.maxDate=U.maximum?new Date(U.maximum):null});function Vw($){return bW(v5,$)}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(s1(U,Q)),$.nonempty=(U)=>$.check(s1(1,U)),$.max=(U,Q)=>$.check(V8(U,Q)),$.length=(U,Q)=>$.check(X8(U,Q)),$.unwrap=()=>$.element});function C5($,J){return xW(QH,$,J)}function Xw($){let J=$._zod.def.shape;return AG(Object.keys(J))}var b5=u("ZodObject",($,J)=>{uN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Oq($,U,Q,_),B$.defineLazy($,"shape",()=>{return J.shape}),$.keyof=()=>AG(Object.keys($._zod.def.shape)),$.catchall=(U)=>$.clone({...$._zod.def,catchall:U}),$.passthrough=()=>$.clone({...$._zod.def,catchall:Y8()}),$.loose=()=>$.clone({...$._zod.def,catchall:Y8()}),$.strict=()=>$.clone({...$._zod.def,catchall:zG()}),$.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(fG,$,U[0]),$.required=(...U)=>B$.required(kG,$,U[0])});function Yw($,J){let U={type:"object",shape:$??{},...B$.normalizeParams(J)};return new b5(U)}function Zw($,J){return new b5({type:"object",shape:$,catchall:zG(),...B$.normalizeParams(J)})}function Kw($,J){return new b5({type:"object",shape:$,catchall:Y8(),...B$.normalizeParams(J)})}var y5=u("ZodUnion",($,J)=>{j5.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>o3($,U,Q,_),$.options=J.options});function RG($,J){return new y5({type:"union",options:$,...B$.normalizeParams(J)})}var GH=u("ZodXor",($,J)=>{y5.init($,J),mN.init($,J),$._zod.processJSONSchema=(U,Q,_)=>o3($,U,Q,_),$.options=J.options});function Nw($,J){return new GH({type:"union",options:$,inclusive:!1,...B$.normalizeParams(J)})}var VH=u("ZodDiscriminatedUnion",($,J)=>{y5.init($,J),cN.init($,J)});function Fw($,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)=>{P3.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 g5=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 g5({type:"record",keyType:$,valueType:J,...B$.normalizeParams(U)})}function Ww($,J,U){let Q=d6($);return Q._zod.values=void 0,new g5({type:"record",keyType:Q,valueType:J,...B$.normalizeParams(U)})}function qw($,J,U){return new g5({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(s2(...U)),$.size=(...U)=>$.check(G8(...U))});function Hw($,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(s2(...U)),$.size=(...U)=>$.check(G8(...U))});function Bw($,J){return new WH({type:"set",valueType:$,...B$.normalizeParams(J)})}var i9=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 i9({...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 i9({...J,checks:[],...B$.normalizeParams(_),entries:G})}});function AG($,J){let U=Array.isArray($)?Object.fromEntries($.map((Q)=>[Q,Q])):$;return new i9({type:"enum",entries:U,...B$.normalizeParams(J)})}function Ow($,J){return new i9({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 jw($,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(s2(U,Q)),$.mime=(U,Q)=>$.check(y9(Array.isArray(U)?U:[U],Q))});function Dw($){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 J8($.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 wG($){return new BH({type:"transform",transform:$})}var fG=u("ZodOptional",($,J)=>{M3.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>t3($,U,Q,_),$.unwrap=()=>$._zod.def.innerType});function k5($){return new fG({type:"optional",innerType:$})}var OH=u("ZodExactOptional",($,J)=>{tN.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>t3($,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 I5($){return new DH({type:"nullable",innerType:$})}function Ew($){return k5(I5($))}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 kG=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 kG({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 Pw($){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 Mw($){return gW(fH,$)}var IG=u("ZodPipe",($,J)=>{GF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Aq($,U,Q,_),$.in=J.in,$.out=J.out});function S5($,J){return new IG({type:"pipe",in:$,out:J})}var SG=u("ZodCodec",($,J)=>{IG.init($,J),D5.init($,J)});function Lw($,J,U){return new SG({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 zw($,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 Rw($){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 Aw($){return new bH({type:"function",input:Array.isArray($?.input)?KH($?.input):$?.input??C5(Y8()),output:$?.output??Y8()})}var x5=u("ZodCustom",($,J)=>{NF.init($,J),N4.init($,J),$._zod.processJSONSchema=(U,Q,_)=>Nq($,U,Q,_)});function ww($){let J=new x4({check:"custom"});return J._zod.check=$,J}function fw($,J){return uW(x5,$??(()=>!0),J)}function yH($,J={}){return mW(x5,$,J)}function gH($){return cW($)}var kw=dW,Iw=lW;function Sw($,J={}){let U=new x5({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 Tw=(...$)=>iW({Codec:SG,Boolean:a9,String:r9},...$);function vw($){let J=vH(()=>{return RG([QG($),pq(),aq(),eq(),C5(J),NH(QG(),J)])});return J}function Cw($,J){return S5(wG($),J)}var sn={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 en($){Y6({customError:$})}function $p(){return Y6().customError}var xH;(function($){})(xH||(xH={}));var R$={...w5,...e3,iso:l9},Jp=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 Up($,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 _p($,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 bw($,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=_p(_,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 bw(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=bw($,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(!Jp.has(X))_[X]=$[X];if(Object.keys(_).length>0)J.registry.add(U,_);return U}function yw($,J){if(typeof $==="boolean")return $?R$.any():R$.never();let U=Up($,J?.defaultTarget),Q=$.$defs||$.definitions||{},_={version:U,defs:Q,refs:new Map,processing:new Set,rootSchema:$,registry:J?.registry??T6};return x6($,_)}var hH={};O0(hH,{string:()=>Qp,number:()=>Gp,date:()=>Yp,boolean:()=>Vp,bigint:()=>Xp});function Qp($){return YW(r9,$)}function Gp($){return BW(p9,$)}function Vp($){return LW(a9,$)}function Xp($){return RW(o9,$)}function Yp($){return yW(v5,$)}Y6(E5());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 Kp=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()}),Np=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),Fp=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()}),Wp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),terminalId:W.string()}),qp=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()}),gw=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),name:W.string(),value:W.string()}),Hp=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()]),xw=W.object({code:Hp,data:W.unknown().optional(),message:W.string()}),hw=W.unknown(),uw=W.unknown(),mw=W.unknown(),Bp=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)}),Op=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),fs:Bp.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:W.boolean().optional().default(!1)}),cw=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),name:W.string(),value:W.string()}),dw=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()}),jp=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()}),Dp=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)}),Ep=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),headers:W.array(cw),name:W.string(),url:W.string()}),Pp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),headers:W.array(cw),name:W.string(),url:W.string()}),Mp=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(gw),name:W.string()}),TG=W.union([Ep.and(W.object({type:W.literal("http")})),Pp.and(W.object({type:W.literal("sse")})),Mp]),dH=W.string(),Lp=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(TG)}),lw=W.string(),zp=W.union([W.literal("allow_once"),W.literal("allow_always"),W.literal("reject_once"),W.literal("reject_always")]),Rp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),kind:zp,name:W.string(),optionId:lw}),Ap=W.union([W.literal("high"),W.literal("medium"),W.literal("low")]),wp=W.union([W.literal("pending"),W.literal("in_progress"),W.literal("completed")]),fp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:W.string(),priority:Ap,status:wp}),kp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),entries:W.array(fp)}),Ip=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)}),iw=W.number().int().gte(0).lte(65535),iH=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),clientCapabilities:Op.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:W.union([dw,W.null()]).optional(),protocolVersion:iw}),Sp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:W.string()}),Tp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),K8=W.union([W.null(),W.coerce.bigint(),W.string()]),NF$=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),requestId:K8}),vp=W.enum(["assistant","user"]),h5=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),audience:W.union([W.array(vp),W.null()]).optional(),lastModified:W.union([W.string(),W.null()]).optional(),priority:W.union([W.number(),W.null()]).optional()}),Cp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h5,W.null()]).optional(),data:W.string(),mimeType:W.string()}),bp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h5,W.null()]).optional(),data:W.string(),mimeType:W.string(),uri:W.union([W.string(),W.null()]).optional()}),yp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h5,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()}),gp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),optionId:lw}),xp=W.union([W.object({outcome:W.literal("cancelled")}),gp.and(W.object({outcome:W.literal("selected")}))]),hp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),outcome:xp}),up=W.string(),rw=W.string(),rH=W.string(),nw=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}),mp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),group:up,name:W.string(),options:W.array(nw)}),cp=W.union([W.array(nw),W.array(mp)]),dp=W.object({currentValue:rH,options:cp}),t9=dp.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:rw,name:W.string()})),lp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.array(t9)}),ip=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}),FF$=W.object({method:W.string(),params:W.union([W.union([nH,hw]),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(gw).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(TG).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(TG),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(TG).optional(),sessionId:O6}),rp=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()}),np=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(rp)}),pp=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()}),ap=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),vG=W.string(),op=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),currentModeId:vG}),tp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),description:W.union([W.string(),W.null()]).optional(),id:vG,name:W.string()}),CG=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),availableModes:W.array(tp),currentModeId:vG}),bG=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),availableModels:W.array(Lp),currentModelId:dH}),sp=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.union([W.array(t9),W.null()]).optional(),models:W.union([bG,W.null()]).optional(),modes:W.union([CG,W.null()]).optional(),sessionId:O6}),ep=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.union([W.array(t9),W.null()]).optional(),models:W.union([bG,W.null()]).optional(),modes:W.union([CG,W.null()]).optional()}),$a=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.union([W.array(t9),W.null()]).optional(),models:W.union([bG,W.null()]).optional(),modes:W.union([CG,W.null()]).optional(),sessionId:O6}),Ja=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.union([W.array(t9),W.null()]).optional(),models:W.union([bG,W.null()]).optional(),modes:W.union([CG,W.null()]).optional()}),Ua=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),_a=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),fork:W.union([ip,W.null()]).optional(),list:W.union([ap,W.null()]).optional(),resume:W.union([Ua,W.null()]).optional()}),Qa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),loadSession:W.boolean().optional().default(!1),mcpCapabilities:Dp.optional().default({http:!1,sse:!1}),promptCapabilities:Ip.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:_a.optional().default({})}),Ga=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),agentCapabilities:Qa.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:W.union([dw,W.null()]).optional(),authMethods:W.array(Kp).optional().default([]),protocolVersion:iw}),Va=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configId:rw,sessionId:O6,value:rH}),Xa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),configOptions:W.array(t9)}),JB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),modeId:vG,sessionId:O6}),Ya=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}),Za=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),Ka=W.union([W.literal("end_turn"),W.literal("max_tokens"),W.literal("max_turn_requests"),W.literal("refusal"),W.literal("cancelled")]),Na=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),stopReason:Ka}),WF$=W.union([W.object({id:K8,result:W.union([Ga,Np,$a,ep,np,sp,Ja,Ya,Xa,Na,Za,mw])}),W.object({error:xw,id:K8})]),Fa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),terminalId:W.string()}),Wa=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()}),qa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),exitStatus:W.union([Wa,W.null()]).optional(),output:W.string(),truncated:W.boolean()}),Ha=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h5,W.null()]).optional(),text:W.string()}),Ba=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()}),Oa=W.union([Ba,Fp]),ja=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),annotations:W.union([h5,W.null()]).optional(),resource:Oa}),QB=W.union([Ha.and(W.object({type:W.literal("text")})),bp.and(W.object({type:W.literal("image")})),Cp.and(W.object({type:W.literal("audio")})),yp.and(W.object({type:W.literal("resource_link")})),ja.and(W.object({type:W.literal("resource")}))]),Da=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}),qF$=W.object({id:K8,method:W.string(),params:W.union([W.union([iH,mH,lH,tH,cH,aH,$B,JB,Va,GB,UB,uw]),W.null()]).optional()}),pw=W.union([Da.and(W.object({type:W.literal("content")})),qp.and(W.object({type:W.literal("diff")})),Fa.and(W.object({type:W.literal("terminal")}))]),aw=W.string(),ow=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()}),tw=W.union([W.literal("pending"),W.literal("in_progress"),W.literal("completed"),W.literal("failed")]),sw=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")]),Ea=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:W.array(pw).optional(),kind:sw.optional(),locations:W.array(ow).optional(),rawInput:W.unknown().optional(),rawOutput:W.unknown().optional(),status:tw.optional(),title:W.string(),toolCallId:aw}),ew=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),content:W.union([W.array(pw),W.null()]).optional(),kind:W.union([sw,W.null()]).optional(),locations:W.union([W.array(ow),W.null()]).optional(),rawInput:W.unknown().optional(),rawOutput:W.unknown().optional(),status:W.union([tw,W.null()]).optional(),title:W.union([W.string(),W.null()]).optional(),toolCallId:aw}),VB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),options:W.array(Rp),sessionId:O6,toolCall:ew}),Pa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),hint:W.string()}),Ma=Pa,La=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),description:W.string(),input:W.union([Ma,W.null()]).optional(),name:W.string()}),za=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),availableCommands:W.array(La)}),Ra=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")})),Ea.and(W.object({sessionUpdate:W.literal("tool_call")})),ew.and(W.object({sessionUpdate:W.literal("tool_call_update")})),kp.and(W.object({sessionUpdate:W.literal("plan")})),za.and(W.object({sessionUpdate:W.literal("available_commands_update")})),op.and(W.object({sessionUpdate:W.literal("current_mode_update")})),lp.and(W.object({sessionUpdate:W.literal("config_option_update")})),pp.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:Ra}),HF$=W.object({method:W.string(),params:W.union([W.union([XB,hw]),W.null()]).optional()}),YB=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional(),sessionId:O6,terminalId:W.string()}),Aa=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}),BF$=W.object({id:K8,method:W.string(),params:W.union([W.union([ZB,sH,VB,pH,_B,eH,YB,oH,uw]),W.null()]).optional()}),wa=W.object({_meta:W.union([W.record(W.string(),W.unknown()),W.null()]).optional()}),OF$=W.union([W.object({id:K8,result:W.union([wa,Sp,hp,Wp,qa,Tp,Aa,jp,mw])}),W.object({error:xw,id:K8})]);function $f($,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(`
|
|
658
|
-
`);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)+`
|
|
659
|
-
`,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 Jf(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 Jf{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 ka{#$;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 $2{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 aF$=U4(Wf(),1),BB=v6.env.ACP_DEBUG==="true",e9=v6.env.ACP_STICKY_SESSION==="true";function M4(...$){if(BB)console.error("[ACP Server]",...$)}var qB="plan-mode",Xo="agent",jf=[{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."}],Yo=new Set(jf.map(($)=>$.id));function Zo($){return Yo.has($)?$:null}function gG($){return{currentModeId:$,availableModes:jf}}function Df(){let $=N9({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 x8({adapter:$})}function Ko(){let $=N9({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 x8({adapter:$})}function qf($,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 Hf="acp-history";function No($){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 Bf($){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 Of($,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 Fo($,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=[],j=new Set;while(!0){let{options:B,optionLabelById:D,doneOptionId:w}=Of(X,V,j,!0),A=await $.requestPermission({sessionId:J,toolCall:{toolCallId:U,title:Z,kind:_,status:"pending",rawInput:Y},options:B}),I=Bf(A.outcome);if(I)return I;if(A.outcome.outcome==="cancelled")return null;let f=A.outcome.optionId;if(w&&f===w)break;let T=D.get(f)??f;if(E.push(T),j.add(f),B.filter((S)=>S.optionId!==w).length<=j.size)break}G[String(V)]=E;continue}let{options:K,optionLabelById:F}=Of(X,V,new Set,!1),N=await $.requestPermission({sessionId:J,toolCall:{toolCallId:U,title:Z,kind:_,status:"pending",rawInput:Y},options:K}),q=Bf(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 Wo($,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 qo($){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 Ho($,J,U){let Q={};for(let _ of U){let{options:G,allowOptionId:V}=qo(_.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 Ef{acpAgent;connection=null;sessions=new Map;stickySessionId=null;currentModeId=Xo;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),e9&&!this.stickySessionId){let Q=await this.findMostRecentSessionId();if(Q)this.stickySessionId=Q}if(e9&&this.stickySessionId)return await this.restoreSession(this.stickySessionId),M4("newSession reuse:",this.stickySessionId),this.scheduleAvailableCommands(this.stickySessionId),{sessionId:this.stickySessionId,modes:gG(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),e9)this.stickySessionId=J;return this.scheduleAvailableCommands(J),{sessionId:J,modes:gG(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),e9)this.stickySessionId=J.agentSessionId;return await this.sendAvailableCommands($.sessionId),{modes:gG(this.currentModeId)}}async unstable_resumeSession($){M4("resumeSession:",$.sessionId);let J=await this.restoreSession($.sessionId);if(e9)this.stickySessionId=J.agentSessionId;return await this.sendAvailableCommands($.sessionId),{modes:gG(this.currentModeId)}}async authenticate($){M4("authenticate called")}async setSessionMode($){M4("setSessionMode called",$);let J=Zo($.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(`
|
|
660
|
-
`),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,j=null;while(!0){H="end_turn";let B=j?this.acpAgent.receiveWithApprovals(j,{session_id:_.agentSessionId}):this.acpAgent.receiveMessage(E??_.conversationHistory,{session_id:_.agentSessionId});E=null,j=null;let D=null,w=null,A=!1,I=!1;for await(let f of B){if(I)continue;if(_.pendingAbort.signal.aborted){H="cancelled";break}let T=f.metadata?.subagent===!0,z=typeof f.metadata?.subagentId==="string"?f.metadata?.subagentId:void 0,S=typeof f.metadata?.subagentType==="string"?f.metadata?.subagentType.trim():void 0,O=typeof f.metadata?.taskDescription==="string"?f.metadata?.taskDescription.trim():void 0,M=T?z??`${S||"subagent"}:${O??""}`:null,P=T&&(S||O)?`[${[S,O].filter(Boolean).join(": ")}]`:null,R=T?`[SUBAGENT${S?`:${S}`:""}${O?`:${O}`:""}]`:"";M4("Received response:",f.role,R,f.metadata?.done?"(done)":"");let k=f.content&&f.content.length>0,L=f.tool_calls&&f.tool_calls.length>0,v=f.role==="assistant"&&f.metadata?.done&&!k&&!L,C=f.role==="tool"&&!!f.tool_call_id&&F.has(f.tool_call_id)&&f.metadata?.error===!0;if(!v&&!C)_.conversationHistory.push(f);if(v){if(f.metadata?.done){if(f.metadata.stopReason)H=qf(f.metadata.stopReason,H);I=!0}continue}if(f.role==="assistant"){if(k){let b=typeof f.content==="string"?f.content:JSON.stringify(f.content);if(b.trim()){let y=f.metadata?.thinking===!0,c=T&&P&&M!==w?`${P} ${b}`:b;if(await J.sessionUpdate({sessionId:U,update:{sessionUpdate:y?"agent_thought_chunk":"agent_message_chunk",content:{type:"text",text:c}}}),!y)w=M}}if(!T&&k)w=null;if(f.metadata?.approval_requested===!0){let b=f.metadata,y=typeof b.tool_call_id==="string"?b.tool_call_id:D,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(f.metadata?.requires_action&&f.metadata?.kind==="ask_user"){let b=typeof f.metadata.tool_call_id==="string"?f.metadata.tool_call_id:D,y=Array.isArray(f.metadata.questions)?f.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 Fo(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$=Wo(y,s),K$={role:"tool",tool_call_id:b,content:JSON.stringify({answers:s})},V$={role:"user",content:`User answers: ${F$}
|
|
661
|
-
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$],A=!0;break}}if(f.metadata?.requires_action&&f.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 f.metadata.tool_call_id==="string"?f.metadata.tool_call_id:D,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 Ho(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}j=x,A=!0;continue}if(L&&f.tool_calls){for(let b of f.tool_calls){D=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}})}w=null}}else if(f.role==="tool"){if(D||f.tool_call_id){let b=f.tool_call_id||D;if(F.has(b)&&f.metadata?.error)continue;let y=typeof f.content==="string"?f.content:f.content?JSON.stringify(f.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}}]}})}w=null}if(f.metadata?.done){if(f.metadata.stopReason)H=qf(f.metadata.stopReason,H);I=!0}}if(!A)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)}r2.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??D9({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($,Hf);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,_),e9)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($,Hf,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=No(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=Df(),_=new j1({name:"CommitAgent",systemPrompt:"You are a git commit assistant.",model:Q,tools:new $2});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:`
|
|
662
|
-
|
|
663
|
-
✗ Commit 失败: ${G instanceof Error?G.message:String(G)}`}}}),{cancelled:!1}}}}async function Pf(){M4("Starting GoatChain ACP Server...");let $=v6.env.WORKSPACE_CWD||v6.cwd();M4("Workspace:",$);let J=new $2,U=Df(),Q=new f2({dir:HB.join($,".goatchain","state"),deleteOnComplete:!0});J.register(new i2({cwd:$})),J.register(new m2({cwd:$})),J.register(new b2({cwd:$})),J.register(new C2({cwd:$})),J.register(new y2({cwd:$})),J.register(new u2({cwd:$})),J.register(new v2({cwd:$})),J.register(new T2({cwd:$})),J.register(new c2),J.register(new d2),J.register(new I2);let _=new $2,G=new Set(r2.blockedTools||[]);for(let j of r2.tools||[]){if(G.has(j))continue;let B=J.get(j);if(B)_.register(B)}let V=Ko(),X=E9({subagents:[r2],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.
|
|
664
|
-
|
|
665
|
-
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.
|
|
666
|
-
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).
|
|
667
|
-
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.
|
|
668
|
-
|
|
669
|
-
If the user asks for help or wants to give feedback inform them of the following:
|
|
670
|
-
- /help: Get help with using GoatChain CLI
|
|
671
|
-
|
|
672
|
-
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.
|
|
673
|
-
|
|
674
|
-
# Tone and style
|
|
675
|
-
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).
|
|
676
|
-
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.
|
|
677
|
-
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.
|
|
678
|
-
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.
|
|
679
|
-
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
|
680
|
-
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.
|
|
681
|
-
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.
|
|
682
|
-
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:
|
|
683
|
-
<example>
|
|
684
|
-
user: 2 + 2
|
|
685
|
-
assistant: 4
|
|
686
|
-
</example>
|
|
687
|
-
|
|
688
|
-
<example>
|
|
689
|
-
user: what is 2+2?
|
|
690
|
-
assistant: 4
|
|
691
|
-
</example>
|
|
692
|
-
|
|
693
|
-
<example>
|
|
694
|
-
user: is 11 a prime number?
|
|
695
|
-
assistant: Yes
|
|
696
|
-
</example>
|
|
697
|
-
|
|
698
|
-
<example>
|
|
699
|
-
user: what command should I run to list files in the current directory?
|
|
700
|
-
assistant: ls
|
|
701
|
-
</example>
|
|
702
|
-
|
|
703
|
-
<example>
|
|
704
|
-
user: what command should I run to watch files in the current directory?
|
|
705
|
-
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]
|
|
706
|
-
npm run dev
|
|
707
|
-
</example>
|
|
708
|
-
|
|
709
|
-
<example>
|
|
710
|
-
user: How many golf balls fit inside a jetta?
|
|
711
|
-
assistant: 150000
|
|
712
|
-
</example>
|
|
713
|
-
|
|
714
|
-
<example>
|
|
715
|
-
user: what files are in the directory src/?
|
|
716
|
-
assistant: [runs bash tool with ls command and sees foo.c, bar.c, baz.c]
|
|
717
|
-
user: which file contains the implementation of foo?
|
|
718
|
-
assistant: src/foo.c
|
|
719
|
-
</example>
|
|
720
|
-
|
|
721
|
-
<example>
|
|
722
|
-
user: write tests for new feature
|
|
723
|
-
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]
|
|
724
|
-
</example>
|
|
725
|
-
|
|
726
|
-
# Proactiveness
|
|
727
|
-
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
|
728
|
-
1. Doing the right thing when asked, including taking actions and follow-up actions
|
|
729
|
-
2. Not surprising the user with actions you take without asking
|
|
730
|
-
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.
|
|
731
|
-
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.
|
|
732
|
-
|
|
733
|
-
# Following conventions
|
|
734
|
-
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
|
|
735
|
-
- 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).
|
|
736
|
-
- 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.
|
|
737
|
-
- 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.
|
|
738
|
-
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
|
|
739
|
-
|
|
740
|
-
# Code style
|
|
741
|
-
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
|
|
742
|
-
|
|
743
|
-
# Doing tasks
|
|
744
|
-
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:
|
|
745
|
-
- 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.
|
|
746
|
-
- Implement the solution using all tools available to you
|
|
747
|
-
- 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.
|
|
748
|
-
- 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.
|
|
749
|
-
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.
|
|
750
|
-
|
|
751
|
-
- 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.
|
|
752
|
-
|
|
753
|
-
# Tool usage policy
|
|
754
|
-
- When doing file search, prefer to use the Task tool in order to reduce context usage.
|
|
755
|
-
- 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.
|
|
756
|
-
|
|
757
|
-
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
|
758
|
-
|
|
759
|
-
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.
|
|
760
|
-
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).
|
|
761
|
-
|
|
762
|
-
# Code References
|
|
763
|
-
|
|
764
|
-
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.
|
|
765
|
-
|
|
766
|
-
<example>
|
|
767
|
-
user: Where are errors from the client handled?
|
|
768
|
-
assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
|
|
769
|
-
</example>`,model:U,tools:J,stateStore:Q});await Y.use(X),await Y.use(RJ({maxTokens:128000,protectedTurns:2,model:U,stateStore:Q})),M4("Agent initialized with tools:",Array.from(J.list().map((j)=>j.name))),M4("Agent initialized with middlewares:",Y.middlewareNames.join(", "));let K=new tQ(Y,{debug:BB,maxIterations:1e4}),F=new Ef(K),N=Go.toWeb(v6.stdin),q=Vo.toWeb(v6.stdout),H=$f(q,N);M4("Creating AgentSideConnection...");let E=new KB((j)=>{return M4("Agent connection established"),F.setConnection(j),F},H);M4("ACP Server ready and listening on stdio"),await E.closed,M4("Connection closed"),K.destroy()}var Bo=import.meta.url===`file://${v6.argv[1]}`||v6.argv[1]?.endsWith("acp-server.ts")||v6.argv[1]?.endsWith("acp-server.js");if(Bo)Pf().catch(($)=>{console.error("[ACP Server] Fatal error:",$),v6.exit(1)});async function*Mf($){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(`
|
|
770
|
-
`),metadata:{done:!0,error:!0,stopReason:"error",originalEventType:"done"}}}}$U();f1();function Sf($,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 Tf($,J){let U=J.baseUrl?.includes("https://chatgpt.com/backend-api");if(U){let{createCodexAdapter:G}=await import("goatchain"),V=async()=>{let Y=await hG("codex");if(!Y)throw Error("Codex OAuth tokens not found. Please login via Settings.");if(Y.expires<Date.now())try{let K=await LB(Y.refresh),F=zB(K)||Y.accountId,N=RB(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 EB("codex",Y)}catch(K){throw Error(`Failed to refresh OAuth token: ${K?.message||"Unknown error"}`)}return Y.access},X=async()=>{let Y=await hG("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 Sf(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 Sf(_,{temperature:J.temperature}),_}function vf($){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 uo(){let $=globalThis.process;return!!$&&typeof $?.versions?.node==="string"}function uG(){return globalThis.process?.env??{}}var Cf="plan-mode";function J1($){return String($??"").trim()||void 0}function bf($){let J=String($??"").trim();if(!J)return;let U=Number.parseFloat(J);return Number.isFinite(U)?U:void 0}function mo($){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 co($,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 lo($){return{id:String($?.id??""),type:"function",function:{name:String($?.function?.name??""),arguments:$?.function?.arguments}}}function io($){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 AB($){if(!$)return"";if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>String(J?.text??"")).join("");return String($)}function wB($){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 yf($){if(!uo())throw Error("GoatChain embedded agent is Node-only");let J=$.debug===!0,U=$.cliTools!==!1,Q=$.planMode===!0,_=$.subagents===!0,G=J1($.stateDir||uG().GOATCHAIN_STATE_DIR||uG().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,R){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(R??"").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:AB(x.content)});else if(x.role==="assistant"){let c={role:"assistant",content:AB(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:AB(x.content),...x.metadata?.error===!0?{isError:!0}:{}})}return b}function H(P,R,k){try{if(!P||!Array.isArray(P.messages))return;let L=q(R,k);if(L.length===0)return;if(P.messages.length>=L.length)return;P.messages=L}catch{}}function E(P){let R=P?.env;if(!R||typeof R!=="object")return;let k=globalThis.process;if(!k?.env)return;for(let[L,v]of Object.entries(R)){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 j=new Map;async function B(){if(V)return V;if(G&&typeof f2==="function")try{return V=new f2({dir:G,deleteOnComplete:!1}),V}catch(P){if(J)console.warn("[goatchain-node] Failed to init FileStateStore:",P);V=null}if(!V&&typeof k2==="function")try{V=new k2({deleteOnComplete:!1})}catch(P){if(J)console.warn("[goatchain-node] Failed to init InMemoryStateStore:",P);V=null}return V}function D(P,R){let k=String(N.current??"").trim();return{id:P,createdAt:R,state:{status:"active",updatedAt:R,lastActiveAt:R},context:{messages:[],messageCount:0,toolCallCount:0},stats:{usage:{promptTokens:0,completionTokens:0,totalTokens:0},responseCount:0},metadata:k?{cwd:k}:void 0}}function w(P){if(!Array.isArray(P)||P.length===0)return;for(let R=P.length-1;R>=0;R--){let k=P[R],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 A(){let P=I6?.SESSION;return typeof P==="string"&&P.trim()?P:"session"}function I(){let P=uG(),R=String(P.GOATCHAIN_INTERLEAVED_THINKING??"").toLowerCase(),k=R==="1"||R==="true"||R==="yes"||R==="on";return{modelId:String(P.GOATCHAIN_MODEL||$.modelId),baseUrl:J1(P.GOATCHAIN_OPENAI_BASE_URL||P.OPENAI_BASE_URL||$.baseUrl),apiKey:J1(P.OPENAI_API_KEY||$.apiKey),temperature:bf(P.GOATCHAIN_TEMPERATURE),interleavedThinking:k?!0:void 0}}function f(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 R=new $2,k=(y)=>{if(!y)return;try{R.register(new y)}catch(x){if(J)console.warn("[goatchain-node] Failed to register tool:",y?.name??"(unknown)",x)}};if(k(C2),k(u2),k(m2),k(y2),k(I2),k(c2),k(d2),U)k(i2),k(b2),k(v2),k(T2);let L=await Tf(N9,P),v=x8({adapter:L}),C=[];if(typeof EQ==="function")try{C.push(EQ({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 DQ==="function")try{C.push(DQ({cwd:()=>N.current}))}catch(y){if(J)console.warn("[goatchain-node] Failed to init agent rules middleware:",y)}if(typeof pQ==="function")try{C.push(pQ({cwd:()=>N.current}))}catch(y){if(J)console.warn("[goatchain-node] Failed to init skills middleware:",y)}if(V&&typeof RJ==="function")try{let y=uG(),x=bf(y.GOATCHAIN_MAX_TOKENS)??128000;C.push(RJ({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 D9==="function"){if(Z=D9({insertEveryIteration:!0}),X==="plan")C.push(Z)}if(_&&typeof E9==="function"&&r2)try{C.push(E9({subagents:[r2],globalToolRegistry:R,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:R,...V?{stateStore:V}:{},...C.length?{middleware:C}:{}}),tools:R}}async function z(){let P=I(),R=f(P);if(R!==F){let{agent:k,tools:L}=await T(P);Y=k,K=L,F=R,j.clear()}}async function S(P,R){let k=J1(P),L=k?j.get(k):void 0;if(L&&R?.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=J1(b?.id)??J1(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 j.set(x,{session:b}),{sessionId:x,session:b}}async function*O(P){for await(let R of P){if(R?.type==="subagent_event"){let v=R?.nestedEvent,C=M(v),b=J1(v?.sessionId);for(let y of C)yield{...y,metadata:{...y.metadata??{},...b?{session_id:b}:{},subagent:!0,subagentId:R?.subagentId,subagentType:R?.subagentType,taskDescription:R?.taskDescription,originalEventType:v?.type}};continue}let k=M(R),L=J1(R?.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:[lo(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 R=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:mo(P.result),metadata:{...R?{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,R){try{E(R);let k=R?.signal,L=J1(R?.session_id),v=R?.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=co(y,k);try{let c=String(R?.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=R?.toolContext,F$=io(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*Mf({session:y,toolContext:K$,signal:k,convertEventStream:O});let _$=wB(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 _$=wB(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$=wB(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{...vf({ensureSharedStateStore:B,sessionStorageKey:A,createEmptySessionSnapshot:D,createId:()=>ho(),applyMessagesToSnapshot:(k,L,v)=>{k.context.messages=L,k.context.messageCount=L.length;let C=w(L);if(C)k.context.lastMessagePreview=C;k.state.updatedAt=v,k.state.lastActiveAt=v}}),rename:async(k,L)=>{let v=J1(k),C=J1(L);if(!v||!C)return null;let b=null,y=j.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 A(),s=await x.load(v,c);if(!s)s=b;if(!s)s=D(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!==Cf);if(Y.clearMiddlewares(),P==="plan")await Y.use(Z,Cf);for(let L of k)await Y.use(L.fn,L.name);j.clear()},getMode(){return X}}}function gf($){let J=$.processEnv;try{return yf({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),yj(U)}}var xf=`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
|
-
`;Q2();async function uf($){let J=Z6("0.0.5-beta.8")??await no($.cwd),U=await fB($.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&&W8(_.contextWindow)!=null)Z.GOATCHAIN_CONTEXT_WINDOW=String(_.contextWindow);if(!Z.GOATCHAIN_TEMPERATURE&&W8(_.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:xf,cwd:X,env:Z,...V?.length?{focusFiles:V}:{}},cacheDir:U.dir,cacheFile:U.filePath,cache:Q}}async function no($){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 dG}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 po($){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 po($.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 mf($){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 cf($){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 df($){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 cG($){return`${$}_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}function IB($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function ao($){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 i5($){if($==null)return"";if(typeof $==="string")return $;if(Array.isArray($))return $.map(i5).join("");if(IB($)){if(typeof $.text==="string")return String($.text);if(String($.type??"")==="image")return"[image]";try{return JSON.stringify($)}catch{return String($)}}return String($)}function oo($){if(IB($))return $;if(typeof $==="string"){let J=$.trim();if(!J)return{};try{let U=JSON.parse(J);return IB(U)?U:{_raw:$}}catch{return{_raw:$}}}return{}}function lf($){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:cG("m"),role:"user",content:i5(V?.content)});continue}if(X==="assistant"){let Z=[],Y=i5(V?.reasoning_content).replace(/\r/g,"").trim();if(Y)Z.push({type:"thinking",title:"Thinking",collapsed:!0,content:Y});let K=i5(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=oo(N?.function?.arguments);if(!q)continue;let j={id:q,name:H,arguments:E};Z.push({type:"tool_call",call:j}),_.set(q,Q.length),G.set(q,H)}Q.push({id:cG("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"?ao(F):null)??i5(F),H=V?.isError?"error":"success",E={id:Z||cG("tool"),output:q,status:H};Q.push({id:cG("m"),role:"tool",result:E});let j=Z?_.get(Z):void 0;if(j==null)continue;let B=Q[j];if(!B||B.role!=="assistant")continue;Q[j]={...B,parts:[...B.parts,{type:"tool_result",result:E}]};continue}}return Q}function rf($){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}Q2();function nf($){return String($?.id??"").trim()}function to($){return Number($?.state?.updatedAt??$?.state?.lastActiveAt??0)||0}function pf($){let J=$?.context?.messages;return Array.isArray(J)?J:[]}function so($){let J=Number($?.context?.messageCount??0);if(Number.isFinite(J)&&J>=0)return J;return pf($).length}function eo($){let J=$?.stats?.usage;return J&&typeof J==="object"?J:null}function af($){let J=nf($);if(!J)return null;let U=to($),Q=Z6($?.metadata?.cwd),_=pf($),G=Z6($?.state?.title)??mf(_),V=cf(_),X=Z6($?.context?.lastMessagePreview)??df(_),Z=so($);return{id:J,updatedAt:U,cwd:Q??void 0,title:G,summary:V,messageCount:Z,lastMessage:X}}function _U($,J){let U=nf(J);if(U)$.state.sessionId=U;let Q=lf(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 _=eo(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 of($){let J=Array.isArray($)?$:[];return rf(J)}Q2();function tf($){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:W8(J?.state?.config?.context_window),temperature:W8(J?.state?.config?.temperature),baseUrl:Q,apiKey:_,toolApprovals:J?.state?.approval?.mode==="all"?"all":"auto"},lastSessionId:Z6(J?.state?.sessionId)||$.prev.lastSessionId}}Q2();function sf($,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 $t($){return String($?.id??"").trim()}function ef($){let J=null,U=$.sessionsBackend??null;return{sessions:U?{async list(){return(await U.list()).map(af).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=$t(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(of(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=sf(async()=>{try{let X=tf({prev:$.cache,store:G});await kB($.cacheFile,X)}catch(X){console.warn("[goatchain] Failed to persist cache:",X)}},300);dG(()=>G.state.sessionId,V.schedule),dG(()=>G.state.config,V.schedule,{deep:!0}),dG(()=>G.state.context,V.schedule,{deep:!0}),dG(()=>G.state.approval.mode,V.schedule),V.schedule()}}}Q2();async function SB($){let J=$.sessionsBackend,U=Z6($.envSessionId);if(J&&U){if(await J.get(U))return U}return U}function $k(){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 Jt($){return Jk.join($,"state")}function Ut($){$.env.GOATCHAIN_STATE_DIR=$.stateDir,$.context.env.GOATCHAIN_STATE_DIR=$.stateDir}async function TB($){let{context:J,cacheDir:U,cacheFile:Q,cache:_}=await uf({cwd:$.cwd,env:$.env}),G=Jt(U);Ut({env:$.env,context:J,stateDir:G});let V=gf({context:J,processEnv:$.env,stateDir:G}),X=V?.__sessions??null,Z=await SB({sessionsBackend:X,envSessionId:$.env.GOATCHAIN_SESSION_ID});$.env.GOATCHAIN_SESSION_ID=Z??"",J.env.GOATCHAIN_SESSION_ID=Z??"";let{sessions:Y,onStoreCreated:K}=ef({cacheFile:Q,cache:_,sessionsBackend:X});return{toolRunner:$k(),context:J,agent:V,onStoreCreated:K,sessions:Y}}var vB=null,lG=null;function Uk($){vB=$}function _k($){return lG=$,()=>{if(lG===$)lG=null}}function r5(){let $=lG;if($&&$.isBusy()){$.showConfirm();return}vB?.()}function iG(){vB?.()}import Q$$ from"node:fs";import{nextTick as LV}from"vue";var Qk=($=0)=>(J)=>`\x1B[${J+$}m`,Gk=($=0)=>(J)=>`\x1B[${38+$};5;${J}m`,Vk=($=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]}},Zq$=Object.keys(n4.modifier),_t=Object.keys(n4.color),Qt=Object.keys(n4.bgColor),Kq$=[..._t,...Qt];function Gt(){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=Qk(),n4.color.ansi256=Gk(),n4.color.ansi16m=Vk(),n4.bgColor.ansi=Qk(10),n4.bgColor.ansi256=Gk(10),n4.bgColor.ansi16m=Vk(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 Vt=Gt(),t4=Vt;function UJ($){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 rG($){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 Xt($){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 CB($){if(!$||!Number.isFinite($))return null;let J=Math.floor($)-1;return Xt(J)}var Yt={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"}},Zt=/^\x1b\[(\d+);(\d+):(\d+)([A-Z~])$/,Kt={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"}},Nt={"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 Xk($){if($==="2")return{repeat:!0,release:!1};if($==="3")return{repeat:!1,release:!0};return{repeat:!1,release:!1}}function Ft($){let J=Zt.exec($);if(!J)return{handled:!1,event:null};let U=J[1],Q=J[2],_=J[3],G=J[4],V;if(G==="~")V=Nt[U];else if(U==="1")V=Kt[G];let X=Xk(_);if(!V)return{handled:!0,event:null};if(X.release)return{handled:!0,event:null};let Z=CB(Number.parseInt(Q,10))??void 0;return{handled:!0,event:b$(V.key,V.code,Z,X.repeat)}}function Wt($,J,U,Q){if(U||Q>2)return!0;if($>=57344)return!0;if(J!=null&&J>16)return!0;return!1}function qt($){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(!Wt(X,K,N,Q.length))return{handled:!1,event:null};let q=Xk(F);if(q.release)return{handled:!0,event:null};let H=CB(K)??void 0,E=Yt[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 Yk($){let J=Ft($);if(J.handled)return J;return qt($)}function Ht($,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,_=rG(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 Bt($){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 Ht(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=rG(_)??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=rG(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 Ot($){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 Zk($){if(!$.startsWith("\x1B"))return{handled:!1,event:null};let J=Bt($);if(J.handled)return J;let U=Ot($);if(U.handled)return U;return{handled:!1,event:null}}import{appendFileSync as jt}from"node:fs";function Dt($){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=(w)=>{if(!Q)return;try{jt(_,`${w}
|
|
882
|
-
`)}catch{}},V=3,X=()=>{let w=V;while(V<$.length){let A=$.charCodeAt(V);if(A<48||A>57)break;V++}if(V===w)return null;return Number.parseInt($.slice(w,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),j=Boolean(Z&8),B=Boolean(Z&16);if((Z&64)===64){let w=Z&1?1:-1;if(U)w=-w;return G(`[${Date.now()}] [MOUSE] wheel b=${Z} bit1=${Z&1} deltaY=${w} x=${q} y=${H}`),{handled:!0,event:{type:"wheel",cellX:q,cellY:H,deltaY:w,shiftKey:E,altKey:j,ctrlKey:B}}}let D=Z&3;if(!N&&(Z&32)===0&&D===3)return{handled:!0,event:{type:"pointerup",cellX:q,cellY:H,button:D,shiftKey:E,altKey:j,ctrlKey:B}};if(N)return{handled:!0,event:{type:"pointerup",cellX:q,cellY:H,button:D,shiftKey:E,altKey:j,ctrlKey:B}};if(Z&32)return{handled:!0,event:{type:"pointermove",cellX:q,cellY:H,button:D,shiftKey:E,altKey:j,ctrlKey:B}};return{handled:!0,event:{type:"pointerdown",cellX:q,cellY:H,button:D,shiftKey:E,altKey:j,ctrlKey:B}}}function Kk($){return Dt($)}import{Buffer as Et}from"node:buffer";import{EventEmitter as Pt}from"node:events";var G2="\x1B",Nk="\x1B[200~",nG="\x1B[201~";function Mt($){if(!$.startsWith(G2))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 Lt($)}if(J.startsWith("]"))return zt($);if(J.startsWith("P"))return Rt($);if(J.startsWith("_"))return At($);if(J.startsWith("O"))return J.length>=2?"complete":"incomplete";if(J.length===1)return"complete";return"complete"}function Lt($){if(!$.startsWith(`${G2}[`))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 zt($){if(!$.startsWith(`${G2}]`))return"complete";if($.endsWith(`${G2}\\`)||$.endsWith("\x07"))return"complete";return"incomplete"}function Rt($){if(!$.startsWith(`${G2}P`))return"complete";if($.endsWith(`${G2}\\`))return"complete";return"incomplete"}function At($){if(!$.startsWith(`${G2}_`))return"complete";if($.endsWith(`${G2}\\`))return"complete";return"incomplete"}function Fk($){let J=[],U=0;while(U<$.length){let Q=$.slice(U);if(Q.startsWith(G2)){let _=1;while(_<=Q.length){let G=Q.slice(0,_),V=Mt(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 bB extends Pt{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(Et.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(nG);if(_!==-1){let G=this.pasteBuffer.slice(0,_),V=this.pasteBuffer.slice(_+nG.length);if(this.pasteMode=!1,this.pasteBuffer="",this.emit("paste",G),V.length>0)this.process(V)}return}let U=this.buffer.indexOf(Nk);if(U!==-1){if(U>0){let G=this.buffer.slice(0,U),V=Fk(G);for(let X of V.sequences)this.emit("data",X)}this.buffer=this.buffer.slice(U+Nk.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let _=this.pasteBuffer.indexOf(nG);if(_!==-1){let G=this.pasteBuffer.slice(0,_),V=this.pasteBuffer.slice(_+nG.length);if(this.pasteMode=!1,this.pasteBuffer="",this.emit("paste",G),V.length>0)this.process(V)}return}let Q=Fk(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 Wk($){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 wt($){if(!$||$.length!==1)return null;let J=$.charCodeAt(0);if(J>=1&&J<=26)return String.fromCharCode(J+96);return null}function pG($){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 bB({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 D=wt(B);if(D){if(D==="i"){$.dispatch(b$("Tab","Tab"));return}if(D==="h"){$.dispatch(b$("Backspace","Backspace"));return}$.dispatch(b$(D,"",{ctrlKey:!0}));return}if(B===""){$.dispatch(b$("Backspace","Backspace"));return}if(B==="\t"){$.dispatch(b$("Tab","Tab"));return}if(Wk(B))$.dispatch(b$(B))},F=(B)=>{let D=B;if(D.type==="pointerdown")$.dispatch(B),X={cellX:D.cellX,cellY:D.cellY,button:D.button??0,shiftKey:Boolean(D.shiftKey),altKey:Boolean(D.altKey),ctrlKey:Boolean(D.ctrlKey)};else if(D.type==="pointermove"){if(X&&(D.button===3||D.button==null)){let w=X;if(X=null,$.dispatch({type:"pointerup",cellX:w.cellX,cellY:w.cellY,button:3,shiftKey:w.shiftKey,altKey:w.altKey,ctrlKey:w.ctrlKey}),w.button===0)$.dispatch({type:"click",cellX:w.cellX,cellY:w.cellY,shiftKey:w.shiftKey,altKey:w.altKey,ctrlKey:w.ctrlKey});return}$.dispatch(B)}else if(D.type==="pointerup"){$.dispatch(B);let w=X;if(X=null,w&&w.cellX===D.cellX&&w.cellY===D.cellY&&w.button===0&&(D.button===0||D.button===3))$.dispatch({type:"click",cellX:D.cellX,cellY:D.cellY,shiftKey:Boolean(D.shiftKey??w?.shiftKey),altKey:Boolean(D.altKey??w?.altKey),ctrlKey:Boolean(D.ctrlKey??w?.ctrlKey)})}else $.dispatch(B)},N=(B)=>{if(G)return;if(!B)return;let D=Kk(B);if(D.handled){if(D.event)F(D.event);return}let w=Yk(B);if(w.handled){if(w.event)$.dispatch(w.event);return}let A=Zk(B);if(A.handled){if(A.event)$.dispatch(A.event);return}if(B.startsWith("\x1B")){if(B.length===2&&Wk(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 D=UJ(B);if(D)$.dispatch({type:"paste",text:D})});let q=(B)=>{if(B.length===1&&B[0]>127){let w=B[0]-128;Y.process(`\x1B${String.fromCharCode(w)}`);return}let D=Z.decode(B,{stream:!0});if(D)Y.process(D)},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 D=B;q(new Uint8Array(D.buffer,D.byteOffset,D.byteLength));return}if(B!=null)try{let D=Z.decode(B,{stream:!0});if(D)Y.process(D)}catch(D){}},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 qk(){return import("node:fs/promises")}function _J(){return{async listDir($){return(await(await qk()).readdir($,{withFileTypes:!0})).map((Q)=>{let _=Q.isDirectory()?"directory":Q.isFile()?"file":"other";return{name:Q.name,kind:_}})},async stat($){let J=await qk();try{let U=await J.lstat($);return{exists:!0,kind:U.isDirectory()?"directory":U.isFile()?"file":"other"}}catch{return{exists:!1,kind:"other"}}}}}function n5($){return $.replace(/\\/g,"/")}function yB($){let J=n5($);if(J.startsWith("/"))return!0;return/^[A-Z]:\//i.test(J)}function Hk($){let J=n5($);if(J==="/")return J;return J.replace(/\/+$/g,"")}function Bk($,J){let U=n5($),Q=n5(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 u0($){let J=n5($);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=u0($),Q=u0(J);if(!U)return Q;if(yB(Q))return Q;return u0(Bk(U,Q))}function Ok($){return $.toLowerCase()}function jk($,J){let U=Ok($),Q=Ok(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 ft($){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 p5($){let J=u0($.workspaceAbs),Q=($.input??"").replace(/\r/g,"").replace(/\\/g,"/"),{dirPrefix:_,query:G}=ft(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(j,B,D){if(B>X)return;let w=[];try{w=await $.listDir(j)}catch{return}for(let A of w){if(!Z&&A.name.startsWith("."))continue;let I=D?`${D}/${A.name}`:A.name;if(A.kind==="directory"){if(!Y)continue;let f=jk(A.name,G);if(f!=null)F.push({score:f,name:A.name,kind:"directory",depth:B,relPath:I});await N(`${j}/${A.name}`,B+1,I);continue}if(A.kind==="file"){if(!K)continue;let f=jk(A.name,G);if(f!=null)F.push({score:f,name:A.name,kind:"file",depth:B,relPath:I});continue}}}await N(V,0,""),F.sort((j,B)=>{if(j.score!==B.score)return B.score-j.score;if(j.depth!==B.depth)return j.depth-B.depth;return j.name.localeCompare(B.name)});let q=Math.max(0,Math.floor($.max)),E=(q?F.slice(0,q):[]).map((j)=>{let B=j.kind==="directory"?"/":"",D=`${_}${j.relPath}${B}`,w=QU(J,`${_}${j.relPath}`);return{kind:j.kind,display:D,completion:D,absPath:w}});return{baseDirAbs:V,dirPrefix:_,query:G,suggestions:E}}function U1($,J){let U=(J??"").replace(/\r/g,"").trim();if(!U)return QU(u0($),".");if(U==="~"||U.startsWith("~/")){let _=globalThis.process?.env?.HOME||globalThis.process?.env?.USERPROFILE||"";if(_){let G=U==="~"?"":U.slice(2);return QU(u0(_),G)}}let Q=U.replace(/\\/g,"/");if(yB(Q))return u0(Q);return QU(u0($),Q)}async function gB(){return import("node:fs")}async function xB($,J){let{writeFileSync:U}=await gB(),Q=J.map((_)=>JSON.stringify(_)).join(`
|
|
887
|
-
`);U($,`${Q}${Q?`
|
|
888
|
-
`:""}`,"utf8")}async function aG($,J){let{writeFileSync:U}=await gB();U($,`${J.join(`
|
|
889
|
-
`)}
|
|
890
|
-
`,"utf8")}async function hB($){let{readFileSync:J}=await gB(),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 Ek($){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 kt($){let J=$>=40&&$<=47?$-10:$>=100&&$<=107?$-10:null;if(J==null)return;return Ek(J)}var Pk={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 Dk($,J,U){let Q="white",_=Number.POSITIVE_INFINITY;for(let[G,V]of Object.entries(Pk)){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 It($){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 Pk[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 St($,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=Ek(_);U={...U,fg:G??U.fg}}else if(_>=40&&_<=47||_>=100&&_<=107){let G=kt(_);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}=It(V),K=Dk(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=Dk(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=St(Q,Z.length?Z:[0]),_=V+1,G=V}if(_<$.length)U.push({text:$.slice(_),style:Q});return U}var Tt=[[4352,4447],[9001,9002],[11904,42191],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65280,65376],[65504,65510]];function vt($){for(let[J,U]of Tt)if($>=J&&$<=U)return!0;return!1}function Ct($){return $>=127744&&$<=129791||$>=127462&&$<=127487}var uB=null;try{uB=new RegExp("\\p{Extended_Pictographic}","u")}catch{uB=null}var mB=null;try{mB=new RegExp("\\p{Emoji_Presentation}","u")}catch{mB=null}var cB=null;try{cB=new RegExp("\\p{Emoji}","u")}catch{cB=null}function u4($){if(!$)return 1;let J=$.codePointAt(0);if(J==null)return 1;let U=$.includes("️");if(vt(J))return 2;if(Ct(J))return 2;if(mB?.test($))return 2;if($.includes("⃣"))return 2;if(U&&cB?.test($))return 2;if(uB?.test($)){if(J<=65535)return U?2:1;return 2}return 1}var fk=Object.freeze({}),Mk=new WeakMap,Lk=new WeakMap,zk=new WeakMap,bt=new WeakMap,yt=new WeakMap,gt=128;function lB($){if(!$)return fk;if(Object.isFrozen($))return $;let J=Mk.get($);if(J)return J;let U=Object.freeze({...$});return Mk.set($,U),U}function Rk($,J){let U=$.get(J);if(U)return U;let Q=new Map;return $.set(J,Q),Q}function oG($,J){if($===" ")return n6(J);let U=lB(J),Q=u4($),_=Q===2?Rk(yt,U):Rk(bt,U),G=_.get($);if(G)return G;let V={ch:$,width:Q,style:U};if(_.set($,V),_.size>gt)_.clear();return V}function n6($){let J=lB($),U=Lk.get(J);if(U)return U;let Q=Object.freeze({ch:" ",width:1,style:J});return Lk.set(J,Q),Q}function kk($){let J=lB($),U=zk.get(J);if(U)return U;let Q=Object.freeze({ch:"",width:1,continuation:!0,style:J});return zk.set(J,Q),Q}function Ik($,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:fk,scrollback:[],scrollbackLimit:1000,rowPool:[]}}function _1($,J,U){return Math.max(J,Math.min(U,$))}function xt($,J){return($.gridStart+J)%$.rows}function Q1($,J){return $.grid[xt($,J)]}function iB($,J,U){return Q1($,U)[J]}function Sk($){if($.rows<=0)return;$.dirtyAll=!0,$.dirtyCount=$.rows,$.dirtyMin=0,$.dirtyMax=$.rows-1}function q8($,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 ht($,J,U){let Q=n6();for(let _=J;_<U;_++)$[_]=Q}function Ak($,J){if(!$[J]?.continuation)return;$[J]=n6()}function dB($,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 tG($,J,U,Q,_){if(U<0||U>=$.rows)return;if(J<0||J>=$.cols)return;let G=Q1($,U);dB(G,J);let V=u4(Q);if(V===2&&J+1>=$.cols){G[J]=n6(),q8($,U);return}if(G[J]=oG(Q,_),V===2&&J+1<$.cols)G[J+1]=kk(_);q8($,U)}function Tk($,J,U,Q,_,G=" ",V){if(Q<=0||_<=0||$.cols===0||$.rows===0)return;let X=_1(Math.floor(J),0,$.cols),Z=_1(Math.floor(U),0,$.rows),Y=_1(Math.floor(J+Q),0,$.cols),K=_1(Math.floor(U+_),0,$.rows);if(Y<=X||K<=Z)return;let F=u4(G);if(F===1){let q=oG(G,V),H=n6();for(let E=Z;E<K;E++){let j=Q1($,E);if(j[X]?.continuation)dB(j,X);if(j.fill(q,X,Y),Y<$.cols&&j[Y]?.continuation)j[Y]=H;q8($,E)}return}let N=F===2?void 0:oG(G,V);for(let q=Z;q<K;q++){let H=Q1($,q);for(let E=X;E<Y;E++)if(dB(H,E),F===2&&E+1>=$.cols)H[E]=n6();else if(H[E]=N??oG(G,V),F===2&&E+1<$.cols)H[E+1]=kk(V);q8($,q)}}function vk($,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=Q1($,K);F.length=$.cols;for(let N=0;N<$.cols;N++)F[N]=Y}Sk($),$.cursorX=0,$.cursorY=0;return}if(Q<=0||_<=0)return;let G=_1(Math.floor(J),0,$.cols),V=_1(Math.floor(U),0,$.rows),X=_1(Math.floor(J+Q),0,$.cols),Z=_1(Math.floor(U+_),0,$.rows);if(X<=G||Z<=V)return;for(let Y=V;Y<Z;Y++){let K=Q1($,Y);if(ht(K,G,X),G-1>=0)Ak(K,G);if(X<$.cols)Ak(K,X);q8($,Y)}}function ut($){return $.rowPool.pop()??null}function wk($){let J=ut($);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 sG($,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]=wk($)}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]=wk($)}Sk($),$.cursorY=_1($.cursorY-U,0,Math.max(0,$.rows-1))}function Ck($,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=Q1($,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(Q1($,Y));$.grid=V,$.gridStart=0,$.cols=Q,$.rows=_,$.dirtyBits=new Uint8Array(_),$.dirtyCount=_?_:0,$.dirtyMin=_?0:Number.POSITIVE_INFINITY,$.dirtyMax=_?_-1:-1,$.dirtyAll=_>0,$.cursorX=_1($.cursorX,0,Math.max(0,Q)),$.cursorY=_1($.cursorY,0,Math.max(0,_-1))}function bk($){let J=Array($.rows);for(let U=0;U<$.rows;U++){let Q=Q1($,U);J[U]=Q.map((_)=>_.continuation?" ":_.ch||" ").join("")}return J}class rB{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 mt($){return $===`
|
|
891
|
-
`||$==="\r"||$==="\t"}var nB=null;try{nB=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{}function pB($){let J=new rB,U=Ik($.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,q8(U,U.cursorY)}function Z(N,q,H,E){let j=q,B=H;if(U.cols===0||U.rows===0)return{x:j,y:B};let D=(A)=>{if(mt(A)){if(A===`
|
|
892
|
-
`){if(j=0,B+=1,B>=U.rows)sG(U,1),B=U.rows-1}else if(A==="\r")j=0;else if(A==="\t"){let T=Math.min(U.cols,j+(4-j%4));for(;j<T;j++)tG(U,j,B," ",E)}return!0}if(B<0||B>=U.rows)return!1;if(j>=U.cols)j=0,B+=1;if(B>=U.rows)sG(U,1),B=U.rows-1;tG(U,j,B,A,E);let I=A===" "?1:iB(U,j,B).width||1;return j+=I,!0},w=0;for(;w<N.length;w++){if(N.charCodeAt(w)>127)break;if(!D(N[w]))return{x:j,y:B}}if(w<N.length){let A=N.slice(w);if(nB){for(let I of nB.segment(A))if(!D(I.segment))break}else for(let I of A)if(!D(I))break}return{x:j,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 j=H;j<=E;j++)if(U.dirtyBits[j]){if(N[q++]=j,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 j=H;j<=E;j++)if(U.dirtyBits[j]){if(U.dirtyBits[j]=0,N[q++]=j,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(Ck(U,N,q),U.cols!==H||U.rows!==E)J.emit("resize",{cols:U.cols,rows:U.rows})},clear(N,q,H,E){V(),vk(U,N,q,H,E)},write(N,q){V();let H=q?.x,E=q?.y,j=q?.style;if(H==null||E==null){let B=Z(N,U.cursorX,U.cursorY,j??U.cursorStyle);U.cursorX=B.x,U.cursorY=B.y}else Z(N,H,E,j)},writeAnsi(N,q){V();let H=q?.x,E=q?.y,j=H!=null&&E!=null,B=j?H:U.cursorX,D=j?E:U.cursorY,w=j?{}:U.cursorStyle;for(let A of GU(N,w)){let I=Z(A.text,B,D,A.style);B=I.x,D=I.y,w=A.style}if(!j)U.cursorX=B,U.cursorY=D,U.cursorStyle=w},put(N,q,H,E){V(),tG(U,N,q,H,E)},fill(N,q,H,E,j,B){V(),Tk(U,N,q,H,E,j??" ",B)},scroll(N){V(),sG(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:bk(U)}},getCell(N,q){if(V(),q<0||q>=U.rows||N<0||N>=U.cols)throw RangeError("Cell out of bounds");return iB(U,N,q)},getRow(N){if(V(),N<0||N>=U.rows)throw RangeError("Row out of bounds");return Q1(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 Ps,h as JO,provide as KU,ref as UO,shallowReactive as _O,shallowRef as _V}from"vue";import{createRenderer as ct}from"vue";function dt($){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 lt($,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 it($){let J=$.parent;if(!J)return;let U=J.children,Q=U.indexOf($);if(Q>=0)U.splice(Q,1);$.parent=null}function rt($){return $.parent}function nt($){let J=$.parent;if(!J)return null;let U=J.children.indexOf($);if(U<0)return null;return J.children[U+1]??null}function pt($,J){$.textContent=J,$.children=[]}function at($){return{type:"text",parent:null,text:$}}function ot($,J){$.text=J}function tt($){return{type:"comment",parent:null,text:$}}function st($,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 et={patchProp:st,insert:lt,remove:it,createElement:dt,createText:at,createComment:tt,setText:ot,setElementText:pt,parentNode:rt,nextSibling:nt},$s=ct(et);function yk(...$){return $s.createApp(...$)}function gk(){return{children:[]}}function Js($,J,U){return J>=$.x&&U>=$.y&&J<$.x+$.w&&U<$.y+$.h}function xk($,J){return J.x>=$.x&&J.y>=$.y&&J.x+J.w<=$.x+$.w&&J.y+J.h<=$.y+$.h}function QJ($){return Math.max(0,$.w)*Math.max(0,$.h)}function H8($){return $.visible!==!1}function Us(){return typeof performance<"u"?performance.now():Date.now()}function aB($){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 _s=0;function oB($){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 R=U.get(P);if(!R)continue;if(R.delete(O),R.size===0)U.delete(P)}Q.delete(O)}function Y(O,M){if(!H8(M))return;let P=aB(M.rect);if(!P)return;Q.set(O,P);for(let R=P.y0;R<=P.y1;R++){let k=U.get(R);if(!k)k=new Set,U.set(R,k);k.add(O)}}function K(O,M){if(!H8(M)){Z(O);return}let P=aB(M.rect),R=Q.get(O);if(!P){Z(O);return}if(R&&R.y0===P.y0&&R.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=[],R=U.get(M);if(!R)return P;for(let k of R){let L=J.get(k);if(!L)continue;if(!H8(L))continue;if(Js(L.rect,O,M))P.push(L)}return P.sort((k,L)=>QJ(L.rect)-QJ(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&&QJ(P.rect)<QJ(M.rect))M=P;return M}function q(O,M){if(!M)return[];return[...O.filter((R)=>R.id!==M.id),M]}function H(O){let M=aB(O.rect),P=M?U.get(M.y0):null;if(!P){let L=[];for(let C of J.values()){if(!H8(C))continue;if(xk(C.rect,O.rect))L.push(C)}let v=L.sort((C,b)=>QJ(b.rect)-QJ(C.rect)||C.zIndex-b.zIndex);return q(v,O)}let R=[];for(let L of P){let v=J.get(L);if(!v)continue;if(!H8(v))continue;if(xk(v.rect,O.rect))R.push(v)}let k=R.sort((L,v)=>QJ(v.rect)-QJ(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:Us(),__stopped:!1,stopPropagation(){this.__stopped=!0},preventDefault(){this.defaultPrevented=!0},composedPath(){return[...M].reverse()}}}function j(O,M,P){if(P.currentTarget=M,!M)return;let R=M.handlers[O];if(R)try{R(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,R){R.target=P;let k=`${O}Capture`;R.eventPhase=1;for(let L of M)if(j(k,L,R),R.__stopped)return;if(P){if(R.eventPhase=2,j(O,P,R),R.__stopped)return}R.eventPhase=3;for(let L=M.length-2;L>=0;L--)if(j(O,M[L],R),R.__stopped)return}function D(O){if(_===O)return;let M=_?J.get(_)??null:null,P=O?J.get(O)??null:null,R=P&&H8(P)?P:null;if(_=R?.id??null,X?.(M?.id??null,_),M){let k=H(M),L=E("blur",k);B("blur",k,M,L)}if(R){let k=H(R),L=E("focus",k);B("focus",k,R,L)}}function w(O,M,P){let R=E(O,M);return Object.assign(R,{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 A(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 R=E(O,M);return Object.assign(R,{key:P.key,code:P.code??"",combo:A(P),ctrlKey:P.ctrlKey,shiftKey:P.shiftKey,altKey:P.altKey,metaKey:P.metaKey,repeat:P.repeat})}function f(O,M,P){let R=E(O,M);return Object.assign(R,{data:P.data,inputType:P.inputType,isComposing:P.isComposing,text:P.text})}function T(O,M,P){let R=F(M.cellX,M.cellY),k=P??N(R),L=k?q(R,k):[],v=w(O,L,M);B(O,L,k,v)}function z(O,M){let P=_?J.get(_)??null:null,R=P?H(P):[],k=I(O,R,M);return B(O,R,P,k),k.defaultPrevented}function S(O,M){let P=_?J.get(_)??null:null,R=P?H(P):[],k=f(O,R,M);return B(O,R,P,k),k.defaultPrevented}return{register(O){let M=O.id??`n${_s++}`,P=O.focusable,R={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,R),Y(M,R),R},update(O,M){let P=J.get(O);if(!P)return;let R=M.visible??P.visible;if(R===!1){if(_===O)D(null);if(G===O)G=null}J.set(O,{...P,...M,rect:M.rect??P.rect,zIndex:M.zIndex??P.zIndex,visible:R,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)D(null)},setMetrics(O){},focus(O){D(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)D(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),R=w("pointermove",P,O);return B("pointermove",P,M,R),R.defaultPrevented}if(O.type==="pointerup"&&G){let M=J.get(G)??null,P=M?H(M):[],R=w("pointerup",P,O);return B("pointerup",P,M,R),G=null,R.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:H8(O),focusable:Boolean(O.focusable)}))},dispose(){U.clear(),Q.clear(),J.clear(),_=null,G=null}}}import{ref as Qs,shallowReactive as Gs}from"vue";function hk($){let J=Qs(Boolean($?.enabled)),U=Gs([]),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 Vs(){let $=globalThis.performance;if($&&typeof $.now==="function")return $.now();return Date.now()}function Xs($){return String($??"").trim()==="1"}function Ys($){return String($??"").trim().toLowerCase()==="json"?"json":"text"}function VU($){let J=globalThis.process?.env;if(!Xs(J?.GOATCHAIN_PROFILE_TUI))return null;let U=Ys(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,j=0,B=0,D=Number(J?.GOATCHAIN_PROFILE_TUI_LOG_EVERY_MS??1000),w=Vs,A=w();function I(){let T=w(),z=T-A;if(z<=0)return;A=T;let S=_?_*1000/z:0,O=Q?Q*1000/z:0,M=_?X/_:0,P=_?Z/_:0,R=_?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:R,full:G,sorted:V,wps:k,avgWriteMs:L,maxWriteMs:q,bps:v,avgBytes:C,writeMode:{stream:E,sync:j,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=${R.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}/${j}/${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,j=0,B=0}return setInterval(I,Number.isFinite(D)?Math.max(100,D):1000).unref?.(),{now:w,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")j++;else B++}}}var eG=Symbol("TerminalContext"),GJ=Symbol("LayoutContext"),a5=Symbol("VisibilityContext"),k0=Symbol("EventZIndex"),$V=Symbol("ImeAnchor");var VJ=Symbol("RenderStack");var o5=!1;function JV($=!1){if(o5=$,o5)try{E$("fs").writeFileSync("/tmp/goatchain-debug.log",`=== GoatChain Debug Log Started at ${new Date().toISOString()} ===
|
|
894
|
-
|
|
895
|
-
`)}catch(J){}return{render:(J)=>uk("[RENDER]",J),stream:(J)=>uk("[STREAM]",J),error:(J,...U)=>{if(!o5)return;let _=`[${new Date().toISOString().split("T")[1].slice(0,-1)}] [ERROR] ${J}`+(U.length?` ${JSON.stringify(U)}`:"");mk(_+`
|
|
896
|
-
`)}}}function uk($,J){if(!o5)return;let U=new Date().toISOString().split("T")[1].slice(0,-1);mk(`[${U}] ${$} ${J}
|
|
897
|
-
`)}function mk($){if(!o5)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,UV=new Map;function lk($){XU++;try{if(XU===1)UV.clear();return $()}finally{if(XU--,XU===0)UV.clear()}}function J7($){for(let J=0;J<$.length;J++)if($.charCodeAt(J)>127)return!1;return!0}function Zs($){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 tB=null;try{tB=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null}catch{tB=null}function sB($,J){if(!$)return;let U=tB;if(!U||!Zs($)){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 YJ($){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(J7($))return $.length;if(XU>0){let Q=UV.get($);if(Q!=null)return Q}let J=js($);if(J!=null)return J;let U=0;if(sB($,(Q)=>{U+=u4(Q)}),XU>0)UV.set($,U);return Ds($,U),U}var t5=new Map,Ks=256;function I4($){if($=Math.max(0,Math.floor($)),$===0)return"";let J=t5.get($);if(J)return J;let U=" ".repeat($);if(t5.size>=Ks)t5.clear();return t5.set($,U),U}var s5=new Map,Ns=8,Fs=256;function YU($,J){if(J=Math.max(0,Math.floor(J)),J===0)return"";if(!$)return"";let U=s5.get($);if(!U){if(s5.size>=Ns)s5.clear();U=new Map,s5.set($,U)}let Q=U.get(J);if(Q)return Q;let _=$.repeat(J);if(U.size>=Fs)U.clear();return U.set(J,_),_}function m4($,J){if(J=Math.max(0,Math.floor(J)),J<=0)return"";if($&&J7($))return $.slice(0,J);let U=[],Q=0;return sB($,(_)=>{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=$&&J7($)?$.length:M$($);if(U>=J)return $;return`${$}${I4(J-U)}`}var e5=new Map,Ws=32,ck=512;function qs($){let J=e5.get($);if(J)return J;if(e5.size>=Ws)e5.clear();return J=new Map,e5.set($,J),J}function eB($,J){if(J=Math.max(0,Math.floor(J)),J===0)return"";if(!$)return I4(J);let U=qs(J),Q=U.get($);if(Q!=null)return Q;let _=z6($);if(_&&J7(_)){let V=_.length>=J?_.slice(0,J):`${_}${I4(J-_.length)}`;if(U.size>=ck)U.clear();return U.set($,V),V}let G=h6(m4(_,J),J);if(U.size>=ck)U.clear();return U.set($,G),G}var $7=new Map,Hs=32,dk=256;function Bs($){let J=$7.get($);if(J)return J;if($7.size>=Hs)$7.clear();return J=new Map,$7.set($,J),J}var XJ=new Map,Os=1024;function js($){let J=XJ.get($);if(J==null)return null;return XJ.delete($),XJ.set($,J),J}function Ds($,J){if(XJ.set($,J),XJ.size>Os){let U=XJ.keys().next().value;if(U!=null)XJ.delete(U)}}function $O(){$7.clear(),t5.clear(),s5.clear(),XJ.clear(),e5.clear()}function K0($,J){J=Math.max(1,Math.floor(J));let U=Bs(J);if($&&J7($)){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>=dk)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(sB(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>=dk)U.clear();return U.set($,G),G}var ZU=JV(K6()),ik=0,Es=0;function rk($){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),j=0,B=Number.POSITIVE_INFINITY,D=-1,w=[],A=[];$.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),j=0,B=Number.POSITIVE_INFINITY,D=-1,$O()});let I=Object.freeze({id:`s${ik++}`,parent:null,zIndex:0,order:0});function f(C,b){return Object.freeze({id:`s${ik++}`,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,j++,F$<B)B=F$;if(F$>D)D=F$}}function S(C){let b=`r${Es++}`,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 R(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&&!_&&j===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=${j}`);let y=N;if(N){K=Array.from(U.values()).sort(R),F=new Map;for(let m=0;m<K.length;m++)F.set(K[m].id,m);N=!1}let x=Q,c=j,s=B,F$=D,K$=Z,V$=null,Y$=!1;if(!x&&!_)if(j===0)K$=[];else{if(w.length<j)w=Array(j);K$=w;let m=0,G$=Number.isFinite(B)?B:0,L$=D;for(let P$=G$;P$<=L$;P$++)if(E[P$]===1)K$[m++]=P$;K$.length=m,Y$=!0,A.length=0,V$=A;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++;A.push(f$,V4)}}else E.fill(0);if(K$===Z)V$=Y;if(Q=!1,_=!1,j=0,B=Number.POSITIVE_INFINITY,D=-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(lk(()=>$.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:f,register:S,update:O,unregister:M,render:v}}var Ms=0;function nk($){if(!$||typeof $!=="object")return!1;let J=Object.getPrototypeOf($);return J===Object.prototype||J===null}function Ls($,J){if($===J)return!0;if(!nk($)||!nk(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 pk($,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(!Ls($[_],J[_]))return!1}return!0}function QO($){let J=pB({cols:$.cols,rows:$.rows}),U=hk({enabled:Boolean(globalThis.__VT_DEBUG_TRACE__)}),Q=VU("cli-scheduler"),_=oB({record:(R)=>U.push({type:"event",at:Date.now(),event:R}),onFocusChange:(R,k)=>U.push({type:"focus",at:Date.now(),prev:R,next:k})}),G=rk(J),V=J.on("commit",({dirtyRows:R})=>{U.push({type:"commit",at:Date.now(),dirtyRows:R,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 j(){if(!q)return;clearTimeout(q),q=null}function B(R){let k=Date.now(),L=Math.max(0,R-k);if(L>0){j(),N=R,q=setTimeout(()=>{q=null,E()},L);return}if(j(),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 D(){if(K)return;if(Z)return;j(),X=!1,E()}function w(R){if(K)return;if(Z)return;let k=R?.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 A=_O([]),I={mount(R,k){let L=`p${Ms++}`,v={...k},C=_O({id:L,component:R,props:v});A.push(C);let b=!0,y={update(x){if(!b)return;let c={...v,...x};if(pk(v,c))return;v=c,C.props=v,w()},move(x,c){if(!b)return;let s={...v,x,y:c};if(pk(v,s))return;v=s,C.props=v,w()},unmount(){if(!b)return;b=!1;let x=A.findIndex((c)=>c.id===L);if(x>=0)A.splice(x,1);w()}};return w(),y}},f=_O({originX:0,originY:0,clipRect:{x:0,y:0,w:$.cols,h:$.rows}}),T=J.on("resize",({cols:R,rows:k})=>{f.clipRect={x:0,y:0,w:R,h:k},w()}),z={terminal:J,renderer:_V(null),events:_V(_),scheduler:{invalidate:w,flush:E,flushNow:D},runtime:I,observability:{trace:U},defaultStyle:UO($.defaultStyle??{}),render:G},S=_V(null),O=Ps({name:"TerminalAppRoot",setup(){return KU(eG,z),KU(GJ,f),KU(a5,UO(!0)),KU(k0,UO(0)),KU(VJ,_V(G.rootStack)),KU($V,S),()=>{let R=A.map((k)=>JO(k.component,{key:k.id,...k.props}));return JO("div",null,[JO($.component,$.props??{}),...R])}}}),M=yk(O),P=gk();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 zs=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 QV($){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 Rs=Object.freeze(Object.fromEntries(Object.entries(zs).map(([$,J])=>[$,QV(J)])));function GO($){if(!$)return;return Rs[$]}var ZJ={lastFrameAt:0,lastFrameBytes:0,lastWriteMs:0,writeEmaMs:0,writeMode:"stream",fps:0,bytesPerSec:0},GV=0,VO=0,XO=0;function YO(){return ZJ}function ak($){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(ZJ.lastFrameAt=J,ZJ.lastFrameBytes=U,ZJ.lastWriteMs=Q,ZJ.writeEmaMs=_,ZJ.writeMode=G,GV===0)GV=J;VO++,XO+=U;let V=J-GV;if(V>0)ZJ.fps=VO*1000/V,ZJ.bytesPerSec=XO*1000/V;if(V>=1000)GV=J,VO=0,XO=0}var ZO=null;function R6(){if(!ZO)ZO=JV(K6());return ZO}var VV=null;try{let $=globalThis.require?.("node:fs")??globalThis.require?.("fs");if($?.writeSync)VV=(J,U)=>{let Q=Buffer.from(U,"utf8");$.writeSync(J,Q)}}catch{}var As="\x1B[?2026h",ok="\x1B[?2026l";function ws($){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 XV($,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??{}),j=U?.env??{},B=ws(j.GOATCHAIN_TUI_WRITE_MODE??j.VUE_TUI_WRITE_MODE),D=Number(j.GOATCHAIN_TUI_CHUNK_SIZE??j.VUE_TUI_CHUNK_SIZE),w=Number.isFinite(D)?Math.max(512,Math.floor(D)):8192,A=Number(j.GOATCHAIN_TUI_CHUNK_THRESHOLD??j.VUE_TUI_CHUNK_THRESHOLD),I=Number.isFinite(A)?Math.max(1024,Math.floor(A)):65536,f=Number(j.GOATCHAIN_TUI_SYNC_MAX_BYTES??j.VUE_TUI_SYNC_MAX_BYTES),T=Number.isFinite(f)?Math.max(1024,Math.floor(f)):131072,z=E&&U?.env?.GOATCHAIN_DISABLE_CURSOR_POS==="1",S=!1,O=0,M=!1,P=null,R=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$]?QV(J.palette[Q$]):GO(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$]?QV(J.palette[Q$]):GO(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<=w){_.write(Q$);return}for(let Z$=0;Z$<Q$.length;Z$+=w){let k$=Q$.slice(Z$,Z$+w);_.write(k$)}return}if(K6())R6().render(`writeChunked: sync chunked write of ${Q$.length} bytes`);try{if(Q$.length<=w)_.write(Q$);else for(let Z$=0;Z$<Q$.length;Z$+=w){let k$=Q$.slice(Z$,Z$+w);_.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?As:""),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?ok:"");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(VV&&_.fd===1);if(l>=I||R>=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=${w}, threshold=${I}, emaMs=${R.toFixed(2)})`);s4(h)}else if(p==="sync"&&VV&&_.fd===1){if(K6())R6().render(" Using writeSync");try{VV(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${ok}`)}catch{}throw l}{let l=performance.now()-q$;if(R=R===0?l:R*0.85+l*0.15,ak({at:Date.now(),bytes:h.length,writeMs:l,writeEmaMs:R,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 fs}from"vue";function p4(){let $=fs(GJ,null);if(!$)throw Error("LayoutContext is missing (TerminalProvider/TView)");return $}import{inject as ks}from"vue";function NU(){let $=ks(VJ,null);if(!$)throw Error("RenderStack is missing");return $}import{computed as Ss,onBeforeUnmount as Ts,ref as vs,watchEffect as Cs}from"vue";import{inject as Is}from"vue";function L4(){let $=Is(eG,null);if(!$)throw Error("TerminalProvider is missing");return $}function N0($){let{events:J}=L4(),U=vs(null),Q=Ss(()=>$()),_=Cs(()=>{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 Ts(()=>{_();let G=J.value;if(G&&U.value)G.unregister(U.value)}),{id:U}}import{computed as bs,inject as ys,provide as gs,ref as tk,vShow as xs}from"vue";var YV="__vueTerminalOnShow",sk=!1;function hs(){if(sk)return;sk=!0;let $=xs,J=$.beforeMount,U=$.updated,Q=$.beforeUnmount,_=(G,V)=>{if(!G||typeof G!=="object")return;let X=G[YV];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 us=Object.freeze({position:"absolute",left:"-9999px",top:"0",width:"0",height:"0",overflow:"hidden"});function p6($){hs();let{scheduler:J}=L4(),U=ys(a5,tk(!0)),Q=tk(!0),_=bs(()=>U.value&&Q.value);if($?.provide)gs(a5,_);let G=(X)=>{Q.value=X,J.invalidate()};return{visible:_,rootProps:{style:us,onVnodeBeforeMount:(X)=>{let Z=X.el;if(Z&&typeof Z==="object")Z[YV]=G},onVnodeBeforeUnmount:(X)=>{let Z=X.el;if(Z&&typeof Z==="object"&&Z[YV]===G)delete Z[YV]}}}}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 ek,defineComponent as is,h as rs,provide as $I,shallowReactive as ns,watchEffect as ps}from"vue";import{computed as ms,onBeforeUnmount as cs,ref as ds,watchEffect as ls}from"vue";function o6($){let{scheduler:J,render:U}=L4(),Q=NU(),_=ds(null),G=ms(()=>$()),V=ls(()=>{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 cs(()=>{if(V(),_.value)U.unregister(_.value),J.invalidate()}),{id:_}}var KJ={tl:"┌",tr:"┐",bl:"└",br:"┘",h:"─",v:"│"},as=-1,os=1e6,N6=is({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=ek(()=>{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=ek(()=>_.createStack(V.value,$.zIndex)),F=ns({originX:0,originY:0,clipRect:null});function N(H,E,j){let B=Math.max(0,Math.floor(H.w)),D=Math.max(0,Math.floor(H.h));if(!$.border||B<2||D<2)return;let w=Math.floor(H.x),A=Math.floor(H.y),I=w+B-1,f=A+D-1,T=Math.max(0,B-2),z=()=>{if(U.write(`${KJ.tl}${YU(KJ.h,T)}${KJ.tr}`,{x:w,y:A,style:E}),$.title){let M=Math.max(0,B-4),P=z6($.title),R=m4(P,M);U.write(` ${R} `,{x:w+1,y:A,style:E})}},S=()=>{U.write(`${KJ.bl}${YU(KJ.h,T)}${KJ.br}`,{x:w,y:f,style:E})},O=(M)=>{U.put(w,M,KJ.v,E),U.put(I,M,KJ.v,E)};if(!j){z(),S();for(let M=A+1;M<f;M++)O(M);return}for(let M of j){if(M<A||M>f)continue;if(M===A)z();else if(M===f)S();else O(M)}}function q(H,E,j){if(!$.clear)return;if(!j){U.fill(H.x,H.y,H.w,H.h," ",E);return}let B=Math.floor(H.y),D=B+Math.max(0,Math.floor(H.h));for(let w of j){if(w<B||w>=D)continue;U.fill(H.x,w,H.w,1," ",E)}}return ps(()=>{let H=Y.value,E=$.border?1:0,j=Math.max(0,Math.floor($.padding)),B=Math.max(0,Math.floor((H.w-E*2-1)/2)),D=Math.max(0,Math.floor((H.h-E*2-1)/2)),w=Math.min(j,B,D),A={x:H.x+E+w,y:H.y+E+w,w:Math.max(0,H.w-E*2-w*2),h:Math.max(0,H.h-E*2-w*2)},I=F0(A,H);if(G.clipRect&&I)I=F0(I,G.clipRect);if(!I)I={x:0,y:0,w:0,h:0};F.originX=A.x-Math.floor($.scrollX),F.originY=A.y-Math.floor($.scrollY),F.clipRect=I}),o6(()=>({stack:K.value,zIndex:as,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,j=$.style??Q.value;q(E,j,H??null)}})),o6(()=>({stack:K.value,zIndex:os,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,j=$.style??Q.value;N(E,j,H??null)}})),$I(GJ,F),$I(VJ,K),()=>rs("div",Z,J.default?.())}});import{computed as KO,defineComponent as ts,h as ss}from"vue";function JI($,J){if(J<=0)return"";return $=z6($),m4($,J)}function UI($){return YJ($).split(`
|
|
900
|
-
`)}function es($){let J=UI($),U=0;for(let Q of J)U=Math.max(U,M$(Q));return U}var t=ts({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=KO(()=>es($.value)),X=KO(()=>{let Y=$.w??V.value;if(Y<=0)return[""];if(!$.wrap)return UI($.value).map((F)=>JI(F,Y));let K=YJ($.value);return K0(K,Y).map((F)=>JI(F,Y))}),Z=KO(()=>{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=(j)=>{let B=j-K.y;if(B<0||B>=K.h)return;if($.clear)J.write(N,{x:K.x,y:j,style:F});if(B<0||B>=H)return;let D=m4(q[B]??"",K.w);J.write(h6(D,K.w),{x:K.x,y:j,style:F})};if(!Y){for(let j=0;j<K.h;j++)E(K.y+j);return}for(let j of Y)E(j)}})),()=>ss("span",G)}});import{computed as U7,defineComponent as $e,h as Je,inject as Ue,provide as NO,shallowReactive as _e,watchEffect as _I}from"vue";var Qe=Object.freeze({x:0,y:0,w:0,h:0}),R4=$e({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=Ue(k0,U7(()=>0)),K=U7(()=>(Y.value??0)+($.zIndex??0)),F=U7(()=>a6({x:$.x,y:$.y,w:$.w,h:$.h},Q.originX,Q.originY)),N=U7(()=>{let j=F.value;if(!Q.clipRect)return j;return F0(j,Q.clipRect)??Qe}),{id:q}=N0(()=>({rect:N.value,zIndex:K.value,visible:X.value,focusable:$.focusable,selectable:$.selectable,handlers:{clickCapture:(j)=>J("clickCapture",j),click:(j)=>J("click",j),dblclickCapture:(j)=>J("dblclickCapture",j),dblclick:(j)=>J("dblclick",j),pointerdownCapture:(j)=>J("pointerdownCapture",j),pointerdown:(j)=>J("pointerdown",j),pointerupCapture:(j)=>J("pointerupCapture",j),pointerup:(j)=>J("pointerup",j),pointermoveCapture:(j)=>J("pointermoveCapture",j),pointermove:(j)=>J("pointermove",j),wheelCapture:(j)=>J("wheelCapture",j),wheel:(j)=>J("wheel",j),keydownCapture:(j)=>J("keydownCapture",j),keydown:(j)=>J("keydown",j),keyupCapture:(j)=>J("keyupCapture",j),keyup:(j)=>J("keyup",j),focusCapture:(j)=>J("focusCapture",j),focus:(j)=>J("focus",j),blurCapture:(j)=>J("blurCapture",j),blur:(j)=>J("blur",j)}}));_I(()=>{if(!$.autoFocus)return;if(!X.value)return;let j=G.value,B=q.value;if(!j||!B)return;if(j.getFocused()===B)return;j.focus(B)});let H=_e({originX:0,originY:0,clipRect:null}),E=U7(()=>_.createStack(V.value,$.zIndex));return _I(()=>{let j=F.value;H.originX=j.x-Math.floor($.scrollX),H.originY=j.y-Math.floor($.scrollY),H.clipRect=N.value}),NO(GJ,H),NO(VJ,E),NO(k0,K),()=>Je("div",Z,U.default?.())}});import{computed as FO,defineComponent as WO,h as V2,onBeforeUnmount as Ge,onMounted as Ve,ref as _7,shallowRef as Xe,watch as GI,watchEffect as Ye}from"vue";function ZV($,J,U){return Math.max(J,Math.min(U,$))}function Ze($){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=ZV(F+G,0,X),N=ZV(N+V,0,Z),{x:F,y:N}}function Ke($){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 QI=WO({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(),_=FO(()=>Q.clipRect?.w??0),G=FO(()=>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=FO(()=>Ze({cols:_.value,rows:G.value,w:$.w,h:$.h,placement:$.placement,offsetX:$.offsetX,offsetY:$.offsetY}));function N(){if(!$.closeOnBackdrop)return;$.onRequestClose()}function q(j){if($.modelValue&&j?.key==="Tab"&&!j?.defaultPrevented&&!Z){let B=J.value;if(B){Z=!0;try{let{x:D,y:w}=F.value,A=Math.max(0,Math.floor($.w)),I=Math.max(0,Math.floor($.h)),f=$.zIndex+($.backdrop?1:0),T={x:D,y:w,w:A,h:I},z=B.debugNodes(),S=z.filter((P)=>{if(!P.visible||!P.focusable)return!1;let R=P.rect;return R.x>=T.x&&R.y>=T.y&&R.x+R.w<=T.x+T.w&&R.y+R.h<=T.y+T.h}),O=S.find((P)=>P.zIndex===f&&P.rect.w===A&&P.rect.h===I),M;try{M=S.filter((P)=>P.id!==O?.id).sort((P,R)=>P.rect.y-R.rect.y||P.rect.x-R.rect.x||R.zIndex-P.zIndex)}catch{M=S.filter((P)=>P.id!==O?.id)}if(M.length>0){j.preventDefault?.();let P=j.shiftKey?-1:1,R=B.getFocused(),k=R?M.findIndex((C)=>C.id===R):-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(D){console.error("[TDialog] Error in Tab handling:",D)}finally{setTimeout(()=>{Z=!1},0)}}}if($.onDialogKeydown?.(j),!$.closeOnEsc)return;if(j?.defaultPrevented)return;if(j?.key!=="Escape")return;j.preventDefault?.(),$.onRequestClose()}let H=_7(null),E=!1;return GI(()=>$.modelValue,(j)=>{if(!j){H.value=null;return}if(Z)return;queueMicrotask(()=>{queueMicrotask(()=>{if(Z)return;let B=J.value;if(!B)return;let{x:D,y:w}=F.value,A=Math.max(0,Math.floor($.w)),I=Math.max(0,Math.floor($.h)),f=$.zIndex+($.backdrop?1:0),T={x:D,y:w,w:A,h:I},z=B.debugNodes().filter((P)=>{if(!P.visible||!P.focusable)return!1;let R=P.rect;return R.x>=T.x&&R.y>=T.y&&R.x+R.w<=T.x+T.w&&R.y+R.h<=T.y+T.h}),S=z.find((P)=>P.zIndex===f&&P.rect.w===A&&P.rect.h===I);if(S)H.value=S.id;let O=B.getFocused();if(O){if(z.find((R)=>R.id===O))return}let M;try{M=z.filter((P)=>P.id!==H.value).sort((P,R)=>P.rect.y-R.rect.y||P.rect.x-R.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 j=Math.max(0,Math.floor($.w)),B=Math.max(0,Math.floor($.h)),{x:D,y:w}=F.value,A=V2(R4,{x:D,y:w,w:j,h:B,zIndex:$.zIndex+($.backdrop?1:0),focusable:!0,autoFocus:!1,onKeydown:q,onClick:(I)=>{I?.stopPropagation?.()},onFocusCapture:Y,onBlurCapture:K},()=>V2(N6,{x:0,y:0,w:j,h:B,border:!0,title:$.title,padding:$.padding,style:$.style},()=>V2($.content)));if(!$.backdrop)return A;return V2(R4,{x:0,y:0,w:_.value,h:G.value,zIndex:$.zIndex,onClick:N},()=>[V2(N6,{x:0,y:0,w:_.value,h:G.value,border:!1,padding:0,clear:!0}),A])}}}),A4=WO({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=_7(!1),X=_7(0),Z=_7(null),Y=_7(null);function K(f,T,z){return T>=f.x&&z>=f.y&&T<f.x+f.w&&z<f.y+f.h}function F(f){return Math.max(0,f.w)*Math.max(0,f.h)}function N(){let f=$.buttons.findIndex((T)=>T.default);return f>=0?f:0}function q(f){let T=$.buttons[f];if(!T)return;if(J("confirm",{...T,index:f}),$.closeOnConfirm)D()}function H(){let f=_.value,T=f?.getFocused()??null;if(Z.value=T,Y.value=null,!f||!T)return;let z=f.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 f=Z.value,T=Y.value;Z.value=null,Y.value=null;let z=()=>{let S=_.value;if(!S)return;if(f){if(S.debugNodes().find((k)=>k.id===f&&k.visible&&k.focusable)){S.focus(f),G.invalidate();return}}if(T){let R=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(R){S.focus(R),G.invalidate();return}}let M=S.debugNodes().filter((P)=>P.visible&&P.focusable).sort((P,R)=>P.zIndex-R.zIndex||F(R.rect)-F(P.rect))[0]?.id??null;if(M)S.focus(M),G.invalidate()};queueMicrotask(()=>{queueMicrotask(()=>{queueMicrotask(()=>{z()})})})}let j=WO({name:"TDialogContent",setup(){return()=>{let f=U.default?.()??null;if(!$.buttons.length)return f;let T=Ke({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$=[V2(t,{key:`btn-t-${C}`,x:k,y:z,w:y,value:b,style:F$}),V2(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 V2("div",null,[f,...L])}}}),B=Xe(null);function D(){V.value=!0,J("update:modelValue",!1),J("close"),E()}function w(){J("focus")}function A(){J("blur")}function I(f){if(J("keydown",f),!$.modelValue)return;if(f?.defaultPrevented)return;if(!$.buttons.length)return;if(f.key==="ArrowLeft"||f.key==="ArrowRight"){f.preventDefault?.();let T=f.key==="ArrowLeft"?-1:1,z=$.buttons.length-1;X.value=ZV(X.value+T,0,z);return}if(f.key==="Enter")f.preventDefault?.(),q(X.value)}return GI(()=>$.modelValue,(f,T)=>{if(f&&!T)H();if(f&&!T)X.value=ZV(N(),0,Math.max(0,$.buttons.length-1));if(!T||f)return;if(V.value){V.value=!1;return}J("close"),E()},{immediate:!0}),Ve(()=>{if(!$.teleport)return;B.value=Q.mount(QI,{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:j,onRequestClose:D,onDialogFocus:w,onDialogBlur:A,onDialogKeydown:I})}),Ye(()=>{if(!$.teleport)return;let f=B.value;if(!f)return;f.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:j,onRequestClose:D,onDialogFocus:w,onDialogBlur:A,onDialogKeydown:I})}),Ge(()=>{if(B.value?.unmount(),B.value=null,Z.value||Y.value)E()}),()=>{if($.teleport)return null;return V2(QI,{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:j,onRequestClose:D,onDialogFocus:w,onDialogBlur:A,onDialogKeydown:I})}}});import{computed as j8,defineComponent as De,h as Ee,inject as jI,onBeforeUnmount as Pe,ref as t6,watch as RO,watchEffect as Me}from"vue";function VI($){let J=String($||""),U=Math.max(J.lastIndexOf("/"),J.lastIndexOf("\\"));return(U>=0?J.slice(U+1):J)||J}function Ne($){let J=$.lastIndexOf(".");if(J===-1)return"";return $.slice(J+1).toLowerCase()}function Fe($){return["png","jpg","jpeg","gif","svg","webp","bmp","ico"].includes($)}function We($){return["mp4","webm","ogg","avi","mov","mkv","flv","wmv"].includes($)}function qe($){return["mp3","wav","ogg","flac","m4a","wma"].includes($)}function He($){return["pdf","doc","docx","txt","rtf","odt"].includes($)}function Be($){return["js","ts","jsx","tsx","html","css","scss","less","json","xml","yml","yaml","md","markdown","py","java","cpp","c","go","rb","php"].includes($)}function XI($){if(!$)return"[file]";let J=VI($);return`[${z6(J)}]`}function KV($,J,U){if(U==="directory")return{...$,fg:"blueBright",underline:!0,bold:!0};let Q=VI(J),_=Ne(Q);if(Fe(_))return{...$,fg:"magentaBright",underline:!0,bold:!0};if(We(_))return{...$,fg:"yellowBright",underline:!0,bold:!0};if(qe(_))return{...$,fg:"greenBright",underline:!0,bold:!0};if(He(_))return{...$,fg:"blueBright",underline:!0,bold:!0};if(Be(_))return{...$,fg:"cyanBright",underline:!0,bold:!0};return{...$,fg:"cyanBright",underline:!0}}function Q7($,J,U){return Math.max(J,Math.min(U,$))}function Oe($){for(let J=0;J<$.length;J++)if($.charCodeAt(J)>127)return!1;return!0}var X2=M$;function qO($,J){let U=X2($);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(Oe($))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 HO($){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 XI(U)}function YI($,J,U=$.length){let Q=0,_=Q7(U,0,$.length);for(let G=0;G<_;G++)if($[G]===J)Q++;return Q}function HU($,J,U=$.length){return YI($,J,U)}function BU($,J,U=$.length){return YI($,J,U)}function ZI($,J,U){return HU($,J,U)}function KI($,J,U){return BU($,J,U)}function NV($,J,U,Q,_,G,V){let X=Q7(G,0,$.length),Z=Q7(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,j=String.fromCodePoint(E);if(N>=X)Y+=u4(j);N+=j.length}return Y}function je($,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 j=$.codePointAt(F)??0,B=String.fromCodePoint(j);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 BO($,J,U,Q,_,G,V){if(G=Math.max(1,Math.floor(G)),V=Math.max(1,Math.floor(V)),G>=V)return je($,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 j=0,B=0;if(E===J){let D=WU(Q,N);B=M$(D),j=1,N++}else if(E===U){let D=qU(_,q);B=M$(D),j=1,q++}else if($.charCodeAt(H)<=127)j=1,B=1;else{let w=$.codePointAt(H)??0,A=String.fromCodePoint(w);j=A.length,B=u4(A)}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+=j,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 NI($,J,U,Q,_,G,V,X){let Z=Q7(G,0,$.length),Y=BO($,J,U,Q,_,V,X);for(let F=0;F<Y.length;F++){let N=Y[F];if(Z<=N.end){let q=NV($,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:NV($,J,U,Q,_,K.start,K.end),lines:Y}}function FI($,J,U,Q,_,G){let V=Q7(G,0,$.length),X=HO($);for(let Y=0;Y<X.length;Y++){let K=X[Y];if(V<=K.end){let F=NV($,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:NV($,J,U,Q,_,Z.start,Z.end),lines:X}}function OO($,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 D=WU(Q,K),w=M$(D);if(Y+w>Z)return{index:N,hit:{kind:"multiline",index:K}};if(Y+=w,Y>=Z)return{index:N+1,hit:null};K++,N+=1;continue}if(q===U){let D=qU(_,F),w=M$(D);if(Y+w>Z)return{index:N,hit:{kind:"mention",index:F}};if(Y+=w,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,j=String.fromCodePoint(E),B=u4(j);if(Y+B>Z)return{index:N,hit:null};if(Y+=B,N+=j.length,Y>=Z)return{index:N,hit:null}}return{index:V,hit:null}}function WI($,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="",j=0,B=[];for(let D=V;D<X;){let w=$[D];if(w===`
|
|
904
|
-
`){D+=1;continue}let A="",I=0,f=0,T=!1,z=null,S=0,O;if(w===U)A=WU(_,q),I=M$(A),f=1,z="multiline",S=q,q++,T=!0;else if(w===Q)A=qU(G,H),I=M$(A),f=1,z="mention",S=H,O=String(G?.[H]??""),H++,T=!0;else if($.charCodeAt(D)<=127)A=J[D]??$[D],f=1,I=1;else{let v=$.codePointAt(D)??0,C=String.fromCodePoint(v);A=J.slice(D,D+C.length),f=C.length,I=u4(A)}let M=N,P=N+I;if(P<=K){N=P,D+=f;continue}if(M>=F)break;let R=Math.max(0,K-M),k=Math.min(P,F)-Math.max(M,K);if(k>0){let L=FU(A,R,k);if(!L&&I>1&&R>0&&I<=Z)L=A;if(E+=L,L===A)j+=I;else j+=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,D+=f}if(j<Z)E+=I4(Z-j);return{text:E,chips:B}}function qI($,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),j=[];for(let B=V;B<X;){let D=$[B];if(D===`
|
|
905
|
-
`){B+=1;continue}let w="",A=0,I=0;if(D===U)w=WU(_,H),A=X2(w),I=1,H++;else if(D===Q)w=qU(G,E),A=X2(w),I=1,E++;else{let M=$.codePointAt(B)??0,P=String.fromCodePoint(M);w=J.slice(B,B+P.length),I=P.length,A=u4(w)}if(B>=Z.end||B+I<=Z.start){q+=A,B+=I;continue}let f=q,T=q+A,z=Math.max(0,F-f),S=Math.min(T,N)-Math.max(f,F);if(T>F&&f<N&&S>0){let M=FU(w,z,S),P=Math.max(f,F)-F;if(M)j.push({startCell:P,text:M})}q=T,B+=I}return j}var m0="",W0="";function jO($,J){return $[J]===m0}function G7($,J){return $[J]===W0}function FV($,J=$.length){return HU($,m0,J)}function DO($,J=$.length){return BU($,W0,J)}function WV($,J){return ZI($,m0,J)}function OU($,J){return KI($,W0,J)}function EO($,J,U,Q,_){return BO($,m0,W0,J,U,Q,_)}function B8($,J,U,Q,_,G){return NI($,m0,W0,J,U,Q,_,G)}function O8($,J,U,Q){return FI($,m0,W0,J,U,Q)}function PO($,J,U,Q,_,G){return OO($,m0,W0,J,U,Q,_,G)}function MO($,J,U,Q,_){return OO($,m0,W0,J,U,Q.start,Q.end,_)}function HI($,J,U,Q,_,G,V,X){return WI($,J,m0,W0,U,Q,_,G,V,X)}function BI($,J,U,Q,_,G,V,X,Z){return qI($,J,m0,W0,U,Q,_,G,V,X,Z)}function j4($,J,U){return Math.max(J,Math.min(U,$))}function I0($){return $===" "||$==="\t"||$===`
|
|
906
|
-
`||$==="\r"}function NJ($){return/^[\p{L}\p{N}_]$/u.test($)}function LO($,J){let U=j4(J,0,$.length);if(U===0)return 0;while(U>0&&I0($[U-1]))U--;if(U===0)return 0;let Q=NJ($[U-1]);while(U>0){let _=$[U-1];if(I0(_))break;if(NJ(_)!==Q)break;U--}return U}function zO($,J){let U=j4(J,0,$.length);if(U>=$.length)return $.length;while(U<$.length&&I0($[U]))U++;if(U>=$.length)return $.length;let Q=NJ($[U]);while(U<$.length){let _=$[U];if(I0(_))break;if(NJ(_)!==Q)break;U++}return U}function OI($,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(I0(Q)){while(_>0&&I0($[_-1]))_--;while(G<$.length&&I0($[G]))G++;return{start:_,end:G}}let V=NJ(Q);while(_>0){let X=$[_-1];if(I0(X))break;if(NJ(X)!==V)break;_--}while(G<$.length){let X=$[G];if(I0(X))break;if(NJ(X)!==V)break;G++}return{start:_,end:G}}function Le($){if($.ctrlKey||$.metaKey||$.altKey)return!1;return $.key.length===1}function wO($){return HO($)}function AO($,J){let U=j4(J,0,$.length),Q=wO($);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:X2(X),lines:Q}}}let _=Q[Q.length-1];return{line:Q.length-1,col:X2($.slice(_.start,_.end)),lines:Q}}var ze=0,J6=De({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=jI($V,null),F=`TInput:${ze++}`,N=jI(k0,j8(()=>0)),q=j8(()=>(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 j=t6(!1),B=t6(0),D=t6(null),w=t6(!1),A=t6(!1),I=t6(0),f=t6(0),T=t6(!1),z=t6(""),S=t6(!1),O=t6(!1),M=t6(!0),P=null,R=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=j8(()=>Math.max(1,Math.floor($.h))>1),m=j8(()=>{let g={x:$.x,y:$.y,w:$.w,h:Math.max(1,Math.floor($.h))};return a6(g,X.originX,X.originY)});RO(()=>$.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,D.value=null;else if(B.value=j4(B.value,0,i),D.value!=null)D.value=j4(D.value,0,i);if(T.value&&g!==h)S.value=!0,T.value=!1,z.value="";let p=FV(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$=j8(()=>{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=j8(()=>{if(D.value==null||D.value===B.value)return null;let g=Math.min(D.value,B.value),h=Math.max(D.value,B.value);return{start:g,end:h}});function A6(){let g=c(),h=OI(g,B.value);if(!h)return;D.value=h.start,B.value=h.end,Z$(),Q.invalidate()}function F4(){let g=c();D.value=0,B.value=g.length,Z$(),Q.invalidate()}let E4=j8(()=>{if(c())return!1;if(!$.placeholder)return!1;if(j.value&&T.value&&z.value)return!1;return!j.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?B8($$.text,$.multilineTexts,$.mentions,$$.cursor,D$,i):O8($$.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(f.value=j4(f.value,0,c$),v$<f.value)f.value=v$;else if(v$>f.value+p-1)f.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=EO(A$,$.multilineTexts,$.mentions,d$,e),_6=j4(f.value+v$,0,W4.length-1),i$=c$,l$=MO(A$,$.multilineTexts,$.mentions,W4[_6],i$);y$=l$.index,X4=l$.hit}else{let W4=wO(A$),_6=j4(f.value+v$,0,W4.length-1),i$=I.value+c$,l$=W4[_6],Y4=PO(A$,$.multilineTexts,$.mentions,l$.start,l$.end,i$);y$=Y4.index,X4=Y4.hit}if(X4){if(B.value=y$,D.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$)D.value=null;else if(D.value==null)D.value=B.value;B.value=y$,R.value=g$?B8(A$,$.multilineTexts,$.mentions,B.value,d$,e).col:O8(A$,$.multilineTexts,$.mentions,B.value).col,Z$()}function t$(g,h,q$=!1){let i=j4(h,0,g.length);if(B.value=i,D.value=null,T.value=!1,z.value="",x.value=g,a.value){let{w:p}=E(o$.value),l=Math.max(1,p),$$=l;R.value=B8(g,$.multilineTexts,$.mentions,i,$$,l).col}else R.value=O8(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(D.value==null)D.value=q$}else D.value=null;if(B.value=j4(g,0,i.length),a.value){let{w:p}=E(o$.value),l=Math.max(1,p),$$=l;R.value=B8(i,$.multilineTexts,$.mentions,B.value,$$,l).col}else R.value=O8(i,$.multilineTexts,$.mentions,B.value).col;Z$(),Q.invalidate()}RO([()=>o$.value.w,()=>o$.value.h,()=>a.value],()=>{Z$(),Q.invalidate()}),RO([()=>$.mentions,()=>$.multilineTexts],()=>{Z$(),Q.invalidate()});function _4(g){let h=F6.value;if(!h)return{value:g,cursor:B.value,deleted:!1};let q$=FV(g,h.start),i=FV(g,h.end);if(i>q$){let e=$.multilineTexts??[],D$=[...e.slice(0,q$),...e.slice(i)];J("update:multilineTexts",D$)}let p=DO(g,h.start),l=DO(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:j,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=WV(l,$$),D$=$.multilineTexts??[],v$=[...D$.slice(0,e),g,...D$.slice(e)];J("update:multilineTexts",v$);let A$=`${l.slice(0,$$)}${m0}${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$}=AO(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$?LO(h,B.value):zO(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(),D.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?LO(h,B.value):B.value-1;q4(i$,q$);return}if(g.key==="ArrowRight"){g.preventDefault();let i$=p?h.length:i?zO(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$?B8(h,$.multilineTexts,$.mentions,B.value,a$,Y4):O8(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=R.value??x$,$6=i$?MO(h,$.multilineTexts,$.mentions,r$[w4],d4).index:PO(h,$.multilineTexts,$.mentions,r$[w4].start,r$[w4].end,d4).index;q4($6,q$),R.value=d4;return}if(g.key==="Home"){if(g.preventDefault(),l)q4(0,q$);else{let{line:i$,lines:l$}=AO(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$}=AO(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]===" "&&G7(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(G7(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(jO(h,B.value-1)){let x$=WV(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(G7(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(G7(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(jO(h,B.value)){let $4=WV(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(),j.value=!1,D.value=null,J("blur"),Q.invalidate();return}if(Le(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;D.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},j.value=!0,A.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=UJ(p$(g)),i=YJ(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?U1($.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:()=>{j.value=!0,J("focus");let g=c().length,h=$.cursorToEndOnFirstFocus&&!w.value&&!A.value;if(A.value=!1,h)B.value=g,D.value=null;w.value=!0,B.value=j4(B.value,0,g),Z$(),C6(),Q.invalidate()},blur:()=>{if(j.value=!1,D.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 Me(()=>{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,j.value,B.value,D.value,I.value,f.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:f.value,l=a.value&&!q$,$$=c(),e=Q$($$),D$=q$?j.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?EO(v$,$.multilineTexts,$.mentions,W4,X4):wO(v$);for(let l$=0;l$<g.h;l$++){let Y4=p+l$,a$=_6[Y4],$4=X4,x$=a$?HI(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})??KV(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=BI(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(j.value&&M.value&&!(F6.value&&!q$)){let l$=X4,Y4=l$,a$=q$?"":e.text,$4=$.secret&&!q$?U6(a$):a$,x$=l?B8($4,$.multilineTexts,$.mentions,e.cursor,Y4,l$):O8($4,$.multilineTexts,$.mentions,e.cursor),r$=x$.col-i,D4=x$.line-p;if(K&&j.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",I8=h.bg??_.value.bg??"black",y0=$6?.style??h,B0={...y0,fg:y0.fg??b6,bg:y0.bg??I8},K1=$6&&!$6.continuation?$6.ch||" ":" ";if($.cursorShape==="underline")U.put(d4,w4,K1,{...B0,underline:!0});else if($.cursorShape==="bar")if(K1===" ")U.put(d4,w4,"│",{...B0,fg:B0.fg??b6});else U.put(d4,w4,K1,{...B0,inverse:!0});else U.put(d4,w4,K1,{...B0,inverse:!0})}}}})),Pe(()=>{z4()}),()=>Ee("span",Y)}});import{watchEffect as Ie}from"vue";import{computed as jU,ref as qV,watch as DI,watchEffect as EI}from"vue";function Re($,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 PI($,J,U){if($===J||$===U)return!0;if(I0($))return!0;return/[,;:!?,。!?、()[\]{}<>]/.test($)}function Ae($,J,U,Q,_){if(!U||$[J]!==U)return!1;if(J<=0)return!0;let G=$[J-1];return PI(G,Q,_)||!/\w/.test(G)}function we($){return/^[\w./~\\:-]$/.test($)}function fe($,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(I0($[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 ke($,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(Ae($,q,U,Q,_)){V=q;break}if(PI(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&&we($[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 MI($){let{props:J,focused:U,cursor:Q,getValue:_,rawAbsRect:G,terminal:V,scheduler:X,multilineToken:Z,mentionToken:Y}=$,K=qV(0),F=qV(null),N=qV(0),q=new Map,H=0;EI(()=>{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=_J();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 fe(_(),Q.value,J.promptTrigger||"/")}),j=jU(()=>{if(!U.value)return null;let T=J.mentionSuggestions?.length>0,z=Boolean(J.mentionWorkspace);if(!T&&!z)return null;return ke(_(),Q.value,J.mentionTrigger||"@",Z,Y)}),B=jU(()=>j.value??E.value);DI(()=>B.value?.key??null,(T,z)=>{if(z&&T!==z)F.value=null});let D=qV([]),w=0;EI(()=>{let T=j.value,z=J.mentionWorkspace;if(!T||!z)return;J.mentionMode,J.mentionShowHidden,J.mentionMaxItems;let S=++w,O=_J(),M=Math.max(0,Math.floor(J.mentionMaxItems));p5({workspaceAbs:z,input:T.query,mode:J.mentionMode,max:M,showHidden:J.mentionShowHidden,listDir:O.listDir,maxDepth:3}).then((P)=>{if(S!==w)return;D.value=P.suggestions.map((R)=>({value:`${J.mentionTrigger}${R.completion}`,insert:`${J.mentionTrigger}${R.completion} `,detail:R.kind})),X.invalidate()}).catch(()=>{if(S!==w)return;D.value=[],X.invalidate()})});let A=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)),R=O?J.mentionWorkspace?D.value:J.mentionSuggestions??[]:J.promptSuggestions??[],k=T.query.trim(),L=[];for(let v=0;v<R.length;v++){let C=R[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=Re(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)});DI(()=>A.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}),f=jU(()=>{let T=G.value,z=V.size(),S={x:0,y:0,w:z.cols,h:z.rows},O=Math.max(1,A.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))),R=Math.floor(T.y)-M,k=Math.floor(T.y)+Math.floor(T.h),L=R>=Math.floor(S.y),v=k+M<=Math.floor(S.y)+Math.floor(S.h),b=j4(L?R:v?k:R,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:j,activeContext:B,promptMatches:A,promptVisible:I,promptRect:f}}function Se($,J,U=$.length){let Q=0,_=j4(U,0,$.length);for(let G=0;G<_;G++)if($[G]===J)Q++;return Q}function Te($,J,U){return Se($,J,U)}function DU(){return{name:"promptMention",install:($)=>{let J=()=>$.getProps(),U=$.render.createStack($.render.rootStack,1e4),Q=new WeakMap,_=MI({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 KV(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),j=[...J().mentions??[]],B=N.slice(0,q),D=N.slice(H),w=D.match(/^[\s\u200B]*\]+/u);if(w){D=D.slice(w[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 A=Te(N,$.mentionToken,q);j.splice(A,0,F),$.emit("update:mentions",j);let I=D;if(I.startsWith(" "))I=I.slice(1);let f=`${B}${$.mentionToken} ${I}`,T=B.length+2;$.pushUndoSnapshot(f),$.applyEdit(f,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 f=N.insert??(N.value.endsWith(" ")?N.value:`${N.value} `),T=$.getValue().slice(0,Y.tokenStart),z=$.getValue().slice(Y.tokenEnd);if(f.endsWith(" ")&&z.startsWith(" "))z=z.slice(1);let S=`${T}${f}${z}`,O=Y.tokenStart+f.length;_.promptSuppressedKey.value=null,$.pushUndoSnapshot(S),$.applyEdit(S,O);return}let A=String(N.value||"").startsWith(q)?String(N.value).slice(q.length):String(N.value),I=J().mentionWorkspace?U1(J().mentionWorkspace,A):A;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} `),j=$.getValue().slice(0,Y.tokenStart),B=$.getValue().slice(Y.tokenEnd);if(E.endsWith(" ")&&B.startsWith(" "))B=B.slice(1);let D=`${j}${E}${B}`,w=Y.tokenStart+E.length;_.promptSuppressedKey.value=null,$.pushUndoSnapshot(D),$.applyEdit(D,w)}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 A={...Y,dim:!0},I={...Y},f={...Y,bg:"yellow",fg:"black"},T={...Y,dim:!0},z={...Y,bg:"yellow",fg:"black",dim:!0},S={...Y,dim:!0};if(F={borderStyle:A,itemStyle:I,selectedStyle:f,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)),j=Math.max(0,H-2),B=F.borderStyle;$.terminal.write(`┌${YU("─",j)}┐`,{x:N,y:q,style:B}),$.terminal.write(`└${YU("─",j)}┘`,{x:N,y:q+E-1,style:B});let D=_.promptMatches.value,w=Math.max(0,E-2);for(let A=0;A<w;A++){let I=q+1+A;if($.terminal.put(N,I,"│",B),$.terminal.put(N+H-1,I,"│",B),A>=D.length){$.terminal.write(I4(j),{x:N+1,y:I,style:B});continue}let f=D[A],T=A===_.promptActive.value,z=z6(f.item.value),S=f.item.detail?z6(f.item.detail):"",O=X2(z),M=S?X2(S):0,P=2,R=j-O-P;if(S&&R>=4){let k=T?F.selectedStyle:F.itemStyle;$.terminal.write(z,{x:N+1,y:I,style:k});let L=j-O-Math.min(M,R),v=T?F.selectedStyle:F.itemStyle;$.terminal.write(I4(L),{x:N+1+O,y:I,style:v});let C=FU(S,0,R),b=T?F.selectedDetailStyle:F.detailStyle;$.terminal.write(C,{x:N+1+O+L,y:I,style:b})}else{let k=qO(FU(z,0,j),j),L=T?F.selectedStyle:F.itemStyle;$.terminal.write(k,{x:N+1,y:I,style:L})}}if(D.length===0&&w>0){let A=q+1;$.terminal.put(N,A,"│",B),$.terminal.put(N+H-1,A,"│",B);let I=qO(FU("(no matches)",0,j),j);$.terminal.write(I,{x:N+1,y:A,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)}}})),Ie(()=>{J().mentions,_.mentionKindVersion.value})}}}function ve($,J){let U=$.selection?$.selection.start:$.cursor,Q=$.selection?$.selection.end:$.cursor;return $.value.slice(0,U)+J+$.value.slice(Q)}function Ce($,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=ve(J,J.text);return $.allow.test(U)?J.text:""}return J.text}function HV($){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=Ce(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 be($,J,U){return Math.max(J,Math.min(U,$))}function ye($){let J=Math.abs($);return J>0&&J<=3&&Number.isInteger($)}function ge($){if(Math.abs($)<=3&&Number.isInteger($))return $;return $/100}function xe($,J){let U=$-J;if(!Number.isFinite(U)||U<=0||U>120)return 1;return 1+(1-U/120)*1.5}function V7(){return{accumulator:0,lastAt:0,lastEdgeDir:0,lastEdgeAt:0}}function X7($,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=ye(J);if(V&&G!==1/0&&G>=0&&G<6)return{nextTop:U,dir:0,lines:0};let X=V?1:$.lastAt?xe(_,$.lastAt):1;$.lastAt=_,$.accumulator+=ge(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=be(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 he,h as ue,inject as me,watchEffect as ce}from"vue";var Y2={tl:"┌",tr:"┐",bl:"└",br:"┘",h:"─",v:"│"},BV=he({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=me(k0,EU(()=>0)),K=EU(()=>(Y.value??0)+($.zIndex??0)),F=EU(()=>X.value&&$.visible),N=EU(()=>{let D=U.size(),w=D.cols,A=D.rows,I=Math.floor(w*0.8),f=Math.floor(A*0.7),T=Math.floor((w-I)/2),z=Math.floor((A-f)/2);return a6({x:T,y:z,w:I,h:f},V.originX,V.originY)}),q=EU(()=>{return YJ(String($.content||"")).split(`
|
|
909
|
-
`)}),H=EU(()=>0);function E(D){if(D.preventDefault(),D.stopPropagation(),D.key==="Escape")J("close"),Q.invalidate()}let j=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:(D)=>{D.preventDefault(),D.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:(D)=>{D.preventDefault(),D.stopPropagation();let w=G.value,A=B.id.value;if(w&&A)w.focus(A)},keydown:E}}));return ce(()=>{if(!F.value)return;let D=G.value,w=B.id.value||j.id.value;if(!D||!w)return;D.focus(w)}),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 D=U.size(),w=$.style??_.value,A={...w,bg:"black",dim:!0},I=I4(D.cols);for(let V$=0;V$<D.rows;V$++)U.write(I,{x:0,y:V$,style:A});let f=N.value,T=w.fg??_.value.fg??"whiteBright",z=w.bg??_.value.bg??"black",S={...w,fg:"white"},O={...w,fg:T,bg:z},M={...w,dim:!0};U.put(f.x,f.y,Y2.tl,S),U.put(f.x+f.w-1,f.y,Y2.tr,S),U.put(f.x,f.y+f.h-1,Y2.bl,S),U.put(f.x+f.w-1,f.y+f.h-1,Y2.br,S);let P=Math.max(0,f.w-2),R=` ${z6($.title)} `,k=Math.min(R.length,P),L=f.x+1;U.write(R.slice(0,k),{x:L,y:f.y,style:S});let v=P-k;if(v>0)U.write(Y2.h.repeat(v),{x:L+k,y:f.y,style:S});let C=" Press ESC to close ",b=Math.min(C.length,P),y=f.x+Math.floor((f.w-b)/2),x=y-f.x-1,c=P-x-b;if(x>0)U.write(Y2.h.repeat(x),{x:f.x+1,y:f.y+f.h-1,style:S});if(U.write(C,{x:y,y:f.y+f.h-1,style:M}),c>0)U.write(Y2.h.repeat(c),{x:y+b,y:f.y+f.h-1,style:S});for(let V$=1;V$<f.h-1;V$++)U.put(f.x,f.y+V$,Y2.v,S),U.put(f.x+f.w-1,f.y+V$,Y2.v,S);let s=Math.max(0,f.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:f.x+1,y:f.y+1+V$,style:O})}}})),()=>ue("span",Z)}});import{computed as Y7,defineComponent as de,h as LI,inject as le,ref as OV,watch as ie,watchEffect as re}from"vue";function PU($,J,U){return Math.max(J,Math.min(U,$))}function zI($){return Boolean($.ctrlKey||$.metaKey)}var jV=de({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=le(k0,Y7(()=>0)),Y=Y7(()=>(Z.value??0)+($.zIndex??0)),K=Y7(()=>$.provider??_J()),F=OV([]),N=OV(0),q=OV(0),H=OV(null),E=1,j=Y7(()=>Math.max(0,Math.floor($.h)-1)),B=Y7(()=>{let P={x:$.x,y:$.y+1,w:$.w,h:j.value},R=a6(P,G.originX,G.originY);if(!G.clipRect)return R;return F0(R,G.clipRect)??{x:0,y:0,w:0,h:0}});function D(){let P=Math.max(0,j.value);if(P<=0){q.value=0;return}let R=Math.max(0,F.value.length-P);if(q.value=PU(q.value,0,R),N.value<q.value)q.value=N.value;else if(N.value>=q.value+P)q.value=PU(N.value-(P-1),0,R)}ie([()=>N.value,()=>F.value.length,()=>j.value],()=>{D()});async function w(){let P=Math.max(0,Math.floor($.maxSuggestions)),R=await p5({workspaceAbs:$.workspace,input:$.modelValue,mode:$.mode,max:P,showHidden:$.showHidden,listDir:K.value.listDir});F.value=R.suggestions,N.value=PU(N.value,0,Math.max(0,F.value.length-1)),D(),Q.invalidate()}let A=0;re(()=>{if(!V.value)return;$.workspace,$.mode,$.showHidden,$.modelValue,j.value,H.value=null;let P=++A;w().catch((R)=>{if(P!==A)return;F.value=[],H.value=R instanceof Error?R.message:String(R),Q.invalidate()})});function I(P){let R=P.replace(/\r/g,"").replace(/\n/g," ");J("update:modelValue",R)}function f(P){let R=F.value.length;if(R<=0)return;let k=PU(N.value+P,0,R-1);if(k!==N.value)N.value=k,D(),Q.invalidate()}function T(){let P=F.value[N.value];if(!P)return;I(P.completion)}async function z(P){let R=await K.value.stat(P);if(!R.exists){H.value="Not found",J("invalid",{reason:"not_found",absPath:P}),Q.invalidate();return}if($.mode==="file"&&R.kind==="directory"){let k=u0(P),L=u0($.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"&&R.kind!=="file"){H.value="Not a file",J("invalid",{reason:"not_file",absPath:P}),Q.invalidate();return}if($.mode==="directory"&&R.kind!=="directory"){H.value="Not a directory",J("invalid",{reason:"not_directory",absPath:P}),Q.invalidate();return}J("select",Hk(P))}async function S(){let P=U1($.workspace,$.modelValue),R=await K.value.stat(P);if(R.exists){if($.mode==="file"&&R.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(),f(-1);return}if(P.key==="ArrowDown"){P.preventDefault(),f(1);return}if(zI(P)&&(P.key==="p"||P.key==="P")){P.preventDefault(),f(-1);return}if(zI(P)&&(P.key==="n"||P.key==="N"))P.preventDefault(),f(1)}let M=V7();return N0(()=>({rect:B.value,zIndex:Y.value,visible:V.value,focusable:!1,handlers:{click:(P)=>{let R=B.value,k=q.value+(P.cellY-R.y);if(k>=0&&k<F.value.length)N.value=k,D(),Q.invalidate()},dblclick:async(P)=>{let R=B.value,k=q.value+(P.cellY-R.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 R=P.deltaY??0;if(!R)return;let k=Math.max(0,j.value),L=Math.max(0,F.value.length-k),{nextTop:v,dir:C}=X7(M,R,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,j.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 R=$.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?{...R,inverse:!0}:R;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:{...R,dim:!0}})}}})),()=>LI("span",X,[LI(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 fO,defineComponent as ne,h as pe,inject as ae,ref as RI,watchEffect as AI}from"vue";function Z2($,J,U){return Math.max(J,Math.min(U,$))}var q0=ne({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=ae(k0,fO(()=>0)),K=fO(()=>(Y.value??0)+($.zIndex??0)),F=RI(!1),N=(()=>{let O=Math.max(0,$.options.length-1);if(!$.multiple){let R=typeof $.modelValue==="number"?$.modelValue:0;return Z2(R,0,O)}let P=(Array.isArray($.modelValue)?$.modelValue:[])[0]??0;return Z2(P,0,O)})(),q=RI(N),H=fO(()=>{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}});AI(()=>{let O=Math.max(0,$.options.length-1);if(!$.multiple){let M=typeof $.modelValue==="number"?$.modelValue:0;q.value=Z2(M,0,O);return}q.value=Z2(q.value,0,O)});function E(O){return typeof O==="string"?O:O.label}function j(O){return typeof O==="string"?void 0:O.detail}function B(O){let M=Z2(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 D(){if(!$.multiple)return[];let O=Math.max(0,$.options.length-1),M=Array.isArray($.modelValue)?$.modelValue:[],P=new Set;for(let R of M){if(typeof R!=="number"||!Number.isFinite(R))continue;P.add(Z2(Math.trunc(R),0,O))}return[...P].sort((R,k)=>R-k)}function w(O){let M=O.map((P)=>$.options[P]).filter(Boolean).map((P)=>E(P));return{indices:O,values:M}}function A(O,M){let P=w(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=Z2(O,0,Math.max(0,$.options.length-1));q.value=M;let P=new Set(D());if(P.has(M))P.delete(M);else P.add(M);let R=[...P].sort((k,L)=>k-L);J("update:modelValue",R),A("change",R)}function f(){let O=D();A("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=Z2(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=Z2(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(),f();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 AI(()=>{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,R=$.highlightStyle??{...P,bg:"yellow",fg:"black"},k={...P,dim:!0},L={...R,dim:!0},v=$.multiple?new Set(D()):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=j(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$?R: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$?R: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$=eB(m,M.w),V4=Y$?R: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$)}}})),()=>pe("span",Z)}});import{computed as oe,inject as wI}from"vue";var MU=Symbol("TerminalRouter"),DV=Symbol("TerminalRoute");function LU(){let $=wI(MU,null);if(!$)throw Error("TerminalRouter is missing");return $}function EV(){let $=wI(DV,null);if(!$)throw Error("TerminalRoute is missing");return oe(()=>$.value)}import{ref as te}from"vue";function fI($,J){let U=typeof $==="string"?{name:$}:$,Q=J.get(U.name);return{name:U.name,params:U.params,meta:Q?.meta}}function Z7($){return typeof $==="string"||typeof $==="object"&&$!=null&&"name"in $}function PV($){let J=new Map($.routes.map((F)=>[F.name,F])),U=te(fI($.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(Z7(E))return E}return!0}async function Y(F,N){let q=U.value,H=fI(F,J),E=J.get(q.name)??null,j=J.get(H.name)??null,B=await Z(G,H,q);if(B===!1)return;if(Z7(B))return Y(B,N);let D=await Z(V,H,q);if(D===!1)return;if(Z7(D))return Y(D,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(j?.onEnter)await j.onEnter(H,q);for(let w of X)w(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(Z7(E))return Y(E,"push");let j=await Z(V,N,F);if(j===!1)return;if(Z7(j))return Y(j,"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(DV,U)}};return K}function kI($,J){let U=$.currentRoute.value;return J.find((_)=>_.name===U.name)?.component??null}import{computed as se,defineComponent as ee,h as $$$,inject as J$$,ref as U$$,watch as _$$}from"vue";var MV=ee({name:"TRouterView",props:{routes:{type:Array,required:!0},forceRemount:{type:Boolean,default:!0}},setup($){let J=J$$(MU,null);if(!J)throw Error("TerminalRouter is missing (did you forget to app.use(router)?)");let U=U$$(0);_$$(()=>J.currentRoute.value,()=>{if($.forceRemount)U.value++},{deep:!0});let Q=se(()=>kI(J,$.routes));return()=>{let _=Q.value;return _?$$$(_,{key:$.forceRemount?U.value:void 0}):null}}});function kO(){return typeof performance<"u"?performance.now():Date.now()}async function IO($){await new Promise((J)=>setTimeout(J,$))}var II=null;function D8($){if(II?.GOATCHAIN_DEBUG==="1")try{let J=new Date().toISOString().split("T")[1].slice(0,-1);Q$$.appendFileSync("/tmp/goatchain-debug.log",`[${J}] [GHOSTTY-KEEPALIVE] ${$}
|
|
910
|
-
`)}catch{}}function G$$($){let J=QO({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 V$$($,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 IO(Math.min(V,5000))}if(G!=null)Q=G;$.dispatch(_),await LV(),J.flush()}}async function SI($){II=$.proc.env,D8("runTerminalUi() called");let J=G$$({cols:$.cols,rows:$.rows,component:$.component,props:$.props,install:$.install,defaultStyle:$.defaultStyle}),U=()=>XV(J.terminal,{output:$.proc.stdout,altScreen:$.altScreen,palette:$.palette,trackResize:!$.sizeLocked,hideCursor:!0,defaultBg:$.defaultBg,getImeAnchor:J.getImeAnchor}),Q=U(),_=[],G=kO(),V=(z)=>{let S=z.time==null?{...z,time:kO()-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)D8(`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??{});D8(`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()}},j=()=>{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?.()},D=()=>{if(H(),X)X.dispose(),X=null;if(Q)Q.dispose(),Q=null},w=!1,A=()=>{if(D(),!w)J.dispose(),w=!0};Uk(()=>{(async()=>{if($.proc.exitCode==null)$.proc.exitCode=0;let z=$.snapshotPath?J.terminal.snapshot().lines:null;if(A(),$.recordPath)await xB($.recordPath,_);if($.snapshotPath&&z)await aG($.snapshotPath,z);B()})()}),$.proc.on("exit",()=>{A()}),$.proc.on("beforeExit",()=>{A()});let f=()=>{D();try{$.proc.removeListener("SIGTSTP",f)}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(f))return}catch{}$.proc.on("SIGTSTP",f)};if(T(),$.proc.on("SIGCONT",()=>{if(T(),!Q)Q=U();if(!X&&!$.replayPath)Z(),X=pG({stdin:$.proc.stdin,stdout:$.proc.stdout,dispatch:V,enableMouse:$.enableMouse,onExit:()=>r5()}),j();J.scheduler.invalidate(),J.scheduler.flush()}),$.replayPath){await LV(),await LV(),J.scheduler.flush();let z=await hB($.replayPath);if(await V$$(J.events,J.scheduler,z),await IO(800),await LV(),J.scheduler.flush(),$.snapshotPath)await aG($.snapshotPath,J.terminal.snapshot().lines);A();return}if(Z(),X=pG({stdin:$.proc.stdin,stdout:$.proc.stdout,dispatch:V,enableMouse:$.enableMouse,onExit:()=>r5()}),Y)D8("Starting keep-alive interval (100ms)"),j(),D8("Keep-alive interval created successfully");if($.proc.on("SIGINT",()=>r5()),$.proc.on("SIGTERM",()=>r5()),Y)D8("Entering ghostty keep-alive loop (waiting forever)"),await new Promise(()=>{}),D8("Keep-alive loop exited (this should never happen)")}var gV=U4(PT(),1);import{spawn as e6$}from"node:child_process";import{existsSync as $0$,readFileSync as J0$}from"node:fs";import rO from"node:path";import{fileURLToPath as U0$}from"node:url";var K2="goatchain-cli",_0$="upgrade-toast.json",Q0$="upgrade-check.log",LT=process.env.GOATCHAIN_DEBUG_LOG||"./goatchain-debug.log",G0$=`https://registry.npmjs.org/${K2}`,V0$=5000;async function X0$(){try{let $=new AbortController,J=setTimeout(()=>$.abort(),V0$),U=await fetch(G0$,{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 zT(){if(await $0("start",{disableAutoUpdate:process.env.GOATCHAIN_DISABLE_AUTOUPDATE==="1",autoUpdate:process.env.GOATCHAIN_AUTOUPDATE!=="0",cwd:N0$(),argv:F0$(),debugLogPath:LT}),process.env.GOATCHAIN_DISABLE_AUTOUPDATE==="1")return await $0("skip-disabled"),null;let $=W0$();if(!$?.version)return await $0("skip-missing-version"),null;let J=$.version,U=$.source==="injected";try{let Q=await X0$();if(await $0("check-result",{current:J,latest:Q,hasInjectedVersion:U}),!Q)return await $0("error",{message:"Failed to fetch latest version"}),null;if(gV.default.valid(J)&&gV.default.valid(Q)){if(gV.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}),Y0$(Q),`Update available: ${K2}@${Q} (current: ${J}). Installing in background. Restart terminal after it finishes.`;return await $0("update-available",{current:J,latest:Q,autoUpdate:!1}),`Update available: ${K2}@${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: ${K2}@${Q} (current: ${J})`}catch(Q){return await $0("error",{message:Q instanceof Error?Q.message:String(Q)}),null}}function Y0$($){try{$0("autoupdate-start",{version:$});let J=e6$("npm",["install","-g",`${K2}@${$}`],{stdio:"ignore",detached:!0});J.unref();let U=!1,Q=(_)=>{if(U)return;U=!0,$0("autoupdate-finish",{version:$,message:_}),MT(_)};J.on("close",(_)=>{if(_===0)Q(`Update installed: ${K2}@${$}. Restart terminal to use the new version.`);else Q(`Auto-update failed. Run: npm install -g ${K2}`)}),J.on("error",()=>{$0("autoupdate-error",{version:$,reason:"process-error"}),Q(`Auto-update failed. Run: npm install -g ${K2}`)})}catch{$0("autoupdate-error",{version:$,reason:"spawn-throw"}),MT(`Auto-update failed. Run: npm install -g ${K2}`)}}function MT($){let J=globalThis?.__GOATCHAIN_UPGRADE_TOAST__;if(typeof J==="function")try{J($);return}catch{}Z0$($)}async function Z0$($){try{let{getGoatChainUserDir:J}=await Promise.resolve().then(() => (Q2(),mG)),[{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,_0$),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(() => (Q2(),mG)),[{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,Q0$),Z={ts:new Date().toISOString(),event:$,...J};await _(X,`${JSON.stringify(Z)}
|
|
911
|
-
`,{encoding:"utf8",mode:384}),await K0$(Z)}catch{}}async function K0$($){try{let{appendFile:J}=await import("node:fs/promises"),Q=`[${String($.ts??new Date().toISOString())}] upgrade_check ${JSON.stringify($)}
|
|
912
|
-
`;await J(LT,Q,{encoding:"utf8"})}catch{}}function N0$(){try{return process.cwd()}catch{return}}function F0$(){try{return process.argv}catch{return}}function W0$(){let $="0.0.5-beta.8".trim();if($)return{version:$,source:"injected"};let J=q0$();if(J)return{version:J,source:"package"};return null}function q0$(){try{let $=rO.dirname(U0$(import.meta.url));for(let J=0;J<6;J++){let U=rO.join($,"package.json");if($0$(U)){let _=J0$(U,"utf8"),G=JSON.parse(_),V=typeof G?.version==="string"?G.version.trim():"";if(V)return V}let Q=rO.dirname($);if(Q===$)break;$=Q}}catch{}return null}import{computed as k6,defineComponent as p1$,h as OJ,inject as a1$,nextTick as o1$,onBeforeUnmount as GC,provide as t1$,ref as b0,watch as w8}from"vue";var P8=Symbol("GoatChainBridge");var RT=["user","assistant","tool"];var AT=["status","thinking","markdown","tool_call","tool_output","tool_result","approve","todo","plan","llm_meta"];var RU=[...RT,...AT];var xV=["black","red","green","yellow","blue","magenta","cyan","white","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"];function nO($,J){let U={};for(let Q of RU)U[Q]={fg:$,bg:J};return U}var wT=Object.freeze({goatchain:{...nO("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:{...nO("white","black"),user:{fg:"white",bg:"black"},assistant:{fg:"white",bg:"black"},tool:{fg:"white",bg:"black"},thinking:{fg:"white",bg:"black"}},contrast:{...nO("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 I1($,J){let U=wT[$.preset]??wT.goatchain,Q=U[J]??U.assistant??{fg:"white",bg:"black"},_=$.overrides?.[J]??{};return{...Q,..._}}import pO from"node:fs";function H0$($){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 fT($){$=H0$($);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 hV=null;try{hV=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null}catch{hV=null}function kT($,J){if(!$)return;if(hV){for(let Q of hV.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 kT($,(U)=>{J+=u4(U.segment)}),J}function uV($,J){if(J=Math.max(0,Math.floor(J)),J<=0)return{chunk:"",rest:$};let U=0,Q=0,_=[];kT($,(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 j7($,J){return uV($,J).chunk}function IT($,J){J=Math.max(0,Math.floor(J));let U=AU($);if(U>=J)return j7($,J);return`${$}${" ".repeat(J-U)}`}function ST($,J){if(J=Math.max(1,Math.floor(J)),!$)return[""];let U=[],Q=$;while(!0){let{chunk:_,rest:G}=uV(Q,J);if(U.push(_),!G)break;Q=G}return U}var M8=new Map,B0$=100,O0$=60000;function j0$($,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 D0$(){let $=Date.now();for(let[J,U]of M8.entries())if($-U.timestamp>O0$)M8.delete(J)}if(typeof setInterval<"u")setInterval(D0$,1e4);function mV($){let J=(Z)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let K=new Date().toISOString().split("T")[1].slice(0,-1);pO.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 cV($,J){let U=(F)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let q=new Date().toISOString().split("T")[1].slice(0,-1);pO.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 j=H.text,B=0,D=H.text.length*10+100;while(j){if(B++,B>D){U(`ERROR: Infinite loop in chunking! span=${K}, token=${q}, iterations=${B}, remaining="${j.slice(0,50)}", col=${V}, width=${J}`);break}let w=J-V;if(w<=0){Y();continue}if(/^\s+$/.test(j)){Y(),j="";continue}let A=uV(j,w),I=A.chunk;if(j=A.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 TT($,J){let U=(f)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let z=new Date().toISOString().split("T")[1].slice(0,-1);pO.appendFileSync("/tmp/goatchain-debug.log",`[${z}] [MARKDOWN-PARSE] ${f}
|
|
915
|
-
`)}}catch{}},Q=Date.now();U(`START: markdown length=${$.length}, width=${J}`);let _=j0$($,J),G=M8.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=fT($).split(`
|
|
916
|
-
`);U(`After sanitize: ${V.length} lines`);let X=[],Z=!1,Y="",K=0,F=2,N=!0,q=!0,H=/[┌┐└┘│─├┤┬┴┼╭╮╯╰]/;function E(f){return Math.max(0,Math.floor(f))}function j(f,T){if(T<=0)return"";return IT(f,T)}function B(f,T){if(T=E(T),T<=0)return"";if(T===1)return"┌";let z=Math.max(0,T-2),O=` ${(f||"code").trim()} `;if(z===0)return"┌┐";let M=j7(O,z),P="─".repeat(Math.max(0,z-AU(M)));return`┌${M}${P}┐`.slice(0,T)}function D(f){if(f=E(f),f<=0)return"";if(f===1)return"└";return`└${"─".repeat(Math.max(0,f-2))}┘`.slice(0,f)}function w(f,T,z){if(z=E(z),z<=0)return"";if(z<4)return j7(f,z);let S=Math.max(0,z-2),M=S<6||!T?"":`${T} │ `;return`│${j(`${M}${f}`,S)}│`.slice(0,z)}let A=0;for(let f of V){if(A%100===0)U(`Processing line #${A}/${V.length}`);let T=f.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=A+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:D(J)}]});A++;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?ST(T,c):[j7(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:w(K$,V$,J)}]})}A++;continue}if(/^#{1,6}\s+/.test(T)){let C=T.replace(/^#{1,6}\s+/,""),b=mV(C);for(let y of cV(b,J))X.push({kind:"heading",spans:y});A++;continue}if(T.startsWith("> ")){let C=T.slice(2),b=mV(C);for(let y of cV(b,Math.max(1,J-2)))X.push({kind:"quote",spans:[{kind:"text",text:"│ "},...y]});A++;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="",R="",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="•",R=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)}.`,R=T.slice(b)}}if(M){let b=`${" ".repeat(k*2)}${P} `,y=AU(b),x=" ".repeat(y),c=mV(R),s=cV(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$]});A++;continue}if(!T.trim()){X.push({kind:"text",spans:[{kind:"text",text:""}]}),A++;continue}let v=mV(T);for(let C of cV(v,J))X.push({kind:"text",spans:C});A++}if(U(`After parsing: ${X.length} output lines`),M8.size>=B0$){let f=null,T=Date.now();for(let[z,S]of M8.entries())if(S.timestamp<T)T=S.timestamp,f=z;if(f)M8.delete(f)}M8.set(_,{hash:_,lines:X,timestamp:Date.now()});let I=Date.now()-Q;return U(`END: total ${I}ms, ${X.length} lines`),X}function vT(){return{type:"none"}}function CT($){return{type:"selectToolCall",callId:$}}function bT(){return{type:"openApproval"}}function yT($){return{type:"openFile",absPath:$}}function aO($,J,U){return{type:"toggleItem",messageId:$,part:J,itemId:U}}function dV($,J,U){return{type:"toggleCollapse",messageId:$,part:J,partIndex:U}}function J0($){return{type:"toggleBashOutput",toolCallId:$}}var lV=null;try{lV=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null}catch{lV=null}function gT($,J){if(!$)return;if(lV){for(let Q of lV.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 xT($){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 D7($,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=[];gT($,(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 hT($,J){let U=Math.max(0,Math.floor(J));if(!U)return{text:"",truncated:$.length>0};let Q=[],_=0,G=0,V=[];gT($,(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 oO=2000,tO=5000000;function sO($,J){let U=new TextEncoder().encode($).length,Q=new TextEncoder().encode(J).length;if(U>tO||Q>tO)return[{type:"context",content:`[Diff too large: ${Math.max(U,Q).toLocaleString()} bytes. Size limit: ${tO.toLocaleString()} bytes]`}];let _=$.replace(/\r/g,"").split(`
|
|
918
|
-
`),G=J.replace(/\r/g,"").split(`
|
|
919
|
-
`),V=_.length,X=G.length;if(V>oO||X>oO)return[{type:"context",content:`[Diff too large: ${Math.max(V,X).toLocaleString()} lines. Line limit: ${oO.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 uT($,J){let U=sO($,J),Q=0,_=0;for(let G of U)if(G.type==="added")Q++;else if(G.type==="removed")_++;return{added:Q,removed:_}}function mT($,J,U){if(!J&&!U)return!1;let Q=uT(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 cT($,J,U){if(!J&&!U)return;let Q=sO(J,U),_=$.maxLines??24,V=E0$(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 E0$($,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 dT($){return $<=31&&$!==9&&$!==10}function lT($){return $>=128&&$<=159}function S0($){let J=String($??""),U="";for(let Q=0;Q<J.length;){let _=J.codePointAt(Q)??0,G=_>65535?2:1;if(_===27||dT(_)||_===127||lT(_)){Q+=G;continue}U+=String.fromCodePoint(_),Q+=G}return U}function eO($){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(dT(_)||_===127||lT(_)){Q+=G;continue}U+=String.fromCodePoint(_),Q+=G}return U}var v0=" ";function T0($,J,U){let Q=I1($,J);return{fg:Q.fg,bg:Q.bg,...U??{}}}function iT($,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 rT($){let J=[],{pushLine:U}=iT(J,$.contentIndent),Q=T0($.theme,"user",{fg:I1($.theme,"user").fg??"whiteBright"}),_=$.message.content.replace(/\r/g,""),G=Math.max(1,$.width-$.contentIndent),V=xT(_),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 j=`[${H.split(/[/\\]/).filter(Boolean).pop()??H}]`,B=K.length?" ":"",D=K.length+B.length;K+=`${B}${j}`;let w=K.length;F.push({start:D,end:w,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 D7(X,G)){let{text:F,start:N,end:q}=K,H=[];for(let E of Z)if(E.end>N&&E.start<q){let j=Math.max(N,E.start),B=Math.min(q,E.end),D=X.slice(j,B),w=X.slice(N,j),A=$.contentIndent+M$(w);H.push({x:A,w:M$(D),text:D,style:{fg:"cyanBright",bold:!0},action:yT(E.absPath)})}if(H.length>0)J.push({text:` ${F}`,style:Q,segments:H});else U(F,Q)}return J}function P0$($,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=T0($.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(S0(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 nT($,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 pT($){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 M0$($,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=T0($.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=pT(Q.output),H=String(Q.output??"").replace(/\r/g,"").split(`
|
|
923
|
-
`),E=q?.length??H.length,j=Math.min(E,N),B=Y?String(Z??"").replace(/\r/g,"").split(`
|
|
924
|
-
`):null,D=M$(v0);if(q){for(let I of q.slice(0,j)){let f=wU(I);$.pushLine(`${v0}${S0(f.text)}`,X)}let A=q.length>K;if(A&&!F){let I={...X,fg:"cyan"},f=q.length-K;$.pushLine(`... (${f} more lines)`,I,J0(J))}else if(A&&F){let I={...X,fg:"cyan"};$.pushLine("... (collapse)",I,J0(J))}return}for(let A=0;A<j;A++){let I=H[A]??"";if(Y&&B&&A<B.length){let T=eO(B[A]??"");if(T===""){$.pushLine(v0,X);continue}let z=GU(T,{}),S=z.map((L)=>L.text).join(""),O=wU(S),M=S0(O.text),P=O.removedCells>0?nT(z,O.removedCells):z,R=$.contentIndent+D,k=[];for(let L of P){let v=S0(L.text),C=M$(v);if(C>0&&Object.keys(L.style??{}).length>0)k.push({x:R,w:C,text:v,style:L.style});R+=C}$.pushLineWithSegments(`${v0}${M}`,X,k);continue}if(I===""){$.pushLine(v0,X);continue}let f=wU(I);$.pushLine(`${v0}${S0(f.text)}`,X)}let w=E>K;if(w&&!F){let A={...X,fg:"cyan"},I=E-K;$.pushLine(`... (${I} more lines)`,A,J0(J))}else if(w&&F){let A={...X,fg:"cyan"};$.pushLine("... (collapse)",A,J0(J))}}var L0$={status($,J){},thinking($,J){let U=J.collapsed?"▸":"▾",_={...T0($.theme,"thinking"),bold:!0},V=T0($.theme,"assistant");if($.pushLine(`${U} ${J.title}`,_,dV($.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=D7(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=T0($.theme,"markdown"),X=TT(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?"▾":"▸",_=T0($.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=((A)=>A!=null&&typeof A==="object"&&!Array.isArray(A))(K)?K:null,q=(()=>{let A=String(J.call.name??"").toLowerCase();if(A==="bash"&&N){let I=typeof N.description==="string"?String(N.description).trim():"";if(I)return` ${I}`}else if(A==="read"&&N){let I=typeof N.file_path==="string"?String(N.file_path).trim():"";if(I){let{limit:f,offset:T}=N,z=[];if(typeof T==="number"&&T>0)z.push(`offset ${T}`);if(typeof f==="number"&&f>0)z.push(`limit ${f}`);if(z.length>0)return` ${I} (${z.join(", ")})`;return` ${I}`}}else if(A==="write"){let I=typeof N?.file_path==="string"?String(N.file_path).trim():"";if(I)return` ${I}`;let f=J.call.argumentsText?.match(/"file_path":\s*"([^"]+)"/);if(f)return` ${f[1]}`}else if(A==="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(A==="grep"&&N){let I=typeof N.pattern==="string"?String(N.pattern).trim():"";if(I)return` ${I}`}else if(A==="askuserquestion"&&N){let I=Array.isArray(N.questions)?N.questions:[];if(I.length>0&&I[0]?.header){let f=String(I[0].header).trim();if(f)return` [${f}]`}}else if(A==="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(A==="todoplan"&&N){let I=N.todos;if(Array.isArray(I)&&I.length>0)return` (${I.length} todos)`}return""})(),H=`${Q} `,E=M$(` ${H}`),j=M$(`${X} ${J.call.name}`),B=Math.max(0,$.width-E-j),D=(()=>{if(!q||B<=0)return"";let A=hT(q.trim(),B);if(!A.truncated)return q;return` ${A.text}…`})(),w=`${X} ${J.call.name}${D}`;if($.pushLineWithSegments(`${H}${w}`,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}],CT(J.call.id)),$.pushLine(""),U){let A={..._,dim:!0},I=Math.max(10,$.width-$.contentIndent-2),f=String(J.call.name??"").toLowerCase();if(f==="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={...A,fg:"yellowBright"},P=T.replace(/\r/g,"").split(`
|
|
927
|
-
`),R=!0;for(let k of P){let L=R?" $ ":" | ",v=Math.max(5,I-M$(L)+2),C=D7(k,v);if(C.length===0){$.pushLine(` ${L.trim()}`,M),R=!1;continue}for(let b of C){let y=R?" $ ":" | ";$.pushLine(` ${y.trim()}${b.text}`,M),R=!1}}}if(S){let O=$.expandedBashOutputs.has(J.call.id),M=10,P=O?Number.POSITIVE_INFINITY:10,R=S.replace(/\r/g,"").split(`
|
|
928
|
-
`),k=R.length>10,L={..._,bold:!0};$.pushLine(" out:",L);for(let v of R.slice(0,P))$.pushLine(` ${v}`,A);if(k&&!O){let v={...A,fg:"cyan"},C=R.length-10;$.pushLine(` ... (${C} more lines)`,v,J0(J.call.id))}else if(k&&O){let v={...A,fg:"cyan"};$.pushLine(" ... (collapse)",v,J0(J.call.id))}}}else{let T=new Set;if(f==="read")T.add("file_path"),T.add("limit"),T.add("offset");else if(f==="glob")T.add("pattern");else if(f==="grep")T.add("pattern");else if(f==="askuserquestion")T.add("questions");else if(f==="write")T.add("file_path");else if(f==="edit")T.add("edit");let z=!1;if(f==="askuserquestion"&&N){let O=Array.isArray(N.questions)?N.questions:[];if(O.length>0){let M={..._,fg:"white"},P={..._,fg:"white"},R={..._,fg:"blackBright"};for(let k=0;k<O.length;k++){let L=O[k];if(L?.question){if($.pushLine(`${v0}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(`${v0}${v0}${c}${b}`,P),y)$.pushLine(`${v0}${v0}${v0}${y}`,R)}}}}z=!0}else if(f==="edit"&&N){let O=typeof N.new_string==="string"?N.new_string:"",M=typeof N.old_string==="string"?N.old_string:"";mT({pushLine:$.pushLine,detailStyle:_},M,O),cT({pushLine:$.pushLine,detailStyle:A,width:$.width,maxLines:24},M,O),z=!0}else if(f==="todoplan"&&N)z=!0;let S=(O,M)=>{let P=typeof M==="string"?M:JSON.stringify(M);if(!P||!String(P).trim())return;let R=`${v0}${O}: ${String(P)}`;for(let k of D7(R,I))$.pushLine(`${k.text}`,A)};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)}}}P0$($,J.call.id),M0$($,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=T0($.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=T0($.theme,"tool_result",{dim:!0});if(J.result.status!=="success")$.pushLine(`✗ ${J.result.status}`,G);if(_)return;if(String(Q).toLowerCase()==="askuserquestion"){let A=J.result.output;if(A&&A.trim()){try{let f;try{f=JSON.parse(A)}catch{if(typeof A==="object")f=A;else{let S=A.match(/\{[\s\S]*\}/);if(S)f=JSON.parse(S[0])}}let T={...G,fg:"cyan",bold:!0},z={...G,fg:"white"};if(f&&typeof f==="object"&&!Array.isArray(f)){let S=f.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 R=Array.isArray(P)?P.join(", "):String(P);$.pushLine(` Q${O}: ${R}`,z)}return}}else if(Array.isArray(f)){f.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(f){console.debug("Failed to parse AskUserQuestion output:",f)}let I=A.split(`
|
|
931
|
-
`);for(let f of I)if(f.trim())$.pushLine(` ${S0(f)}`,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=pT(J.result.output),q=String(J.result.output??"").replace(/\r/g,"").split(`
|
|
932
|
-
`),H=N?.length??q.length,E=Math.min(H,F),j=Z?String(X??"").replace(/\r/g,"").split(`
|
|
933
|
-
`):null,B=" ",D=M$(B);if(N){for(let I of N.slice(0,E))$.pushLine(`${B}${S0(wU(I).text)}`,G);let A=N.length>Y;if(A&&!K){let I={...G,fg:"cyan"},f=N.length-Y;$.pushLine(` ... (${f} more lines)`,I,J0(J.result.id))}else if(A&&K){let I={...G,fg:"cyan"};$.pushLine(" ... (collapse)",I,J0(J.result.id))}return}for(let A=0;A<E;A++){let I=q[A]??"";if(Z&&j&&A<j.length){let f=eO(j[A]??"");if(f===""){$.pushLine(B,G);continue}let T=GU(f,{}),z=T.map((k)=>k.text).join(""),S=wU(z),O=S0(S.text),M=S.removedCells>0?nT(T,S.removedCells):T,P=$.contentIndent+D,R=[];for(let k of M){let L=S0(k.text),v=M$(L);if(v>0&&Object.keys(k.style??{}).length>0)R.push({x:P,w:v,text:L,style:k.style});P+=v}$.pushLineWithSegments(`${B}${O}`,G,R);continue}if(I===""){$.pushLine(B,G);continue}$.pushLine(`${B}${S0(wU(I).text)}`,G)}let w=H>Y;if(w&&!K){let A={...G,fg:"cyan"},I=H-Y;$.pushLine(` ... (${I} more lines)`,A,J0(J.result.id))}else if(w&&K){let A={...G,fg:"cyan"};$.pushLine(" ... (collapse)",A,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"?"✓":"✗",_=T0($.theme,"approve"),G={..._,dim:!0};if($.pushLine(`${Q} ${J.request.tool} — ${J.request.permission}`,U==="pending"?{..._,bold:!0}:G,U==="pending"?bT():vT()),U==="pending")$.pushLine(` ${J.request.reason}`,G)},todo($,J){let U=J.collapsed?"▸":"▾",Q=T0($.theme,"todo"),_={...Q,dim:!0};if($.pushLine(`${U} ${J.title}`,{...Q,bold:!0},dV($.messageId,J.type)),!J.collapsed)for(let G of J.items){let V=G.done?"☑":"☐";$.pushLine(` ${V} ${G.text}`,_,aO($.messageId,J.type,G.id))}},plan($,J){let U=J.collapsed?"▸":"▾",Q=T0($.theme,"plan"),_={...Q,dim:!0};if($.pushLine(`${U} ${J.title}`,{...Q,bold:!0},dV($.messageId,J.type)),!J.collapsed)for(let G of J.items){let V=G.done?"☑":"☐";$.pushLine(` ${V} ${G.text}`,_,aO($.messageId,J.type,G.id))}},llm_meta($,J){let U=T0($.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 aT($){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}=iT(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=L0$[H.type],j={...K,partIndex:N};J(` Part #${N}: calling renderer for type=${H.type}`),E(j,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 z0$($){return Array.from($).sort().join(",")}function R0$($){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 iV($){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 $j($,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=rT({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=aT({message:$,width:J,contentIndent:2,selectedToolCallId:U,expandedBashOutputs:Q,theme:_});return G(`Assistant message: ${X.length} lines`),{role:$.role,messageId:$.id,lines:X}}function Jj($,J,U){let Q=(j)=>{try{if(globalThis.process?.env?.GOATCHAIN_DEBUG==="1"){let D=E$("fs"),w=new Date().toISOString().split("T")[1].slice(0,-1);D.appendFileSync("/tmp/goatchain-debug.log",`[${w}] [DECORATE] ${j}
|
|
936
|
-
`)}}catch{}};Q(`START: role=${$.role}, lines=${$.lines.length}, isFirst=${U}`);let _=Date.now(),G=[],V=I1(J,"assistant"),X=I1(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 j of $.lines){if(F){let B=[{x:0,w:1,text:"┃",style:q},...j.segments.map((D)=>({...D,x:D.x+1,style:{...D.style??{},bg:Y}}))];G.push({text:`┃${j.text}`,style:{...j.style,bg:Y},segments:B,action:j.action,hasBackground:!0,messageId:$.messageId})}else{let B=j.style?.bg??Z;G.push({text:j.text,style:{...j.style,bg:B},segments:j.segments.map((D)=>({...D,style:{...D.style??{},bg:B}})),action:j.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 oT(){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(j,B){for(let D=0;D<j.length;D++){let w=j[D]?.action;if(w?.type==="selectToolCall")V.set(w.callId,B+D)}}function H(j){G=[],V=new Map,Y.length=0,K.clear(),F.clear();let B=Math.max(0,j.width),D=0;for(let w of j.messages){let A=$j(w,B,j.selectedToolCallId,j.expandedBashOutputs,j.theme);if(!A)continue;let I=iV(w),f=Jj(A,j.theme,D===0);D++;let T=G.length;G.push(...f);let z=G.length;Y.push(A.messageId),K.set(A.messageId,{start:T,end:z}),F.set(A.messageId,I),q(f,T)}}function E(j,B,D,w){let A=B.id,I=K.get(A);if(!I)return;let{start:f,end:T}=I,z=T-f,S=$j(B,w.width,w.selectedToolCallId,w.expandedBashOutputs,w.theme);if(!S)return;let O=Jj(S,w.theme,j===0);G.splice(f,z,...O);let M=O.length-z,P=f+O.length;if(K.set(A,{start:f,end:P}),F.set(A,D),M!==0)for(let k=j+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 R=new Map;for(let[k,L]of V.entries()){if(L<f){R.set(k,L);continue}if(L>=T){R.set(k,L+M);continue}}V=R,q(O,f)}return(j)=>{let B=Math.max(0,j.width),D=j.selectedToolCallId??null,w=z0$(j.expandedBashOutputs),A=R0$(j.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=${j.messages.length}
|
|
937
|
-
`)}}catch{}if(B!==$||D!==J||w!==U||A!==Q)return H(j),$=B,J=D,U=w,Q=A,I=!0,N(),{lines:X,toolLineById:Z};let T=[];for(let O of j.messages){if(O.role==="tool")continue;T.push(O)}if(T.length<Y.length)return H(j),I=!0,N(),{lines:X,toolLineById:Z};for(let O=0;O<Y.length;O++)if(T[O]?.id!==Y[O])return H(j),I=!0,N(),{lines:X,toolLineById:Z};for(let O=Y.length;O<T.length;O++){let M=T[O],P=$j(M,B,D,j.expandedBashOutputs,j.theme);if(!P)continue;let R=iV(M),k=Jj(P,j.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,R),q(k,L),I=!0}if(typeof j.dirtySeq==="number"&&j.dirtySeq!==_){_=j.dirtySeq;let O=String(j.dirtyMessageId??"").trim();if(O){let M=Y.indexOf(O),P=M>=0?T[M]:null;if(P){let R=iV(P),k=F.get(O);if(R!==k)E(M,P,R,{width:B,selectedToolCallId:D,expandedBashOutputs:j.expandedBashOutputs,theme:j.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,R=iV(M),k=F.get(P);if(R!==k)E(O,M,R,{width:B,selectedToolCallId:D,expandedBashOutputs:j.expandedBashOutputs,theme:j.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 A0$,h as l0,inject as w0$,onMounted as f0$,ref as k0$}from"vue";var H0=Symbol("GoatChainChatPageContext");var rV={fg:"whiteBright",bg:"black"},E7={fg:"white",dim:!0,bg:"blackBright"},tT={fg:"whiteBright",bg:"blackBright"},sT={fg:"whiteBright",bg:"blackBright"},FJ={fg:"white",dim:!0,bg:"black"};async function I0$($){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 eT=A0$({name:"GoatChainChatBottomPanel",setup(){let $=w0$(H0);if(!$)throw Error("GoatChainChatBottomPanel missing ChatPageContext");let J=$,{events:U,scheduler:Q}=L4(),_=k0$(!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 D=B?.rect;return D&&D.x===X&&D.y===Z&&D.w===Y&&D.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 D=B?.rect;return D&&q>=D.x&&H>=D.y&&q<D.x+D.w&&H<D.y+D.h});E.sort((B,D)=>{let w=B?.zIndex??0,A=D?.zIndex??0;if(A!==w)return A-w;let I=B?.rect??{w:0,h:0},f=D?.rect??{w:0,h:0};return I.w*I.h-f.w*f.h});let j=E[0];if(j?.id)V.focus(j.id),_.value=!0,Q.invalidate()}return f0$(()=>{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=[l0(t,{key:"panel-top-border",x:J.panelX.value,y:J.panelTopY.value-1,w:J.panelW.value,value:Z,style:E7,zIndex:-20}),l0(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:tT,zIndex:-20}),l0(t,{key:"panel-left-border",x:J.panelX.value,y:J.panelTopY.value,w:1,h:X,value:K,style:E7,zIndex:-19}),l0(t,{key:"panel-right-border",x:J.panelX.value+J.panelW.value-1,y:J.panelTopY.value,w:1,h:X,value:F,style:E7,zIndex:-19}),l0(t,{key:"panel-bottom-border",x:J.panelX.value,y:J.panelTopY.value+J.panelH.value,w:J.panelW.value,value:Y,style:E7,zIndex:-20}),l0(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()}}),l0(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:sT,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)I0$(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,j=J.modelInfo.value.label,B=M$(H),D=M$(E),w=M$(j),A=2,I=B+2+D+1+w,f=J.inputX.value+Math.max(0,J.inputInnerW.value-I),T=Math.max(0,f-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(l0(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,R=Math.max(0,T-M-1);if(J.assistantStatusDisplay.value&&R>0)N.push(l0(t,{key:"panel-status",x:P,y:q,w:R,value:J.assistantStatusDisplay.value,style:J.assistantStatusStyle.value,zIndex:-18}))}return N.push(l0(t,{key:"ctx-pct",x:f,y:q,value:H,style:{fg:"white",dim:!0,bg:"blackBright"},zIndex:-18})),N.push(l0(t,{key:"model-chip",x:f+B+2,y:q,value:E,style:{fg:"blueBright",bold:!0,bg:"blackBright"},zIndex:-18})),N.push(l0(t,{key:"model-label",x:f+B+2+D+1,y:q,w:Math.max(0,J.inputX.value+J.inputInnerW.value-(f+B+2+D+1)),value:j,style:{fg:"white",dim:!0,bg:"blackBright"},zIndex:-18})),N}}});import{defineComponent as S0$,h as fU,inject as T0$}from"vue";var $v=S0$({name:"GoatChainChatFooter",setup(){let $=T0$(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:FJ,zIndex:21})];return[J.rows.value>0?fU(t,{key:"footer-bg",x:0,y:U,w:J.cols.value,value:"",style:rV,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:FJ,zIndex:21})]}}});import{defineComponent as v0$,h as P7,inject as C0$}from"vue";function nV($,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 Jv=v0$({name:"GoatChainChatHeader",setup(){let $=C0$(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?nV(Z,N):"",H=q?M$(q):0,E=q?Math.max(0,J.contentW.value-2-H):0,j=2,B=H?Math.max(0,Y-H-2):Y,D=nV(J.sessionHeaderTitle.value,B),w=2,A=2,I=Math.max(0,_-2-2),f=[P7(t,{key:"page-title",x:2,y:0,w:Y,value:"GoatChain",style:FJ}),P7(t,{key:"session-title",x:2,y:1,w:B,value:D,style:{fg:"blueBright",bold:!0,bg:"black"}})];if(q)f.push(P7(t,{key:"header-meta",x:E,y:1,value:q,style:FJ}));if(f.push(P7(t,{key:"header-stats",x:_,y:2,value:U,style:FJ})),I>0)f.push(P7(t,{key:"header-summary",x:2,y:2,w:I,value:nV(J.sessionHeaderSummary.value,I),style:FJ}));return f}}});import{computed as b0$,defineComponent as Qj,h as N2,inject as y0$}from"vue";var Uj=null;try{Uj=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null}catch{Uj=null}function Uv($,J){if(!$)return;let U=0,Q=Uj;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 _j($,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 Uv($,(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 M7($,J,U){if(J=Math.max(0,Math.floor(J)),U=Math.max(0,Math.floor(U)),U<=J)return"";let Q=_j($,J,U),_=Q.startCol,G=Q.endCol;if(G<=_)return"";let V="";return Uv($,(X,Z,Y)=>{if(Y<=_)return;if(Z>=G)return!1;V+=X;return}),V}function _v($,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(M7(Y,G,V));else if(Z===Q)X.push(M7(Y,G,Number.MAX_SAFE_INTEGER));else if(Z===_)X.push(M7(Y,0,V));else X.push(Y)}return X.join(`
|
|
941
|
-
`).trim()}function g0$($,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 Qv=Qj({name:"GoatChainChatMessages",setup(){let $=y0$(H0);if(!$)throw Error("GoatChainChatMessages missing ChatPageContext");let J=$,U=b0$(()=>g0$(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,j=U.value,B=j.active&&N>=j.startRow&&N<=j.endRow,D=0,w=0;if(B)if(j.startRow===j.endRow)D=j.startCol,w=j.endCol;else if(N===j.startRow)D=j.startCol,w=F;else if(N===j.endRow)D=0,w=j.endCol;else D=0,w=F;let A=Y.segments.length,I=B&&w>D,f=Boolean(Y.action),T=(I?1:0)+(f?1:0),z=[N2(t,{key:`r${K}_bg`,x:0,y:K,w:F,value:I4(F),style:{bg:E},zIndex:0}),N2(t,{key:`r${K}_base`,x:0,y:K,w:F,value:Y.text,style:G(Y.style,E),zIndex:1})];z.length=2+A*2+T;let S=2;for(let O=0;O<A;O++){let M=Y.segments[O];if(z[S++]=N2(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++]=N2(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 R=M.action.absPath;if(P?.metaKey||P?.ctrlKey)try{if(!R||R.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",[R],{shell:!1,detached:!0,stdio:"ignore"}).unref()}catch{}}})}if(I){let O=_j(Y.text,D,w),M=Math.max(0,Math.min(F,O.startCol)),P=Math.max(0,Math.min(F,O.endCol)),R=Math.min(P-M,F-M);if(R>0){let k=h6(M7(Y.text,M,M+R),R);z[S++]=N2(t,{key:`r${K}_sel`,x:M,y:K,w:R,value:k,style:{fg:"whiteBright",bg:"blueBright"},zIndex:3})}}if(!f)return z.length=S,z;return z[S++]=N2(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=Qj({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=Qj({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()=>N2(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 D=K[B],w=String(D?.messageId??"").trim();if(!w){q[H++]={kind:"spacer",startRow:B,lines:[D]};continue}let A=Y.get(w)==="user"?"user":"assistant",I=q[H-1];if(I&&I.kind!=="spacer"&&I.messageId===w){I.lines.push(D);continue}q[H++]={kind:A,messageId:w,startRow:B,lines:[D]}}q.length=H;let E=[];E.length=H;let j=0;for(let B=0;B<H;B++){let D=q[B];if(D.kind==="spacer")E[j++]=V(D.lines[0],D.startRow)[0];else if(D.kind==="user")E[j++]=N2(X,{key:`u_${D.startRow}`,startRow:D.startRow,lines:D.lines});else E[j++]=N2(Z,{key:`a_${D.startRow}`,startRow:D.startRow,lines:D.lines})}return E.length=j,E})}});import{defineComponent as z1$,inject as R1$}from"vue";import{h as Wv}from"vue";import{defineComponent as x0$,h as S1,ref as Vv,watch as h0$}from"vue";function Gv($){return Math.max(1,Math.ceil($.length/4))}function kU($){try{return JSON.stringify($)}catch{return'"[unserializable]"'}}function V1($){return $.replace(/\r/g,"").trimEnd()}function IU($,J,U){return Math.max(J,Math.min(U,$))}function Xv($){let J=V1($),U=J.search(/\s(?:Args|Command|Description):\s/i);if(U<=0)return J;return J.slice(0,U).trimEnd()}function u0$($){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 Yv($){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 Zv($){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 Kv=x0$({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=Vv(0),_=Vv(null);return h0$([()=>$.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=u0$(G),X=()=>{let Z=$.request,Y=Z.args,K=Yv($.call)??Zv(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 j=Xv(Z.reason),B=K0(j,Math.max(1,F)),D=Math.max(0,H-E),w=K?(K.description?2:0)+(K.command?4:0):0,A=(D>=2?1:0)+(D>=2+w?w:0),I=IU(Math.max(1,D-A),1,Math.max(1,D)),f=Math.max(0,B.length-I);return{reasonH:I,maxOffset:f}};return S1(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=Yv($.call)??Zv(Y),F=Math.max(0,$.w-4),N=Math.max(0,$.h-4),q=1,H=Math.max(0,N-1),E=[S1(t,{x:0,y:0,w:F,h:N,value:"",style:{bg:"black"}}),S1(t,{x:0,y:0,w:F,value:`Tool: ${Z.tool}`,style:{fg:"whiteBright",bold:!0,bg:"black"}}),S1(t,{x:0,y:1,w:F,value:`Permission: ${Z.permission}`,style:{fg:"cyanBright",bg:"black"}})],j=2;if(H-j>=4)j+=1;if(j<H){let B=Math.max(1,H-j),D=Xv(Z.reason),w=K0(D,Math.max(1,F)),A=Math.max(0,H-j),I=K?(K.description?2:0)+(K.command?4:0):0,f=(A>=2?1:0)+(A>=2+I?I:0),T=IU(Math.max(1,A-f),1,B),z=Math.max(0,w.length-T),S=IU(Q.value,0,z),O=w.slice(S,S+T).join(`
|
|
942
|
-
`);if(E.push(S1(t,{x:0,y:j,w:F,h:T,value:O,style:{fg:"white",dim:!0,bg:"black"}})),F>0&&T>0){if(S>0)E.push(S1(t,{x:F-1,y:j,w:1,value:"↑",style:{fg:"whiteBright",dim:!0,bg:"black"}}));if(S+T<w.length)E.push(S1(t,{x:F-1,y:j+T-1,w:1,value:"↓",style:{fg:"whiteBright",dim:!0,bg:"black"}}))}j+=T}if(K&&j<H){if(K.description&&j<H){let B=Math.max(1,H-j),D=IU(2,1,B);E.push(S1(t,{x:0,y:j,w:F,h:D,wrap:!0,value:`Description: ${V1(K.description)}`,style:{fg:"white",dim:!0,bg:"black"}})),j+=D}if(K.command&&j<H){if(E.push(S1(t,{x:0,y:j,w:F,value:"Command:",style:{fg:"yellowBright",bg:"blackBright",bold:!0}})),j+=1,j<H){let B=Math.max(1,H-j),D=IU(3,1,B);E.push(S1(t,{x:0,y:j,w:F,h:D,wrap:!0,value:V1(K.command),style:{fg:"whiteBright",bg:"blackBright"}})),j+=D}}}return E})}}});import{computed as m0$,defineComponent as c0$,h as C0,ref as L8,watch as Nv}from"vue";function z8($,J,U){return Math.max(J,Math.min(U,$))}var Fv=c0$({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=L8(0),Q=L8(0),_=L8({}),G=L8({}),V=L8({}),X=L8({}),Z=L8({});Nv(()=>[$.toolCallId,$.questions.length],()=>{U.value=0,Q.value=0;let N={},q={},H={},E={},j={};for(let B=0;B<$.questions.length;B++){let D=String(B);N[D]=0,q[D]=[],H[D]="",E[D]=0,j[D]="select"}_.value=N,G.value=q,V.value=H,X.value=E,Z.value=j},{immediate:!0});let Y=m0$(()=>{let N={};for(let q=0;q<$.questions.length;q++){let H=String(q),E=$.questions[q],D=[...(E.options||[]).map((w)=>w.label),"Other"];if(E.multiSelect){let w=G.value[H]??[],A=w.map((z)=>D[z]).filter((z)=>Boolean(z)&&z!=="Other"),I=V.value[H]?.trim(),f=D.length-1;if(w.includes(f)&&I)A.push(I);N[H]=A.length>0?A:[]}else{let w=_.value[H]??0,A=D[w]??"";if(A==="Other")N[H]=V.value[H]||"";else N[H]=A}}return N});function K(){J("submit",{...Y.value}),J("update:modelValue",!1)}function F(){J("cancel"),J("update:modelValue",!1)}return Nv(()=>$.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},j={fg:"white",dim:!0},B=z8(U.value,0,Math.max(0,$.questions.length-1)),D=$.questions[B],w=D?.multiSelect??!1,A=String(B);if(!D)return C0(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()},()=>[C0(t,{x:0,y:0,w:N,value:"No questions to answer.",style:j})]);let I=D.options||[],f=I.map((L)=>({label:L.label,detail:L.description}));f.push({label:"Other",detail:"Provide a custom answer"});let z=[...I.map((L)=>L.label),"Other"],S=z.length-1,O=w?(G.value[A]??[]).includes(S):(_.value[A]??0)===S,M=B>=$.questions.length-1,P=B<=0,R=[{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 C0(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(L)=>J("update:modelValue",L),onKeydownCapture:(L)=>{if(L?.key==="Enter"&&O){let v=(V.value[A]??"").trim(),C=Number(L?.target?.rect?.h??0);if(!v&&C>1){L.preventDefault?.(),L.stopPropagation?.(),Z.value={...Z.value,[A]:"input"};let b=X.value[A]??0;X.value={...X.value,[A]:b+1};return}}if(L?.key==="Escape")L.preventDefault?.(),L.stopPropagation?.(),F()},w:$.w,h:$.h,title:`Question ${B+1}/${$.questions.length}: ${D.header||"Question"}`,placement:"center",backdrop:!1,padding:1,style:{fg:"cyanBright",bg:"black"},buttons:R,closeOnConfirm:!1,onKeydown:(L)=>{if(w&&L?.key==="Enter"&&L.defaultPrevented){L.preventDefault?.(),L.stopPropagation?.();let v=z8(Q.value,0,Math.max(0,R.length-1)),C=R[v];k(String(C?.value??""))}if((L?.key==="ArrowLeft"||L?.key==="ArrowRight")&&!L.defaultPrevented){let v=L.key==="ArrowLeft"?-1:1;Q.value=z8(Q.value+v,0,Math.max(0,R.length-1))}},onConfirm:(L)=>{if(typeof L?.index==="number")Q.value=z8(L.index,0,Math.max(0,R.length-1));k(String(L?.value??""))},onClose:()=>F()},()=>{let L=0,v=[];if(O&&Z.value[A]==="buttons"){let C=Math.max(0,N-1),b=Math.max(0,q-1);v.push(C0(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,[A]:"input"}}}))}if(v.push(C0(t,{x:0,y:L++,w:N,wrap:!0,value:D.question||"",style:E})),L++,w){v.push(C0(t,{x:0,y:L++,w:N,value:"[Multi-select] Space to toggle, Enter to confirm",style:{fg:"yellow"}})),L++;let C=G.value[A]??[],b=Math.min(z.length,Math.max(3,q-L-2));if(b>0&&L<q-2){if(v.push(C0(q0,{x:0,y:L,w:N,h:b,multiple:!0,options:f,modelValue:C,"onUpdate:modelValue":(y)=>{if(!Array.isArray(y))return;G.value={...G.value,[A]:y};let x=y.includes(S);Z.value={...Z.value,[A]:x?"input":"select"}},onFocus:()=>{Z.value={...Z.value,[A]:"select"}},autoFocus:Z.value[A]==="select",style:H,highlightStyle:{fg:"whiteBright",bg:"blueBright",bold:!0}})),L+=b+1,O&&L<q-1)v.push(C0(t,{x:0,y:L++,w:N,value:"Custom answer:",style:j})),v.push(C0(J6,{key:`custom-input:${A}:${X.value[A]??0}`,x:0,y:L,w:N,modelValue:V.value[A]||"","onUpdate:modelValue":(y)=>{V.value={...V.value,[A]:y}},onFocus:()=>{Z.value={...Z.value,[A]:"input"}},onKeydown:(y)=>{if(y?.key==="ArrowDown"){y.preventDefault?.(),y.stopPropagation?.(),Z.value={...Z.value,[A]:"buttons"};return}if(y?.key==="Enter"&&!y?.shiftKey){y.preventDefault?.(),y.stopPropagation?.();let x=z8(Q.value,0,Math.max(0,R.length-1)),c=R[x];k(String(c?.value??""));return}if(y?.key!=="ArrowUp")return;y.preventDefault?.(),y.stopPropagation?.(),Z.value={...Z.value,[A]:"select"}},autoFocus:Z.value[A]==="input",placeholder:"Type your answer...",style:{fg:"whiteBright",bg:"blackBright"}}))}}else{v.push(C0(t,{x:0,y:L++,w:N,value:"[Single-select] Use arrows, Enter to confirm",style:{fg:"yellow"}})),L++;let C=_.value[A]??0,b=Math.min(z.length,Math.max(3,q-L-2));if(v.push(C0(q0,{x:0,y:L,w:N,h:b,options:f,modelValue:C,"onUpdate:modelValue":(y)=>{_.value={..._.value,[A]:y},Z.value={...Z.value,[A]:y===S?"input":"select"}},onFocus:()=>{Z.value={...Z.value,[A]:"select"}},autoFocus:Z.value[A]==="select",style:H,highlightStyle:{fg:"whiteBright",bg:"blueBright",bold:!0}})),L+=b+1,O&&L<q-1)v.push(C0(t,{x:0,y:L++,w:N,value:"Custom answer:",style:j})),v.push(C0(J6,{key:`custom-input:${A}:${X.value[A]??0}`,x:0,y:L,w:N,modelValue:V.value[A]||"","onUpdate:modelValue":(y)=>{V.value={...V.value,[A]:y}},onFocus:()=>{Z.value={...Z.value,[A]:"input"}},onKeydown:(y)=>{if(y?.key==="ArrowDown"){y.preventDefault?.(),y.stopPropagation?.(),Z.value={...Z.value,[A]:"buttons"};return}if(y?.key==="Enter"&&!y?.shiftKey){y.preventDefault?.(),y.stopPropagation?.();let s=z8(Q.value,0,Math.max(0,R.length-1)),F$=R[s];k(String(F$?.value??""));return}if(y?.key!=="ArrowUp")return;y.preventDefault?.(),y.stopPropagation?.();let x=_.value[A]??0,c=z8(x-1,0,S);_.value={..._.value,[A]:c},Z.value={...Z.value,[A]:"select"}},autoFocus:Z.value[A]==="input",placeholder:"Type your answer...",style:{fg:"whiteBright",bg:"blackBright"}}))}return v})}}});function d0$($,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 qv($){return[$.showApproval.value&&$.activeApproval.value?Wv(Kv,{modelValue:$.showApproval.value,"onUpdate:modelValue":(J)=>$.showApproval.value=J,request:$.activeApproval.value,call:d0$($,$.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?Wv(Fv,{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 n0$}from"vue";import{computed as pV,defineComponent as l0$,ref as i0$,watch as r0$}from"vue";function Hv($,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 WJ($,J,U){return Math.max(J,Math.min(U,$))}function Bv($,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=Hv(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 Ov($,J){let U=$.findIndex((Q)=>Q.idx===J);return U>=0?U:0}import{h as X1}from"vue";function jv($){if(!$.modelValue)return null;let J=Math.max(0,Math.floor($.cols)),U=Math.max(0,Math.floor($.rows)),Q=J<=0?0:WJ(Math.floor(J*0.78),Math.min(44,J),J),_=U<=0?0:WJ(12,10,Math.max(10,Math.min(18,U))),G=Math.max(0,Math.floor(($.cols-Q)/2)),V=WJ(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),j=WJ(F.length,1,Math.max(1,E-q)),B=Math.max(1,j),D=Math.max(0,F.length-B),w=WJ($.selectedFilteredIndex-Math.floor(B/2),0,D),A=F.slice(w,w+B),I=F[$.selectedFilteredIndex]?.opt,f=I?.detail?String(I.detail):"",T=f?K0(f,Math.max(1,Y)).slice(0,2):[],z=()=>{$.onUpdateModelValue(!1),$.onClose()},S=(M)=>{if(!F.length)return;let P=F.length-1,R=$.selectedFilteredIndex+M;if(R<0)R=P;else if(R>P)R=0;let k=F[R]?.idx;if(k!=null)$.onUpdateSelectedIndex(k)},O=()=>{let M=F[$.selectedFilteredIndex];$.onSelect(M?.opt?.label??null)};return X1(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()}},()=>X1(N6,{x:G,y:V,w:Q,h:_,border:!0,title:$.title,padding:1,style:{fg:"blueBright",bg:"black"},zIndex:110},()=>[X1(t,{x:0,y:0,w:Y,h:K,value:"",style:{bg:"black"}}),X1(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?X1(t,{x:0,y:N,w:Y,value:"─".repeat(Y),style:{fg:"white",dim:!0,bg:"black"}}):null,F.length?X1(q0,{x:0,y:q,w:Y,h:j,options:A.map((M)=>({label:M.opt.label})),modelValue:WJ($.selectedFilteredIndex-w,0,Math.max(0,A.length-1)),"onUpdate:modelValue":(M)=>{let P=A[WJ(M,0,Math.max(0,A.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}):X1(t,{x:0,y:q,w:Y,h:j,value:"No matches",style:{fg:"white",dim:!0,bg:"blackBright"}}),T.length?T.map((M,P)=>X1(t,{key:`detail-${P}`,x:0,y:E+P,w:Y,value:M,style:{fg:"white",dim:!0,bg:"black"}})):X1(t,{x:0,y:E,w:Y,h:2,value:"",style:{bg:"black"}}),X1(t,{x:0,y:H,w:Y,value:"Type to filter • Enter: open • Esc: close",style:{fg:"white",dim:!0,bg:"black"}}),Y>0?X1(t,{x:Math.max(0,Y-1),y:H,w:1,value:" ",style:{bg:"black"}}):null]))}var aV=l0$({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=pV(()=>U.clipRect?.w??0),_=pV(()=>U.clipRect?.h??0),G=i0$("");r0$(()=>[$.modelValue,$.initialQuery],([Y])=>{if(Y)G.value=String($.initialQuery??"")});function V(){J("close")}let X=pV(()=>Bv($.options,G.value)),Z=pV(()=>Ov(X.value,$.selectedIndex));return()=>{return jv({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 Dv($){return[n0$(aV,{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 a0$}from"vue";import{defineComponent as p0$,h as Gj}from"vue";var Ev=p0$({name:"GoatChainExitSessionDialog",props:{modelValue:{type:Boolean,required:!0}},emits:{"update:modelValue":($)=>!0,exit:()=>!0},setup($,{emit:J}){return()=>{if(!$.modelValue)return null;return Gj(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)},()=>[Gj(t,{x:0,y:0,w:50,wrap:!0,value:"Exit the current session and return to Home?",style:{fg:"whiteBright",bg:"black"}}),Gj(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 Pv($){return[a0$(Ev,{modelValue:$.showExitConfirm.value,"onUpdate:modelValue":(J)=>$.showExitConfirm.value=J,onExit:async()=>{$.showExitConfirm.value=!1,await $.exitSessionToHome()}})]}import{h as R8}from"vue";import{defineComponent as o0$,h as oV}from"vue";var Mv=o0$({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 oV(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:_},()=>oV(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[oV(t,{key:`action-t-${X}`,x:0,y:X,w:44,value:`${K}${V}`,style:Y}),oV(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 t0$,h as Lv}from"vue";var zv=t0$({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 Lv(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},()=>[Lv(t,{x:0,y:1,w:48,value:"Are you sure you want to restore the reverted messages?",style:{fg:"white"}})])}}});function Rv($){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(R8(t,{key:"revert-banner-bg",x:2,y:_,w:G,h:2,value:"",style:{bg:"black"},zIndex:50}),R8(t,{key:"revert-banner-bar",x:2,y:_,w:1,h:2,value:V,style:{fg:"blueBright",bg:"black"},zIndex:51}),R8(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}),R8(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}),R8(R4,{key:"revert-banner-hit",x:2,y:_,w:G,h:2,zIndex:60,focusable:!0,onClick:()=>{$.confirmRestore(),$.focusBrowserTextarea()}}))}return J.push(R8(Mv,{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()}}),R8(zv,{modelValue:$.showRedoConfirm.value,"onUpdate:modelValue":(U)=>$.showRedoConfirm.value=U,onConfirm:$.confirmRestore,onCancel:$.cancelRestore})),J}import{h as $1$}from"vue";import{defineComponent as s0$,h as Vj,watch as e0$}from"vue";var tV=s0$({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=_J(),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=U1($.workspace,$.query);if(X===Z)return Q=!1,{exists:!1,kind:"other"}}return U.stat(X)}};return e0$(()=>$.modelValue,(X)=>{if(!X)_()}),()=>{if(!$.modelValue)return null;let X=Math.max(0,$.w-2),Z=Math.max(0,$.h-2);return Vj(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")}},()=>[Vj(t,{x:0,y:0,w:X,value:"↑/↓ select • Tab complete • Enter confirm • Esc close",style:{fg:"white",dim:!0}}),Vj(jV,{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 Av($){return[$1$(tV,{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 Q1$}from"vue";import{defineComponent as J1$,h as Xj,ref as U1$,watch as _1$}from"vue";var wv=J1$({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=U1$(String($.initialValue??""));_1$(()=>$.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 Xj(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()}},()=>[Xj(t,{x:0,y:0,w:V,value:"Session name",style:{fg:"white",dim:!0,bg:"black"}}),Xj(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 fv($){if(!$.showRenameSession.value)return[];return[Q1$(wv,{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 Tv}from"vue";import{defineComponent as F1$,ref as W1$,watch as q1$}from"vue";function qJ($,J,U){return Math.max(J,Math.min(U,$))}function G1$($,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 V1$($,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 X1$($,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 Y1$($,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 Z1$($){return $.title||$.summary||"New session"}function kv($,J){return G1$($.updatedAt,J)}function K1$($){return Y1$($.cwd,3)}function N1$($){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 Iv($){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=qJ(Y,1,Math.max(1,G-2-1)),F=qJ($.selectedIndex,0,Math.max(0,Y-1)),N=Date.now(),q=Math.max(0,...Z.map((M)=>M$(kv(M,N)))),H=1,E=Math.max(0,Q-1-q),{cwdW:j,summaryW:B,colGap:D}=N1$(E),w=Math.max(1,K),A=Math.max(0,Y-w),I=qJ(F-Math.floor(w/2),0,A),T=Z.slice(I,I+w).map((M)=>{let P=[];if(j>0){let R=K1$(M)||"—",k=h6(X1$(R,j),j);P.push(k)}if(B>0){let R=Z1$(M),k=h6(V1$(R,B),B);P.push(k)}return{label:P.filter(Boolean).join(" ".repeat(D)).trimEnd(),detail:kv(M,N)}}),z=qJ(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>w?` • Showing ${I+1}-${Math.min(Y,I+w)}`:""}`:"No saved sessions yet";return{w:J,h:U,innerW:Q,listY:2,listH:K,offset:I,windowSize:w,totalSessions:Y,selectedIndex:F,selectedOptionIndex:z,title:S,headerText:O,options:T}}import{h as Yj}from"vue";function Sv($){if(!$.modelValue)return null;return Yj(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()},()=>[Yj(t,{x:0,y:0,w:$.vm.innerW,value:$.vm.headerText,style:{fg:"white",dim:!0,bg:"black"}}),Yj(q0,{x:0,y:$.vm.listY,w:$.vm.innerW,h:$.vm.listH,options:$.vm.options,modelValue:$.vm.selectedOptionIndex,"onUpdate:modelValue":(J)=>{let U=qJ($.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 sV=F1$({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=W1$(0),_="__goatchainSessionsDialogHandled";function G(){return $.deleteArmed?U.indexOf("delete"):U.indexOf("open")}function V(Y){let K=U.length-1;Q.value=qJ(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 q1$(()=>$.modelValue,(Y,K)=>{if(Y&&!K)Q.value=G()},{immediate:!0}),()=>{let Y=Iv({modelValue:$.modelValue,loading:$.loading,deleteArmed:$.deleteArmed,sessions:$.sessions,selectedIndex:$.selectedIndex});return Sv({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 H1$,h as eV}from"vue";var $X=H1$({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 eV(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)},()=>[eV(t,{x:0,y:0,w:60,wrap:!0,value:U?`Switch to ${U}?`:"Switch sessions now?",style:{fg:"whiteBright",bg:"blackBright"}}),eV(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?eV(t,{x:0,y:4,w:60,wrap:!0,value:`Reason: ${Q}`,style:{fg:"white",dim:!0,bg:"blackBright"}}):null])}}});function vv($){return[Tv(sV,{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()}}),Tv($X,{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 Nj}from"vue";import{defineComponent as O1$}from"vue";import{h as U0}from"vue";function B1$($,J,U){return Math.max(J,Math.min(U,$))}function Cv($,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),j=V>=H*q+1,B=j?U0(t,{x:0,y:0,w:_,value:"Tab/Shift+Tab switch field • Enter Apply • Esc Cancel",style:X}):null,D=H===N?1:2,w=B1$(Math.floor(_*0.28),16,Math.max(16,_-(16+D))),A=Math.max(0,_-w-D),I=j?1+K:0,f=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 R=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:f,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,h:H,border:!0,title:"Context Window",padding:0,style:Z,clear:!0},()=>U0(J6,{x:0,y:0,w:Math.max(0,w-2),h:E,modelValue:$.contextWindow,"onUpdate:modelValue":(C)=>J.updateContextWindow(C),placeholder:"128000",cursorToEndOnFirstFocus:!0,cursorToEndOnExternalUpdate:!0,style:Y,zIndex:1002})),U0(N6,{x:w+D,y:T,w:A,h:H,border:!0,title:"Temperature",padding:0,style:Z,clear:!0},()=>U0(J6,{x:0,y:0,w:Math.max(0,A-2),h:E,modelValue:$.temperature,"onUpdate:modelValue":(C)=>J.updateTemperature(C),placeholder:"0.7",cursorToEndOnFirstFocus:!0,cursorToEndOnExternalUpdate:!0,style:Y,zIndex:1002,plugins:[HV({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:R,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 JX=O1$({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 Cv({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 Zj,defineComponent as j1$,h as i0,ref as Kj,watch as D1$}from"vue";var UX=["goatchain","mono","contrast"],bv=["inherit",...xV];function yv($,J,U){return Math.max(J,Math.min(U,$))}function gv($){if(!$)return 0;let J=xV.indexOf($);return J>=0?J+1:0}function _X($){if($<=0)return;return xV[$-1]}var xv=j1$({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=Kj(0),Q=Kj(0),_=Kj(0),G=Zj(()=>{return RU[yv(U.value,0,RU.length-1)]});D1$([()=>$.modelValue,G,()=>$.overrides],()=>{if(!$.modelValue)return;let K=$.overrides[G.value];Q.value=gv(K?.fg),_.value=gv(K?.bg)},{immediate:!0});function V(K){Q.value=K;let F=_X(K),N=_X(_.value);J("setOverride",G.value,!F&&!N?null:{fg:F,bg:N})}function X(K){_.value=K;let F=_X(Q.value),N=_X(K);J("setOverride",G.value,!F&&!N?null:{fg:F,bg:N})}let Z=Zj(()=>{let K={preset:$.preset,overrides:$.overrides};return I1(K,G.value)}),Y=Zj(()=>{let K=UX.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 i0(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)},()=>[i0(t,{x:0,y:0,w:60,value:"Preset",style:N}),i0(q0,{x:0,y:1,w:60,h:3,options:[...UX],modelValue:Y.value,"onUpdate:modelValue":(H)=>{let E=UX[yv(H,0,UX.length-1)]??"goatchain";J("update:preset",E)},autoFocus:!0,style:F,highlightStyle:K}),i0(t,{x:0,y:5,w:24,value:"Message Type",style:N}),i0(q0,{x:0,y:6,w:24,h:4,options:[...RU],modelValue:U.value,"onUpdate:modelValue":(H)=>U.value=H,style:F,highlightStyle:K}),i0(t,{x:28,y:5,w:10,value:"fg",style:N}),i0(t,{x:46,y:5,w:10,value:"bg",style:N}),i0(q0,{x:28,y:6,w:16,h:4,options:[...bv],modelValue:Q.value,"onUpdate:modelValue":(H)=>V(H),style:F,highlightStyle:K}),i0(q0,{x:46,y:6,w:16,h:4,options:[...bv],modelValue:_.value,"onUpdate:modelValue":(H)=>X(H),style:F,highlightStyle:K}),i0(t,{x:0,y:11,w:60,value:"Preview",style:N}),i0(t,{x:0,y:12,w:60,value:` ${G.value} `,style:{fg:Z.value.fg??"whiteBright",bg:Z.value.bg??"black"}}),i0(t,{x:0,y:14,w:60,value:'Tip: set fg/bg to "inherit" to use preset.',style:q})])}}});import{defineComponent as E1$,h as L7,ref as P1$,watch as M1$}from"vue";function L1$($,J){let Q=Math.max(20,Math.floor(J/1));return Math.max(1,Math.ceil($.length/Q))}var QX=E1$({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=P1$(0);function _(G){return G==="all"?1:0}return M1$([()=>$.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=L1$(q,G),D=E+1,w=2,A=D+B+1,I=A+w,f=Math.max($.h,I+4);return L7(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:f,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)},()=>[L7(t,{x:0,y:H,w:G,value:`Current: ${$.mode}`,style:{fg:"white",dim:!0,bg:"blackBright"}}),L7(t,{x:0,y:E,w:G,value:N,style:V}),L7(t,{x:0,y:D,w:G,h:B,wrap:!0,value:q,style:Z}),L7(t,{x:0,y:A,w:G,h:2,wrap:!0,value:"Tip: use ←/→ to move between buttons, Enter to confirm, Esc to close.",style:X})])}}});function hv($){return[Nj(xv,{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()}),Nj(JX,{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}),Nj(QX,{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 GX}from"vue";function VX($){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,j=Math.min(Math.max(E,H),q),B=Math.max(1,j-Y*2-K*2),D=m4(G,B),w=M$(D),A=Math.max(0,Math.floor((B-w)/2)),I=h6(`${I4(A)}${D}`,B),f=1+F*2,T=Math.max(2,N-j-2),z=1;return[GX(t,{key:"copy-toast-bg",x:T,y:z,w:j,h:f,value:I4(j),style:{bg:V},zIndex:220}),GX(t,{key:"copy-toast-accent-left",x:T,y:z,w:Y,h:f,value:I4(Y),style:{bg:Z},zIndex:221}),GX(t,{key:"copy-toast-accent-right",x:T+j-Y,y:z,w:Y,h:f,value:I4(Y),style:{bg:Z},zIndex:221}),GX(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 uv($){return VX({visible:$.copyToastVisible,text:$.copyToastText,cols:$.cols})}import{h as XX}from"vue";function YX($){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),j=Math.max(1,E-X-Z*2),B=3,D=[...K0(K,j)];if(D.length>B){D=D.slice(0,B);let f=B-1;if(j>1)D[f]=`${m4(D[f],j-1)}…`;else D[f]="…"}let w=Math.max(1,D.length)+Y*2,A=Math.max(2,F-E-2),I=1;return J.push(XX(t,{key:"upgrade-toast-bg",x:A,y:I,w:E,h:w,value:I4(E),style:{bg:V.bg},zIndex:200}),XX(t,{key:"upgrade-toast-accent",x:A,y:I,w:X,h:w,value:I4(X),style:{bg:V.accentBg},zIndex:201}),XX(t,{key:"upgrade-toast-text",x:A+X+Z,y:I+Y,w:j,h:D.length,value:D.join(`
|
|
944
|
-
`),style:{fg:V.fg,bg:V.bg,bold:!0},zIndex:202})),J.push(XX(R4,{key:"upgrade-toast-hit",x:A,y:I,w:E,h:w,zIndex:210,focusable:!0,onClick:()=>{$.onDismiss?.(),$.onFocus?.()}})),J}function mv($){return YX({notification:$.store.upgradeNotification.value,cols:$.cols.value,onDismiss:()=>{$.store.dismissUpgradeNotification(),$.focusBrowserTextarea()}})}var cv=z1$({name:"GoatChainChatOverlays",setup(){let $=R1$(H0);if(!$)throw Error("GoatChainChatOverlays missing ChatPageContext");let J=$;return()=>[...Dv(J),...Av(J),...vv(J),...hv(J),...fv(J),...qv(J),...Rv(J),...Pv(J),...uv(J),...mv(J)]}});import{computed as z7,defineComponent as A1$,h as A8,inject as w1$,onBeforeUnmount as f1$,ref as Fj}from"vue";function k1$($){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 dv=A1$({name:"GoatChainDebugPerfPanel",setup(){let $=w1$(H0);if(!$)throw Error("GoatChainDebugPerfPanel missing ChatPageContext");let J=$,{scheduler:U,defaultStyle:Q}=L4(),_=z7(()=>J.nodeLike&&Boolean(J.store.state?.ui?.debugPerfPanel)),G=YO(),V=Fj(""),X=Fj(""),Z=Fj(""),Y=setInterval(()=>{if(!_.value)return;try{let E=Number(G.fps)||0,j=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 ${j.toFixed(1)}ms ${k1$(B)}`}catch{Z.value="",X.value=""}try{let E=globalThis?.process?.memoryUsage?.(),j=Number(E?.rss??0),B=Number(E?.heapUsed??0);V.value=`mem rss=${(j/1048576).toFixed(1)}MB heap=${(B/1048576).toFixed(1)}MB`}catch{V.value=""}U?.invalidate?.()},500);Y.unref?.(),f1$(()=>clearInterval(Y));let K=z7(()=>Math.min(48,Math.max(28,J.cols.value-4))),F=z7(()=>Math.max(0,J.cols.value-K.value-1)),N=z7(()=>1),q=z7(()=>{let E=String(J.store.state.sessionId??"").trim(),j=J.store.state.context?.env??{},B=String(j.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 j=q.value;if(!j||j.includes("\x00"))return;try{let{spawn:B}=await import("node:child_process"),D=globalThis.process,w=String(D?.platform||"");B(w==="darwin"?"open":w==="win32"?"explorer.exe":"xdg-open",[j],{shell:!1,detached:!0,stdio:"ignore"}).unref()}catch{}}return()=>{if(!_.value)return null;let E=K.value,j=F.value,B=N.value,D=Z.value,w=X.value,A=q.value,I=A?`ctrl+click: ${A}`:"ctrl+click: (no session dir)",f={...Q.value,dim:!0};return A8(R4,{x:j,y:B,w:E,h:6,zIndex:50,focusable:!1},()=>[A8(N6,{x:0,y:0,w:E,h:6,border:!0,title:"Debug",padding:0,style:{fg:"yellowBright"}}),A8(t,{x:1,y:1,w:E-2,value:D,style:f}),A8(t,{x:1,y:2,w:E-2,value:w,style:f}),A8(t,{x:1,y:3,w:E-2,value:V.value,style:f}),A8(t,{x:1,y:4,w:E-2,value:I,style:{...f,fg:A?"cyanBright":"white"}}),A8(R4,{x:1,y:4,w:E-2,h:1,focusable:!1,onClick:H})])}}});import{appendFileSync as I1$}from"node:fs";import{computed as f6,ref as lv,watch as iv}from"vue";function O4($,J,U){return Math.max(J,Math.min(U,$))}var S1$="";function T1$($){let J=String($||"");if(!J)return"[file]";return`[${J.split(/[/\\]/).filter(Boolean).pop()??J}]`}function Wj($,J,U=[]){if(J<=0)return 1;let Q=0,_="";for(let G of String($)){if(G===S1$){_+=T1$(U[Q]??""),Q++;continue}_+=G}return K0(_,J).length||1}function rv($){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(()=>Wj($.input.value,q.value,$.mentions.value)),E=f6(()=>{return O4(H.value+1,2,4)}),j=f6(()=>H.value+1>4?1:0),B=f6(()=>$.hasRevertedMessages.value?3:1),D=f6(()=>E.value+j.value+1),w=f6(()=>D.value+2),A=f6(()=>Math.max(0,U.value-4-w.value-2-B.value)),I=4,f=f6(()=>4+A.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:A,mainY:4,panelW:T,panelX:z,panelTopY:f,panelH:D,inputX:S,inputInnerW:O,inputLines:E,modelRowGap:j,inputWrapWidth:q,footerH:2,contentPadX:1}}function nv($){let J=lv(0),U=lv(!0),Q=f6(()=>Math.max(0,$.lines.value.length-$.mainH.value));iv([()=>$.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=V7(),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{I1$(F,`${H}
|
|
945
|
-
`)}catch{}}iv(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 j=Date.now();if(G&&Number.isInteger(E)&&Math.abs(E)===1&&X!==0){let A=E>0?1:-1,I=j-Z;if(A===-X&&I>=0&&I<160){if(Y+=1,Y<2){N(`[${j}] [CHAT_SCROLL] wheel suppressed dy=${E} dt=${I} top=${J.value} lastAppliedDir=${X}`),H.preventDefault?.();return}V.accumulator=0,N(`[${j}] [CHAT_SCROLL] wheel reversal confirmed dy=${E} dt=${I} top=${J.value} lastAppliedDir=${X}`)}else Y=0}else Y=0;let{nextTop:B,dir:D,lines:w}=X7(V,E,J.value,Q.value,j);if(N(`[${j}] [CHAT_SCROLL] wheel dy=${E} top=${J.value} max=${Q.value} stick=${U.value?1:0} -> next=${B} dir=${D} lines=${w} ghostty=${G?1:0}`),!D||B===J.value){H.preventDefault?.();return}if(D<0&&U.value)U.value=!1;if(J.value=O4(B,0,Q.value),X=D,Z=j,D>0&&J.value===Q.value&&!U.value)U.value=!0}return{scrollTop:J,stickToBottom:U,maxScroll:Q,visibleLines:_,onWheel:q}}import{computed as Y1,ref as TU,watch as ZX}from"vue";function qj($){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"&&!qj(J)}function pv($,J){if($==="all")return!0;return J==="require_action"}function av($){let J=TU(!1),U=TU(0),Q=TU(!1),_=TU(!1),G=TU(!1),V=TU(!1),X=Y1(()=>$.store.state.approval.active),Z=Y1(()=>{let I=Math.min(86,Math.max(1,$.contentW.value)),f=Math.min(46,I),T=Math.floor($.contentW.value*0.5);return O4(T,f,I)}),Y=Y1(()=>O4(11,9,Math.max(9,$.rows.value-6))),K=Y1(()=>$.store.state.paused?.kind==="ask_user"?$.store.state.paused:null),F=Y1(()=>O4(Math.floor($.contentW.value*0.62),40,90)),N=Y1(()=>O4(18,14,Math.max(14,$.rows.value-4))),q=Y1(()=>O4(Math.floor($.contentW.value*0.78),56,84)),H=Y1(()=>O4(24,18,Math.max(18,$.rows.value-4))),E=Y1(()=>O4(Math.floor($.contentW.value*0.62),46,86)),j=Y1(()=>O4(14,11,Math.max(11,$.rows.value-6)));function B(I){if(String($.store.state.approval.mode??"auto")==="all")return!1;return qj(I)}ZX(()=>X.value?.id??null,()=>{let I=X.value;if(I&&I.status==="pending"&&B(I))_.value=!0;else _.value=!1},{immediate:!0}),ZX(()=>$.store.state.approval.mode,()=>{let I=X.value;if(!I||I.status!=="pending"||!B(I))_.value=!1}),ZX(()=>K.value?.toolCallId??null,(I)=>{G.value=Boolean(I)});let D=Y1(()=>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);ZX(D,(I)=>{if(!I)$.focusMode.value="input"});function w(){J.value=!0,U.value=0}function A(){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:j,anyDialogOpen:D,openCommandPalette:w,closeCommandPalette:A}}function ov($){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 j=$.getSelectedMessageText();if(!j)return!1;return Y.stopPropagation?.(),Y.preventDefault?.(),$.copyTextToClipboard(j).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=Wj($.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 tv($){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 v1$($){if($.role!=="assistant")return $;let J=$.parts.filter((U)=>U.type!=="status"&&U.type!=="thinking"&&U.type!=="tool_output");return{...$,parts:J}}function sv($,J){let U=$.findIndex((Q)=>Q.id===J);if(U<0)return null;return $.slice(0,U).map(v1$)}async function ev($){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 C1$,shallowRef as Hj,triggerRef as b1$}from"vue";function $C($){let J=Hj(null),U=Hj(null),Q=Hj(!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=C1$(()=>{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,b1$(U)}function N(){return _v($.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 j(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 R=(S.cellY??0)-$.mainY,k=$.scrollTop.value+R,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)),f()}function D(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 R=$.lines.value[O.row];if(!R?.messageId)return;if($.store.state.messages.find((L)=>L.id===R.messageId)?.role!=="user")return;$.messageActionsTargetId.value=R.messageId,$.showMessageActions.value=!0}}function w(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 A(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 f(){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)),R=Math.max(0,-M),k=P>0&&$.scrollTop.value<O,L=R>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,R=Math.max(0,P-(O-1)),k=Math.max(0,-P),L=0,v=0;if(R>0&&$.scrollTop.value<M)L=1,v=R;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))}}f()}return{messageSelectStart:J,messageSelectEnd:U,isSelecting:Q,hasMessageSelection:K,focusBrowserTextarea:H,getSelectedMessageText:N,getNativeSelectionText:q,clearMessageSelection:E,onMessageClick:w,onMessagePointerDown:j,onMessagePointerMove:B,onMessagePointerUp:D,onMessageContextMenu:A}}import{computed as Z1,onBeforeUnmount as y1$,ref as g1$,watch as x1$}from"vue";function JC($){let J=Z1(()=>{let w=$.store.state.messages.length,A=Math.max(0,Number($.store.state.usage.prompt_tokens)||0),I=Math.max(0,Number($.store.state.usage.completion_tokens)||0),f=A+I,T=`${w.toLocaleString()} msgs · ${f.toLocaleString()} tok`;return $.copyToastVisible.value&&$.copyToastText.value?`${T} ${$.copyToastText.value}`:T});function U(w){if(w>=88)return"●";if(w>=63)return"◕";if(w>=38)return"◑";if(w>=13)return"◔";return"○"}let Q=Z1(()=>{let w=Math.max(0,Number($.store.state.usage.prompt_tokens)||0),A=Math.max(0,Number($.store.state.usage.completion_tokens)||0),I=w+A,f=Math.max(1,Number($.store.state.config.context_window)||128000),T=O4(Math.round(I/f*100),0,100);return`${U(T)} ${T}%`}),_=Z1(()=>{return{build:"■",label:String($.store.state.config.model??"model")}}),G=Z1(()=>$.uiMode.value),V=-1,X=-1,Z=Z1(()=>{let w=$.store.state.messages,A=w.length;if(A!==X){if(X=A,V>=A)V=-1}let I=V>=0?w[V]:void 0;if(!I||I.role!=="assistant"){V=-1;for(let z=w.length-1;z>=0;z--){let S=w[z];if(S&&S.role==="assistant"){V=z,I=S;break}}}if(!I||I.role!=="assistant")return"";let f=I.parts.find((z)=>z.type==="status"),T=String(f?.text??"").trim();return!T||T==="Done."?"":T}),Y=Z1(()=>{return{fg:I1($.store.state.ui.theme,"status").fg??"white",bg:"blackBright",dim:!0}}),K=Z1(()=>Boolean($.store.state.runningToolCallId)||Boolean($.store.state.runningAgentRound)),F=g1$(0),N=10,q=3,H=null,E=Z1(()=>{if(K.value)return!0;return/^thinking\b/i.test(Z.value)});x1$(E,(w)=>{if(w&&!H)H=setInterval(()=>{F.value=(F.value+1)%N},100);else if(!w&&H)clearInterval(H),H=null,F.value=0},{immediate:!0}),y1$(()=>{if(H)clearInterval(H);H=null});let j=Z1(()=>{let w=Z.value;if(!w)return"";return w}),B=Z1(()=>{let w=[];for(let A=0;A<N;A++){let I=(A-F.value+N)%N;w.push(I>=N-q?"■":"·")}return w.join("")}),D=Z1(()=>"Ctrl+K: config Tab: mode Ctrl+P: commands");return{headerStatsDisplay:J,ctxPctChip:Q,modelInfo:_,modeLabel:G,assistantStatusDisplay:j,assistantStatusStyle:Y,isLoading:K,loadingDots:B,footerRight:D}}function HJ(){if(typeof globalThis.window<"u")return!1;let $=globalThis.process;return!!$&&typeof $?.versions?.node==="string"&&typeof $?.cwd==="function"}function UC(){try{let $=globalThis.process;return(typeof $?.cwd==="function"?String($.cwd()):"")||"/"}catch{return"/"}}async function KX($){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(HJ())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=HJ()?(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 NX($){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 FX($){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 R7,ref as WX}from"vue";function qX($){let J=WX(!1),U=WX("directory"),Q=WX(""),_=WX(null),G=R7(()=>{let N=String($.store.state.context?.cwd??".");if(!$.nodeLike)return N;return U1(UC(),N)}),V=R7(()=>U.value==="directory"?"Select Workspace":"Select File"),X=R7(()=>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=R7(()=>O4(Math.min(72,Math.max(32,Math.floor($.cols.value*0.72))),32,Math.max(32,$.cols.value-4))),Y=R7(()=>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 h1$}from"node:fs";function u1$(){let $=globalThis.process;return Boolean($&&typeof $?.versions?.node==="string")}function m1$(){if(!u1$())return!1;let $=globalThis.process?.env??{},J=String($.GOATCHAIN_DEBUG??"").trim().toLowerCase();return J==="1"||J==="true"||J==="yes"||J==="on"}function c1$(){let $=globalThis.process?.env??{};return String($.GOATCHAIN_DEBUG_LOG??"").trim()||"./goatchain-debug.log"}function b4($,J){if(!m1$())return;let U=String($??"").trim()||"event",_=`[${new Date().toISOString()}] ${U}`;if(J!==void 0)try{_+=` ${JSON.stringify(J)}`}catch{}_+=`
|
|
947
|
-
`;try{h1$(c1$(),_)}catch{}}import{ref as T1,watch as d1$}from"vue";function HX($){let J=T1(!1),U=T1(!1),Q=T1("Switch Session"),_=T1(""),G=T1(""),V=T1(!1),X=T1(!1),Z=T1([]),Y=T1(0),K=T1(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 f=$.sessionsApi;if(!f){Z.value=[],Y.value=0;return}V.value=!0;try{let T=await f.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 j(I){let f=$.sessionsApi,T=Z.value[Y.value];if(!f||!T)return;await q({title:"Switch Session",targetLabel:String(T.title||T.id),run:async()=>{let z=String($.store.state.sessionId??"");await f.use(T.id),b4("session_switch_run",{from:z,to:String(T.id),kind:"use"}),await I?.after?.()}})}async function B(I){let f=$.sessionsApi;if(!f){$.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 f.createNew(),b4("session_switch_run",{from:T,to:String($.store.state.sessionId??""),kind:"new"}),await I?.after?.()}})}async function D(){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 w(){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 d1$([J,()=>String($.store.state.sessionId??"").trim()],([I,f])=>{if(!I)return;if(!$.sessionsApi||!f)return;H({preferId:f})}),{showSessions:J,showSwitchConfirm:U,switchConfirmTitle:Q,switchConfirmTargetLabel:_,switchConfirmReason:G,sessionsLoading:V,sessionsDeleteArmed:X,sessionsList:Z,sessionsIndex:Y,refreshSessions:H,openSessionsDialog:E,openSelectedSession:j,createNewSession:B,confirmSwitch:D,cancelSwitch:w}}import{computed as l1$,ref as BJ}from"vue";function _C($){let J=String($??"").trim();if(!J)return"";return`***${J.slice(-4)||"****"}`}function BX($){let J=BJ(!1),U=BJ(!1),Q=BJ(""),_=BJ(""),G=BJ(""),V=BJ(!1),X=BJ(""),Z=BJ(""),Y=l1$(()=>{let j=$.store.state.context?.env??{};return _C(j.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 j=$.store.state.context?.env??{};X.value=String(j.GOATCHAIN_OPENAI_BASE_URL||j.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 j=Q.value.trim();if(j)$.store.state.config.model=j;$.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 D=Z.value.trim();if(D)$.store.setEnvVar("OPENAI_API_KEY",D);if($.nodeLike){let w=globalThis.process;if(w?.env){w.env.GOATCHAIN_MODEL=$.store.state.config.model,w.env.GOATCHAIN_CONTEXT_WINDOW=String($.store.state.config.context_window),w.env.GOATCHAIN_TEMPERATURE=String($.store.state.config.temperature??""),w.env.GOATCHAIN_INTERLEAVED_THINKING=V.value?"1":"0";let A=X.value.trim();if(A)w.env.GOATCHAIN_OPENAI_BASE_URL=A;else delete w.env.GOATCHAIN_OPENAI_BASE_URL;if(D)w.env.OPENAI_API_KEY=D}}Z.value="",N()}function H(){if(K()){$.showToast("Resolve the pending approval before changing settings.");return}U.value=!0}function E(j){if($.store.state.approval.mode=j,$.store.setEnvVar("GOATCHAIN_TOOL_APPROVALS",j),$.nodeLike){let B=globalThis.process;if(B?.env)B.env.GOATCHAIN_TOOL_APPROVALS=j}$.showToast(`Tool approvals: ${j}`)}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}}function OX($){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)i1$(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 i1$($,J){try{let{getGoatChainUserDir:U}=await Promise.resolve().then(() => (Q2(),mG)),[{readFile:Q,unlink:_},G]=await Promise.all([import("node:fs/promises"),import("node:path")]),V=await U($),X=G.join(V,"upgrade-toast.json"),Z=await Q(X,"utf8"),Y=JSON.parse(Z),K=String(Y?.message??"").trim();if(await _(X),K)J(K)}catch{}}import{onBeforeUnmount as r1$,ref as QC}from"vue";function jX($=1200){let J=QC(!1),U=QC(""),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 r1$(()=>{if(Q)clearTimeout(Q);Q=null}),{visible:J,text:U,show:_}}function n1$($,J=120){let U=S0(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 A7($,J){let U=globalThis.process,Q=J?.stdout??U?.stdout;if(!Q||typeof Q.write!=="function")return;if(!J?.force&&!Q.isTTY)return;let _=n1$($,J?.maxLen??120);if(!_)return;let G="\x1B";Q.write(`${G}]0;${_}${G}\\`)}var Bj=p1$({name:"GoatChainChatPage",setup(){let $=HJ(),J=LU(),U=EV(),Q=p4(),{events:_,scheduler:G}=L4(),V=a1$(P8,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=b0(""),N=k6(()=>{let N$=[];for(let C$ of X.state.messages){if(!C$||C$.role!=="user")continue;let Z4=String(C$.content??""),f4=UJ(Z4).trim();if(!f4)continue;N$.push(f4)}return N$}),q=b0(N.value.length),H=b0([]),E=b0("input"),j=b0(X.getMode?.()??"agent");function B(N$=1){let C$=["plan","agent"],Z4=j.value,a4=(C$.indexOf(Z4)+N$+C$.length)%C$.length,j6=C$[a4]??"agent";j.value=j6,X.setMode?.(j6)}let D=rv({cols:Y,rows:K,input:F,mentions:H,hasRevertedMessages:X.hasRevertedMessages}),{contentW:w,mainW:A,mainH:I,mainY:f,panelW:T,panelX:z,panelTopY:S,panelH:O,inputX:M,inputInnerW:P,inputLines:R,modelRowGap:k,inputWrapWidth:L,footerH:v}=D,C=jX(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,GC(()=>{if(N$.__VT_SHOW_COPY_TOAST__===Z4)if(C$)N$.__VT_SHOW_COPY_TOAST__=C$;else delete N$.__VT_SHOW_COPY_TOAST__})}let c=JC({store:X,uiMode:j,copyToastVisible:b,copyToastText:y}),{headerStatsDisplay:s,ctxPctChip:F$,modelInfo:K$,modeLabel:V$,assistantStatusDisplay:Y$,assistantStatusStyle:u$,isLoading:_$,loadingDots:n,footerRight:a}=c,m=BX({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=HX({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$=qX({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$;OX({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:()=>Aj("/approvals")},{value:"/rename",detail:"Rename current session",insert:"",onSelect:()=>{return F2(),!1}}],y$=b0(!1),X4=b0(0),W4=b0(!1),_6=b0(null),i$=b0(null),l$=b0(!1),Y4=av({store:X,rows:K,contentW:w,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:I8,askUserW:y0,askUserH:B0,configW:K1,configH:DJ,toolApprovalsW:zX,toolApprovalsH:bU,anyDialogOpen:yU,openCommandPalette:RX,closeCommandPalette:EJ}=Y4;w8(H,(N$)=>{X.setFocusFiles(N$)});let N1=k6(()=>String(X.state.sessionId??"").trim());w8(N1,(N$)=>{if(!Z||!N$)return;g({preferId:N$})},{immediate:!0}),w8(()=>[N1.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 S8=k6(()=>{let N$=N1.value;if(!N$)return null;return e4.value.find((C$)=>C$.id===N$)??null}),w7=k6(()=>{return`# ${N1.value||"new"}`}),AX=k6(()=>{return String(S8.value?.title??"").trim()||""}),gU=k6(()=>O4(Math.floor(w.value*0.62),44,86)),PJ=k6(()=>9);function F2(){let N$=N1.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 f7(N$){let C$=N1.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 T8=k6(()=>{let N$=String(S8.value?.title??"").trim();if(N$)return N$;let C$=String(S8.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();A7(a4?`${C$} ${a4}`:C$)};w8(T8,(f4)=>Z4(f4),{immediate:!0}),GC(()=>A7(C$))}let C1=k6(()=>[...FX({openSessionsDialog:()=>void h(),createNewSession:()=>void Q4(),openConfig:o$,openToolApprovals:F4}),{label:"Theme",detail:"Message colors",run:()=>x$.value=!0}]),b1=k6(()=>C1.value.map((N$)=>({label:N$.label,detail:N$.detail})));function wX(N$){if(EJ(),!N$)return;C1.value.find((Z4)=>Z4.label===N$)?.run()}let fX=oT(),MJ=b0(null),v8=b0(0),kX=k6(()=>{let N$=Math.max(0,A.value-4);return fX({messages:X.state.messages,width:N$,selectedToolCallId:X.state.selectedToolCallId,expandedBashOutputs:X.state.expandedBashOutputs,theme:X.state.ui.theme,dirtyMessageId:MJ.value,dirtySeq:v8.value})}),LJ={get value(){return kX.value}},k7=-1,C8=new Map,IX=k6(()=>{let N$=X.state.messages.length;if(N$===k7&&C8.size>0)return C8;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 k7=N$,C8=C$,C$}),I7=k6(()=>{let N$=Array.from(LJ.value.toolLineById.entries());return N$.sort((C$,Z4)=>C$[1]-Z4[1]),N$.map(([C$])=>C$)}),SX=nv({lines:k6(()=>LJ.value.lines),mainH:I}),{scrollTop:r,stickToBottom:J4,maxScroll:g4,visibleLines:Q6,onWheel:W2}=SX,y1=$C({nodeLike:$,store:X,mainY:f,mainH:I,scrollTop:r,lines:k6(()=>LJ.value.lines),focusMode:E,hoveredUserMessageId:i$,messageActionsTargetId:_6,showMessageActions:y$,copyTextToClipboard:KX,showCopyToast:x}),{messageSelectStart:hU,messageSelectEnd:g1,hasMessageSelection:q2,focusBrowserTextarea:p0,getSelectedMessageText:zJ,clearMessageSelection:_0,onMessageClick:W6,onMessagePointerDown:b8,onMessagePointerMove:S7,onMessagePointerUp:T7,onMessageContextMenu:v7}=y1;function yC(N$){if(!N$||N$.type==="none")return;if(p0(),N$.type==="selectToolCall"){X.selectToolCall(X.state.selectedToolCallId===N$.callId?null:N$.callId),E.value="input",TX(),b7();return}if(N$.type==="openApproval"){if(d4.value)r$.value=!0;return}if(N$.type==="toggleItem"){MJ.value=N$.messageId,v8.value++,X.toggleChecklist(N$.messageId,N$.part,N$.itemId);return}if(N$.type==="toggleCollapse"){MJ.value=N$.messageId,v8.value++,X.toggleBlockCollapsed(N$.messageId,N$.part,N$.partIndex);return}if(N$.type==="toggleBashOutput"){X.toggleBashOutput(N$.toolCallId),E.value="input",TX(),b7();return}if(N$.type==="showMessageActions")_6.value=N$.messageId,y$.value=!0}function gC(){let N$=_6.value;if(!N$)return;X.revertFromMessage(N$),y$.value=!1,_6.value=null,J4.value=!0}function xC(){let N$=_6.value;if(!N$)return;let C$=X.state.messages.find((f4)=>f4.id===N$);if(!C$)return;let Z4=tv(C$);if(Z4)KX(Z4).then((f4)=>x(f4?"Copied":"Copy failed")).catch(()=>x("Copy failed"));y$.value=!1,_6.value=null}function hC(){X.restoreRevertedMessages(),W4.value=!1,J4.value=!0}function uC(){W4.value=!1}async function mC(){let N$=_6.value;if(!N$)return;let C$=sv(X.state.messages,N$);if(!C$)return;y$.value=!1,_6.value=null,X4.value=0;try{await ev({sessionsApi:Z,store:X,seed:C$})}catch{x("Failed to fork session.")}J4.value=!0,F.value="",H.value=[]}let C7=k6(()=>X.state.selectedToolCallId);async function cC(){if(!C7.value||X.state.runningToolCallId)return;await X.runToolCall(C7.value)}function dC(N$){let C$=LJ.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 lC(N$){let C$=I7.value;if(C$.length===0)return;let Z4=C7.value,f4=Z4?C$.indexOf(Z4):-1,a4=(()=>{if(f4<0)return C$.length-1;let F1=f4+N$;if(F1<0)return C$.length-1;if(F1>=C$.length)return 0;return F1})(),j6=C$[a4];if(!j6)return;X.selectToolCall(j6),dC(j6)}function Aj(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=UJ(N$);Z4=Z4.replaceAll("","");let f4=Z4.trimEnd(),a4=H.value;if(!f4&&a4.length===0)return;let j6=NX(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 F1=N1.value;if(!Z||typeof Z.rename!=="function"){x("Rename is only available in Node/CLI mode."),F.value="";return}if(!F1){x("No active session to rename."),F.value="";return}let y8=String(j6.title??"").trim();if(!y8){x("Usage: /rename <title>"),F.value="";return}(async()=>{await Z.rename(F1,y8),await g({preferId:F1}),x(`Renamed session to: ${y8}`)})(),F.value="";return}if(j6.kind==="rename_invalid_args"){F2(),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 wj(){if(X.interrupt(),X.state.sessionId="",X.setEnvVar("GOATCHAIN_SESSION_ID",void 0),HJ()){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")}w8(()=>U.value.params,(N$)=>{if(N$?.open==="settings")o$(),J.replace("chat")},{immediate:!0});function iC(N$){X.setCwd(N$)}let rC=ov({nodeLike:$,store:X,events:_,input:F,inputWrapWidth:L,mentions:H,history:N,historyIndex:q,focusMode:E,toolCallIds:I7,selectedToolCallId:C7,moveToolSelection:lC,runSelected:cC,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:RX,closeCommandPalette:EJ,openConfig:o$,closeConfig:F6,closePathPicker:c$,cycleUiMode:B,isLoading:_$,hasMessageSelection:q2,clearMessageSelection:_0,getSelectedMessageText:zJ,copyTextToClipboard:KX,showCopyToast:x,exitSessionToHome:wj}),{onInputKeydown:nC,onSelectionKeydown:pC,onGlobalKeydown:aC,onGlobalKeydownCapture:oC}=rC;function TX(){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(R.value),j6=(N$.debugNodes?.()??[]).filter((x1)=>x1?.visible&&x1?.focusable),F1=j6.find((x1)=>{let y6=x1?.rect;return y6&&y6.x===C$&&y6.y===Z4&&y6.w===f4&&y6.h===a4});if(F1?.id){N$.focus(F1.id);return}let y8=C$+Math.floor(Math.max(0,f4-1)/2),fj=Z4+Math.floor(Math.max(0,a4-1)/2),kj=j6.filter((x1)=>{let y6=x1?.rect;return y6&&y8>=y6.x&&fj>=y6.y&&y8<y6.x+y6.w&&fj<y6.y+y6.h});kj.sort((x1,y6)=>{let Sj=x1?.zIndex??0,Tj=y6?.zIndex??0;if(Tj!==Sj)return Tj-Sj;let vj=x1?.rect??{w:0,h:0},Cj=y6?.rect??{w:0,h:0};return vj.w*vj.h-Cj.w*Cj.h});let Ij=kj[0];if(Ij?.id)N$.focus(Ij.id),G.invalidate()}async function b7(){await o1$(),queueMicrotask(()=>{queueMicrotask(()=>{setTimeout(()=>{p0(),TX()},0)})})}return w8(yU,(N$)=>{if(N$)return;b7()}),w8(_$,(N$,C$)=>{if(N$||!C$)return;if(yU.value||q2.value)return;E.value="input",b7()}),t1$(H0,{nodeLike:$,router:J,store:X,sessionsApi:Z,cols:Y,rows:K,contentW:w,mainY:f,mainW:A,mainH:I,scrollTop:r,visibleLines:Q6,messageRoleById:IX,messageSelectStart:hU,messageSelectEnd:g1,focusMode:E,hoveredUserMessageId:i$,onWheel:W2,onSelectionKeydown:pC,onMessageClick:W6,onMessagePointerDown:b8,onMessagePointerMove:S7,onMessagePointerUp:T7,onMessageContextMenu:v7,onLineClick:yC,focusBrowserTextarea:p0,showCopyToast:x,copyToastVisible:b,copyToastText:y,sessionHeaderTitle:w7,sessionHeaderSummary:T8,headerStatsDisplay:s,panelW:T,panelX:z,panelTopY:S,panelH:O,inputX:M,inputInnerW:P,inputLines:R,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:Aj,onInputKeydown:nC,setContextCwd:iC,ctxPctChip:F$,modelInfo:K$,modeLabel:V$,assistantStatusDisplay:Y$,assistantStatusStyle:u$,footerH:v,footerRight:a,isLoading:_$,loadingDots:n,commandOptions:b1,commandIndex:$4,onCommandSelect:wX,closeCommandPalette:EJ,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:gC,handleCopyMessage:xC,handleForkSession:mC,confirmRestore:hC,cancelRestore:uC,pickerW:D$,pickerH:v$,pathPickerTitle:A$,pathPickerPlaceholder:g$,configW:K1,configH:DJ,modelId:P$,contextWindow:f$,temperature:V4,interleavedThinking:s4,baseUrl:U6,apiKeyDraft:z4,apiKeyMasked:C6,applyConfig:A6,closeConfig:F6,toolApprovalsW:zX,toolApprovalsH:bU,applyToolApprovals:E4,activeApproval:d4,approvalW:$6,approvalH:b6,activeAskUser:I8,showAskUser:D4,askUserW:y0,askUserH:B0,renameSessionW:gU,renameSessionH:PJ,renameSessionInitialValue:AX,openRenameSession:F2,applyRenameSession:f7,cancelRenameSession:xU,showExitConfirm:w4,exitSessionToHome:wj}),()=>OJ(R4,{x:0,y:0,w:Y.value,h:K.value,zIndex:0,focusable:!1,onKeydownCapture:oC,onKeydown:aC},()=>[OJ(t,{key:"bg",x:0,y:0,w:Y.value,h:K.value,value:"",style:rV,zIndex:-100}),OJ(Jv),OJ(Qv),OJ(eT),OJ($v),OJ(dv),OJ(cv)])}});import{computed as G4,defineComponent as J2$,h as h4,inject as U2$,onBeforeUnmount as _2$,ref as v1,watch as KC}from"vue";import{defineComponent as s1$,h as r0}from"vue";var VC=s1$({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 r0(A4,{modelValue:$.modelValue,"onUpdate:modelValue":(j)=>J("update:modelValue",j),onKeydownCapture:(j)=>{if(j?.key==="Escape"){j.preventDefault?.(),j.stopPropagation?.(),J("close"),J("update:modelValue",!1);return}if(F&&$.codexModels.length>0){if(j?.key==="ArrowDown"){j.preventDefault?.(),j.stopPropagation?.();let B=($.modelIndex+1)%$.codexModels.length;J("update:modelIndex",B);return}if(j?.key==="ArrowUp"){j.preventDefault?.(),j.stopPropagation?.();let B=($.modelIndex-1+$.codexModels.length)%$.codexModels.length;J("update:modelIndex",B);return}}if(j?.key==="Enter"&&!N){if(j.preventDefault?.(),j.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=j?.key;if(B>="1"&&B<="9"){let D=parseInt(B)-1;if(D<$.codexModels.length){j.preventDefault?.(),j.stopPropagation?.();let w=$.codexModels[D];J("selectModel",w.id),J("update:selectedModel",w.id),J("update:modelIndex",D),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:(j)=>{if(j?.value==="login")J("login");else if(j?.value==="logout")J("logout");else J("close")},onClose:()=>J("close")},()=>[r0(t,{x:0,y:0,w:_,value:E,style:V}),r0(N6,{x:0,y:2,w:_,h:3,border:!0,title:"Status",padding:0,style:X,clear:!0},()=>r0(t,{x:1,y:0,w:Math.max(0,_-4),value:q,style:H})),$.oauthUrl&&!F?r0(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((D)=>{try{let[w,A]=D.split("?");if(!A)return[D];let I=[w+"?"],f=A.split("&");return f.forEach((T,z)=>{let S=z===f.length-1,O=` ${T}${S?"":"&"}`;I.push(O)}),I}catch{let w=Math.max(50,_-6),A=[],I=D;while(I.length>0)A.push(I.substring(0,w)),I=I.substring(w);return A}})($.oauthUrl).map((D,w)=>r0(t,{x:0,y:w,w:Math.max(0,_-4),value:D,style:{fg:"cyanBright",bg:"blackBright"},wrap:!1}))}):null,F&&$.codexModels.length>0?(()=>{let j=Math.max(0,G-9),B=Math.max(0,j-2),D=1,w=Math.floor(B/1),A=0;if($.codexModels.length>w){let T=$.modelIndex;if(T>=A+w)A=T-w+1;else if(T<A)A=T}let f=$.codexModels.length>w?` [${A+1}-${Math.min(A+w,$.codexModels.length)} of ${$.codexModels.length}]`:"";return r0(N6,{x:0,y:6,w:_,h:Math.max(0,G-9),border:!0,title:`Select Model (↑↓/1-9, Enter to select)${f}`,padding:1,style:X,clear:!0},()=>{return $.codexModels.slice(A,A+w).map((T,z)=>{let S=A+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 R=`${M?" ✓":""}${O?" ◄":""}`,k=`${S+1}. ${T.name}${R}`,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 r0(t,{x:0,y:z*1,w:L,value:v,style:P})})})})():!N&&!$.oauthUrl?r0(N6,{x:0,y:6,w:_,h:Math.max(0,G-9),border:!0,title:"About Codex OAuth",padding:1,style:X,clear:!0},()=>[r0(t,{x:0,y:0,w:Math.max(0,_-4),value:"• Requires ChatGPT Pro/Plus subscription",style:Z}),r0(t,{x:0,y:1,w:Math.max(0,_-4),value:"• No API key costs (included in subscription)",style:Z}),r0(t,{x:0,y:2,w:Math.max(0,_-4),value:"• Access to Codex models (gpt-5.x)",style:Z})]):null])}}});import{ref as f8,watch as e1$}from"vue";function XC($){let J=f8(!1),U=f8("unauthenticated"),Q=f8(""),_=f8(""),G=f8(""),V=f8([]),X=f8(0);async function Z(){try{let{getOAuthTokens:E}=await Promise.resolve().then(() => ($U(),d5)),{CODEX_MODELS:j}=await Promise.resolve().then(() => (f1(),_2));V.value=[...j];let B=await E("codex");if(B){U.value="authenticated",Q.value=B.email||"ChatGPT Account";let{loadUserSettings:D}=await Promise.resolve().then(() => c5),w=await D();G.value=w.model||j[0].id;let A=j.findIndex((I)=>I.id===G.value);X.value=A>=0?A: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...");let{startOAuthServer:E,generatePKCE:j,generateState:B,buildAuthorizeUrl:D}=await Promise.resolve().then(() => (f1(),_2));console.log("Starting OAuth server...");let{redirectUri:w}=await E();console.log("OAuth server started, redirect URI:",w),console.log("Generating PKCE...");let A=await j();console.log("Generating state...");let I=B();console.log("Building authorize URL...");let f=D(w,A,I);console.log("Generated OAuth URL:",f.substring(0,50)+"..."),_.value=f,globalThis.__goatchain_oauth_pending={pkce:A,state:I},$.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,j=globalThis.__goatchain_oauth_pending;if(!j?.pkce||!j?.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{waitForOAuthCallback:B,stopOAuthServer:D,extractAccountId:w,extractEmail:A}=await Promise.resolve().then(() => (f1(),_2)),{setOAuthTokens:I}=await Promise.resolve().then(() => ($U(),d5)),T=await B(j.pkce,j.state);D(),_.value="",delete globalThis.__goatchain_oauth_pending;let z=w(T),S=A(T);await I("codex",{type:"oauth",refresh:T.refresh_token,access:T.access_token,expires:Date.now()+(T.expires_in??3600)*1000,accountId:z,email:S}),U.value="authenticated",Q.value=S||"ChatGPT Account";let{CODEX_MODELS:O}=await Promise.resolve().then(() => (f1(),_2));V.value=[...O];let{loadUserSettings:M}=await Promise.resolve().then(() => c5),R=(await M()).model||O[0].id;if(!O.some((C)=>C.id===R))R=O[0].id;G.value=R;let L=O.findIndex((C)=>C.id===R);X.value=L>=0?L:0,await H(R),$.showToast("Successfully authenticated with Codex!");let v=globalThis.process;if(v?.env)v.env.GOATCHAIN_USE_CODEX_OAUTH="1"}catch(E){U.value="unauthenticated",$.showToast(`OAuth login failed: ${E?.message||"Unknown error"}`);try{let{stopOAuthServer:j}=await Promise.resolve().then(() => (f1(),_2));j()}catch{}}}async function F(){try{let{removeOAuthTokens:E}=await Promise.resolve().then(() => ($U(),d5));await E("codex"),U.value="unauthenticated",Q.value="",_.value="",$.showToast("Logged out from Codex");let j=globalThis.process;if(j?.env)delete j.env.GOATCHAIN_USE_CODEX_OAUTH;delete globalThis.__goatchain_oauth_pending;try{let{stopOAuthServer:B}=await Promise.resolve().then(() => (f1(),_2));B()}catch{}q()}catch(E){$.showToast(`Logout failed: ${E?.message||"Unknown error"}`)}}function N(){J.value=!0}e1$(J,async(E)=>{if(E)try{if(await Z(),U.value==="unauthenticated")await Y()}catch(j){$.showToast(`Dialog initialization error: ${j?.message||String(j)}`),console.error("CodexOAuth dialog error:",j)}});function q(){if(J.value=!1,U.value==="unauthenticated"&&_.value)_.value="",delete globalThis.__goatchain_oauth_pending,Promise.resolve().then(() => (f1(),_2)).then(({stopOAuthServer:E})=>{E()}).catch(()=>{})}async function H(E){try{G.value=E;let{getOAuthTokens:j,OAUTH_DUMMY_KEY:B}=await Promise.resolve().then(() => ($U(),d5)),{CODEX_BASE_URL:D}=await Promise.resolve().then(() => (f1(),_2)),w=await j("codex");if($.store)$.store.state.config.model=E,$.store.state.config.baseUrl=D,$.store.state.config.apiKey=w?.access||B,$.store.setEnvVar("GOATCHAIN_MODEL",E),$.store.setEnvVar("GOATCHAIN_OPENAI_BASE_URL",D),$.store.setEnvVar("OPENAI_BASE_URL",D),$.store.setEnvVar("OPENAI_API_KEY",w?.access||B);let{loadGoatChainUserCache:A,saveGoatChainUserCache:I}=await Promise.resolve().then(() => c5),{filePath:f,cache:T}=await A(),z={...T,updatedAt:Date.now(),settings:{...T.settings,model:E,baseUrl:D,apiKey:w?.access||B,authMethod:"oauth"}};if(await I(f,z),$.nodeLike){let S=globalThis.process;if(S?.env)S.env.GOATCHAIN_MODEL=E,S.env.GOATCHAIN_OPENAI_BASE_URL=D,S.env.OPENAI_BASE_URL=D,S.env.OPENAI_API_KEY=w?.access||B,S.env.GOATCHAIN_USE_CODEX_OAUTH="1"}$.showToast(`Model switched to ${E}`)}catch(j){$.showToast(`Failed to select model: ${j?.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 YC=7,$2$=["________ ________ ________ _________ ________ ___ ___ ________ ___ ________","|\\ ____\\|\\ __ \\|\\ __ \\|\\___ ___\\ |\\ ____\\|\\ \\|\\ \\|\\ __ \\|\\ \\|\\ ___ \\","\\ \\ \\___|\\ \\ \\|\\ \\ \\ \\|\\ \\|___ \\ \\_| \\ \\ \\___|\\ \\ \\\\\\ \\ \\ \\|\\ \\ \\ \\ \\ \\\\ \\ \\"," \\ \\ \\ __\\ \\ \\\\\\ \\ \\ __ \\ \\ \\ \\ \\ \\ \\ \\ \\ __ \\ \\ __ \\ \\ \\ \\ \\\\ \\ \\"," \\ \\ \\|\\ \\ \\ \\\\\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\____\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\\ \\ \\"," \\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\ \\__\\ \\ \\_______\\ \\__\\ \\__\\ \\__\\ \\__\\ \\__\\ \\__\\\\ \\__\\"," \\|_______|\\|_______|\\|__|\\|__| \\|__| \\|_______|\\|__|\\|__|\\|__|\\|__|\\|__|\\|__| \\|__|"];function ZC($,J=1){return $2$}var NC="",FC="";async function Q2$($){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 G2$($){return`[... ${($.match(/\n/g)||[]).length+1} lines]`}function V2$($){let J=String($||"");if(!J)return"[file]";return`[${J.split(/[/\\]/).filter(Boolean).pop()??J}]`}function X2$($,J){if(!$)return"";let U=[],Q=0;for(let _=0;_<$.length;){let G=$[_];if(G===NC){U.push(J[Q]??""),Q++,_+=1;continue}if(G===FC){_+=1;continue}let V=$.codePointAt(_)??0,X=String.fromCodePoint(V);U.push(X),_+=X.length}return U.join("")}function Y2$($,J,U){if(!$)return"";let Q=[],_=0,G=0;for(let V=0;V<$.length;){let X=$[V];if(X===NC){let K=J[_]??"";Q.push(G2$(K)),_++,V+=1;continue}if(X===FC){Q.push(V2$(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 Oj=J2$({name:"GoatChainHomePage",setup(){let $=LU(),J=p4(),{events:U}=L4(),Q=G4(()=>J.clipRect?.w??0),_=G4(()=>J.clipRect?.h??0),G=U2$(P8,null);if(!G)throw Error("GoatChainBridge is missing (did you forget to wrap with <GoatChainProvider />?)");let{store:V,sessions:X}=G,Z=HJ(),Y=v1(""),K=v1(!1),F=v1(!1),N=v1(0),q=v1([]),H=v1([]),E=v1(!1),j=v1(""),B=v1("Multiline Text"),D=v1(V.getMode?.()??"agent");function w(r=1){let J4=["plan","agent"],g4=D.value,W2=(J4.indexOf(g4)+r+J4.length)%J4.length,y1=J4[W2]??"agent";D.value=y1,V.setMode?.(y1)}function A(r){let J4=H.value[r];if(J4){j.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 f=jX(1200),T=f.visible,z=f.text,S=f.show;if(Z){let r=globalThis,J4=r.__VT_SHOW_COPY_TOAST__,g4=(Q6)=>S(Q6);r.__VT_SHOW_COPY_TOAST__=g4,_2$(()=>{if(r.__VT_SHOW_COPY_TOAST__===g4)if(J4)r.__VT_SHOW_COPY_TOAST__=J4;else delete r.__VT_SHOW_COPY_TOAST__})}let O=BX({store:V,nodeLike:Z,showToast:S,guardPendingApprovals:!1}),{showConfig:M,showToolApprovals:P,modelId:R,contextWindow:k,temperature:L,interleavedThinking:v,baseUrl:C,apiKeyDraft:b,apiKeyMasked:y,openConfig:x,closeConfig:c,applyConfig:s,openToolApprovals:F$,applyToolApprovals:K$}=O,V$=HX({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$=qX({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=XC({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;OX({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",LJ()}}];KC(q,(r)=>{V.setFocusFiles(r)});let $$=G4(()=>{return[...FX({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?ZC("goat",y$.value):["goat"]),_6=G4(()=>d$.value?YC: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=Y2$(Y.value,H.value,q.value);return Math.max(1,K0(J4,r).length)}),$6=G4(()=>O4(d4.value,1,7)),b6=1,I8=1,y0=G4(()=>b6+$6.value+I8+1+b6),B0=2,K1=G4(()=>{let r=Math.max(1,_.value-B0-_6.value-y0.value-3);return O4(Math.floor(_.value*0.32),1,r)}),DJ=G4(()=>K1.value+_6.value+4),zX=G4(()=>DJ.value+y0.value-1),bU=G4(()=>DJ.value+b6),yU=G4(()=>bU.value+$6.value+I8),RX=G4(()=>Array.from({length:Math.max(0,y0.value)},()=>"┃").join(`
|
|
948
|
-
`)),EJ=G4(()=>F.value||F6.value||Y$.value||M.value||P.value||Q4.value||E.value);function N1(){if(Z)return;try{globalThis.document?.querySelector?.("[data-vt-host] textarea")?.focus?.()}catch{}}function S8(){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),W2=Math.floor($6.value),y1=(r.debugNodes?.()??[]).filter((_0)=>_0?.visible&&_0?.focusable),hU=y1.find((_0)=>{let W6=_0?.rect;return W6&&W6.x===J4&&W6.y===g4&&W6.w===Q6&&W6.h===W2});if(hU?.id){r.focus(hU.id);return}let g1=J4+Math.floor(Math.max(0,Q6-1)/2),q2=g4+Math.floor(Math.max(0,W2-1)/2),p0=y1.filter((_0)=>{let W6=_0?.rect;return W6&&g1>=W6.x&&q2>=W6.y&&g1<W6.x+W6.w&&q2<W6.y+W6.h});p0.sort((_0,W6)=>{let b8=_0?.zIndex??0,S7=W6?.zIndex??0;if(S7!==b8)return S7-b8;let T7=_0?.rect??{w:0,h:0},v7=W6?.rect??{w:0,h:0};return T7.w*T7.h-v7.w*v7.h});let zJ=p0[0];if(zJ?.id)r.focus(zJ.id)}KC(EJ,(r)=>{if(r)return;setTimeout(()=>{N1(),S8()},0)});let w7=G4(()=>{return{build:"■",label:String(V.state.config.model??"model")}}),AX=G4(()=>D.value),gU=" ",PJ=G4(()=>"tab"),F2=G4(()=>"mode"),xU=G4(()=>"ctrl+p"),f7=G4(()=>"commands"),T8=G4(()=>{return M$(PJ.value)+1+M$(F2.value)+M$(gU)+M$(xU.value)+1+M$(f7.value)}),C1=G4(()=>{let r=T8.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)}),b1=G4(()=>zX.value+2),wX=G4(()=>b1.value>=0&&b1.value<=_.value-B0-1&&C1.value+T8.value<=Q.value),fX=G4(()=>{return c4.value}),MJ=G4(()=>{let r=V.state.context?.env??{},J4=r.GOATCHAIN_VERSION||r.VUE_TERMINAL_VERSION;return J4?`v${J4}`:""});function v8(r){$.push(r)}function kX(r){V.setCwd(r)}async function LJ(){let J4=X2$(Y.value,H.value).trim(),g4=q.value;if(!J4&&g4.length===0)return;let Q6=NX(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=[],v8("chat"),g4.length>0)V.sendUserInput({content:J4,focusFiles:g4});else V.sendUser(J4);q.value=[]}function k7(){F.value=!0,N.value=0}function C8(){F.value=!1}function IX(r){if(EJ.value)return;if(r?.key==="Tab"&&!r?.metaKey&&!r?.ctrlKey&&!r?.altKey)r?.stopPropagation?.(),r?.preventDefault?.(),w(r.shiftKey?-1:1)}function I7(r){if(r?.defaultPrevented)return;if((r?.ctrlKey||r?.metaKey)&&(r?.key==="p"||r?.key==="P")){r?.preventDefault?.(),k7();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?.(),w(r.shiftKey?-1:1);return}if(r?.key==="Escape")r?.preventDefault?.(),Y.value="",H.value=[]}function SX(r){if(C8(),!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:IX},()=>[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:K1.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:K1.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:DJ.value,w:a$.value,h:y0.value,value:"",style:A$.value,zIndex:-20}),h4(t,{key:"panel-accent",x:$4.value,y:DJ.value,w:1,h:y0.value,value:RX.value,style:c$.value,zIndex:-19}),h4(R4,{key:"panel-hit",x:$4.value,y:DJ.value,w:a$.value,h:y0.value,zIndex:10,focusable:!1,onPointerdownCapture:()=>{N1(),S8()}}),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:!EJ.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)Q2$(r)},collapseMultiline:!0,multilineTexts:H.value,"onUpdate:multilineTexts":(r)=>H.value=[...r],onMultilineClick:A,onChange:()=>void LJ(),onKeydown:(r)=>I7(r),onFocus:()=>{K.value=!0},onBlur:()=>K.value=!1,zIndex:11}),(()=>{let r=yU.value,J4=w7.value.build,g4=w7.value.label,Q6=M$(J4),W2=M$(g4),y1=Q6+1+W2,hU=2,g1=r$.value+Math.max(0,w4.value-y1-2),q2=Math.max(0,g1-r$.value-1),p0=[];if(q2>0){let zJ=AX.value,_0=` ${zJ.toUpperCase()} `,W6=zJ==="plan"?"magentaBright":"greenBright",b8=Math.min(q2,M$(_0));p0.push(h4(t,{key:"panel-mode",x:r$.value,y:r,w:b8,value:_0,style:{fg:"black",bg:W6,bold:!0},zIndex:-18}))}return p0.push(h4(t,{key:"model-chip",x:g1,y:r,value:J4,style:{fg:"blueBright",bold:!0,bg:"blackBright"},zIndex:-18})),p0.push(h4(t,{key:"model-label",x:g1+Q6+1,y:r,w:Math.max(0,r$.value+w4.value-(g1+Q6+1)),value:g4,style:{fg:"whiteBright",dim:!0,bg:"blackBright"},zIndex:-18})),p0})(),wX.value?[h4(t,{key:"hints-bg",x:C1.value,y:b1.value,w:T8.value,value:"",style:{bg:"black"},zIndex:4}),h4(t,{key:"hints-key1",x:C1.value,y:b1.value,value:PJ.value,style:{fg:"whiteBright",bold:!0,bg:"black"},clear:!1,zIndex:5}),h4(t,{key:"hints-label1",x:C1.value+M$(PJ.value)+1,y:b1.value,value:F2.value,style:{fg:"white",dim:!0,bg:"black"},clear:!1,zIndex:5}),h4(t,{key:"hints-key2",x:C1.value+M$(PJ.value)+1+M$(F2.value)+M$(gU),y:b1.value,value:xU.value,style:{fg:"whiteBright",bold:!0,bg:"black"},clear:!1,zIndex:5}),h4(t,{key:"hints-label2",x:C1.value+M$(PJ.value)+1+M$(F2.value)+M$(gU)+M$(xU.value)+1,y:b1.value,value:f7.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 ${fX.value}`,style:v$.value,clear:!1,zIndex:21}):null,_.value>0&&MJ.value?h4(t,{key:"footer-right",x:Math.max(2,Q.value-2-M$(MJ.value)),y:_.value-B0,value:MJ.value,style:v$.value,clear:!1,zIndex:21}):null,h4(aV,{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)=>SX(r),onClose:C8}),h4(tV,{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")kX(r);else if(!q.value.includes(r))q.value=[...q.value,r];q4()},onClose:q4}),h4(sV,{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()=>v8("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($X,{modelValue:u$.value,"onUpdate:modelValue":(r)=>{if(u$.value=r,!r)G$()},title:_$.value,targetLabel:n.value,reason:a.value,onConfirm:()=>void m()}),h4(JX,{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:R.value,"onUpdate:modelId":(r)=>R.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(QX,{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(VC,{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}),...YX({notification:V.upgradeNotification?.value,cols:Q.value,onDismiss:()=>{V.dismissUpgradeNotification?.()}}),...VX({visible:T,text:z,cols:Q}),h4(BV,{visible:E.value,content:j.value,title:B.value,onClose:I,zIndex:2000})])}});import{defineComponent as T2$,h as SC,inject as v2$,onUnmounted as C2$,provide as b2$,ref as TC}from"vue";import{computed as DX,reactive as I2$,watch as fC}from"vue";function Z2$($,J){let U=$.replace(/\[/g,"\\[").replace(/\]/g,"\\]"),Q=J.replace(/\)/g,"\\)");return`- [${U}](<${Q}>)`}function K2$($){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 Z2$(G,_)}).join(`
|
|
952
|
-
`)}
|
|
953
|
-
|
|
954
|
-
`}function N2$($){return{id:$.id,type:"function",function:{name:$.name,arguments:$.arguments}}}function F2$($){if($.role==="user")return{role:"user",content:`${K2$($.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(N2$):void 0;if(!J&&(!Q||Q.length===0))return null;return{role:"assistant",content:J||"",tool_calls:Q}}function W2$($){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 q2$($){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 jj($){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"&&W2$(Q)){if(J.length&&J[J.length-1]?.role==="user")J.pop();for(let _ of q2$(Q))U.add(_);continue}J.push(Q)}return J}function WC($,J){let U=[];U.push({role:"system",content:String($??"")});for(let Q of jj(J)){let _=F2$(Q);if(_)U.push(_)}return U}function qC($){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 HC($){let J=$.str("GOATCHAIN_TOOL_APPROVALS").toLowerCase(),U=J==="all"?"all":"auto";if(!J)return $.bool("GOATCHAIN_SKIP_APPROVAL")?"all":"auto";return U}function BC($){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 OC($){return $.str("GOATCHAIN_SESSION_ID")||""}function jC($){return{idleMs:$.int("GOATCHAIN_STREAM_IDLE_TIMEOUT_MS")??90000,totalMs:$.int("GOATCHAIN_STREAM_TOTAL_TIMEOUT_MS")??300000}}function Dj($){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 jJ($,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 H2$($){let U=String($??"").replace(/\\/g,"/").split("/").filter(Boolean);return(U[U.length-1]??"").trim()}function EC($){let J=H2$($).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 DC($){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 Ej($){return`\x1B[${$.join(";")}m`}function B2$($){return Ej([38,2,$.r,$.g,$.b])}function O2$($){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 j2$($,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 PC($){let J=String($.language??"").trim()||"text",U=String($.theme??"github-dark").trim()||"github-dark",Q=Math.max(1,Math.floor($.maxLines??24)),G=j2$($.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=DC(N)??{r:255,g:255,b:255},H="";for(let E=0;E<Y.length;E++){let j=Y[E];for(let B of j){let D=DC(B?.color)??q,w=O2$(B?.fontStyle);if(H+=B2$(D),w.length)H+=Ej(w);H+=String(B?.content??""),H+=Ej([0])}if(E<Y.length-1)H+=`
|
|
959
|
-
`}return H}catch{return null}}function D2$($,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 E2$($,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 P2$($){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 M2$($,J){return!1}function MC($){let J=String($.result.id??"").trim();if(!J)return;let U=D2$($.state.messages,$.assistantId,J),Q=E2$($.state.messages,$.assistantId,J),_=P2$(Q?.arguments);if(!M2$(U,_))return;let G=EC(_);if(!G)return;(async()=>{let V=await PC({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 L2$=0;function vU($){return`${$}_${Date.now()}_${L2$++}`}import{computed as LC}from"vue";function zC($){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 R=P.parts.slice(),k=-1;if(O!==void 0){let v=0;for(let C=0;C<R.length;C++)if(R[C].type==="thinking"){if(v===O){k=C;break}v++}}else k=R.findLastIndex((v)=>v.type==="thinking");if(k>=0){let v=R[k];return R[k]={type:"thinking",title:v.title,collapsed:v.collapsed,content:M},{...P,parts:R}}let L=Math.max(0,R.findIndex((v)=>v.type==="status")+1);return R.splice(L,0,{type:"thinking",title:"Thinking",collapsed:!1,content:M}),{...P,parts:R}})}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(),R=-1,k=0;for(let L=0;L<P.length;L++)if(P[L].type==="thinking"){if(k===S){R=L;break}k++}if(R>=0){let L=P[R];return P[R]={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 R=P.parts.slice();return R.push({type:"llm_meta",durationMs:O,...M?{modelId:M}:{}}),{...P,parts:R}})}function K(z,S,O,M){let P=String(S??"").trim();if(!P)return;let R=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:R,argumentsText:`${x}${k}`};return v[C]={type:"tool_call",call:c},{...L,parts:L.parts}}let b={id:P,name:R,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,(R)=>{let k=R.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{...R,parts:k}})}function N(z,S,O){let M=String(S??"").trim();if(!M)return;let P=String(O??"").trim()||"tool";Q(z,(R)=>{let k=R.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,{...R,parts:R.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{...R,parts:R.parts}})}function q(z,S,O,M){let P=String(S??"").trim();if(!P)return;let R=String(M??"");if(!R)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}${R}`},{...L,parts:L.parts}}let b={type:"tool_output",toolCallId:P,toolName:k,output:R},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(),R=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(R>=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(),R=P.findIndex((k)=>k.type==="tool_call"&&k.call.id===S.toolCallId);if(R>=0)P.splice(R+1,0,{type:"approve",request:S});else P.push({type:"approve",request:S});return{...O,parts:P}})}function j(z,S,O){let M=$.messages.find((R)=>R.id===z);if(!M||M.role!=="assistant")return;let P=M.parts.map((R)=>{if(R.type!==S)return R;return{...R,items:R.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((R)=>R.id===z);if(!M||M.role!=="assistant")return;let P=M.parts.map((R,k)=>{if(R.type!==S)return R;if(O!==void 0&&k!==O)return R;return{...R,collapsed:!R.collapsed}});U(z,{...M,parts:P})}function D(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 w(){if($.revertedMessages.length===0)return 0;let z=$.revertedMessages.length;return $.messages.push(...$.revertedMessages),$.revertedMessages=[],z}function A(){$.revertedMessages=[]}let I=LC(()=>$.revertedMessages.length>0),f=LC(()=>$.revertedMessages.length);function T(z,S,O,M){let P=M?.todos;if(!Array.isArray(P))return;let R=P.map((L,v)=>({id:`${O}:${v}`,text:String(L?.content??"").trim(),done:String(L?.status??"")==="completed"})).filter((L)=>Boolean(L.text));if(R.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:R},{...L,parts:v}}return v.push({type:S,title:k,collapsed:!1,items:R}),{...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:j,toggleBlockCollapsed:B,revertFromMessage:D,restoreRevertedMessages:w,clearRevertedMessages:A,hasRevertedMessages:I,revertedMessageCount:f,upsertChecklistPartFromGoatChain:T}}var z2$=["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 RC($){let J=$?.metadata?.originalEventType;return z2$.includes(J)?J:null}function CU($){if(!$)return"";if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>String(J?.text??"")).join("");return""}var R2$=180;function Pj($){return V1($).replace(/\s+/g," ").trim()}function A2$($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return`${$.slice(0,J-3).trimEnd()}...`}function w2$($,J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let U=J;if(String($??"").toLowerCase()==="bash"){let G=typeof U.command==="string"?Pj(U.command):"",V=typeof U.description==="string"?Pj(U.description):"";if(G&&V)return`Command: ${G} - ${V}`;if(G)return`Command: ${G}`;if(V)return`Description: ${V}`}let _=Pj(kU(U));if(!_||_==="{}"||_==="null")return null;return`Args: ${_}`}function f2$($,J,U){let Q=w2$(J,U);if(!Q)return $;return`${$} ${A2$(Q,R2$)}`}function AC($){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 j(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 R=$.state.messages[P];if(!R||R.role!=="assistant")continue;for(let k of R.parts)if(k.type==="tool_call"&&k.call.id===S){let L=String(k.call.name??"").trim()||"tool",v={assistantId:R.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 R=P.call.arguments;if(R&&typeof R==="object"&&!Array.isArray(R))return R;return null}}return null}function D(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 w={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 A(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 f(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),R=$.id("m");w.assistantId(R),w.sessionId($.state.sessionId),$.state.thinking.active=!1,$.pushMessage({id:R,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===R);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(R,"")},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(R,"");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(R,f({appendToExisting:I(R)})),$.state.paused=null,$.state.approval.active=null,$.state.approval.pendingAutoRun=null,$.state.approval.queue=[],$.state.approval.decisions={},$.setAssistantStatus(R,"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(R,"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=jJ(g,z$)||"Hint: retry or start a new session if context is too large.";$.appendAssistantMarkdown(R,["# 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(R,"Error.");break}let{value:_4,done:Q4}=q4.value;if(Q4)break;let n$=_4;F$=Date.now();let T$=n$?.metadata;T$=A(T$);let y4=String(T$?.session_id??"").trim();if(y4&&y4!==$.state.sessionId)$.state.sessionId=y4;if(T$?.usage)$.applyUsageFromSession(T$.usage);let p$=RC(n$)??String(T$?.originalEventType??"");if(C6(p$||`${n$.role}_message`),p$==="tool_output_start"){let z$=D(T$,{eventType:p$,assistantId:R});if(z$){let g=j(z$),h=w.toolName(T$?.toolName??T$?.tool_name??g?.toolName??q(R,z$)),q$=g?.assistantId??R;$.upsertToolOutputStart(q$,z$,h)}await z4(),o$();continue}if(p$==="tool_output_delta"){let z$=D(T$,{eventType:p$,assistantId:R});if(z$){let g=j(z$),h=w.toolName(T$?.toolName??T$?.tool_name??g?.toolName??q(R,z$)),q$=g?.assistantId??R,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(R),a(),await z4(),o$();continue}if(p$==="thinking_delta"){a();let z$=CU(n$.content);if(z$&&Y$>=0)V$[Y$]+=z$,$.setAssistantThinking(R,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(R,Y$,V$[Y$])}await z4(),o$();continue}if($.state.thinking.active)m();if(p$==="tool_call_delta"){$.upsertToolCallDelta(R,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(R,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=w.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(R,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:f2$(`GoatChain approval required (${String($$??"unknown")}).`,l,A$),...A$?{args:A$}:{},source:"goatchain",riskLevel:$$,status:"pending"},y$=j(p)?.assistantId??R;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(R,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(R,$.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?j(g):null,p=i?.assistantId??R;$.pushMessage({id:$.id("m"),role:"tool",result:q$}),$.attachToolResultPart(p,q$),$.scheduleToolResultHighlight(p,q$),await z4(),o$();let l=g?i?.toolName??q(R,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(R,{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(R,$.state.paused?.kind==="ask_user"?"Awaiting answers…":"Awaiting approval…");else{if(e4?.error)$.ensureErrorVisibleInTranscript(R,e4.error);$.setAssistantStatus(R,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===R),E4=F4&&F4.role==="assistant"?F4.parts.find((c4)=>c4.type==="status"):null;if(E4&&E4.text==="Thinking…")$.setAssistantStatus(R,"Done.")}let A6=(()=>{let F4=$.state.messages.find((E4)=>E4.id===R);if(!F4||F4.role!=="assistant")return[];return F4.parts.flatMap((E4)=>E4.type==="tool_call"?[E4.call]:[])})();return{assistantId:R,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$=jJ(s,F$);$.appendAssistantMarkdown(R,["# Error","","```text",s,"```",...K$?["",K$]:[]].join(`
|
|
963
|
-
`)),$.setAssistantStatus(R,"Error."),b4("agent_round_error",{session_id:String($.state.sessionId??""),error_message:c.message,error_name:c.name,assistant_id:R});let V$=(()=>{let Y$=$.state.messages.find((u$)=>u$.id===R);if(!Y$||Y$.role!=="assistant")return[];return Y$.parts.flatMap((u$)=>u$.type==="tool_call"?[u$.call]:[])})();return{assistantId:R,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 k2$($){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 wC($){function J(G,V){let X=k2$(V);if(!X)return"ok";if(pv($.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 j=async()=>{$.state.paused=null,await $.runAgentRound({toolContext:{approval:{decisions:q}}})};if($.isInSendQueueRun()){await j();return}await $.serializeReceive(j);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",V1(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 k8($){await new Promise((J)=>setTimeout(J,$))}function kC($){let J=Boolean($.agent),U=$.context?.env,Q=qC(U),_=HC(Q),G=I2$({config:{...BC(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:OC(Q),paused:null,approval:{active:null,approvedToolCalls:{},pendingAutoRun:null,mode:_,queue:[],decisions:{}}}),V=jC(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=DX(()=>{let i=Math.max(1,G.usage.budget);return Math.min(1,G.usage.total_tokens/i)}),q=DX(()=>{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 jj(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 Gv(i)}),H=DX(()=>{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 j(){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$,U2,m5);let y$=c$("XDG_CONFIG_HOME");if(y$)return A$.resolve(y$,F8,U2,m5);return A$.resolve(v$(),F8,U2,m5)}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 k8(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 D(i){let p=G.context,l=String(i??"").trim()||".";G.context={...p??{},cwd:l}}function w(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 A(i){w("GOATCHAIN_AGENT",i)}function I(i){G.ui.theme.preset=i}function f(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=zC(G),{pushMessage:S,updateAssistant:O,setAssistantStatus:M,setAssistantThinking:P,startNewThinkingBlock:R,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$=jJ(e,A$);else if(p){g$=Dj(p);let d$=/(?:^|\n)#+\s*error\b/i.test(e),y$=g$.trim()?e.includes(g$):!1;if(!d$&&!y$){c$=jJ(g$,A$),L(i,`${D$?`
|
|
995
|
-
|
|
996
|
-
`:""}${["# Error","","```text",g$,"```",...c$?["",c$]:[]].join(`
|
|
997
|
-
`)}`);return}c$=jJ(g$,A$)}if(c$)L(i,`
|
|
998
|
-
|
|
999
|
-
${c$}`)}function P$(i,p){MC({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=AC({state:G,agent:K,id:vU,buildAcpConversation:WC,streamIdleTimeoutMs:X,streamTotalTimeoutMs:Z,pushMessage:S,setAssistantStatus:M,setAssistantThinking:P,startNewThinkingBlock:R,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:j,ensureErrorVisibleInTranscript:L$}),{runAgentRound:A6,cancelActiveAgentStream:F4,abortActiveAgentRound:E4}=F6,c4=wC({state:G,externalAgentProvided:J,toolRunner:$.toolRunner,id:vU,pushMessage:S,updateAssistant:O,setAssistantStatus:M,insertApprovalPart:s,attachToolResultPart:c,runAgentRound:(i)=>A6(i),sleep:k8,serializeReceive:o$,isInSendQueueRun:()=>Y}),{ensureApproved:Q$,findToolCall:Z$,resolveActiveApproval:k$,runToolCall:t$}=c4;fC(()=>G.approval.mode,()=>{if(F())k$("approved")}),fC(()=>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,$$=V1(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 k8(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 k8(500),M(A$,g$.length?"Planning…":"Drafting…"),await k8(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 k8(500);let X4=await t$(g$[0].id);if(await k8(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",V1(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$=Dj(A$),d$=jJ(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$=DX(()=>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:D,setEnvVar:w,setAgent:A,setThemePreset:I,setMessageTypeThemeOverride:f,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 S2$,h as EX}from"vue";var IC=S2$({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 EX(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)},()=>[EX(t,{x:0,y:0,w:60,wrap:!0,value:"Exit now?",style:{fg:"whiteBright",bg:"black"}}),EX(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?EX(t,{x:0,y:4,w:60,wrap:!0,value:`Reason: ${U}`,style:{fg:"white",dim:!0,bg:"black"}}):null])}}});var Mj=T2$({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(v2$(P8,null))return()=>J.default?.();let Q=kC({toolRunner:$.toolRunner,context:$.context,agent:$.agent});$.onStoreCreated?.(Q),b2$(P8,{store:Q,sessions:$.sessions});let _=TC(!1),G=TC(""),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=_k({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 C2$(()=>X()),()=>SC("div",null,[J.default?.(),SC(IC,{modelValue:_.value,"onUpdate:modelValue":(Z)=>_.value=Z,reason:G.value,onExit:()=>iG()})])}});var PX=[{name:"home",component:Oj},{name:"chat",component:Bj}];function y2$($){if(typeof $==="string")return $;if($&&typeof $==="object"&&"name"in $)return String($.name??"");return""}function g2$($,J){let U=y2$(J)||"home";return $.some((Q)=>Q.name===U)?U:"home"}function Lj($){return PV({routes:PX,initialRoute:g2$(PX,$?.initialRoute??"home")})}import{defineComponent as x2$,h as vC}from"vue";var zj=x2$({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()=>vC(Mj,{toolRunner:$.toolRunner,context:$.context,agent:$.agent,onStoreCreated:$.onStoreCreated,sessions:$.sessions},()=>vC(MV,{routes:PX}))}});var LX=process.env.GOATCHAIN_DEBUG==="1"||process.argv.includes("--debug"),MX=process.env.GOATCHAIN_DEBUG_LOG||"./goatchain-debug.log",CC=1500;function n0($,J){if(!LX)return;let Q=`[${new Date().toISOString()}] ${$}${J?`: ${JSON.stringify(J,null,2)}`:""}
|
|
1004
|
-
`;try{h2$(MX,Q)}catch{}}function bC(){if(!LX)return;u2$(MX,`=== 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)=>{n0("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: ${MX}`),Rj(1)}),process.on("unhandledRejection",($,J)=>{let U=$ instanceof Error?$:Error(String($));n0("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: ${MX}`),Rj(1)}),process.on("SIGINT",()=>{n0("Received SIGINT")}),process.on("SIGTERM",()=>{n0("Received SIGTERM")}),n0("Crash handlers installed")}function Rj($){let J=Number.isFinite($)?Math.trunc($):1;process.exitCode=J;try{iG();return}catch{}setTimeout(()=>{try{process.exit(J)}catch{}},1500).unref?.()}function m2$($){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 c2$($,J){return await Promise.race([$,new Promise((U)=>setTimeout(()=>U(null),J))])}async function d2$($){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=bj(U,{stdout:J.stdout}),_=String(J.env.GOATCHAIN_TERM_TITLE_BASE??"").trim()||String(Q.app??"").trim()||"goatchain";if(J.env.GOATCHAIN_TERM_TITLE_BASE=_,A7(_,{stdout:J.stdout}),Q.debug){if(J.env.GOATCHAIN_DEBUG="1",!LX)LX=!0,bC()}if(n0("[CLI] runCli() called"),n0("[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=Lj({initialRoute:Q.initialRoute||"home"});X.use(Z)}:void 0;n0("[CLI] Before createGoatChainShellProps");let V=Q.app==="goatchain"?await TB({cwd:String(J.cwd?.()??"."),env:J.env}):{cols:Q.cols,rows:Q.rows};n0("[CLI] After createGoatChainShellProps"),n0("[CLI] About to call runTerminalUi"),await SI({proc:J,cols:Q.cols,rows:Q.rows,sizeLocked:Q.sizeLocked,component:zj,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 l2$(){if(bC(),bX(process.argv.slice(2))){console.log(yX());try{process.stdin?.pause?.()}catch{}process.exit(0)}let $=!1,J=(_)=>{if($||!_)return;$=!0,m2$(_)},U=zT();U.then(J).catch((_)=>{n0("[CLI] npm upgrade check failed",{error:_ instanceof Error?_.message:String(_)})});let Q=await c2$(U,CC);if(Q===null)n0("[CLI] npm upgrade check timed out",{timeoutMs:CC});J(Q),await d2$()}if(E$.main==E$.module||import.meta.url===`file://${process.argv[1]}`)l2$().catch(($)=>{console.error("Fatal error during setup:",$),Rj(1)});export{d2$ as runCli};
|