@dahawa/hawa-code 2.7.18 → 2.7.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/cli.js +4 -4
  2. package/hands.js +3 -3
  3. package/package.json +1 -1
package/cli.js CHANGED
@@ -653,7 +653,7 @@ globstar while`,e,d,t,f,p),this.matchOne(e.slice(d),t.slice(f),r))return this.de
653
653
  `)),UYr(e,o,{encoding:r,flush:!0})}var Zot=new Lj.default({fetchMethod:e=>VYr(e),ttl:300*1e3,ttlAutopurge:!1,max:1e3});async function sit(e){let t=EU(e);return Zot.get(t)||Zot.fetchMethod?.(t)}async function VYr(e){let t=new AbortController;setTimeout(()=>{t.abort()},1e3);let r=await _et(e,t.signal,15),n=0;for(let o of r)M1(o)==="CRLF"&&n++;return n>3?"CRLF":"LF"}function ait(e,t,r){if(e.has(t))return e.get(t);let n=r();return e.set(t,n),n}var WYr=new Lj.default({fetchMethod:e=>lit(e),ttl:300*1e3,ttlAutopurge:!1,max:1e3});function Zd(e){let t=EU(e);return ait(WYr,t,()=>lit(t))}function lit(e){let r=Buffer.alloc(4096),n;try{n=Xot(e,"r");let o=eit(n,r,0,4096,0);return o===0?"utf8":o>=2&&r[0]===255&&r[1]===254?"utf16le":o>=3&&r[0]===239&&r[1]===187&&r[2]===191||r.slice(0,o).toString("utf8").length>0?"utf8":"ascii"}catch(o){return be(`Error detecting encoding for file ${e}: ${o}`),"utf8"}finally{n&&tit(n)}}var jYr=new Lj.default({fetchMethod:e=>cit(e),ttl:300*1e3,ttlAutopurge:!1,max:1e3});function M1(e){let t=EU(e);return ait(jYr,t,()=>cit(t))}function cit(e,t="utf8"){try{if(!rit(e).isFile())return"LF";let n=Buffer.alloc(4096),o=Xot(e,"r"),i=eit(o,n,0,4096,0);tit(o);let s=n.toString(t,0,i),a=0,l=0;for(let c=0;c<s.length;c++)s[c]===`
654
654
  `&&(c>0&&s[c-1]==="\r"?a++:l++);return a>l?"CRLF":"LF"}catch(r){return be(`Error detecting line endings for file ${e}: ${r}`),"LF"}}function gB(e){let t=nit(e)?e:EU(Oe(),e);return t.endsWith(" AM.png")?t.replace(" AM.png","\u202FAM.png"):t.endsWith(" PM.png")?t.replace(" PM.png","\u202FPM.png"):t}function I_e(e){return e?nit(e)?e:EU(Oe(),e):void 0}function uit(e){try{let t=I_e(e),r=t?qYr(Oe(),t):void 0;return{absolutePath:t,relativePath:r}}catch(t){return te("getAbsoluteAndRelativePaths error ",t),{absolutePath:null,relativePath:null}}}function Fj(e){try{let t=YYr(e),r=jot(e,Kot(e));if(!GYr(t))return;let i=HYr(t).filter(s=>jot(s,Kot(s))===r&&zYr(t,s)!==e)[0];return i||void 0}catch(t){be(`Error finding similar file for ${e}: ${t}`);return}}function v_e(){let e=process.env.HAWA_CODE_COMPACT_LINE_PREFIX;return!(e==="0"||e==="false")}function lC({content:e,startLine:t}){if(!e)return"";let r=e.split(/\r?\n/);return v_e()?r.map((n,o)=>`${o+t} ${n}`).join(`
655
655
  `):r.map((n,o)=>{let i=String(o+t);return i.length>=6?`${i}\u2192${n}`:`${i.padStart(6," ")}\u2192${n}`}).join(`
656
- `)}function dit(e){try{let t=$Yr(e),r=t.readSync();return t.closeSync(),r===null}catch(t){return be(`Error checking directory: ${t}`),!1}}Pe();function oC(){let e=Nn();e.hasCompletedProjectOnboarding||ti({...e,hasCompletedProjectOnboarding:!0})}function x_e({workspaceDir:e}){let r=!Nn().hasCompletedProjectOnboarding;if(!r)return null;let n=KYr(JYr(e,Qo)),o=dit(e),i=!n&&!o,s=lB.isEnabled&&!Qr().shiftEnterKeyBindingInstalled,a=re();return(0,h.jsxs)(x,{flexDirection:"column",gap:1,padding:1,paddingBottom:0,children:[r&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(I,{color:a.secondaryText,children:"Tips for getting started:"}),(0,h.jsx)(Dc,{children:(()=>{let l=[];return o&&l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Ask ",it," to create a new app or clone a repository."]})},"workspace")),i&&l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Run ",(0,h.jsx)(I,{color:a.text,children:"/init"})," to create a",Qo," file with instructions for Hawa code."]})},"claudemd")),s&&l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Run ",(0,h.jsx)(I,{color:a.text,children:"/terminal-setup"}),(0,h.jsx)(I,{bold:!1,children:" to set up terminal integration"})]})},"terminal")),l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Ask ",it," questions about your codebase."]})},"questions")),l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Ask ",it," to implement changes to your codebase."]})},"changes")),l})()})]}),e===ZYr()&&(0,h.jsxs)(I,{color:re().warning,children:["Note: You have launched ",(0,h.jsx)(I,{bold:!0,children:it})," in your home directory. For the best experience, launch it in a project directory instead."]})]})}function w_e({isFocused:e,isSelected:t,smallPointer:r,children:n}){let{styles:o}=Ai("Select");return(0,h.jsxs)(x,{...o.option({isFocused:e}),children:[e&&(0,h.jsx)(I,{...o.focusIndicator(),children:r?nr.triangleDownSmall:nr.pointer}),(0,h.jsx)(I,{...o.label({isFocused:e,isSelected:t}),children:n}),t&&(0,h.jsx)(I,{...o.selectedIndicator(),children:nr.tick})]})}var Xd=Ie(Ve(),1);import{isDeepStrictEqual as XYr}from"node:util";var bU=class extends Map{first;constructor(t){let r=[],n,o,i=0;for(let s of t){let a={...s,previous:o,next:void 0,index:i};o&&(o.next=a),n||=a;let l="value"in s?s.value:R_e(s);r.push([l,a]),i++,o=a}super(r),this.first=n}};var ezr=(e,t)=>{switch(t.type){case"focus-next-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.next;for(;n&&!("value"in n);)n=n.next;if(!n)return e;if(!(n.index>=e.visibleToIndex))return{...e,focusedValue:n.value};let i=Math.min(e.optionMap.size,e.visibleToIndex+1),s=i-e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:s,visibleToIndex:i}}case"focus-previous-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.previous;for(;n&&!("value"in n);)n=n.previous;if(!n)return e;if(!(n.index<=e.visibleFromIndex))return{...e,focusedValue:n.value};let i=Math.max(0,e.visibleFromIndex-1),s=i+e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:i,visibleToIndex:s}}case"select-focused-option":return{...e,previousValue:e.value,value:e.focusedValue};case"reset":return t.state;case"set-focus":return{...e,focusedValue:t.value}}},N_e=e=>e.flatMap(t=>{if("options"in t){let r=N_e(t.options),n=r.flatMap(i=>"value"in i?i.value:[]);return[...t.header!==void 0?[{header:t.header,optionValues:n}]:[],...r]}return t}),pit=({visibleOptionCount:e,defaultValue:t,options:r})=>{let n=N_e(r),o=typeof e=="number"?Math.min(e,n.length):n.length,i=new bU(n),s=i.first,a=s&&"value"in s?s.value:void 0;return{optionMap:i,visibleOptionCount:o,focusedValue:a,visibleFromIndex:0,visibleToIndex:o,previousValue:t,value:t}},D_e=({visibleOptionCount:e=5,options:t,defaultValue:r,onChange:n,onFocus:o,focusValue:i})=>{let s=N_e(t),[a,l]=(0,Xd.useReducer)(ezr,{visibleOptionCount:e,defaultValue:r,options:t},pit),[c,u]=(0,Xd.useState)(s);s!==c&&!XYr(s,c)&&(l({type:"reset",state:pit({visibleOptionCount:e,defaultValue:r,options:t})}),u(s));let d=(0,Xd.useCallback)(()=>{l({type:"focus-next-option"})},[]),f=(0,Xd.useCallback)(()=>{l({type:"focus-previous-option"})},[]),p=(0,Xd.useCallback)(()=>{l({type:"select-focused-option"})},[]),A=(0,Xd.useMemo)(()=>s.map((_,E)=>({..._,index:E})).slice(a.visibleFromIndex,a.visibleToIndex),[s,a.visibleFromIndex,a.visibleToIndex]);return(0,Xd.useEffect)(()=>{a.value&&a.previousValue!==a.value&&n?.(a.value)},[a.previousValue,a.value,t,n]),(0,Xd.useEffect)(()=>{a.focusedValue&&o?.(a.focusedValue)},[a.focusedValue,o]),(0,Xd.useEffect)(()=>{i&&l({type:"set-focus",value:i})},[i]),{focusedValue:a.focusedValue,visibleFromIndex:a.visibleFromIndex,visibleToIndex:a.visibleToIndex,value:a.value,visibleOptions:A,focusNextOption:d,focusPreviousOption:f,selectFocusedOption:p}};var O_e=({isDisabled:e=!1,state:t})=>{ft((r,n)=>{n.downArrow&&t.focusNextOption(),n.upArrow&&t.focusPreviousOption(),n.return&&t.selectFocusedOption()},{isActive:!e})};var R_e=e=>`HEADER-${e.optionValues.join(",")}`;function Fb({isDisabled:e=!1,visibleOptionCount:t=5,highlightText:r,options:n,defaultValue:o,onChange:i,onFocus:s,focusValue:a}){let l=D_e({visibleOptionCount:t,options:n,defaultValue:o,onChange:i,onFocus:s,focusValue:a});O_e({isDisabled:e,state:l});let{styles:c}=Ai("Select");return(0,h.jsx)(x,{...c.container(),children:l.visibleOptions.map(u=>{let d="value"in u?u.value:R_e(u),f=!e&&l.focusedValue!==void 0&&("value"in u?l.focusedValue===u.value:u.optionValues.includes(l.focusedValue)),p=!!l.value&&("value"in u?l.value===u.value:u.optionValues.includes(l.value)),A="header"in u,_="label"in u?u.label:u.header,E=_;if(r&&_.includes(r)){let S=_.indexOf(r);E=(0,h.jsxs)(h.Fragment,{children:[_.slice(0,S),(0,h.jsx)(I,{...c.highlightedText(),children:r}),_.slice(S+r.length)]})}return(0,h.jsx)(w_e,{isFocused:f,isSelected:p,smallPointer:A,children:E},d)})})}function mit({onDone:e}){return ft((t,r)=>{(r.ctrl&&(t==="c"||t==="d")||r.escape)&&e()}),(0,h.jsxs)(x,{flexDirection:"column",borderStyle:"round",padding:1,borderColor:re().secondaryBorder,children:[(0,h.jsx)(x,{marginBottom:1,flexDirection:"column",children:(0,h.jsx)(I,{bold:!0,children:"You've spent $5 this session."})}),(0,h.jsx)(x,{children:(0,h.jsx)(Fb,{options:[{value:"ok",label:"Got it, thanks!"}],onChange:e})})]})}var Jt=Ie(Ve(),1);Pe();lr();r_();var nzr="2.7.18",n_={VERSION:nzr,PACKAGE_URL:"@dahawa/hawa-code",README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var k_e=46,hit=["(\u2740\u2579\u25E1\u2579)","(\u25D5\u072B\u25D5)","\u239D(\u25D5u\u25D5)\u23A0","\u10DA(\u25C9\u25DE\u0C6A\u25DF\u25C9 )\u10DA","(\xB4\u25C9\u203F\u25C9\uFF40)","\u0E01\u0E47\u0295\u2022\u0361\u1D25\u2022\u0294 \u0E01\u0E49","\uFF0F/( \u25D5\u203F\u203F\u25D5 )\uFF3C"];function Qj({isDefaultModel:e=!1}){let t=Math.max(k_e,Oe().length+12),r=re(),n=hit[Math.floor(Math.random()*hit.length)];return(0,h.jsx)(x,{flexDirection:"column",children:(0,h.jsxs)(x,{flexDirection:"column",gap:1,paddingLeft:1,width:"100%",children:[(0,h.jsxs)(I,{children:[(0,h.jsx)(I,{children:n})," Welcome to"," ",(0,h.jsx)(I,{bold:!0,children:it}),(0,h.jsxs)(I,{color:r.secondaryText,children:[" v",n_.VERSION]})]}),(0,h.jsx)(h.Fragment,{children:(0,h.jsxs)(x,{paddingLeft:2,flexDirection:"column",gap:1,children:[(0,h.jsx)(I,{color:r.secondaryText,italic:!0,children:"/help for help"}),(0,h.jsxs)(I,{color:r.secondaryText,children:["cwd: ",Oe()]}),(0,h.jsxs)(I,{color:r.secondaryText,children:["model: ",Jn.getConfig().routing.MODEL?.map(o=>`${o.source}__${o.model}`).join(", ")??"N/A"]}),(0,h.jsxs)(I,{color:r.secondaryText,children:["small fast model: ",Jn.getConfig().routing.SMALL_FAST_MODEL?.map(o=>`${o.source}__${o.model}`).join(", ")??"N/A"]})]})})]})})}we();import{randomUUID as $g}from"crypto";ji();we();er();lr();we();Pe();import{existsSync as Gb,readdirSync as Ojr,statSync as Bjr}from"fs";import{join as mC,relative as Mjr}from"path";import{homedir as clt}from"os";import{platform as kjr}from"process";import{readFile as fC}from"fs/promises";lr();um();Kt();import{join as czr,sep as uzr}from"path";function ld(){if(!Oc())return!1;try{let e=Je();if(e.autoMemory?.teamMemoryEnabled!==void 0)return e.autoMemory.teamMemoryEnabled}catch{}return!1}function ep(){return(czr(Oe(),".hcode","team-memory")+uzr).normalize("NFC")}function zf(e){let t=e.normalize("NFC"),r=ep();return t.startsWith(r)}um();var ult=Ie(RU(),1);po();var X_e=(e,t,r)=>{let n=e instanceof RegExp?Pat(e,r):e,o=t instanceof RegExp?Pat(t,r):t,i=n!==null&&o!=null&&y7r(n,o,r);return i&&{start:i[0],end:i[1],pre:r.slice(0,i[0]),body:r.slice(i[0]+n.length,i[1]),post:r.slice(i[1]+o.length)}},Pat=(e,t)=>{let r=t.match(e);return r?r[0]:null},y7r=(e,t,r)=>{let n,o,i,s,a,l=r.indexOf(e),c=r.indexOf(t,l+1),u=l;if(l>=0&&c>0){if(e===t)return[l,c];for(n=[],i=r.length;u>=0&&!a;){if(u===l)n.push(u),l=r.indexOf(e,u+1);else if(n.length===1){let d=n.pop();d!==void 0&&(a=[d,c])}else o=n.pop(),o!==void 0&&o<i&&(i=o,s=c),c=r.indexOf(t,u+1);u=l<c&&l>=0?l:c}n.length&&s!==void 0&&(a=[i,s])}return a};var Fat="\0SLASH"+Math.random()+"\0",Qat="\0OPEN"+Math.random()+"\0",rEe="\0CLOSE"+Math.random()+"\0",Uat="\0COMMA"+Math.random()+"\0",Gat="\0PERIOD"+Math.random()+"\0",C7r=new RegExp(Fat,"g"),T7r=new RegExp(Qat,"g"),I7r=new RegExp(rEe,"g"),v7r=new RegExp(Uat,"g"),x7r=new RegExp(Gat,"g"),w7r=/\\\\/g,R7r=/\\{/g,N7r=/\\}/g,D7r=/\\,/g,O7r=/\\\./g,B7r=1e5,M7r=4e6;function eEe(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function k7r(e){return e.replace(w7r,Fat).replace(R7r,Qat).replace(N7r,rEe).replace(D7r,Uat).replace(O7r,Gat)}function L7r(e){return e.replace(C7r,"\\").replace(T7r,"{").replace(I7r,"}").replace(v7r,",").replace(x7r,".")}function Hat(e){if(!e)return[""];let t=[],r=X_e("{","}",e);if(!r)return e.split(",");let{pre:n,body:o,post:i}=r,s=n.split(",");s[s.length-1]+="{"+o+"}";let a=Hat(i);return i.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),t.push.apply(t,s),t}function $at(e,t={}){if(!e)return[];let{max:r=B7r,maxLength:n=M7r}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),tEe(k7r(e),r,n,!0).map(L7r)}function P7r(e){return"{"+e+"}"}function F7r(e){return/^-?0\d/.test(e)}function Q7r(e,t){return e<=t}function U7r(e,t){return e>=t}function NU(e,t,r,n,o,i){let s=[],a=0;for(let l=0;l<e.length;l++)for(let c=0;c<r.length;c++){if(s.length>=n)return s;let u=e[l]+t+r[c];if(!(i&&!u)){if(a+u.length>o)return s;s.push(u),a+=u.length}}return s}function G7r(e,t,r,n){let o=e.split(/\.\./),i=[];if(o[0]===void 0||o[1]===void 0)return i;let s=eEe(o[0]),a=eEe(o[1]),l=Math.max(o[0].length,o[1].length),c=o.length===3&&o[2]!==void 0?Math.max(Math.abs(eEe(o[2])),1):1,u=Q7r;a<s&&(c*=-1,u=U7r);let f=o.some(F7r),p=0;for(let A=s;u(A,a)&&i.length<r;A+=c){let _;if(t)_=String.fromCharCode(A),_==="\\"&&(_="");else if(_=String(A),f){let E=l-_.length;if(E>0){let S=new Array(E+1).join("0");A<0?_="-"+S+_.slice(1):_=S+_}}if(p+_.length>n)break;i.push(_),p+=_.length}return i}function tEe(e,t,r,n){let o=[""],i=!1,s=!0;for(;;){let a=X_e("{","}",e);if(!a)return NU(o,e,[""],t,r,i);let l=a.pre;if(/\$$/.test(l)){if(o=NU(o,l+"{"+a.body+"}",[""],t,r,i&&!a.post.length),s=!1,!a.post.length)break;e=a.post;continue}let c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(a.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(a.body),d=c||u,f=a.body.indexOf(",")>=0;if(!d&&!f){if(a.post.match(/,(?!,).*\}/)){e=a.pre+"{"+a.body+rEe+a.post,n=!0;continue}return NU(o,l+"{"+a.body+"}"+a.post,[""],t,r,i)}s&&(i=n&&!d,s=!1);let p;if(d)p=G7r(a.body,u,t,r);else{let A=Hat(a.body);if(A.length===1&&A[0]!==void 0&&(A=tEe(A[0],t,r,!1).map(P7r),A.length===1)){if(o=NU(o,l+A[0],[""],t,r,i&&!a.post.length),!a.post.length)break;e=a.post;continue}let _=i&&!a.post.length&&!l;for(let S=0;_&&S<o.length;S++)o[S]&&(_=!1);p=[];let E=0;e:for(let S=0;S<A.length;S++){let C=tEe(A[S],t,r,!1);for(let v=0;v<C.length;v++){let R=C[v];if(!(_&&!R)){if(p.length>=t||E+R.length>r)break e;p.push(R),E+=R.length}}}}if(o=NU(o,l,p,t,r,i&&!a.post.length),!a.post.length)break;e=a.post}return o}var DU=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")};var H7r={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},OU=e=>e.replace(/[[\]\\-]/g,"\\$&"),$7r=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),qat=e=>e.join(""),Yat=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],o=[],i=r+1,s=!1,a=!1,l=!1,c=!1,u=r,d="";e:for(;i<e.length;){let _=e.charAt(i);if((_==="!"||_==="^")&&i===r+1){c=!0,i++;continue}if(_==="]"&&s&&!l){u=i+1;break}if(s=!0,_==="\\"&&!l){l=!0,i++;continue}if(_==="["&&!l){for(let[E,[S,C,v]]of Object.entries(H7r))if(e.startsWith(E,i)){if(d)return["$.",!1,e.length-r,!0];i+=E.length,v?o.push(S):n.push(S),a=a||C;continue e}}if(l=!1,d){_>d?n.push(OU(d)+"-"+OU(_)):_===d&&n.push(OU(_)),d="",i++;continue}if(e.startsWith("-]",i+1)){n.push(OU(_+"-")),i+=2;continue}if(e.startsWith("-",i+1)){d=_,i+=2;continue}n.push(OU(_)),i++}if(u<i)return["",!1,0,!1];if(!n.length&&!o.length)return["$.",!1,e.length-r,!0];if(o.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let _=n[0].length===2?n[0].slice(-1):n[0];return[$7r(_),!1,u-r,!1]}let f="["+(c?"^":"")+qat(n)+"]",p="["+(c?"":"^")+qat(o)+"]";return[n.length&&o.length?"("+f+"|"+p+")":n.length?f:p,a,u-r,!0]};var pC=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!0}={})=>r?t?e.replace(/\[([^/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):t?e.replace(/\[([^/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var rp,q7r=new Set(["!","?","+","*","@"]),nEe=e=>q7r.has(e),zat=e=>nEe(e.type),Y7r=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),z7r=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),V7r=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),Vat=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),W7r="(?!(?:^|/)\\.\\.?(?:$|/))",Jj="(?!\\.)",j7r=new Set(["[","."]),K7r=new Set(["..","."]),J7r=new Set("().*{}+?[]^$\\!"),Z7r=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),oEe="[^/]",Wat=oEe+"*?",jat=oEe+"+?",X7r=0,H1=class{type;#e;#t;#n=!1;#r=[];#i;#o;#l;#s=!1;#a;#d;#m=!1;id=++X7r;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(t,r,n={}){this.type=t,t&&(this.#t=!0),this.#i=r,this.#e=this.#i?this.#i.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#l=this.#e===this?[]:this.#e.#l,t==="!"&&!this.#e.#s&&this.#l.push(this),this.#o=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#d=this.#r.map(t=>String(t)).join("")}#p(){if(this!==this.#e)throw new Error("should only call on root");if(this.#s)return this;this.toString(),this.#s=!0;let t;for(;t=this.#l.pop();){if(t.type!=="!")continue;let r=t,n=r.#i;for(;n;){for(let o=r.#o+1;!n.type&&o<n.#r.length;o++)for(let i of t.#r){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(n.#r[o])}r=n,n=r.#i}}return this}push(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof rp&&r.#i===this))throw new Error("invalid part: "+r);this.#r.push(r)}}toJSON(){let t=this.type===null?this.#r.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#r.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type==="!")&&t.push({}),t}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#o===0)return!0;let t=this.#i;for(let r=0;r<this.#o;r++){let n=t.#r[r];if(!(n instanceof rp&&n.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type==="!")return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let t=this.#i?this.#i.#r.length:0;return this.#o===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let r=new rp(this.type,t);for(let n of this.#r)r.copyIn(n);return r}static#c(t,r,n,o,i){let s=o.maxExtglobRecursion??2,a=!1,l=!1,c=-1,u=!1;if(r.type===null){let _=n,E="";for(;_<t.length;){let S=t.charAt(_++);if(a||S==="\\"){a=!a,E+=S;continue}if(l){_===c+1?(S==="^"||S==="!")&&(u=!0):S==="]"&&!(_===c+2&&u)&&(l=!1),E+=S;continue}else if(S==="["){l=!0,c=_,u=!1,E+=S;continue}if(!o.noext&&nEe(S)&&t.charAt(_)==="("&&i<=s){r.push(E),E="";let v=new rp(S,r);_=rp.#c(t,v,_,o,i+1),r.push(v);continue}E+=S}return r.push(E),_}let d=n+1,f=new rp(null,r),p=[],A="";for(;d<t.length;){let _=t.charAt(d++);if(a||_==="\\"){a=!a,A+=_;continue}if(l){d===c+1?(_==="^"||_==="!")&&(u=!0):_==="]"&&!(d===c+2&&u)&&(l=!1),A+=_;continue}else if(_==="["){l=!0,c=d,u=!1,A+=_;continue}if(!o.noext&&nEe(_)&&t.charAt(d)==="("&&(i<=s||r&&r.#_(_))){let S=r&&r.#_(_)?0:1;f.push(A),A="";let C=new rp(_,f);f.push(C),d=rp.#c(t,C,d,o,i+S);continue}if(_==="|"){f.push(A),A="",p.push(f),f=new rp(null,r);continue}if(_===")")return A===""&&r.#r.length===0&&(r.#m=!0),f.push(A),A="",r.push(...p,f),d;A+=_}return r.type=null,r.#t=void 0,r.#r=[t.substring(n-1)],d}#g(t){return this.#A(t,z7r)}#A(t,r=Y7r){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null)return!1;let n=t.#r[0];return!n||typeof n!="object"||n.type===null?!1:this.#_(n.type,r)}#_(t,r=V7r){return!!r.get(this.type)?.includes(t)}#h(t,r){let n=t.#r[0],o=new rp(null,n,this.options);o.#r.push(""),n.push(o),this.#v(t,r)}#v(t,r){let n=t.#r[0];this.#r.splice(r,1,...n.#r);for(let o of n.#r)typeof o=="object"&&(o.#i=this);this.#d=void 0}#b(t){return!!Vat.get(this.type)?.has(t)}#C(t){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let r=t.#r[0];return!r||typeof r!="object"||r.type===null?!1:this.#b(r.type)}#T(t){let r=Vat.get(this.type),n=t.#r[0],o=r?.get(n.type);if(!o)return!1;this.#r=n.#r;for(let i of this.#r)typeof i=="object"&&(i.#i=this);this.type=o,this.#d=void 0,this.#m=!1}static fromGlob(t,r={}){let n=new rp(null,void 0,r);return rp.#c(t,n,0,r,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let t=this.toString(),[r,n,o,i]=this.toRegExpSource();if(!(o||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){let r=t??!!this.#a.dot;if(this.#e===this&&(this.#E(),this.#p()),!zat(this)){let l=this.isStart()&&this.isEnd()&&!this.#r.some(p=>typeof p!="string"),c=this.#r.map(p=>{let[A,_,E,S]=typeof p=="string"?rp.#y(p,this.#t,l):p.toRegExpSource(t);return this.#t=this.#t||E,this.#n=this.#n||S,A}).join(""),u="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&K7r.has(this.#r[0]))){let A=j7r,_=r&&A.has(c.charAt(0))||c.startsWith("\\.")&&A.has(c.charAt(2))||c.startsWith("\\.\\.")&&A.has(c.charAt(4)),E=!r&&!t&&A.has(c.charAt(0));u=_?W7r:E?Jj:""}let d="";return this.isEnd()&&this.#e.#s&&this.#i?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,pC(c),this.#t=!!this.#t,this.#n]}let n=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#S(r);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let l=this.toString(),c=this;return c.#r=[l],c.type=null,c.#t=void 0,[l,pC(this.toString()),!1,!1]}let s=!n||t||r||!Jj?"":this.#S(!0);s===i&&(s=""),s&&(i=`(?:${i})(?:${s})*?`);let a="";if(this.type==="!"&&this.#m)a=(this.isStart()&&!r?Jj:"")+jat;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?Jj:"")+Wat+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=o+i+l}return[a,pC(i),this.#t=!!this.#t,this.#n]}#E(){if(zat(this)){let t=0,r=!1;do{r=!0;for(let n=0;n<this.#r.length;n++){let o=this.#r[n];typeof o=="object"&&(o.#E(),this.#A(o)?(r=!1,this.#v(o,n)):this.#g(o)?(r=!1,this.#h(o,n)):this.#C(o)&&(r=!1,this.#T(o)))}}while(!r&&++t<10)}else for(let t of this.#r)typeof t=="object"&&t.#E();this.#d=void 0}#S(t){return this.#r.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,o,i,s]=r.toRegExpSource(t);return this.#n=this.#n||s,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#y(t,r,n=!1){let o=!1,i="",s=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(o){o=!1,i+=(J7r.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,i+=n&&/^[*]+$/.test(t)?jat:Wat,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?i+="\\\\":o=!0;continue}if(c==="["){let[u,d,f,p]=Yat(t,l);if(f){i+=u,s=s||d,l+=f-1,r=r||p;continue}}if(c==="?"){i+=oEe,r=!0;continue}i+=Z7r(c)}return[i,pC(t),!!r,s]}};rp=H1;var iEe=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!1}={})=>r?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&");var Bc=(e,t,r={})=>(DU(t),!r.nocomment&&t.charAt(0)==="#"?!1:new vB(t,r).match(e)),ejr=/^\*+([^+@!?*[(]*)$/,tjr=e=>t=>!t.startsWith(".")&&t.endsWith(e),rjr=e=>t=>t.endsWith(e),njr=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),ojr=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),ijr=/^\*+\.\*+$/,sjr=e=>!e.startsWith(".")&&e.includes("."),ajr=e=>e!=="."&&e!==".."&&e.includes("."),ljr=/^\.\*+$/,cjr=e=>e!=="."&&e!==".."&&e.startsWith("."),ujr=/^\*+$/,djr=e=>e.length!==0&&!e.startsWith("."),pjr=e=>e.length!==0&&e!=="."&&e!=="..",mjr=/^\?+([^+@!?*[(]*)?$/,fjr=([e,t=""])=>{let r=Zat([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},gjr=([e,t=""])=>{let r=Xat([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},hjr=([e,t=""])=>{let r=Xat([e]);return t?n=>r(n)&&n.endsWith(t):r},Ajr=([e,t=""])=>{let r=Zat([e]);return t?n=>r(n)&&n.endsWith(t):r},Zat=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},Xat=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},elt=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Kat={win32:{sep:"\\"},posix:{sep:"/"}},_jr=elt==="win32"?Kat.win32.sep:Kat.posix.sep;Bc.sep=_jr;var wu=Symbol("globstar **");Bc.GLOBSTAR=wu;var Ejr="[^/]",bjr=Ejr+"*?",Sjr="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",yjr="(?:(?!(?:\\/|^)\\.).)*?",Cjr=(e,t={})=>r=>Bc(r,e,t);Bc.filter=Cjr;var Vf=(e,t={})=>Object.assign({},e,t),Tjr=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return Bc;let t=Bc;return Object.assign((n,o,i={})=>t(n,o,Vf(e,i)),{Minimatch:class extends t.Minimatch{constructor(o,i={}){super(o,Vf(e,i))}static defaults(o){return t.defaults(Vf(e,o)).Minimatch}},AST:class extends t.AST{constructor(o,i,s={}){super(o,i,Vf(e,s))}static fromGlob(o,i={}){return t.AST.fromGlob(o,Vf(e,i))}},unescape:(n,o={})=>t.unescape(n,Vf(e,o)),escape:(n,o={})=>t.escape(n,Vf(e,o)),filter:(n,o={})=>t.filter(n,Vf(e,o)),defaults:n=>t.defaults(Vf(e,n)),makeRe:(n,o={})=>t.makeRe(n,Vf(e,o)),braceExpand:(n,o={})=>t.braceExpand(n,Vf(e,o)),match:(n,o,i={})=>t.match(n,o,Vf(e,i)),sep:t.sep,GLOBSTAR:wu})};Bc.defaults=Tjr;var tlt=(e,t={})=>(DU(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:$at(e,{max:t.braceExpandMax}));Bc.braceExpand=tlt;var Ijr=(e,t={})=>new vB(e,t).makeRe();Bc.makeRe=Ijr;var vjr=(e,t,r={})=>{let n=new vB(t,r);return e=e.filter(o=>n.match(o)),n.options.nonull&&!e.length&&e.push(t),e};Bc.match=vjr;var Jat=/[?*]|[+@!]\(.*?\)|\[|\]/,xjr=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vB=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,r={}){DU(t),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=t,this.platform=r.platform||elt,this.isWindows=this.platform==="win32";let n="allowWindowsEscape";this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r[n]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let r of t)if(typeof r!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,r=this.options;if(!r.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let o=this.globParts.map((i,s,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=i[0]===""&&i[1]===""&&(i[2]==="?"||!Jat.test(i[2]))&&!Jat.test(i[3]),c=/^[a-z]:/i.test(i[0]);if(l)return[...i.slice(0,4),...i.slice(4).map(u=>this.parse(u))];if(c)return[i[0],...i.slice(1).map(u=>this.parse(u))]}return i.map(l=>this.parse(l))});if(this.debug(this.pattern,o),this.set=o.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let s=this.set[i];s[0]===""&&s[1]===""&&this.globParts[i][2]==="?"&&typeof s[3]=="string"&&/^[a-z]:$/i.test(s[3])&&(s[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let n of t)for(let o=0;o<n.length;o++)n[o]==="**"&&(n[o]="*");let{optimizationLevel:r=1}=this.options;return r>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):r>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let o=n;for(;r[o+1]==="**";)o++;o!==n&&r.splice(n,o-n)}return r})}levelOneOptimize(t){return t.map(r=>(r=r.reduce((n,o)=>{let i=n[n.length-1];return o==="**"&&i==="**"?n:o===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(n.pop(),n):(n.push(o),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let o=1;o<t.length-1;o++){let i=t[o];o===1&&i===""&&t[0]===""||(i==="."||i==="")&&(r=!0,t.splice(o,1),o--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(r=!0,t.pop())}let n=0;for(;(n=t.indexOf("..",n+1))!==-1;){let o=t[n-1];o&&o!=="."&&o!==".."&&o!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(o))&&(r=!0,t.splice(n-1,2),n-=2)}}while(r);return t.length===0?[""]:t}firstPhasePreProcess(t){let r=!1;do{r=!1;for(let n of t){let o=-1;for(;(o=n.indexOf("**",o+1))!==-1;){let s=o;for(;n[s+1]==="**";)s++;s>o&&n.splice(o+1,s-o);let a=n[o+1],l=n[o+2],c=n[o+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;r=!0,n.splice(o,1);let u=n.slice(0);u[o]="**",t.push(u),o--}if(!this.preserveMultipleSlashes){for(let s=1;s<n.length-1;s++){let a=n[s];s===1&&a===""&&n[0]===""||(a==="."||a==="")&&(r=!0,n.splice(s,1),s--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(r=!0,n.pop())}let i=0;for(;(i=n.indexOf("..",i+1))!==-1;){let s=n[i-1];if(s&&s!=="."&&s!==".."&&s!=="**"){r=!0;let l=i===1&&n[i+1]==="**"?["."]:[];n.splice(i-1,2,...l),n.length===0&&n.push(""),i-=2}}}}while(r);return t}secondPhasePreProcess(t){for(let r=0;r<t.length-1;r++)for(let n=r+1;n<t.length;n++){let o=this.partsMatch(t[r],t[n],!this.preserveMultipleSlashes);if(o){t[r]=[],t[n]=o;break}}return t.filter(r=>r.length)}partsMatch(t,r,n=!1){let o=0,i=0,s=[],a="";for(;o<t.length&&i<r.length;)if(t[o]===r[i])s.push(a==="b"?r[i]:t[o]),o++,i++;else if(n&&t[o]==="**"&&r[i]===t[o+1])s.push(t[o]),o++;else if(n&&r[i]==="**"&&t[o]===r[i+1])s.push(r[i]),i++;else if(t[o]==="*"&&r[i]&&(this.options.dot||!r[i].startsWith("."))&&r[i]!=="**"){if(a==="b")return!1;a="a",s.push(t[o]),o++,i++}else if(r[i]==="*"&&t[o]&&(this.options.dot||!t[o].startsWith("."))&&t[o]!=="**"){if(a==="a")return!1;a="b",s.push(r[i]),o++,i++}else return!1;return t.length===r.length&&s}parseNegate(){if(this.nonegate)return;let t=this.pattern,r=!1,n=0;for(let o=0;o<t.length&&t.charAt(o)==="!";o++)r=!r,n++;n&&(this.pattern=t.slice(n)),this.negate=r}matchOne(t,r,n=!1){let o=0,i=0;if(this.isWindows){let a=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),l=!a&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),c=typeof r[0]=="string"&&/^[a-z]:$/i.test(r[0]),u=!c&&r[0]===""&&r[1]===""&&r[2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3]),d=l?3:a?0:void 0,f=u?3:c?0:void 0;if(typeof d=="number"&&typeof f=="number"){let[p,A]=[t[d],r[f]];p.toLowerCase()===A.toLowerCase()&&(r[f]=p,i=f,o=d)}}let{optimizationLevel:s=1}=this.options;return s>=2&&(t=this.levelTwoFileOptimize(t)),r.includes(wu)?this.#e(t,r,n,o,i):this.#n(t,r,n,o,i)}#e(t,r,n,o,i){let s=r.indexOf(wu,i),a=r.lastIndexOf(wu),[l,c,u]=n?[r.slice(i,s),r.slice(s+1),[]]:[r.slice(i,s),r.slice(s+1,a),r.slice(a+1)];if(l.length){let C=t.slice(o,o+l.length);if(!this.#n(C,l,n,0,0))return!1;o+=l.length,i+=l.length}let d=0;if(u.length){if(u.length+o>t.length)return!1;let C=t.length-u.length;if(this.#n(t,u,n,C,0))d=u.length;else{if(t[t.length-1]!==""||o+u.length===t.length||(C--,!this.#n(t,u,n,C,0)))return!1;d=u.length+1}}if(!c.length){let C=!!d;for(let v=o;v<t.length-d;v++){let R=String(t[v]);if(C=!0,R==="."||R===".."||!this.options.dot&&R.startsWith("."))return!1}return n||C}let f=[[[],0]],p=f[0],A=0,_=[0];for(let C of c)C===wu?(_.push(A),p=[[],0],f.push(p)):(p[0].push(C),A++);let E=f.length-1,S=t.length-d;for(let C of f)C[1]=S-(_[E--]+C[0].length);return!!this.#t(t,f,o,0,n,0,!!d)}#t(t,r,n,o,i,s,a){let l=r[o];if(!l){for(let d=n;d<t.length;d++){a=!0;let f=t[d];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return a}let[c,u]=l;for(;n<=u;){if(this.#n(t.slice(0,n+c.length),c,i,n,0)&&s<this.maxGlobstarRecursion){let p=this.#t(t,r,n+c.length,o+1,i,s+1,a);if(p!==!1)return p}let f=t[n];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1;n++}return i||null}#n(t,r,n,o,i){let s,a,l,c;for(s=o,a=i,c=t.length,l=r.length;s<c&&a<l;s++,a++){this.debug("matchOne loop");let u=r[a],d=t[s];if(this.debug(r,u,d),u===!1||u===wu)return!1;let f;if(typeof u=="string"?(f=d===u,this.debug("string match",u,d,f)):(f=u.test(d),this.debug("pattern match",u,d,f)),!f)return!1}if(s===c&&a===l)return!0;if(s===c)return n;if(a===l)return s===c-1&&t[s]==="";throw new Error("wtf?")}braceExpand(){return tlt(this.pattern,this.options)}parse(t){DU(t);let r=this.options;if(t==="**")return wu;if(t==="")return"";let n,o=null;(n=t.match(ujr))?o=r.dot?pjr:djr:(n=t.match(ejr))?o=(r.nocase?r.dot?ojr:njr:r.dot?rjr:tjr)(n[1]):(n=t.match(mjr))?o=(r.nocase?r.dot?gjr:fjr:r.dot?hjr:Ajr)(n):(n=t.match(ijr))?o=r.dot?ajr:sjr:(n=t.match(ljr))&&(o=cjr);let i=H1.fromGlob(t,this.options).toMMPattern();return o&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:o}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?bjr:r.dot?Sjr:yjr,o=new Set(r.nocase?["i"]:[]),i=t.map(l=>{let c=l.map(d=>{if(d instanceof RegExp)for(let f of d.flags.split(""))o.add(f);return typeof d=="string"?xjr(d):d===wu?wu:d._src});c.forEach((d,f)=>{let p=c[f+1],A=c[f-1];d!==wu||A===wu||(A===void 0?p!==void 0&&p!==wu?c[f+1]="(?:\\/|"+n+"\\/)?"+p:c[f]=n:p===void 0?c[f-1]=A+"(?:\\/|\\/"+n+")?":p!==wu&&(c[f-1]=A+"(?:\\/|\\/"+n+"\\/)"+p,c[f+1]=wu))});let u=c.filter(d=>d!==wu);if(this.partial&&u.length>=1){let d=[];for(let f=1;f<=u.length;f++)d.push(u.slice(0,f).join("/"));return"(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[s,a]=t.length>1?["(?:",")"]:["",""];i="^"+s+i+a+"$",this.partial&&(i="^(?:\\/|"+s+i.slice(1,-1)+a+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,r=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&r)return!0;let n=this.options;this.isWindows&&(t=t.split("\\").join("/"));let o=this.slashSplit(t);this.debug(this.pattern,"split",o);let i=this.set;this.debug(this.pattern,"set",i);let s=o[o.length-1];if(!s)for(let a=o.length-2;!s&&a>=0;a--)s=o[a];for(let a of i){let l=o;if(n.matchBase&&a.length===1&&(l=[s]),this.matchOne(l,a,r))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(t){return Bc.defaults(t).Minimatch}};Bc.AST=H1;Bc.Minimatch=vB;Bc.escape=iEe;Bc.unescape=pC;var olt=Ie(RU(),1);lr();Pe();we();nd();import{readFile as rlt}from"fs/promises";import{existsSync as sEe,readdirSync as wjr,statSync as Rjr}from"fs";import{join as aEe,relative as ilt}from"path";import{homedir as Njr}from"os";function nlt(e){try{let t=(0,olt.default)(e),r=t.data.paths,n=[];return typeof r=="string"?n=r.split(",").map(o=>o.trim()).filter(Boolean):Array.isArray(r)&&(n=r.filter(o=>typeof o=="string")),{paths:n,content:t.content.trim()}}catch(t){return be(t),{paths:[],content:e.trim()}}}function Djr(e,t){return t.length===0?!0:t.some(r=>{try{return Bc(e,r,{matchBase:!0,dot:!0})}catch(n){return be(n),!1}})}function lEe(e){let t=[];try{if(!sEe(e))return t;let r=wjr(e);for(let n of r){let o=aEe(e,n),i=Rjr(o);i.isDirectory()?t.push(...lEe(o)):i.isFile()&&n.endsWith(".md")&&t.push(o)}}catch(r){be(r)}return t}async function Zj(){let e=[];try{let t=aEe(Njr(),Tn,"rules");if(sEe(t)){let r=lEe(t);for(let n of r)try{let o=await rlt(n,"utf-8"),{paths:i,content:s}=nlt(o);i.length>0&&e.push({filePath:n,content:s,paths:i,isProjectRule:!1})}catch(o){be(o)}}}catch(t){be(t)}try{let t=aEe(Oe(),Tn,"rules");if(sEe(t)){let r=lEe(t);for(let n of r)try{let o=await rlt(n,"utf-8"),{paths:i,content:s}=nlt(o);i.length>0&&e.push({filePath:ilt(Oe(),n),content:s,paths:i,isProjectRule:!0})}catch(o){be(o)}}}catch(t){be(t)}return e}function slt(e,t){e=B7(e);let r=B7(Oe()),n=e.startsWith(r)?ilt(r,e):e;return t.filter(o=>Djr(n,o.paths))}function alt(e){return e.length===0?"":e.map(r=>{let n=r.isProjectRule?"project instructions, checked into the codebase":"user's private global instructions for all projects";return`Contents of ${r.filePath} (${n}):
656
+ `)}function dit(e){try{let t=$Yr(e),r=t.readSync();return t.closeSync(),r===null}catch(t){return be(`Error checking directory: ${t}`),!1}}Pe();function oC(){let e=Nn();e.hasCompletedProjectOnboarding||ti({...e,hasCompletedProjectOnboarding:!0})}function x_e({workspaceDir:e}){let r=!Nn().hasCompletedProjectOnboarding;if(!r)return null;let n=KYr(JYr(e,Qo)),o=dit(e),i=!n&&!o,s=lB.isEnabled&&!Qr().shiftEnterKeyBindingInstalled,a=re();return(0,h.jsxs)(x,{flexDirection:"column",gap:1,padding:1,paddingBottom:0,children:[r&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(I,{color:a.secondaryText,children:"Tips for getting started:"}),(0,h.jsx)(Dc,{children:(()=>{let l=[];return o&&l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Ask ",it," to create a new app or clone a repository."]})},"workspace")),i&&l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Run ",(0,h.jsx)(I,{color:a.text,children:"/init"})," to create a",Qo," file with instructions for Hawa code."]})},"claudemd")),s&&l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Run ",(0,h.jsx)(I,{color:a.text,children:"/terminal-setup"}),(0,h.jsx)(I,{bold:!1,children:" to set up terminal integration"})]})},"terminal")),l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Ask ",it," questions about your codebase."]})},"questions")),l.push((0,h.jsx)(Dc.Item,{children:(0,h.jsxs)(I,{color:a.secondaryText,children:["Ask ",it," to implement changes to your codebase."]})},"changes")),l})()})]}),e===ZYr()&&(0,h.jsxs)(I,{color:re().warning,children:["Note: You have launched ",(0,h.jsx)(I,{bold:!0,children:it})," in your home directory. For the best experience, launch it in a project directory instead."]})]})}function w_e({isFocused:e,isSelected:t,smallPointer:r,children:n}){let{styles:o}=Ai("Select");return(0,h.jsxs)(x,{...o.option({isFocused:e}),children:[e&&(0,h.jsx)(I,{...o.focusIndicator(),children:r?nr.triangleDownSmall:nr.pointer}),(0,h.jsx)(I,{...o.label({isFocused:e,isSelected:t}),children:n}),t&&(0,h.jsx)(I,{...o.selectedIndicator(),children:nr.tick})]})}var Xd=Ie(Ve(),1);import{isDeepStrictEqual as XYr}from"node:util";var bU=class extends Map{first;constructor(t){let r=[],n,o,i=0;for(let s of t){let a={...s,previous:o,next:void 0,index:i};o&&(o.next=a),n||=a;let l="value"in s?s.value:R_e(s);r.push([l,a]),i++,o=a}super(r),this.first=n}};var ezr=(e,t)=>{switch(t.type){case"focus-next-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.next;for(;n&&!("value"in n);)n=n.next;if(!n)return e;if(!(n.index>=e.visibleToIndex))return{...e,focusedValue:n.value};let i=Math.min(e.optionMap.size,e.visibleToIndex+1),s=i-e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:s,visibleToIndex:i}}case"focus-previous-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.previous;for(;n&&!("value"in n);)n=n.previous;if(!n)return e;if(!(n.index<=e.visibleFromIndex))return{...e,focusedValue:n.value};let i=Math.max(0,e.visibleFromIndex-1),s=i+e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:i,visibleToIndex:s}}case"select-focused-option":return{...e,previousValue:e.value,value:e.focusedValue};case"reset":return t.state;case"set-focus":return{...e,focusedValue:t.value}}},N_e=e=>e.flatMap(t=>{if("options"in t){let r=N_e(t.options),n=r.flatMap(i=>"value"in i?i.value:[]);return[...t.header!==void 0?[{header:t.header,optionValues:n}]:[],...r]}return t}),pit=({visibleOptionCount:e,defaultValue:t,options:r})=>{let n=N_e(r),o=typeof e=="number"?Math.min(e,n.length):n.length,i=new bU(n),s=i.first,a=s&&"value"in s?s.value:void 0;return{optionMap:i,visibleOptionCount:o,focusedValue:a,visibleFromIndex:0,visibleToIndex:o,previousValue:t,value:t}},D_e=({visibleOptionCount:e=5,options:t,defaultValue:r,onChange:n,onFocus:o,focusValue:i})=>{let s=N_e(t),[a,l]=(0,Xd.useReducer)(ezr,{visibleOptionCount:e,defaultValue:r,options:t},pit),[c,u]=(0,Xd.useState)(s);s!==c&&!XYr(s,c)&&(l({type:"reset",state:pit({visibleOptionCount:e,defaultValue:r,options:t})}),u(s));let d=(0,Xd.useCallback)(()=>{l({type:"focus-next-option"})},[]),f=(0,Xd.useCallback)(()=>{l({type:"focus-previous-option"})},[]),p=(0,Xd.useCallback)(()=>{l({type:"select-focused-option"})},[]),A=(0,Xd.useMemo)(()=>s.map((_,E)=>({..._,index:E})).slice(a.visibleFromIndex,a.visibleToIndex),[s,a.visibleFromIndex,a.visibleToIndex]);return(0,Xd.useEffect)(()=>{a.value&&a.previousValue!==a.value&&n?.(a.value)},[a.previousValue,a.value,t,n]),(0,Xd.useEffect)(()=>{a.focusedValue&&o?.(a.focusedValue)},[a.focusedValue,o]),(0,Xd.useEffect)(()=>{i&&l({type:"set-focus",value:i})},[i]),{focusedValue:a.focusedValue,visibleFromIndex:a.visibleFromIndex,visibleToIndex:a.visibleToIndex,value:a.value,visibleOptions:A,focusNextOption:d,focusPreviousOption:f,selectFocusedOption:p}};var O_e=({isDisabled:e=!1,state:t})=>{ft((r,n)=>{n.downArrow&&t.focusNextOption(),n.upArrow&&t.focusPreviousOption(),n.return&&t.selectFocusedOption()},{isActive:!e})};var R_e=e=>`HEADER-${e.optionValues.join(",")}`;function Fb({isDisabled:e=!1,visibleOptionCount:t=5,highlightText:r,options:n,defaultValue:o,onChange:i,onFocus:s,focusValue:a}){let l=D_e({visibleOptionCount:t,options:n,defaultValue:o,onChange:i,onFocus:s,focusValue:a});O_e({isDisabled:e,state:l});let{styles:c}=Ai("Select");return(0,h.jsx)(x,{...c.container(),children:l.visibleOptions.map(u=>{let d="value"in u?u.value:R_e(u),f=!e&&l.focusedValue!==void 0&&("value"in u?l.focusedValue===u.value:u.optionValues.includes(l.focusedValue)),p=!!l.value&&("value"in u?l.value===u.value:u.optionValues.includes(l.value)),A="header"in u,_="label"in u?u.label:u.header,E=_;if(r&&_.includes(r)){let S=_.indexOf(r);E=(0,h.jsxs)(h.Fragment,{children:[_.slice(0,S),(0,h.jsx)(I,{...c.highlightedText(),children:r}),_.slice(S+r.length)]})}return(0,h.jsx)(w_e,{isFocused:f,isSelected:p,smallPointer:A,children:E},d)})})}function mit({onDone:e}){return ft((t,r)=>{(r.ctrl&&(t==="c"||t==="d")||r.escape)&&e()}),(0,h.jsxs)(x,{flexDirection:"column",borderStyle:"round",padding:1,borderColor:re().secondaryBorder,children:[(0,h.jsx)(x,{marginBottom:1,flexDirection:"column",children:(0,h.jsx)(I,{bold:!0,children:"You've spent $5 this session."})}),(0,h.jsx)(x,{children:(0,h.jsx)(Fb,{options:[{value:"ok",label:"Got it, thanks!"}],onChange:e})})]})}var Jt=Ie(Ve(),1);Pe();lr();r_();var nzr="2.7.19",n_={VERSION:nzr,PACKAGE_URL:"@dahawa/hawa-code",README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var k_e=46,hit=["(\u2740\u2579\u25E1\u2579)","(\u25D5\u072B\u25D5)","\u239D(\u25D5u\u25D5)\u23A0","\u10DA(\u25C9\u25DE\u0C6A\u25DF\u25C9 )\u10DA","(\xB4\u25C9\u203F\u25C9\uFF40)","\u0E01\u0E47\u0295\u2022\u0361\u1D25\u2022\u0294 \u0E01\u0E49","\uFF0F/( \u25D5\u203F\u203F\u25D5 )\uFF3C"];function Qj({isDefaultModel:e=!1}){let t=Math.max(k_e,Oe().length+12),r=re(),n=hit[Math.floor(Math.random()*hit.length)];return(0,h.jsx)(x,{flexDirection:"column",children:(0,h.jsxs)(x,{flexDirection:"column",gap:1,paddingLeft:1,width:"100%",children:[(0,h.jsxs)(I,{children:[(0,h.jsx)(I,{children:n})," Welcome to"," ",(0,h.jsx)(I,{bold:!0,children:it}),(0,h.jsxs)(I,{color:r.secondaryText,children:[" v",n_.VERSION]})]}),(0,h.jsx)(h.Fragment,{children:(0,h.jsxs)(x,{paddingLeft:2,flexDirection:"column",gap:1,children:[(0,h.jsx)(I,{color:r.secondaryText,italic:!0,children:"/help for help"}),(0,h.jsxs)(I,{color:r.secondaryText,children:["cwd: ",Oe()]}),(0,h.jsxs)(I,{color:r.secondaryText,children:["model: ",Jn.getConfig().routing.MODEL?.map(o=>`${o.source}__${o.model}`).join(", ")??"N/A"]}),(0,h.jsxs)(I,{color:r.secondaryText,children:["small fast model: ",Jn.getConfig().routing.SMALL_FAST_MODEL?.map(o=>`${o.source}__${o.model}`).join(", ")??"N/A"]})]})})]})})}we();import{randomUUID as $g}from"crypto";ji();we();er();lr();we();Pe();import{existsSync as Gb,readdirSync as Ojr,statSync as Bjr}from"fs";import{join as mC,relative as Mjr}from"path";import{homedir as clt}from"os";import{platform as kjr}from"process";import{readFile as fC}from"fs/promises";lr();um();Kt();import{join as czr,sep as uzr}from"path";function ld(){if(!Oc())return!1;try{let e=Je();if(e.autoMemory?.teamMemoryEnabled!==void 0)return e.autoMemory.teamMemoryEnabled}catch{}return!1}function ep(){return(czr(Oe(),".hcode","team-memory")+uzr).normalize("NFC")}function zf(e){let t=e.normalize("NFC"),r=ep();return t.startsWith(r)}um();var ult=Ie(RU(),1);po();var X_e=(e,t,r)=>{let n=e instanceof RegExp?Pat(e,r):e,o=t instanceof RegExp?Pat(t,r):t,i=n!==null&&o!=null&&y7r(n,o,r);return i&&{start:i[0],end:i[1],pre:r.slice(0,i[0]),body:r.slice(i[0]+n.length,i[1]),post:r.slice(i[1]+o.length)}},Pat=(e,t)=>{let r=t.match(e);return r?r[0]:null},y7r=(e,t,r)=>{let n,o,i,s,a,l=r.indexOf(e),c=r.indexOf(t,l+1),u=l;if(l>=0&&c>0){if(e===t)return[l,c];for(n=[],i=r.length;u>=0&&!a;){if(u===l)n.push(u),l=r.indexOf(e,u+1);else if(n.length===1){let d=n.pop();d!==void 0&&(a=[d,c])}else o=n.pop(),o!==void 0&&o<i&&(i=o,s=c),c=r.indexOf(t,u+1);u=l<c&&l>=0?l:c}n.length&&s!==void 0&&(a=[i,s])}return a};var Fat="\0SLASH"+Math.random()+"\0",Qat="\0OPEN"+Math.random()+"\0",rEe="\0CLOSE"+Math.random()+"\0",Uat="\0COMMA"+Math.random()+"\0",Gat="\0PERIOD"+Math.random()+"\0",C7r=new RegExp(Fat,"g"),T7r=new RegExp(Qat,"g"),I7r=new RegExp(rEe,"g"),v7r=new RegExp(Uat,"g"),x7r=new RegExp(Gat,"g"),w7r=/\\\\/g,R7r=/\\{/g,N7r=/\\}/g,D7r=/\\,/g,O7r=/\\\./g,B7r=1e5,M7r=4e6;function eEe(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function k7r(e){return e.replace(w7r,Fat).replace(R7r,Qat).replace(N7r,rEe).replace(D7r,Uat).replace(O7r,Gat)}function L7r(e){return e.replace(C7r,"\\").replace(T7r,"{").replace(I7r,"}").replace(v7r,",").replace(x7r,".")}function Hat(e){if(!e)return[""];let t=[],r=X_e("{","}",e);if(!r)return e.split(",");let{pre:n,body:o,post:i}=r,s=n.split(",");s[s.length-1]+="{"+o+"}";let a=Hat(i);return i.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),t.push.apply(t,s),t}function $at(e,t={}){if(!e)return[];let{max:r=B7r,maxLength:n=M7r}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),tEe(k7r(e),r,n,!0).map(L7r)}function P7r(e){return"{"+e+"}"}function F7r(e){return/^-?0\d/.test(e)}function Q7r(e,t){return e<=t}function U7r(e,t){return e>=t}function NU(e,t,r,n,o,i){let s=[],a=0;for(let l=0;l<e.length;l++)for(let c=0;c<r.length;c++){if(s.length>=n)return s;let u=e[l]+t+r[c];if(!(i&&!u)){if(a+u.length>o)return s;s.push(u),a+=u.length}}return s}function G7r(e,t,r,n){let o=e.split(/\.\./),i=[];if(o[0]===void 0||o[1]===void 0)return i;let s=eEe(o[0]),a=eEe(o[1]),l=Math.max(o[0].length,o[1].length),c=o.length===3&&o[2]!==void 0?Math.max(Math.abs(eEe(o[2])),1):1,u=Q7r;a<s&&(c*=-1,u=U7r);let f=o.some(F7r),p=0;for(let A=s;u(A,a)&&i.length<r;A+=c){let _;if(t)_=String.fromCharCode(A),_==="\\"&&(_="");else if(_=String(A),f){let E=l-_.length;if(E>0){let S=new Array(E+1).join("0");A<0?_="-"+S+_.slice(1):_=S+_}}if(p+_.length>n)break;i.push(_),p+=_.length}return i}function tEe(e,t,r,n){let o=[""],i=!1,s=!0;for(;;){let a=X_e("{","}",e);if(!a)return NU(o,e,[""],t,r,i);let l=a.pre;if(/\$$/.test(l)){if(o=NU(o,l+"{"+a.body+"}",[""],t,r,i&&!a.post.length),s=!1,!a.post.length)break;e=a.post;continue}let c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(a.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(a.body),d=c||u,f=a.body.indexOf(",")>=0;if(!d&&!f){if(a.post.match(/,(?!,).*\}/)){e=a.pre+"{"+a.body+rEe+a.post,n=!0;continue}return NU(o,l+"{"+a.body+"}"+a.post,[""],t,r,i)}s&&(i=n&&!d,s=!1);let p;if(d)p=G7r(a.body,u,t,r);else{let A=Hat(a.body);if(A.length===1&&A[0]!==void 0&&(A=tEe(A[0],t,r,!1).map(P7r),A.length===1)){if(o=NU(o,l+A[0],[""],t,r,i&&!a.post.length),!a.post.length)break;e=a.post;continue}let _=i&&!a.post.length&&!l;for(let S=0;_&&S<o.length;S++)o[S]&&(_=!1);p=[];let E=0;e:for(let S=0;S<A.length;S++){let C=tEe(A[S],t,r,!1);for(let v=0;v<C.length;v++){let R=C[v];if(!(_&&!R)){if(p.length>=t||E+R.length>r)break e;p.push(R),E+=R.length}}}}if(o=NU(o,l,p,t,r,i&&!a.post.length),!a.post.length)break;e=a.post}return o}var DU=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")};var H7r={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},OU=e=>e.replace(/[[\]\\-]/g,"\\$&"),$7r=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),qat=e=>e.join(""),Yat=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],o=[],i=r+1,s=!1,a=!1,l=!1,c=!1,u=r,d="";e:for(;i<e.length;){let _=e.charAt(i);if((_==="!"||_==="^")&&i===r+1){c=!0,i++;continue}if(_==="]"&&s&&!l){u=i+1;break}if(s=!0,_==="\\"&&!l){l=!0,i++;continue}if(_==="["&&!l){for(let[E,[S,C,v]]of Object.entries(H7r))if(e.startsWith(E,i)){if(d)return["$.",!1,e.length-r,!0];i+=E.length,v?o.push(S):n.push(S),a=a||C;continue e}}if(l=!1,d){_>d?n.push(OU(d)+"-"+OU(_)):_===d&&n.push(OU(_)),d="",i++;continue}if(e.startsWith("-]",i+1)){n.push(OU(_+"-")),i+=2;continue}if(e.startsWith("-",i+1)){d=_,i+=2;continue}n.push(OU(_)),i++}if(u<i)return["",!1,0,!1];if(!n.length&&!o.length)return["$.",!1,e.length-r,!0];if(o.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let _=n[0].length===2?n[0].slice(-1):n[0];return[$7r(_),!1,u-r,!1]}let f="["+(c?"^":"")+qat(n)+"]",p="["+(c?"":"^")+qat(o)+"]";return[n.length&&o.length?"("+f+"|"+p+")":n.length?f:p,a,u-r,!0]};var pC=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!0}={})=>r?t?e.replace(/\[([^/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):t?e.replace(/\[([^/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var rp,q7r=new Set(["!","?","+","*","@"]),nEe=e=>q7r.has(e),zat=e=>nEe(e.type),Y7r=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),z7r=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),V7r=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),Vat=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),W7r="(?!(?:^|/)\\.\\.?(?:$|/))",Jj="(?!\\.)",j7r=new Set(["[","."]),K7r=new Set(["..","."]),J7r=new Set("().*{}+?[]^$\\!"),Z7r=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),oEe="[^/]",Wat=oEe+"*?",jat=oEe+"+?",X7r=0,H1=class{type;#e;#t;#n=!1;#r=[];#i;#o;#l;#s=!1;#a;#d;#m=!1;id=++X7r;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(t,r,n={}){this.type=t,t&&(this.#t=!0),this.#i=r,this.#e=this.#i?this.#i.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#l=this.#e===this?[]:this.#e.#l,t==="!"&&!this.#e.#s&&this.#l.push(this),this.#o=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#d=this.#r.map(t=>String(t)).join("")}#p(){if(this!==this.#e)throw new Error("should only call on root");if(this.#s)return this;this.toString(),this.#s=!0;let t;for(;t=this.#l.pop();){if(t.type!=="!")continue;let r=t,n=r.#i;for(;n;){for(let o=r.#o+1;!n.type&&o<n.#r.length;o++)for(let i of t.#r){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(n.#r[o])}r=n,n=r.#i}}return this}push(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof rp&&r.#i===this))throw new Error("invalid part: "+r);this.#r.push(r)}}toJSON(){let t=this.type===null?this.#r.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#r.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type==="!")&&t.push({}),t}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#o===0)return!0;let t=this.#i;for(let r=0;r<this.#o;r++){let n=t.#r[r];if(!(n instanceof rp&&n.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type==="!")return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let t=this.#i?this.#i.#r.length:0;return this.#o===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let r=new rp(this.type,t);for(let n of this.#r)r.copyIn(n);return r}static#c(t,r,n,o,i){let s=o.maxExtglobRecursion??2,a=!1,l=!1,c=-1,u=!1;if(r.type===null){let _=n,E="";for(;_<t.length;){let S=t.charAt(_++);if(a||S==="\\"){a=!a,E+=S;continue}if(l){_===c+1?(S==="^"||S==="!")&&(u=!0):S==="]"&&!(_===c+2&&u)&&(l=!1),E+=S;continue}else if(S==="["){l=!0,c=_,u=!1,E+=S;continue}if(!o.noext&&nEe(S)&&t.charAt(_)==="("&&i<=s){r.push(E),E="";let v=new rp(S,r);_=rp.#c(t,v,_,o,i+1),r.push(v);continue}E+=S}return r.push(E),_}let d=n+1,f=new rp(null,r),p=[],A="";for(;d<t.length;){let _=t.charAt(d++);if(a||_==="\\"){a=!a,A+=_;continue}if(l){d===c+1?(_==="^"||_==="!")&&(u=!0):_==="]"&&!(d===c+2&&u)&&(l=!1),A+=_;continue}else if(_==="["){l=!0,c=d,u=!1,A+=_;continue}if(!o.noext&&nEe(_)&&t.charAt(d)==="("&&(i<=s||r&&r.#_(_))){let S=r&&r.#_(_)?0:1;f.push(A),A="";let C=new rp(_,f);f.push(C),d=rp.#c(t,C,d,o,i+S);continue}if(_==="|"){f.push(A),A="",p.push(f),f=new rp(null,r);continue}if(_===")")return A===""&&r.#r.length===0&&(r.#m=!0),f.push(A),A="",r.push(...p,f),d;A+=_}return r.type=null,r.#t=void 0,r.#r=[t.substring(n-1)],d}#g(t){return this.#A(t,z7r)}#A(t,r=Y7r){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null)return!1;let n=t.#r[0];return!n||typeof n!="object"||n.type===null?!1:this.#_(n.type,r)}#_(t,r=V7r){return!!r.get(this.type)?.includes(t)}#h(t,r){let n=t.#r[0],o=new rp(null,n,this.options);o.#r.push(""),n.push(o),this.#v(t,r)}#v(t,r){let n=t.#r[0];this.#r.splice(r,1,...n.#r);for(let o of n.#r)typeof o=="object"&&(o.#i=this);this.#d=void 0}#b(t){return!!Vat.get(this.type)?.has(t)}#C(t){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let r=t.#r[0];return!r||typeof r!="object"||r.type===null?!1:this.#b(r.type)}#T(t){let r=Vat.get(this.type),n=t.#r[0],o=r?.get(n.type);if(!o)return!1;this.#r=n.#r;for(let i of this.#r)typeof i=="object"&&(i.#i=this);this.type=o,this.#d=void 0,this.#m=!1}static fromGlob(t,r={}){let n=new rp(null,void 0,r);return rp.#c(t,n,0,r,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let t=this.toString(),[r,n,o,i]=this.toRegExpSource();if(!(o||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){let r=t??!!this.#a.dot;if(this.#e===this&&(this.#E(),this.#p()),!zat(this)){let l=this.isStart()&&this.isEnd()&&!this.#r.some(p=>typeof p!="string"),c=this.#r.map(p=>{let[A,_,E,S]=typeof p=="string"?rp.#y(p,this.#t,l):p.toRegExpSource(t);return this.#t=this.#t||E,this.#n=this.#n||S,A}).join(""),u="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&K7r.has(this.#r[0]))){let A=j7r,_=r&&A.has(c.charAt(0))||c.startsWith("\\.")&&A.has(c.charAt(2))||c.startsWith("\\.\\.")&&A.has(c.charAt(4)),E=!r&&!t&&A.has(c.charAt(0));u=_?W7r:E?Jj:""}let d="";return this.isEnd()&&this.#e.#s&&this.#i?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,pC(c),this.#t=!!this.#t,this.#n]}let n=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#S(r);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let l=this.toString(),c=this;return c.#r=[l],c.type=null,c.#t=void 0,[l,pC(this.toString()),!1,!1]}let s=!n||t||r||!Jj?"":this.#S(!0);s===i&&(s=""),s&&(i=`(?:${i})(?:${s})*?`);let a="";if(this.type==="!"&&this.#m)a=(this.isStart()&&!r?Jj:"")+jat;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?Jj:"")+Wat+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=o+i+l}return[a,pC(i),this.#t=!!this.#t,this.#n]}#E(){if(zat(this)){let t=0,r=!1;do{r=!0;for(let n=0;n<this.#r.length;n++){let o=this.#r[n];typeof o=="object"&&(o.#E(),this.#A(o)?(r=!1,this.#v(o,n)):this.#g(o)?(r=!1,this.#h(o,n)):this.#C(o)&&(r=!1,this.#T(o)))}}while(!r&&++t<10)}else for(let t of this.#r)typeof t=="object"&&t.#E();this.#d=void 0}#S(t){return this.#r.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,o,i,s]=r.toRegExpSource(t);return this.#n=this.#n||s,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#y(t,r,n=!1){let o=!1,i="",s=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(o){o=!1,i+=(J7r.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,i+=n&&/^[*]+$/.test(t)?jat:Wat,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?i+="\\\\":o=!0;continue}if(c==="["){let[u,d,f,p]=Yat(t,l);if(f){i+=u,s=s||d,l+=f-1,r=r||p;continue}}if(c==="?"){i+=oEe,r=!0;continue}i+=Z7r(c)}return[i,pC(t),!!r,s]}};rp=H1;var iEe=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!1}={})=>r?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&");var Bc=(e,t,r={})=>(DU(t),!r.nocomment&&t.charAt(0)==="#"?!1:new vB(t,r).match(e)),ejr=/^\*+([^+@!?*[(]*)$/,tjr=e=>t=>!t.startsWith(".")&&t.endsWith(e),rjr=e=>t=>t.endsWith(e),njr=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),ojr=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),ijr=/^\*+\.\*+$/,sjr=e=>!e.startsWith(".")&&e.includes("."),ajr=e=>e!=="."&&e!==".."&&e.includes("."),ljr=/^\.\*+$/,cjr=e=>e!=="."&&e!==".."&&e.startsWith("."),ujr=/^\*+$/,djr=e=>e.length!==0&&!e.startsWith("."),pjr=e=>e.length!==0&&e!=="."&&e!=="..",mjr=/^\?+([^+@!?*[(]*)?$/,fjr=([e,t=""])=>{let r=Zat([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},gjr=([e,t=""])=>{let r=Xat([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},hjr=([e,t=""])=>{let r=Xat([e]);return t?n=>r(n)&&n.endsWith(t):r},Ajr=([e,t=""])=>{let r=Zat([e]);return t?n=>r(n)&&n.endsWith(t):r},Zat=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},Xat=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},elt=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Kat={win32:{sep:"\\"},posix:{sep:"/"}},_jr=elt==="win32"?Kat.win32.sep:Kat.posix.sep;Bc.sep=_jr;var wu=Symbol("globstar **");Bc.GLOBSTAR=wu;var Ejr="[^/]",bjr=Ejr+"*?",Sjr="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",yjr="(?:(?!(?:\\/|^)\\.).)*?",Cjr=(e,t={})=>r=>Bc(r,e,t);Bc.filter=Cjr;var Vf=(e,t={})=>Object.assign({},e,t),Tjr=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return Bc;let t=Bc;return Object.assign((n,o,i={})=>t(n,o,Vf(e,i)),{Minimatch:class extends t.Minimatch{constructor(o,i={}){super(o,Vf(e,i))}static defaults(o){return t.defaults(Vf(e,o)).Minimatch}},AST:class extends t.AST{constructor(o,i,s={}){super(o,i,Vf(e,s))}static fromGlob(o,i={}){return t.AST.fromGlob(o,Vf(e,i))}},unescape:(n,o={})=>t.unescape(n,Vf(e,o)),escape:(n,o={})=>t.escape(n,Vf(e,o)),filter:(n,o={})=>t.filter(n,Vf(e,o)),defaults:n=>t.defaults(Vf(e,n)),makeRe:(n,o={})=>t.makeRe(n,Vf(e,o)),braceExpand:(n,o={})=>t.braceExpand(n,Vf(e,o)),match:(n,o,i={})=>t.match(n,o,Vf(e,i)),sep:t.sep,GLOBSTAR:wu})};Bc.defaults=Tjr;var tlt=(e,t={})=>(DU(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:$at(e,{max:t.braceExpandMax}));Bc.braceExpand=tlt;var Ijr=(e,t={})=>new vB(e,t).makeRe();Bc.makeRe=Ijr;var vjr=(e,t,r={})=>{let n=new vB(t,r);return e=e.filter(o=>n.match(o)),n.options.nonull&&!e.length&&e.push(t),e};Bc.match=vjr;var Jat=/[?*]|[+@!]\(.*?\)|\[|\]/,xjr=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vB=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,r={}){DU(t),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=t,this.platform=r.platform||elt,this.isWindows=this.platform==="win32";let n="allowWindowsEscape";this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r[n]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let r of t)if(typeof r!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,r=this.options;if(!r.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let o=this.globParts.map((i,s,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=i[0]===""&&i[1]===""&&(i[2]==="?"||!Jat.test(i[2]))&&!Jat.test(i[3]),c=/^[a-z]:/i.test(i[0]);if(l)return[...i.slice(0,4),...i.slice(4).map(u=>this.parse(u))];if(c)return[i[0],...i.slice(1).map(u=>this.parse(u))]}return i.map(l=>this.parse(l))});if(this.debug(this.pattern,o),this.set=o.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let s=this.set[i];s[0]===""&&s[1]===""&&this.globParts[i][2]==="?"&&typeof s[3]=="string"&&/^[a-z]:$/i.test(s[3])&&(s[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let n of t)for(let o=0;o<n.length;o++)n[o]==="**"&&(n[o]="*");let{optimizationLevel:r=1}=this.options;return r>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):r>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let o=n;for(;r[o+1]==="**";)o++;o!==n&&r.splice(n,o-n)}return r})}levelOneOptimize(t){return t.map(r=>(r=r.reduce((n,o)=>{let i=n[n.length-1];return o==="**"&&i==="**"?n:o===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(n.pop(),n):(n.push(o),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let o=1;o<t.length-1;o++){let i=t[o];o===1&&i===""&&t[0]===""||(i==="."||i==="")&&(r=!0,t.splice(o,1),o--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(r=!0,t.pop())}let n=0;for(;(n=t.indexOf("..",n+1))!==-1;){let o=t[n-1];o&&o!=="."&&o!==".."&&o!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(o))&&(r=!0,t.splice(n-1,2),n-=2)}}while(r);return t.length===0?[""]:t}firstPhasePreProcess(t){let r=!1;do{r=!1;for(let n of t){let o=-1;for(;(o=n.indexOf("**",o+1))!==-1;){let s=o;for(;n[s+1]==="**";)s++;s>o&&n.splice(o+1,s-o);let a=n[o+1],l=n[o+2],c=n[o+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;r=!0,n.splice(o,1);let u=n.slice(0);u[o]="**",t.push(u),o--}if(!this.preserveMultipleSlashes){for(let s=1;s<n.length-1;s++){let a=n[s];s===1&&a===""&&n[0]===""||(a==="."||a==="")&&(r=!0,n.splice(s,1),s--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(r=!0,n.pop())}let i=0;for(;(i=n.indexOf("..",i+1))!==-1;){let s=n[i-1];if(s&&s!=="."&&s!==".."&&s!=="**"){r=!0;let l=i===1&&n[i+1]==="**"?["."]:[];n.splice(i-1,2,...l),n.length===0&&n.push(""),i-=2}}}}while(r);return t}secondPhasePreProcess(t){for(let r=0;r<t.length-1;r++)for(let n=r+1;n<t.length;n++){let o=this.partsMatch(t[r],t[n],!this.preserveMultipleSlashes);if(o){t[r]=[],t[n]=o;break}}return t.filter(r=>r.length)}partsMatch(t,r,n=!1){let o=0,i=0,s=[],a="";for(;o<t.length&&i<r.length;)if(t[o]===r[i])s.push(a==="b"?r[i]:t[o]),o++,i++;else if(n&&t[o]==="**"&&r[i]===t[o+1])s.push(t[o]),o++;else if(n&&r[i]==="**"&&t[o]===r[i+1])s.push(r[i]),i++;else if(t[o]==="*"&&r[i]&&(this.options.dot||!r[i].startsWith("."))&&r[i]!=="**"){if(a==="b")return!1;a="a",s.push(t[o]),o++,i++}else if(r[i]==="*"&&t[o]&&(this.options.dot||!t[o].startsWith("."))&&t[o]!=="**"){if(a==="a")return!1;a="b",s.push(r[i]),o++,i++}else return!1;return t.length===r.length&&s}parseNegate(){if(this.nonegate)return;let t=this.pattern,r=!1,n=0;for(let o=0;o<t.length&&t.charAt(o)==="!";o++)r=!r,n++;n&&(this.pattern=t.slice(n)),this.negate=r}matchOne(t,r,n=!1){let o=0,i=0;if(this.isWindows){let a=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),l=!a&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),c=typeof r[0]=="string"&&/^[a-z]:$/i.test(r[0]),u=!c&&r[0]===""&&r[1]===""&&r[2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3]),d=l?3:a?0:void 0,f=u?3:c?0:void 0;if(typeof d=="number"&&typeof f=="number"){let[p,A]=[t[d],r[f]];p.toLowerCase()===A.toLowerCase()&&(r[f]=p,i=f,o=d)}}let{optimizationLevel:s=1}=this.options;return s>=2&&(t=this.levelTwoFileOptimize(t)),r.includes(wu)?this.#e(t,r,n,o,i):this.#n(t,r,n,o,i)}#e(t,r,n,o,i){let s=r.indexOf(wu,i),a=r.lastIndexOf(wu),[l,c,u]=n?[r.slice(i,s),r.slice(s+1),[]]:[r.slice(i,s),r.slice(s+1,a),r.slice(a+1)];if(l.length){let C=t.slice(o,o+l.length);if(!this.#n(C,l,n,0,0))return!1;o+=l.length,i+=l.length}let d=0;if(u.length){if(u.length+o>t.length)return!1;let C=t.length-u.length;if(this.#n(t,u,n,C,0))d=u.length;else{if(t[t.length-1]!==""||o+u.length===t.length||(C--,!this.#n(t,u,n,C,0)))return!1;d=u.length+1}}if(!c.length){let C=!!d;for(let v=o;v<t.length-d;v++){let R=String(t[v]);if(C=!0,R==="."||R===".."||!this.options.dot&&R.startsWith("."))return!1}return n||C}let f=[[[],0]],p=f[0],A=0,_=[0];for(let C of c)C===wu?(_.push(A),p=[[],0],f.push(p)):(p[0].push(C),A++);let E=f.length-1,S=t.length-d;for(let C of f)C[1]=S-(_[E--]+C[0].length);return!!this.#t(t,f,o,0,n,0,!!d)}#t(t,r,n,o,i,s,a){let l=r[o];if(!l){for(let d=n;d<t.length;d++){a=!0;let f=t[d];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return a}let[c,u]=l;for(;n<=u;){if(this.#n(t.slice(0,n+c.length),c,i,n,0)&&s<this.maxGlobstarRecursion){let p=this.#t(t,r,n+c.length,o+1,i,s+1,a);if(p!==!1)return p}let f=t[n];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1;n++}return i||null}#n(t,r,n,o,i){let s,a,l,c;for(s=o,a=i,c=t.length,l=r.length;s<c&&a<l;s++,a++){this.debug("matchOne loop");let u=r[a],d=t[s];if(this.debug(r,u,d),u===!1||u===wu)return!1;let f;if(typeof u=="string"?(f=d===u,this.debug("string match",u,d,f)):(f=u.test(d),this.debug("pattern match",u,d,f)),!f)return!1}if(s===c&&a===l)return!0;if(s===c)return n;if(a===l)return s===c-1&&t[s]==="";throw new Error("wtf?")}braceExpand(){return tlt(this.pattern,this.options)}parse(t){DU(t);let r=this.options;if(t==="**")return wu;if(t==="")return"";let n,o=null;(n=t.match(ujr))?o=r.dot?pjr:djr:(n=t.match(ejr))?o=(r.nocase?r.dot?ojr:njr:r.dot?rjr:tjr)(n[1]):(n=t.match(mjr))?o=(r.nocase?r.dot?gjr:fjr:r.dot?hjr:Ajr)(n):(n=t.match(ijr))?o=r.dot?ajr:sjr:(n=t.match(ljr))&&(o=cjr);let i=H1.fromGlob(t,this.options).toMMPattern();return o&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:o}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?bjr:r.dot?Sjr:yjr,o=new Set(r.nocase?["i"]:[]),i=t.map(l=>{let c=l.map(d=>{if(d instanceof RegExp)for(let f of d.flags.split(""))o.add(f);return typeof d=="string"?xjr(d):d===wu?wu:d._src});c.forEach((d,f)=>{let p=c[f+1],A=c[f-1];d!==wu||A===wu||(A===void 0?p!==void 0&&p!==wu?c[f+1]="(?:\\/|"+n+"\\/)?"+p:c[f]=n:p===void 0?c[f-1]=A+"(?:\\/|\\/"+n+")?":p!==wu&&(c[f-1]=A+"(?:\\/|\\/"+n+"\\/)"+p,c[f+1]=wu))});let u=c.filter(d=>d!==wu);if(this.partial&&u.length>=1){let d=[];for(let f=1;f<=u.length;f++)d.push(u.slice(0,f).join("/"));return"(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[s,a]=t.length>1?["(?:",")"]:["",""];i="^"+s+i+a+"$",this.partial&&(i="^(?:\\/|"+s+i.slice(1,-1)+a+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,r=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&r)return!0;let n=this.options;this.isWindows&&(t=t.split("\\").join("/"));let o=this.slashSplit(t);this.debug(this.pattern,"split",o);let i=this.set;this.debug(this.pattern,"set",i);let s=o[o.length-1];if(!s)for(let a=o.length-2;!s&&a>=0;a--)s=o[a];for(let a of i){let l=o;if(n.matchBase&&a.length===1&&(l=[s]),this.matchOne(l,a,r))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(t){return Bc.defaults(t).Minimatch}};Bc.AST=H1;Bc.Minimatch=vB;Bc.escape=iEe;Bc.unescape=pC;var olt=Ie(RU(),1);lr();Pe();we();nd();import{readFile as rlt}from"fs/promises";import{existsSync as sEe,readdirSync as wjr,statSync as Rjr}from"fs";import{join as aEe,relative as ilt}from"path";import{homedir as Njr}from"os";function nlt(e){try{let t=(0,olt.default)(e),r=t.data.paths,n=[];return typeof r=="string"?n=r.split(",").map(o=>o.trim()).filter(Boolean):Array.isArray(r)&&(n=r.filter(o=>typeof o=="string")),{paths:n,content:t.content.trim()}}catch(t){return be(t),{paths:[],content:e.trim()}}}function Djr(e,t){return t.length===0?!0:t.some(r=>{try{return Bc(e,r,{matchBase:!0,dot:!0})}catch(n){return be(n),!1}})}function lEe(e){let t=[];try{if(!sEe(e))return t;let r=wjr(e);for(let n of r){let o=aEe(e,n),i=Rjr(o);i.isDirectory()?t.push(...lEe(o)):i.isFile()&&n.endsWith(".md")&&t.push(o)}}catch(r){be(r)}return t}async function Zj(){let e=[];try{let t=aEe(Njr(),Tn,"rules");if(sEe(t)){let r=lEe(t);for(let n of r)try{let o=await rlt(n,"utf-8"),{paths:i,content:s}=nlt(o);i.length>0&&e.push({filePath:n,content:s,paths:i,isProjectRule:!1})}catch(o){be(o)}}}catch(t){be(t)}try{let t=aEe(Oe(),Tn,"rules");if(sEe(t)){let r=lEe(t);for(let n of r)try{let o=await rlt(n,"utf-8"),{paths:i,content:s}=nlt(o);i.length>0&&e.push({filePath:ilt(Oe(),n),content:s,paths:i,isProjectRule:!0})}catch(o){be(o)}}}catch(t){be(t)}return e}function slt(e,t){e=B7(e);let r=B7(Oe()),n=e.startsWith(r)?ilt(r,e):e;return t.filter(o=>Djr(n,o.paths))}function alt(e){return e.length===0?"":e.map(r=>{let n=r.isProjectRule?"project instructions, checked into the codebase":"user's private global instructions for all projects";return`Contents of ${r.filePath} (${n}):
657
657
 
658
658
  ${r.content}`}).join(`
659
659
 
@@ -754,7 +754,7 @@ data: ${JSON.stringify(F)}
754
754
  `);a=O.pop()||"";for(let F of O){let G=F.trim();if(!(!G||G==="data: [DONE]"))if(G.startsWith("data: ")){let P=G.slice(6);try{let $=JSON.parse(P);R($)}catch($){this.logger&&this.logger.error({err:$,line:G},"Failed to parse Gemini SSE chunk")}}else try{let P=JSON.parse(G);R(P)}catch{}}};(async()=>{try{for(;;){let{value:O,done:F}=await s.read();if(F)break;a+=n.decode(O,{stream:!0}),D()}v()}catch(O){i.error(O)}})()}})}convertGeminiResponseToAnthropic(t){this.logger&&this.logger.debug({response:t},"Original Gemini response");try{if(!t.candidates||!t.candidates[0])throw new Error("No candidates found in Gemini response");let r=t.candidates[0],n=[];r.content&&r.content.parts&&r.content.parts.forEach(i=>{if(i.text&&n.push({type:"text",text:i.text}),i.functionCall){let s=`toolu_${jB()}`,a=i.functionCall.thoughtSignature||i.functionCall.thought_signature||null;n.push({type:"tool_use",id:s,name:i.functionCall.name,input:i.functionCall.args||{},thought_signature:a})}}),r.groundingMetadata&&(this.logger&&this.logger.debug({groundingMetadata:r.groundingMetadata},"Processing grounding metadata"),r.groundingMetadata.webSearchQueries&&n.push({type:"text",text:`
755
755
 
756
756
  [Search queries used: ${r.groundingMetadata.webSearchQueries.join(", ")}]`}));let o={id:`msg_${Math.random().toString(36).slice(2)}`,type:"message",role:"assistant",model:t.modelVersion||"gemini",content:n,stop_reason:r.finishReason?r.finishReason==="STOP"&&n.some(i=>i.type==="tool_use")?"tool_use":this.mapGeminiFinishReason(r.finishReason):"end_turn",stop_sequence:null,usage:{input_tokens:t.usageMetadata?.promptTokenCount||0,output_tokens:t.usageMetadata?.candidatesTokenCount||0}};return this.logger&&this.logger.debug({result:o},"Conversion complete, final Anthropic response"),o}catch{throw Xen(`Provider error: ${JSON.stringify(t)}`,500,"provider_error")}}mapGeminiFinishReason(t){switch(t){case"STOP":return"end_turn";case"MAX_TOKENS":return"max_tokens";case"SAFETY":case"RECITATION":return"stop_sequence";default:return"end_turn"}}},ESe=new _Se;var TEt=Ie(SEt(),1);Kt();ji();function Oh(e){return e?typeof e.entries=="function"?Object.fromEntries(e.entries()):{...e}:{}}function yEt(e){let t=String(e?.["x-thinking-level"]??"medium").toLowerCase();return["off","low","medium","high"].includes(t)?t:"medium"}function mAn(e,t){if(t==="off"){delete e.reasoning;return}e.reasoning={effort:t}}function fAn(e,t){if(t==="off"){delete e.reasoning;return}e.reasoning={effort:t,summary:"auto"}}function gAn(e,t="chat"){let r={request:{},response:{},openai:{request:{},response:{}}};return r.request.model=e.request.body.model,r.request.messages=e.request.body.messages,r.request.system=e.request.body.system,r.response.content=e.response.body.content,r.response.usage=e.response.body?.usage,t==="responses"?(r.openai.request.model=e.openai.request.body.model,r.openai.request.input=e.openai.request.body.input,r.openai.response.output=e.openai.response.body?.output,r.openai.response.usage=e.openai.response.body?.usage):(r.openai.request.model=e.openai.request.body.model,r.openai.request.messages=e.openai.request.body.messages,r.openai.response.choices=e.openai.response.body.choices,r.openai.response.usage=e.openai.response.body?.usage),r}function w5(e,t,r){RY(t,e),NY(t,gAn(e,r),r)}function PM(e){let t=[],r=e.getReader(),n,o=new Promise(l=>n=l),i=!1,s=()=>{i||(i=!0,n(Buffer.concat(t).toString("utf8")))};return{stream:new ReadableStream({async pull(l){try{let{done:c,value:u}=await r.read();if(c){l.close(),s();return}t.push(u),l.enqueue(u)}catch(c){l.error(c),s()}},cancel(l){r.cancel(l).catch(()=>{}),s()}}),done:o}}function R5(e){let t=new Headers(e);return t.delete("content-encoding"),t.delete("content-length"),t.delete("transfer-encoding"),t}function VTe(e,t,r,n,o){let i;try{i={type:"error",error:{type:"api_error",message:JSON.parse(o).error?.message??`${e}: ${n}`,code:`${t}_${r}_ERROR`}}}catch{i={type:"error",error:{type:"api_error",message:`${e}: ${n}`,code:`${t}_${r}_ERROR`}}}return new Response(JSON.stringify(i),{status:r,statusText:n,headers:{"Content-Type":"application/json"}})}var CEt=["/v1/messages"];function WTe(e){let t;try{typeof e=="string"?t=new Dx(e):e instanceof Dx?t=e:t=new Dx(e.url)}catch{return""}let r=t.pathname;for(let n of CEt){let o=r.indexOf(n);if(o!==-1)return t.origin+r.slice(0,o)}return t.origin}function BX(e,t){let r=typeof e=="string"?e:e instanceof Dx?e.toString():e.url,n;try{n=new Dx(r).pathname}catch{return!1}return CEt.some(o=>n.includes(o))&&(t.method==="POST"||t.method==="post")}function hAn(e){return async(t,r)=>{if(!BX(t,r))return e(t,r);let n=JSON.parse(r.body),o=await MJ.transformRequestOut(n),i=WTe(t)+"/chat/completions",s=Oh(r.headers),a=s.authorization??s.Authorization??"";mAn(o,yEt(s));let l=await e(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:a},body:JSON.stringify(o),signal:r.signal});if(!l.ok){let E=await l.text();return te(`OpenAI Chat Completions API error: ${l.status}`,{url:i,errorResponse:E}),VTe("OpenAI Chat Completions API error","OPENROUTER",l.status,l.statusText,E)}let c=n.stream===!0,u=s["x-agent-id"],d={request:{url:i,method:r.method,headers:s,body:n},response:{status:l.status,statusText:l.statusText,headers:Oh(l.headers)},openai:{request:{body:o},response:{}}};if(!c){let E=await l.text(),S=new Response(E,{status:l.status,statusText:l.statusText,headers:R5(l.headers)}),C=await MJ.transformResponseIn(S,n),v=await C.text();try{w5({...d,openai:{...d.openai,response:{body:JSON.parse(E)}},response:{...d.response,body:JSON.parse(v)}},u)}catch(R){te("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Chat \u975E\u6D41\u5F0F):",R)}return new Response(v,{status:C.status,statusText:C.statusText,headers:C.headers})}let f=PM(l.body),p=new Response(f.stream,{status:l.status,statusText:l.statusText,headers:R5(l.headers)}),A=await MJ.transformResponseIn(p,n),_=PM(A.body);return Promise.all([f.done,_.done]).then(async([E,S])=>{try{w5({...d,openai:{...d.openai,response:{body:await Jct(E)}},response:{...d.response,body:await b9(S)}},u)}catch(C){te("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Chat \u6D41\u5F0F):"+C?.stack)}}).catch(E=>te("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Chat):"+E)),new Response(_.stream,{status:A.status,statusText:A.statusText,headers:A.headers})}}function AAn(e){return async(t,r)=>{if(!BX(t,r))return e(t,r);let n=JSON.parse(r.body),o=await kJ.transformRequestOut(n),i=Oh(r.headers);fAn(o,yEt(i));let s=JSON.stringify(o),l=WTe(t)+"/responses",c=i.authorization??i.Authorization??"";if(!c)return new Response(JSON.stringify({type:"error",error:{type:"api_error",message:"Missing Authorization header",code:"RESPONSES_AUTH_MISSING"}}),{status:401,headers:{"Content-Type":"application/json"}});let u=await e(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:c,"x-api-key":c.replace(/^Bearer\s+/i,"").trim()},body:s,signal:r.signal});if(!u.ok){let C=await u.text();return te(`OpenAI Responses API error: ${u.status} ${u.statusText}`,{url:l,status:u.status,errorResponse:C}),VTe("OpenAI Responses API error","RESPONSES",u.status,u.statusText,C)}let d=n.stream===!0,f=i["x-agent-id"],p={request:{url:l,method:r.method,headers:i,body:n},response:{status:u.status,statusText:u.statusText,headers:Oh(u.headers)},openai:{request:{body:o},response:{}}};if(!d){let C=await u.text(),v=new Response(C,{status:u.status,statusText:u.statusText,headers:R5(u.headers)}),R=await kJ.transformResponseIn(v,n),D=await R.text();try{w5({...p,openai:{...p.openai,response:{body:JSON.parse(C)}},response:{...p.response,body:JSON.parse(D)}},f,"responses")}catch(O){te("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Responses \u975E\u6D41\u5F0F):",O)}return new Response(D,{status:R.status,statusText:R.statusText,headers:R.headers})}let A=PM(u.body),_=new Response(A.stream,{status:u.status,statusText:u.statusText,headers:R5(u.headers)}),E=await kJ.transformResponseIn(_,n),S=PM(E.body);return Promise.all([A.done,S.done]).then(async([C,v])=>{try{w5({...p,openai:{...p.openai,response:{body:await Kct(C)}},response:{...p.response,body:await b9(v)}},f,"responses")}catch(R){te("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Responses \u6D41\u5F0F):"+R?.stack)}}).catch(C=>te("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Responses):"+C)),new Response(S.stream,{status:E.status,statusText:E.statusText,headers:E.headers})}}function _An(e){return async(t,r)=>{if(!BX(t,r))return e(t,r);let n=JSON.parse(r.body),o=Oh(r.headers),i=await ESe.transformRequestOut(n),s=JSON.stringify(i),a=WTe(t)+`/models/${n.model}:streamGenerateContent?alt=sse`,l=o.authorization??o.Authorization??"",c;try{c=await e(a,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":String(l).replace(/^Bearer\s+/i,"").trim()},body:s,signal:r.signal})}catch(S){throw te("gemini request error:",S),S}if(!c.ok){let S=await c.text();return te(`Gemini API error response: ${c.status} ${c.statusText}`,{url:a,status:c.status,errorResponse:S}),VTe("Gemini API error","Gemini",c.status,c.statusText,S)}let u=n.stream===!0,d=o["x-agent-id"],f={request:{url:a,method:r.method,headers:Oh(r.headers),body:n},response:{status:c.status,statusText:c.statusText,headers:Oh(c.headers)},openai:{request:{body:i},response:{}}},p=PM(c.body),A=new Response(p.stream,{status:c.status,statusText:c.statusText,headers:R5(c.headers)}),_=await ESe.transformResponseIn(A),E=PM(_.body);return Promise.all([p.done,E.done]).then(async([S,C])=>{try{let v=u?Zct(S):JSON.parse(S),R=u?await b9(C):JSON.parse(C);w5({...f,openai:{...f.openai,response:{body:v}},response:{...f.response,body:R}},d)}catch(v){te("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Gemini):"+v?.stack)}}).catch(S=>te("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Gemini):"+S)),new Response(E.stream,{status:_.status,statusText:_.statusText,headers:_.headers})}}function EAn(e){return async(t,r)=>{if(!BX(t,r))return e(t,r);let n=r.body;if(r.body)try{let d=JSON.parse(r.body);n=JSON.stringify(d)}catch{}let o=Oh(r.headers);["1","true"].includes(String(process.env.HAWA_CODE_X_API_KEY_DISABLED??"").toLowerCase())&&(delete o["x-api-key"],delete o["X-API-Key"]),["1","true"].includes(String(process.env.HAWA_CODE_AUTH_DISABLED??"").toLowerCase())&&(delete o.authorization,delete o.Authorization),delete o["content-length"];let a=await e(t,{method:r.method,headers:o,body:n,signal:r.signal});if(!a.ok){let d=await a.text();te(`API error response: ${a.status} ${a.statusText}`,{url:typeof t=="string"?t:t instanceof Dx?t.toString():t.url,status:a.status,errorResponse:d});let f;try{let p=JSON.parse(d);f={type:"error",error:{type:"api_error",message:p.error?.message||p.message||`API error: ${a.statusText}`,code:p.error?.code||p.code||`API_${a.status}_ERROR`}},p.error?.details&&(f.error.details=p.error.details)}catch{f={type:"error",error:{type:"api_error",message:`API error: ${a.statusText}`,code:`API_${a.status}_ERROR`}}}return new Response(JSON.stringify(f),{status:a.status,statusText:a.statusText,headers:{"Content-Type":"application/json"}})}let l=a.clone(),c=!(Object.hasOwn(JSON.parse(n),"stream")&&!JSON.parse(n).stream),u={request:{url:typeof t=="string"?t:t instanceof Dx?t.toString():t.url,method:r.method,headers:Oh(r.headers),body:JSON.parse(n)},response:{status:a.status,statusText:a.statusText,headers:Oh(a.headers)}};return(async()=>{if(c){let p=await a.text();u.response.body=await b9(p)}else u.response.body=await a.json();let f=Oh(r.headers)["x-agent-id"];RY(f,u),NY(f,{request:u.request.body.messages,response:u.response.body.content,usage:u.response.body?.usage})})().catch(d=>te(`\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF:
757
- Stack trace: `+d.stack)),new Response(l.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}var OX=null,zTe=!1;function bAn(){OX=null,zTe=!1}Qt.on("proxy:changed",bAn);function SAn(){if(zTe)return OX;if(zTe=!0,Je().proxy!==!0)return null;let e=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;return e&&(OX=new TEt.ProxyAgent({uri:e}),Dt(`[proxy] using proxy: ${e}`)),OX}function yAn(){let e=SAn();return e?((t,r={})=>global.fetch(t,{...r,dispatcher:e})):global.fetch}function MX(e){let t=e||process.env.API_TYPE,r=yAn();switch(t){case"openai":return hAn(r);case"openai-responses":return AAn(r);case"gemini":return _An(r);default:return EAn(r)}}r_();we();Pe();Pe();var jTe="2.7.18";globalThis.MACRO={VERSION:jTe,PACKAGE_URL:`@dahawa/${Uo}`,README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var kX=process.env.HAWA_CODE_USER_AGENT||`${Uo}/${jTe} (${process.env.USER_TYPE})`;we();we();er();function Du(e,t){let r=[],n=new Set;return e.filter(o=>o.type!=="progress"&&o.type!=="reminder").forEach(o=>{switch(o.type){case"user":{let i=yc(r);if(i?.type==="user"){r[r.length-1]=IEt(i,o);return}r.push(o);return}case"assistant":r.push(o);return;case"insert":{let i=yc(r);i?.type==="user"&&(r[r.length-1]=CAn(i,o));return}case"path_rules":{let i=t?.pathRules;if(!i)return;let s=o.content.paths.filter(u=>!n.has(u));if(s.length===0)return;let a=s.map(u=>i.get(u)).filter(u=>u!==void 0);if(s.forEach(u=>n.add(u)),a.length===0)return;let l=At([{type:"text",text:`<system-rules>
757
+ Stack trace: `+d.stack)),new Response(l.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}var OX=null,zTe=!1;function bAn(){OX=null,zTe=!1}Qt.on("proxy:changed",bAn);function SAn(){if(zTe)return OX;if(zTe=!0,Je().proxy!==!0)return null;let e=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;return e&&(OX=new TEt.ProxyAgent({uri:e}),Dt(`[proxy] using proxy: ${e}`)),OX}function yAn(){let e=SAn();return e?((t,r={})=>global.fetch(t,{...r,dispatcher:e})):global.fetch}function MX(e){let t=e||process.env.API_TYPE,r=yAn();switch(t){case"openai":return hAn(r);case"openai-responses":return AAn(r);case"gemini":return _An(r);default:return EAn(r)}}r_();we();Pe();Pe();var jTe="2.7.19";globalThis.MACRO={VERSION:jTe,PACKAGE_URL:`@dahawa/${Uo}`,README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var kX=process.env.HAWA_CODE_USER_AGENT||`${Uo}/${jTe} (${process.env.USER_TYPE})`;we();we();er();function Du(e,t){let r=[],n=new Set;return e.filter(o=>o.type!=="progress"&&o.type!=="reminder").forEach(o=>{switch(o.type){case"user":{let i=yc(r);if(i?.type==="user"){r[r.length-1]=IEt(i,o);return}r.push(o);return}case"assistant":r.push(o);return;case"insert":{let i=yc(r);i?.type==="user"&&(r[r.length-1]=CAn(i,o));return}case"path_rules":{let i=t?.pathRules;if(!i)return;let s=o.content.paths.filter(u=>!n.has(u));if(s.length===0)return;let a=s.map(u=>i.get(u)).filter(u=>u!==void 0);if(s.forEach(u=>n.add(u)),a.length===0)return;let l=At([{type:"text",text:`<system-rules>
758
758
  ${alt(a)}
759
759
  </system-rules>`}]),c=yc(r);c?.type==="user"?r[r.length-1]=IEt(c,l,{skipTrailingSystemReminders:!0}):r.push(l);return}}}),r}function CAn(e,t){return{...e,message:{...e.message,content:IAn(e.message.content,TAn(t.content.content))}}}function TAn(e){return`
760
760
  <system-reminder>
@@ -1125,7 +1125,7 @@ try {
1125
1125
  `],{encoding:"utf8",maxBuffer:Qvt,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function uwn(){try{let e=o3("where",["pwsh.exe"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0];if(e)return e}catch{}return"powershell.exe"}var dwn="[Image pasted]";function $vt(e){return function(t){return(new Map(e).get(t)??(()=>{}))(t)}}function Yvt({value:e,onChange:t,onSubmit:r,onExit:n,onExitMessage:o,onMessage:i,onHistoryUp:s,onHistoryDown:a,onHistoryReset:l,onCancel:c,onEscape:u,mask:d="",multiline:f=!1,cursorChar:p,invert:A,columns:_,onImagePaste:E,disableCursorMovementForUpDownKeys:S=!1,externalOffset:C,onOffsetChange:v}){let R=C,D=v,O=n3.fromText(e,_,R),[F,G]=(0,qvt.useState)(null);function P(){F&&(clearTimeout(F),G(null),i?.(!1))}let $=uw(W=>{P(),o?.(W,"Ctrl-C")},()=>n?.(),()=>{e&&(t(""),l?.())}),U=uw(W=>{if(u&&!e){u();return}if(c){P(),i?.(!!e&&W,"Press Escape again to cancel");return}P(),i?.(!!e&&W,"Press Escape again to clear")},()=>{if(!(u&&!e)){if(c){c();return}e&&t("")}});function le(){return n3.fromText("",_,0)}let K=uw(W=>o?.(W,"Ctrl-D"),()=>n?.());function k(){return P(),O.text===""?(K(),O):O.del()}function ie(){if(d)return O;let W=Hvt();return W===null?(Gvt()&&(i?.(!0,Uvt),P(),G(setTimeout(()=>{i?.(!1)},4e3))),O):(E?.(W),O.insert(dwn))}let Z=$vt([["a",()=>O.startOfLine()],["b",()=>O.left()],["c",$],["d",k],["e",()=>O.endOfLine()],["f",()=>O.right()],["h",()=>(P(),O.backspace())],["k",()=>O.deleteToLineEnd()],["l",()=>le()],["n",()=>ne()],["p",()=>ee()],["u",()=>O.deleteToLineStart()],["v",ie],["w",()=>O.deleteWordBefore()],["o",ie]]),se=$vt([["b",()=>O.prevWord()],["f",()=>O.nextWord()],["d",()=>O.deleteWordAfter()]]);function X(W){if(f&&O.offset>0&&O.text[O.offset-1]==="\\")return O.backspace().insert(`
1126
1126
  `);if(W.meta||W.shift)return O.insert(`
1127
1127
  `);r?.(e)}function ee(){if(S)return s?.(),O;let W=O.up();return W.equals(O)&&s?.(),W}function ne(){if(S)return a?.(),O;let W=O.down();return W.equals(O)&&a?.(),W}function ue(W,j){if(j.tab)return;if(j.backspace||j.delete||W==="\b"||W==="\x7F"||W==="\b"){let Ke=O.backspace();O.equals(Ke)||(D(Ke.offset),O.text!==Ke.text&&t(Ke.text));return}if(!j.ctrl&&!j.meta&&W.length>1){let Ke=O.insert(W);O.equals(Ke)||(D(Ke.offset),O.text!==Ke.text&&t(Ke.text));return}let Te=Se(j)(W);Te&&(O.equals(Te)||(D(Te.offset),O.text!==Te.text&&t(Te.text)))}function Se(W){if(W.backspace||W.delete)return P(),()=>O.backspace();switch(!0){case W.escape:return u&&!e?()=>(u(),O):U;case(W.leftArrow&&(W.ctrl||W.meta||"fn"in W&&W.fn)):return()=>O.prevWord();case(W.rightArrow&&(W.ctrl||W.meta||"fn"in W&&W.fn)):return()=>O.nextWord();case W.ctrl:return Z;case("home"in W&&W.home):return()=>O.startOfLine();case("end"in W&&W.end):return()=>O.endOfLine();case W.pageDown:return()=>O.endOfLine();case W.pageUp:return()=>O.startOfLine();case W.return:return()=>X(W);case W.meta:return se;case W.upArrow:return ee;case W.downArrow:return ne;case W.leftArrow:return()=>O.left();case W.rightArrow:return()=>O.right()}return function(j){switch(!0){case(j=="\x1B[H"||j=="\x1B[1~"):return O.startOfLine();case(j=="\x1B[F"||j=="\x1B[4~"):return O.endOfLine();case(j==="\b"||j==="\x7F"||j==="\b"):return P(),O.backspace();default:return O.insert(j.replace(/\r/g,`
1128
- `))}}}return{onInput:ue,renderedValue:O.render(p,d,A),offset:R,setOffset:D}}function Kh({value:e,placeholder:t="",focus:r=!0,mask:n,multiline:o=!1,highlightPastedText:i=!1,showCursor:s=!0,onChange:a,onSubmit:l,onExit:c,onHistoryUp:u,onHistoryDown:d,onExitMessage:f,onMessage:p,onHistoryReset:A,onCancel:_,onEscape:E,columns:S,onImagePaste:C,onPaste:v,isDimmed:R=!1,disableCursorMovementForUpDownKeys:D=!1,cursorOffset:O,onChangeCursorOffset:F}){let{onInput:G,renderedValue:P}=Yvt({value:e,onChange:a,onSubmit:l,onExit:c,onExitMessage:f,onMessage:p,onHistoryReset:A,onHistoryUp:u,onHistoryDown:d,onCancel:_,onEscape:E,focus:r,mask:n,multiline:o,cursorChar:s?" ":"",highlightPastedText:i,invert:se=>mt.bgHex("#ffffff").hex("#000000")(se),themeText:se=>mt.hex(re().text)(se),columns:S,onImagePaste:C,disableCursorMovementForUpDownKeys:D,externalOffset:O,onOffsetChange:F}),[$,U]=zvt.default.useState({chunks:[],timeoutId:null}),le=se=>(se&&clearTimeout(se),setTimeout(()=>{U(({chunks:X})=>{let ee=X.join("");return Promise.resolve().then(()=>v(ee)),{chunks:[],timeoutId:null}})},100));ft((se,X)=>{if(v&&(se.length>10||$.timeoutId)){U(({chunks:ee,timeoutId:ne})=>({chunks:[...ee,se],timeoutId:le(ne)}));return}G(se,X)},{isActive:r});let k=t?mt.hex(re().secondaryText)(t):void 0,ie=se=>mt.bgHex("#ffffff").hex("#000000")(se);s&&r&&(k=t.length>0?ie(t[0])+mt.hex(re().secondaryText)(t.slice(1)):ie(" "));let Z=e.length==0&&t;return(0,h.jsx)(I,{wrap:"truncate-end",dimColor:R,children:Z?k:P})}var pwn=["General","Context"];function Vvt({onClose:e}){let[t,r]=(0,Es.useState)(Qr()),n=zc.useRef(Qr()),[o,i]=(0,Es.useState)(0),[s,a]=(0,Es.useState)("General"),l=rs(()=>process.exit(0)),[c,u]=(0,Es.useState)(Je().webServer?.enabled??!1),[d,f]=(0,Es.useState)(Je().proxy??!1),p=zc.useRef(Je().proxy??!1),[A,_]=(0,Es.useState)(Ge.getLazyToolMode()),E=zc.useRef(Ge.getLazyToolMode()),[S,C]=(0,Es.useState)(Ge.getProxyToolSchemaFormat()),v=zc.useRef(Ge.getProxyToolSchemaFormat()),[R,D]=(0,Es.useState)(Je().autoMode?.enabled??!0),O=zc.useRef(Je().autoMode?.enabled??!0),[F,G]=(0,Es.useState)(Je().memo??!1),P=zc.useRef(Je().memo??!1),[$,U]=(0,Es.useState)(Je().headlessBrowser??!1),[le,K]=(0,Es.useState)("not_installed"),[k,ie]=(0,Es.useState)(Je().showWindowTokens??!1),Z=zc.useRef(Je().showWindowTokens??!1),[se,X]=(0,Es.useState)(Je().messageArchiving??!1),ee=zc.useRef(Je().messageArchiving??!1),[ne,ue]=(0,Es.useState)(Je().archiveToolUseInputs??!1),Se=zc.useRef(Je().archiveToolUseInputs??!1),[W,j]=(0,Es.useState)(Je().archiveThinking??!1),Te=zc.useRef(Je().archiveThinking??!1),[Ke,Ze]=(0,Es.useState)(Je().planDirectory??""),je=zc.useRef(Je().planDirectory??""),[tt,yt]=(0,Es.useState)(String(Je().agentDepth??1)),Sr=zc.useRef(String(Je().agentDepth??1)),[Ar,Un]=(0,Es.useState)(String(Ge.getCodemodeMethodsMax())),Yr=zc.useRef(String(Ge.getCodemodeMethodsMax())),[Mr,Wt]=(0,Es.useState)(Je().codemodeSession??!1),An=zc.useRef(Je().codemodeSession??!1),[Ct,eo]=(0,Es.useState)(Je().disableSuggestion??!1),xr=zc.useRef(Je().disableSuggestion??!1),[wr,Bt]=(0,Es.useState)(Je().plugins?.pluginClaudeCompat??!1),hr=zc.useRef(Je().plugins?.pluginClaudeCompat??!1),[dn,Gr]=(0,Es.useState)(null),[lt,Tt]=(0,Es.useState)(""),[jt,Rr]=(0,Es.useState)(0),at=[...process.env.ANTHROPIC_API_KEY?[{id:"apiKey",label:`Use custom API key: ${mt.bold(eC(process.env.ANTHROPIC_API_KEY))}`,value:!!(process.env.ANTHROPIC_API_KEY&&t.customApiKeyResponses?.approved?.includes(eC(process.env.ANTHROPIC_API_KEY))),type:"boolean",onChange(xe){let _e={...Qr()};if(_e.customApiKeyResponses||(_e.customApiKeyResponses={approved:[],rejected:[]}),_e.customApiKeyResponses.approved||(_e.customApiKeyResponses.approved=[]),_e.customApiKeyResponses.rejected||(_e.customApiKeyResponses.rejected=[]),process.env.ANTHROPIC_API_KEY){let rt=eC(process.env.ANTHROPIC_API_KEY);xe?(_e.customApiKeyResponses.approved=[..._e.customApiKeyResponses.approved.filter(nt=>nt!==rt),rt],_e.customApiKeyResponses.rejected=_e.customApiKeyResponses.rejected.filter(nt=>nt!==rt)):(_e.customApiKeyResponses.approved=_e.customApiKeyResponses.approved.filter(nt=>nt!==rt),_e.customApiKeyResponses.rejected=[..._e.customApiKeyResponses.rejected.filter(nt=>nt!==rt),rt])}Ho(_e),r(_e)}}]:[],{id:"verbose",label:"Verbose output",value:t.verbose,type:"boolean",onChange(xe){let _e={...Qr(),verbose:xe};Ho(_e),r(_e)}},{id:"theme",label:"Theme",value:t.theme,options:["light","dark","light-daltonized","dark-daltonized"],type:"enum",onChange(xe){let _e={...Qr(),theme:xe};Ho(_e),r(_e)}},{id:"notifChannel",label:"Notifications",value:t.preferredNotifChannel,options:["iterm2","terminal_bell","iterm2_with_bell","notifications_disabled"],type:"enum",onChange(xe){let _e={...Qr(),preferredNotifChannel:xe};Ho(_e),r(_e)}},{id:"webServer",label:"Web Server",value:c?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";u(_e);let rt=Je(),nt={...rt.webServer,enabled:_e,port:rt.webServer?.port||3210,host:rt.webServer?.host||"127.0.0.1"};kr.updateSetting("webServer",nt),_e?e3.start().catch(()=>{}):e3.stop().catch(()=>{})}},{id:"proxy",label:"Proxy",tab:"Context",value:d?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";f(_e),kr.updateSetting("proxy",_e),Qt.emit("proxy:changed")}},{id:"lazyTool",label:"Lazy Tool",tab:"Context",value:A,options:["off","loading","proxy"],type:"enum",onChange(xe){let _e=xe;_(_e),kr.updateSetting("lazyTool",_e)}},{id:"proxyToolSchemaFormat",label:"Proxy Tool Schema Format",tab:"Context",value:S,options:["ts","json","xml"],type:"enum",onChange(xe){let _e=xe==="ts"?"ts":xe==="xml"?"xml":"json";C(_e),kr.updateSetting("proxyToolSchemaFormat",_e)}},{id:"autoMode",label:"Auto Mode",value:R?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";D(_e);let nt={...Je().autoMode,enabled:_e};kr.updateSetting("autoMode",nt)}},{id:"memo",label:"Memo",tab:"Context",value:F?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";G(_e),kr.updateSetting("memo",_e)}},{id:"headlessBrowser",label:"Headless Browser (JS pages)",value:$?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";U(_e),kr.updateSetting("headlessBrowser",_e),_e?(K("installing"),Aw().then(rt=>{K(rt?"installed":"failed")})):K("not_installed")}},{id:"showWindowTokens",label:"Window tokens usage",value:k?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";ie(_e),kr.updateSetting("showWindowTokens",_e)}},{id:"messageArchiving",label:"Message Archiving",tab:"Context",value:se?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";X(_e),kr.updateSetting("messageArchiving",_e)}},{id:"archiveToolUseInputs",label:"Archive Tool Use Inputs",tab:"Context",value:ne?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";ue(_e),kr.updateSetting("archiveToolUseInputs",_e)}},{id:"archiveThinking",label:"Archive Thinking",tab:"Context",value:W?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";j(_e),kr.updateSetting("archiveThinking",_e)}},{id:"pluginClaudeCompat",label:"Claude Code plugin compatibility",value:wr?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";Bt(_e);let nt={...Je().plugins,pluginClaudeCompat:_e};kr.updateSetting("plugins",nt)}},{id:"planDirectory",label:"Plan directory",value:Ke,placeholder:"Leave empty for default",type:"string",onChange(xe){Ze(xe),kr.updateSetting("planDirectory",xe||void 0)}},{id:"agentDepth",label:"Agent depth",value:tt,placeholder:"1-5",type:"string",onChange(xe){let _e=parseInt(xe,10),rt=Number.isNaN(_e)?1:Math.min(5,Math.max(1,_e)),nt=String(rt);yt(nt),kr.updateSetting("agentDepth",rt)}},{id:"codemodeMethodsMax",label:"Codemode methods max",value:Ar,placeholder:"1-100",type:"string",onChange(xe){let _e=parseInt(xe,10),rt=Number.isNaN(_e)?20:Math.min(100,Math.max(1,_e)),nt=String(rt);Un(nt),kr.updateSetting("codemodeMethodsMax",rt)}},{id:"codemodeSession",label:"Codemode Session Storage",value:Mr?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";Wt(_e),kr.updateSetting("codemodeSession",_e)}},{id:"disableSuggestion",label:"Suggestion",value:Ct?"off":"on",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="off";eo(_e),kr.updateSetting("disableSuggestion",_e)}}],Qe=at.filter(xe=>(xe.tab??"General")===s);return ft((xe,_e)=>{if(_e.escape){let nt=[],Vn=!!(process.env.ANTHROPIC_API_KEY&&n.current.customApiKeyResponses?.approved?.includes(eC(process.env.ANTHROPIC_API_KEY))),ar=!!(process.env.ANTHROPIC_API_KEY&&t.customApiKeyResponses?.approved?.includes(eC(process.env.ANTHROPIC_API_KEY)));Vn!==ar&&nt.push(` \u23BF ${ar?"Enabled":"Disabled"} custom API key`),t.verbose!==n.current.verbose&&nt.push(` \u23BF Set verbose to ${mt.bold(t.verbose)}`),t.theme!==n.current.theme&&nt.push(` \u23BF Set theme to ${mt.bold(t.theme)}`),t.preferredNotifChannel!==n.current.preferredNotifChannel&&nt.push(` \u23BF Set notifications to ${mt.bold(t.preferredNotifChannel)}`),d!==p.current&&nt.push(` \u23BF Set proxy to ${mt.bold(d?"on":"off")}`),A!==E.current&&nt.push(` \u23BF Set lazy tool to ${mt.bold(A)}`),S!==v.current&&nt.push(` \u23BF Set proxy tool schema format to ${mt.bold(S)}`),R!==O.current&&nt.push(` \u23BF Set auto mode to ${mt.bold(R?"on":"off")}`),F!==P.current&&nt.push(` \u23BF Set memo to ${mt.bold(F?"on":"off")}`),$!==Je().headlessBrowser&&nt.push(` \u23BF Set headless browser to ${mt.bold($?"on":"off")}`),k!==Z.current&&nt.push(` \u23BF Set window tokens usage to ${mt.bold(k?"on":"off")}`),se!==ee.current&&nt.push(` \u23BF Set message archiving to ${mt.bold(se?"on":"off")}`),ne!==Se.current&&nt.push(` \u23BF Set archive tool use inputs to ${mt.bold(ne?"on":"off")}`),W!==Te.current&&nt.push(` \u23BF Set archive thinking to ${mt.bold(W?"on":"off")}`),wr!==hr.current&&nt.push(` \u23BF Set Claude Code plugin compatibility to ${mt.bold(wr?"on":"off")}`),Ke!==je.current&&nt.push(` \u23BF Set plan directory to ${mt.bold(Ke||"default")}`),tt!==Sr.current&&nt.push(` \u23BF Set agent depth to ${mt.bold(tt)}`),Ar!==Yr.current&&nt.push(` \u23BF Set codemode methods max to ${mt.bold(Ar)}`),Mr!==An.current&&nt.push(` \u23BF Set codemode session storage to ${mt.bold(Mr?"on":"off")}`),Ct!==xr.current&&nt.push(` \u23BF Set suggestion to ${mt.bold(Ct?"off":"on")}`),nt.length>0&&console.log(mt.gray(nt.join(`
1128
+ `))}}}return{onInput:ue,renderedValue:O.render(p,d,A),offset:R,setOffset:D}}function Kh({value:e,placeholder:t="",focus:r=!0,mask:n,multiline:o=!1,highlightPastedText:i=!1,showCursor:s=!0,onChange:a,onSubmit:l,onExit:c,onHistoryUp:u,onHistoryDown:d,onExitMessage:f,onMessage:p,onHistoryReset:A,onCancel:_,onEscape:E,columns:S,onImagePaste:C,onPaste:v,isDimmed:R=!1,disableCursorMovementForUpDownKeys:D=!1,cursorOffset:O,onChangeCursorOffset:F}){let{onInput:G,renderedValue:P}=Yvt({value:e,onChange:a,onSubmit:l,onExit:c,onExitMessage:f,onMessage:p,onHistoryReset:A,onHistoryUp:u,onHistoryDown:d,onCancel:_,onEscape:E,focus:r,mask:n,multiline:o,cursorChar:s?" ":"",highlightPastedText:i,invert:se=>mt.bgHex("#ffffff").hex("#000000")(se),themeText:se=>mt.hex(re().text)(se),columns:S,onImagePaste:C,disableCursorMovementForUpDownKeys:D,externalOffset:O,onOffsetChange:F}),[$,U]=zvt.default.useState({chunks:[],timeoutId:null}),le=se=>(se&&clearTimeout(se),setTimeout(()=>{U(({chunks:X})=>{let ee=X.join("");return Promise.resolve().then(()=>v(ee)),{chunks:[],timeoutId:null}})},100));ft((se,X)=>{if(v&&(se.length>10||$.timeoutId)){U(({chunks:ee,timeoutId:ne})=>({chunks:[...ee,se],timeoutId:le(ne)}));return}G(se,X)},{isActive:r});let k=t?mt.hex(re().secondaryText)(t):void 0,ie=se=>mt.bgHex("#ffffff").hex("#000000")(se);s&&r&&(k=t.length>0?ie(t[0])+mt.hex(re().secondaryText)(t.slice(1)):ie(" "));let Z=e.length==0&&t;return(0,h.jsx)(I,{wrap:"truncate-end",dimColor:R,children:Z?k:P})}var pwn=["General","Context"];function Vvt({onClose:e}){let[t,r]=(0,Es.useState)(Qr()),n=zc.useRef(Qr()),[o,i]=(0,Es.useState)(0),[s,a]=(0,Es.useState)("General"),l=rs(()=>process.exit(0)),[c,u]=(0,Es.useState)(Je().webServer?.enabled??!1),[d,f]=(0,Es.useState)(Je().proxy??!1),p=zc.useRef(Je().proxy??!1),[A,_]=(0,Es.useState)(Ge.getLazyToolMode()),E=zc.useRef(Ge.getLazyToolMode()),[S,C]=(0,Es.useState)(Ge.getProxyToolSchemaFormat()),v=zc.useRef(Ge.getProxyToolSchemaFormat()),[R,D]=(0,Es.useState)(Je().autoMode?.enabled??!0),O=zc.useRef(Je().autoMode?.enabled??!0),[F,G]=(0,Es.useState)(Je().memo??!1),P=zc.useRef(Je().memo??!1),[$,U]=(0,Es.useState)(Je().headlessBrowser??!1),[le,K]=(0,Es.useState)("not_installed"),[k,ie]=(0,Es.useState)(Je().showWindowTokens??!1),Z=zc.useRef(Je().showWindowTokens??!1),[se,X]=(0,Es.useState)(Je().messageArchiving??!1),ee=zc.useRef(Je().messageArchiving??!1),[ne,ue]=(0,Es.useState)(Je().archiveToolUseInputs??!1),Se=zc.useRef(Je().archiveToolUseInputs??!1),[W,j]=(0,Es.useState)(Je().archiveThinking??!1),Te=zc.useRef(Je().archiveThinking??!1),[Ke,Ze]=(0,Es.useState)(Je().planDirectory??""),je=zc.useRef(Je().planDirectory??""),[tt,yt]=(0,Es.useState)(String(Je().agentDepth??1)),Sr=zc.useRef(String(Je().agentDepth??1)),[Ar,Un]=(0,Es.useState)(String(Ge.getCodemodeMethodsMax())),Yr=zc.useRef(String(Ge.getCodemodeMethodsMax())),[Mr,Wt]=(0,Es.useState)(Je().codemodeSession??!1),An=zc.useRef(Je().codemodeSession??!1),[Ct,eo]=(0,Es.useState)(Je().disableSuggestion??!1),xr=zc.useRef(Je().disableSuggestion??!1),[wr,Bt]=(0,Es.useState)(Je().plugins?.pluginClaudeCompat??!1),hr=zc.useRef(Je().plugins?.pluginClaudeCompat??!1),[dn,Gr]=(0,Es.useState)(null),[lt,Tt]=(0,Es.useState)(""),[jt,Rr]=(0,Es.useState)(0),at=[...process.env.ANTHROPIC_API_KEY?[{id:"apiKey",label:`Use custom API key: ${mt.bold(eC(process.env.ANTHROPIC_API_KEY))}`,value:!!(process.env.ANTHROPIC_API_KEY&&t.customApiKeyResponses?.approved?.includes(eC(process.env.ANTHROPIC_API_KEY))),type:"boolean",onChange(xe){let _e={...Qr()};if(_e.customApiKeyResponses||(_e.customApiKeyResponses={approved:[],rejected:[]}),_e.customApiKeyResponses.approved||(_e.customApiKeyResponses.approved=[]),_e.customApiKeyResponses.rejected||(_e.customApiKeyResponses.rejected=[]),process.env.ANTHROPIC_API_KEY){let rt=eC(process.env.ANTHROPIC_API_KEY);xe?(_e.customApiKeyResponses.approved=[..._e.customApiKeyResponses.approved.filter(nt=>nt!==rt),rt],_e.customApiKeyResponses.rejected=_e.customApiKeyResponses.rejected.filter(nt=>nt!==rt)):(_e.customApiKeyResponses.approved=_e.customApiKeyResponses.approved.filter(nt=>nt!==rt),_e.customApiKeyResponses.rejected=[..._e.customApiKeyResponses.rejected.filter(nt=>nt!==rt),rt])}Ho(_e),r(_e)}}]:[],{id:"verbose",label:"Verbose output",value:t.verbose,type:"boolean",onChange(xe){let _e={...Qr(),verbose:xe};Ho(_e),r(_e)}},{id:"theme",label:"Theme",value:t.theme,options:["light","dark","light-daltonized","dark-daltonized"],type:"enum",onChange(xe){let _e={...Qr(),theme:xe};Ho(_e),r(_e)}},{id:"notifChannel",label:"Notifications",value:t.preferredNotifChannel,options:["iterm2","terminal_bell","iterm2_with_bell","notifications_disabled"],type:"enum",onChange(xe){let _e={...Qr(),preferredNotifChannel:xe};Ho(_e),r(_e)}},{id:"webServer",label:"Web Server",value:c?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";u(_e);let rt=Je(),nt={...rt.webServer,enabled:_e,port:rt.webServer?.port||3210,host:rt.webServer?.host||"127.0.0.1"};kr.updateSetting("webServer",nt),_e?e3.start().catch(()=>{}):e3.stop().catch(()=>{})}},{id:"proxy",label:"Proxy",value:d?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";f(_e),kr.updateSetting("proxy",_e),Qt.emit("proxy:changed")}},{id:"lazyTool",label:"Lazy Tool",tab:"Context",value:A,options:["off","loading","proxy"],type:"enum",onChange(xe){let _e=xe;_(_e),kr.updateSetting("lazyTool",_e)}},{id:"proxyToolSchemaFormat",label:"Proxy Tool Schema Format",tab:"Context",value:S,options:["ts","json","xml"],type:"enum",onChange(xe){let _e=xe==="ts"?"ts":xe==="xml"?"xml":"json";C(_e),kr.updateSetting("proxyToolSchemaFormat",_e)}},{id:"autoMode",label:"Auto Mode",value:R?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";D(_e);let nt={...Je().autoMode,enabled:_e};kr.updateSetting("autoMode",nt)}},{id:"headlessBrowser",label:"Headless Browser (JS pages)",value:$?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";U(_e),kr.updateSetting("headlessBrowser",_e),_e?(K("installing"),Aw().then(rt=>{K(rt?"installed":"failed")})):K("not_installed")}},{id:"showWindowTokens",label:"Window tokens usage",value:k?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";ie(_e),kr.updateSetting("showWindowTokens",_e)}},{id:"messageArchiving",label:"Message Archiving",tab:"Context",value:se?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";X(_e),kr.updateSetting("messageArchiving",_e)}},{id:"archiveToolUseInputs",label:"Archive Tool Use Inputs",tab:"Context",value:ne?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";ue(_e),kr.updateSetting("archiveToolUseInputs",_e)}},{id:"archiveThinking",label:"Archive Thinking",tab:"Context",value:W?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";j(_e),kr.updateSetting("archiveThinking",_e)}},{id:"pluginClaudeCompat",label:"Claude Code plugin compatibility",value:wr?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";Bt(_e);let nt={...Je().plugins,pluginClaudeCompat:_e};kr.updateSetting("plugins",nt)}},{id:"planDirectory",label:"Plan directory",value:Ke,placeholder:"Leave empty for default",type:"string",onChange(xe){Ze(xe),kr.updateSetting("planDirectory",xe||void 0)}},{id:"agentDepth",label:"Agent depth",value:tt,placeholder:"1-5",type:"string",onChange(xe){let _e=parseInt(xe,10),rt=Number.isNaN(_e)?1:Math.min(5,Math.max(1,_e)),nt=String(rt);yt(nt),kr.updateSetting("agentDepth",rt)}},{id:"codemodeMethodsMax",label:"Codemode methods max",value:Ar,placeholder:"1-100",type:"string",onChange(xe){let _e=parseInt(xe,10),rt=Number.isNaN(_e)?20:Math.min(100,Math.max(1,_e)),nt=String(rt);Un(nt),kr.updateSetting("codemodeMethodsMax",rt)}},{id:"codemodeSession",label:"Codemode Session Storage",value:Mr?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";Wt(_e),kr.updateSetting("codemodeSession",_e)}},{id:"disableSuggestion",label:"Suggestion",value:Ct?"off":"on",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="off";eo(_e),kr.updateSetting("disableSuggestion",_e)}},{id:"memo",label:"Memo",tab:"Context",value:F?"on":"off",options:["off","on"],type:"enum",onChange(xe){let _e=xe==="on";G(_e),kr.updateSetting("memo",_e)}}],Qe=at.filter(xe=>(xe.tab??"General")===s);return ft((xe,_e)=>{if(_e.escape){let nt=[],Vn=!!(process.env.ANTHROPIC_API_KEY&&n.current.customApiKeyResponses?.approved?.includes(eC(process.env.ANTHROPIC_API_KEY))),ar=!!(process.env.ANTHROPIC_API_KEY&&t.customApiKeyResponses?.approved?.includes(eC(process.env.ANTHROPIC_API_KEY)));Vn!==ar&&nt.push(` \u23BF ${ar?"Enabled":"Disabled"} custom API key`),t.verbose!==n.current.verbose&&nt.push(` \u23BF Set verbose to ${mt.bold(t.verbose)}`),t.theme!==n.current.theme&&nt.push(` \u23BF Set theme to ${mt.bold(t.theme)}`),t.preferredNotifChannel!==n.current.preferredNotifChannel&&nt.push(` \u23BF Set notifications to ${mt.bold(t.preferredNotifChannel)}`),d!==p.current&&nt.push(` \u23BF Set proxy to ${mt.bold(d?"on":"off")}`),A!==E.current&&nt.push(` \u23BF Set lazy tool to ${mt.bold(A)}`),S!==v.current&&nt.push(` \u23BF Set proxy tool schema format to ${mt.bold(S)}`),R!==O.current&&nt.push(` \u23BF Set auto mode to ${mt.bold(R?"on":"off")}`),F!==P.current&&nt.push(` \u23BF Set memo to ${mt.bold(F?"on":"off")}`),$!==Je().headlessBrowser&&nt.push(` \u23BF Set headless browser to ${mt.bold($?"on":"off")}`),k!==Z.current&&nt.push(` \u23BF Set window tokens usage to ${mt.bold(k?"on":"off")}`),se!==ee.current&&nt.push(` \u23BF Set message archiving to ${mt.bold(se?"on":"off")}`),ne!==Se.current&&nt.push(` \u23BF Set archive tool use inputs to ${mt.bold(ne?"on":"off")}`),W!==Te.current&&nt.push(` \u23BF Set archive thinking to ${mt.bold(W?"on":"off")}`),wr!==hr.current&&nt.push(` \u23BF Set Claude Code plugin compatibility to ${mt.bold(wr?"on":"off")}`),Ke!==je.current&&nt.push(` \u23BF Set plan directory to ${mt.bold(Ke||"default")}`),tt!==Sr.current&&nt.push(` \u23BF Set agent depth to ${mt.bold(tt)}`),Ar!==Yr.current&&nt.push(` \u23BF Set codemode methods max to ${mt.bold(Ar)}`),Mr!==An.current&&nt.push(` \u23BF Set codemode session storage to ${mt.bold(Mr?"on":"off")}`),Ct!==xr.current&&nt.push(` \u23BF Set suggestion to ${mt.bold(Ct?"off":"on")}`),nt.length>0&&console.log(mt.gray(nt.join(`
1129
1129
  `))),e();return}function rt(){let nt=Qe[o];if(!(!nt||!nt.onChange)){if(nt.type==="boolean"){nt.onChange(!nt.value);return}if(nt.type==="enum"){let ar=(nt.options.indexOf(nt.value)+1)%nt.options.length;nt.onChange(nt.options[ar]);return}if(nt.type==="string"){Gr(nt.id),Tt(nt.value);return}}}if(_e.return||xe===" "){rt();return}_e.upArrow&&i(nt=>Math.max(0,nt-1)),_e.downArrow&&i(nt=>Math.min(Qe.length-1,nt+1)),(_e.leftArrow||_e.rightArrow)&&(a(nt=>nt==="General"?"Context":"General"),i(0))},{isActive:dn===null}),(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(x,{flexDirection:"column",borderStyle:"round",borderColor:re().secondaryBorder,paddingX:1,marginTop:1,children:[(0,h.jsxs)(x,{flexDirection:"column",minHeight:2,marginBottom:1,children:[(0,h.jsx)(I,{bold:!0,children:"Settings"}),(0,h.jsxs)(I,{dimColor:!0,children:["Configure ",it," preferences"]})]}),(0,h.jsx)(x,{gap:3,marginBottom:1,children:pwn.map(xe=>(0,h.jsx)(I,{bold:xe===s,color:xe===s?"blue":void 0,children:xe===s?`[ ${xe} ]`:` ${xe} `},xe))}),Qe.map((xe,_e)=>{let rt=_e===o;return(0,h.jsxs)(x,{height:2,minHeight:2,children:[(0,h.jsx)(x,{width:44,children:(0,h.jsxs)(I,{color:rt?"blue":void 0,children:[rt?nr.pointer:" "," ",xe.label]})}),(0,h.jsxs)(x,{children:[xe.type==="boolean"?(0,h.jsx)(I,{color:rt?"blue":void 0,children:xe.value.toString()}):xe.type==="string"&&dn===xe.id?(0,h.jsx)(Kh,{value:lt,onChange:Tt,onSubmit:nt=>{let Vn=at.find(ar=>ar.id===xe.id);Vn&&Vn.type==="string"&&Vn.onChange(nt),Gr(null),Rr(0)},onCancel:()=>{Gr(null),Tt(""),Rr(0)},placeholder:xe.placeholder,columns:Math.max(20,process.stdout.columns-50),cursorOffset:jt,onChangeCursorOffset:Rr}):(0,h.jsxs)(I,{color:(xe.id==="webServer"||xe.id==="proxy"||xe.id==="autoMode"||xe.id==="memo"||xe.id==="headlessBrowser"||xe.id==="showWindowTokens"||xe.id==="messageArchiving"||xe.id==="archiveToolUseInputs"||xe.id==="archiveThinking"||xe.id==="codemodeSession"||xe.id==="pluginClaudeCompat"||xe.id==="disableSuggestion")&&xe.value==="on"||xe.id==="lazyTool"&&xe.value!=="off"?"green":rt?"blue":void 0,children:[xe.id==="lazyTool"&&xe.value==="loading"?"load":xe.id==="headlessBrowser"&&xe.value==="on"&&le==="installing"?"installing...":xe.id==="headlessBrowser"&&xe.value==="on"&&le==="failed"?"on (install failed)":xe.value.toString(),xe.id==="webServer"&&xe.value==="on"?` (${e3.getUrl()})`:""]}),xe.id==="headlessBrowser"&&xe.value==="on"&&le!=="installed"&&(0,h.jsx)(I,{dimColor:!0,children:" manual install: npx -y playwright-core@1.64.1 install chromium"})]})]},xe.id)})]}),(0,h.jsx)(x,{marginLeft:3,children:(0,h.jsx)(I,{dimColor:!0,children:l.pending?(0,h.jsxs)(h.Fragment,{children:["Press ",l.keyName," again to exit"]}):dn?(0,h.jsx)(h.Fragment,{children:"Enter to save \xB7 Esc to cancel"}):(0,h.jsx)(h.Fragment,{children:"\u2190/\u2192 switch tab \xB7 \u2191/\u2193 to select \xB7 Enter/Space to change \xB7 Esc to close"})})})]})}var mwn={type:"local-jsx",name:"config",description:()=>"Open config panel",isEnabled:!0,isHidden:!1,async call(e){return(0,h.jsx)(Vvt,{onClose:e})},userFacingName(){return"config"}},Wvt=mwn;function _w(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function jvt(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let r=Math.floor(t/60),n=t%60;return`${r}m ${n.toFixed(0)}s`}function Kvt(e){return`${e.toFixed(1)}%`}function Jvt({costUSD:e,durationMs:t,apiDurationMs:r,inputTokens:n,outputTokens:o,cacheCreationTokens:i,cacheReadTokens:s,currentContextTokens:a,contextLimit:l,onDone:c}){let u=re();ft((A,_)=>{_.escape&&c()});let d=n+i+s,f=d>0?s/d*100:0,p=l>0?a/l*100:0;return(0,h.jsxs)(x,{flexDirection:"column",borderStyle:"round",paddingLeft:1,paddingRight:1,borderColor:u.secondaryBorder,children:[(0,h.jsx)(x,{marginBottom:1,flexDirection:"column",children:(0,h.jsx)(I,{bold:!0,children:"Session Cost & Usage"})}),(0,h.jsx)(x,{flexDirection:"column",marginBottom:1,children:(0,h.jsxs)(I,{children:[(0,h.jsx)(I,{dimColor:!0,children:"Cost: "}),(0,h.jsxs)(I,{children:["$",e.toFixed(4)]})]})}),(0,h.jsxs)(x,{flexDirection:"column",marginBottom:1,children:[(0,h.jsx)(I,{dimColor:!0,children:"Session Tokens"}),(0,h.jsxs)(x,{marginLeft:2,flexDirection:"column",children:[(0,h.jsxs)(I,{children:[(0,h.jsx)(I,{children:"Input: "}),(0,h.jsx)(I,{bold:!0,children:_w(d)}),(0,h.jsxs)(I,{dimColor:!0,children:[" (uncached: ",_w(n),")"]})]}),(0,h.jsxs)(I,{children:[(0,h.jsx)(I,{children:"Output: "}),(0,h.jsx)(I,{bold:!0,children:_w(o)})]})]})]}),(0,h.jsx)(x,{flexDirection:"column",marginBottom:1,children:(0,h.jsxs)(I,{children:[(0,h.jsx)(I,{dimColor:!0,children:"Context Window: "}),(0,h.jsx)(I,{bold:!0,children:Kvt(p)}),(0,h.jsxs)(I,{dimColor:!0,children:[" (",_w(a)," / ",_w(l)," tokens)"]})]})}),(0,h.jsx)(x,{flexDirection:"column",marginBottom:1,children:(0,h.jsxs)(I,{children:[(0,h.jsx)(I,{dimColor:!0,children:"Cache Hit Rate: "}),(0,h.jsx)(I,{bold:!0,children:Kvt(f)}),(0,h.jsxs)(I,{dimColor:!0,children:[" ","(read: ",_w(s),", creation:"," ",_w(i),")"]})]})}),(0,h.jsxs)(x,{flexDirection:"column",marginBottom:1,children:[(0,h.jsx)(I,{dimColor:!0,children:"Duration"}),(0,h.jsxs)(x,{marginLeft:2,flexDirection:"column",children:[(0,h.jsxs)(I,{children:[(0,h.jsx)(I,{children:"API: "}),(0,h.jsx)(I,{bold:!0,children:jvt(r)})]}),(0,h.jsxs)(I,{children:[(0,h.jsx)(I,{children:"Wall: "}),(0,h.jsx)(I,{bold:!0,children:jvt(t)})]})]})]}),(0,h.jsx)(x,{marginTop:1,children:(0,h.jsx)(I,{dimColor:!0,children:"Esc to close"})})]})}var fwn={type:"local-jsx",name:"cost",description:()=>"Show session cost, token usage, context window, and cache rate",isEnabled:!0,isHidden:!1,disableCancel:!0,async call(e){let t=_1(),r=2e5;try{r=await P_()}catch{}return(0,h.jsx)(Jvt,{costUSD:VO(),durationMs:z7(),apiDurationMs:Ktt(),inputTokens:t.inputTokens,outputTokens:t.outputTokens,cacheCreationTokens:t.cacheCreationTokens,cacheReadTokens:t.cacheReadTokens,currentContextTokens:Ztt(),contextLimit:r,onDone:()=>e()})},userFacingName(){return"cost"}},Zvt=fwn;var ext=Ie(X1t(),1);o4();Pe();var Zwn=4;function Xwn(e){let t=[],r=e.indexOf("<context");if(r>0){let l=e.slice(0,r).trim();l&&t.push({title:"Core Sysprompt",content:l})}let n=r,o="",i=/<context\s+name="([^"]*)">([\s\S]*?)<\/context>/g,s;for(;(s=i.exec(e))!==null;){s.index>n&&(o+=e.slice(n,s.index));let[,l="Unnamed Section",c=""]=s;t.push({title:l==="codeStyle"?`CodeStyle + ${Qo}'s`:l,content:c.trim()}),n=s.index+s[0].length}n<e.length&&(o+=e.slice(n));let a=o.trim();return a&&t.push({title:"Non-contextualized Content",content:a}),t}function Dk(e){let r=e/Zwn/1e3;return`${Math.round(r*10)/10}k`}function Ok(e){let t=e/1024;return`${Math.round(t*10)/10}kb`}function eRn(e,t,r,n){let o=new ext.default({head:["Component","Tokens","Size","% Used"],style:{head:["bold"]},chars:{mid:"\u2500","left-mid":"\u251C","mid-mid":"\u253C","right-mid":"\u2524"}}),i=JSON.stringify(n),s=JSON.stringify(r),a=e.length+s.length+i.length,l=c=>`${Math.round(c/a*100)}%`;o.push(["System prompt",Dk(e.length),Ok(e.length),l(e.length)]);for(let c of t)o.push([` ${c.title}`,Dk(c.content.length),Ok(c.content.length),l(c.content.length)]);o.push(["Tool definitions",Dk(s.length),Ok(s.length),l(s.length)]);for(let c of r)o.push([` ${c.name}`,Dk(c.description.length),Ok(c.description.length),l(c.description.length)]);return o.push(["Messages",Dk(i.length),Ok(i.length),l(i.length)],["Total",Dk(a),Ok(a),"100%"]),o.toString()}var tRn={name:"ctx-viz",description:()=>"[ANT-ONLY] Show token usage breakdown for the current conversation context",isEnabled:process.env.USER_TYPE==="ant",isHidden:!1,type:"local",userFacingName(){return this.name},async call(e,t){let[r,n]=await Promise.all([Vh(),qo()]),o=t.options.tools,i=r.join(`
1130
1130
  `);for(let[c,u]of Object.entries(n))i+=`
1131
1131
  <context name="${c}">${u}</context>`;let s=o.map(c=>{let u=c.prompt({},t),d=JSON.stringify("inputJSONSchema"in c&&c.inputJSONSchema?c.inputJSONSchema:fS(c.inputSchema));return{name:c.name,description:`${u}
@@ -3484,7 +3484,7 @@ Files modified by other users:
3484
3484
  \xB7 Design an implementation strategy
3485
3485
  \xB7 Present a plan for your approval
3486
3486
 
3487
- No code changes will be made until you approve the plan.`})}),xce.map((o,i)=>(0,h.jsx)(x,{flexDirection:"row",marginLeft:2,children:(0,h.jsxs)(I,{color:t===i?n.highlight:n.text,children:[t===i?"\u276F":" "," ",o.label]})},o.value))]})};var Xlr=Ie(Ve(),1);Pe();Om();var wce=[{label:"Yes, and auto-accept edits",value:"auto",description:"Proceed with the plan and auto-accept all edits"},{label:"Yes, and manually approve edits",value:"manual",description:"Proceed with the plan but manually approve each edit"},{label:"No, keep planning",value:"reject",description:"Reject the plan and continue planning"}],ecr=({plan:e,context:t,onApprove:r,onReject:n})=>{let[o,i]=Xlr.useState(0),s=Fn.getCurrentPlanFilePath();ft((l,c)=>{if(c.upArrow)i(u=>u>0?u-1:wce.length-1);else if(c.downArrow)i(u=>u<wce.length-1?u+1:0);else if(c.return){let u=wce[o];u.value==="auto"?r(!1):u.value==="manual"?r(!0):n()}else c.ctrl&&l==="o"&&s?Kk(s,{wait:!1}):c.escape&&n()});let a=re();return(0,h.jsxs)(x,{flexDirection:"column",marginY:1,children:[(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:a.info,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:a.info,children:"Ready to code?"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsxs)(I,{bold:!0,color:a.info,children:["Here is ",it,"'s plan:"]})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{color:a.info,children:"\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{color:a.text,children:e})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{color:a.info,children:"\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:a.info,children:"Would you like to proceed?"})}),wce.map((l,c)=>(0,h.jsxs)(x,{flexDirection:"row",marginLeft:2,children:[(0,h.jsxs)(I,{color:o===c?a.highlight:a.text,children:[o===c?"\u276F":" "," ",l.label]}),(0,h.jsxs)(I,{dimColor:!0,children:[" - ",l.description]})]},l.value)),s&&(0,h.jsx)(x,{marginTop:1,children:(0,h.jsxs)(I,{dimColor:!0,children:["ctrl-o to edit \xB7 ",s]})})]})};var tcr=Ie(Ve(),1);Pe();var Rce=[{label:"Yes",value:"yes"},{label:"No",value:"no"}],rcr=({onConfirm:e,onCancel:t})=>{let[r,n]=tcr.useState(0);ft((s,a)=>{a.upArrow?n(l=>l>0?l-1:Rce.length-1):a.downArrow?n(l=>l<Rce.length-1?l+1:0):a.return?Rce[r].value==="yes"?e():t():a.escape&&t()});let o=re(),{columns:i}=zo();return(0,h.jsxs)(x,{flexDirection:"column",marginY:1,children:[(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:o.info,children:"\u2500".repeat(Math.max(i-2,10))})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:o.info,children:"Exit plan mode?"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsxs)(I,{color:o.text,children:[it," wants to exit plan mode"]})}),Rce.map((s,a)=>(0,h.jsx)(x,{flexDirection:"row",marginLeft:2,children:(0,h.jsxs)(I,{color:r===a?o.highlight:o.text,children:[r===a?"\u276F":" "," ",a+1,". ",s.label]})},s.value))]})};var ncr=Ie(Ve(),1);we();function ocr(e){(0,ncr.useEffect)(()=>{tm(e.filter(t=>t.type!=="progress"))},[e])}ra();gk();we();var scr=Ie(Ve(),1);var s3e=Ie(Ve(),1);function i3e({debug:e,erroredToolUseIDs:t,inProgressToolUseIDs:r,message:n,normalizedMessages:o,tools:i,unresolvedToolUseIDs:s,verbose:a}){let{columns:l}=zo();return Ln([n]).filter(c=>c.type==="assistant").map((c,u)=>(0,h.jsxs)(x,{flexDirection:"column",children:[(0,h.jsx)(wE,{addMargin:!1,erroredToolUseIDs:t,debug:e,inProgressToolUseIDs:r,message:c,messages:o,shouldAnimate:!1,shouldShowDot:!0,tools:i,unresolvedToolUseIDs:s,verbose:a,width:l/2-6}),(0,h.jsx)(pmo,{message:c,verbose:a})]},u))}function pmo({message:e,verbose:t}){let{columns:r}=zo();if(e.type!=="assistant")return null;let n=e.message.content[0];switch(n.type){case"tool_use":switch(n.name){case Xc.name:{let o=Xc.inputSchema.safeParse(n.input);return o.success?(0,h.jsx)(rce,{file_path:o.data.file_path,new_string:o.data.new_string,old_string:o.data.old_string,verbose:t,width:r/2-12}):null}case $u.name:{let o=$u.inputSchema.safeParse(n.input);return o.success?(0,h.jsx)(Cce,{file_path:o.data.file_path,content:o.data.content,verbose:t,width:r/2-12}):null}default:return null}default:return null}}Pe();var mmo="https://go/cli-feedback";function fmo(){return[{label:"Choose for me",value:"no-preference"},{label:"Left option looks better",value:"prefer-left"},{label:"Right option looks better",value:"prefer-right"},{label:`Neither, and tell ${it} what to do differently (${mt.bold.hex(re().warning)("esc")})`,value:"neither"}]}function icr({m1:e,m2:t,onChoose:r,debug:n,erroredToolUseIDs:o,inProgressToolUseIDs:i,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c}){let u=re(),[d,f]=(0,s3e.useState)("no-preference"),[p,A]=(0,s3e.useState)(void 0),_=rs(()=>process.exit(1));return ft((E,S)=>{S.leftArrow?A("prefer-left"):S.rightArrow?A("prefer-right"):S.escape&&r?.("neither")}),(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(x,{flexDirection:"column",height:"100%",width:"100%",borderStyle:"round",borderColor:u.permission,children:[(0,h.jsxs)(x,{width:"100%",justifyContent:"space-between",paddingX:1,children:[(0,h.jsxs)(I,{bold:!0,color:u.permission,children:["[ANT-ONLY] Help train ",it]}),(0,h.jsx)(I,{children:(0,h.jsx)(Qk,{url:mmo,children:"[?]"})})]}),(0,h.jsxs)(x,{flexDirection:"row",width:"100%",flexGrow:1,paddingTop:1,children:[(0,h.jsx)(x,{flexDirection:"column",flexGrow:1,flexBasis:1,gap:1,borderStyle:d==="prefer-left"?"bold":"single",borderColor:d==="prefer-left"?u.success:u.secondaryBorder,marginRight:1,padding:1,children:(0,h.jsx)(i3e,{erroredToolUseIDs:o,debug:n,inProgressToolUseIDs:i,message:e,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c})}),(0,h.jsx)(x,{flexDirection:"column",flexGrow:1,flexBasis:1,gap:1,borderStyle:d==="prefer-right"?"bold":"single",borderColor:d==="prefer-right"?u.success:u.secondaryBorder,marginLeft:1,padding:1,children:(0,h.jsx)(i3e,{erroredToolUseIDs:o,debug:n,inProgressToolUseIDs:i,message:t,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c})})]}),(0,h.jsxs)(x,{flexDirection:"column",paddingTop:1,paddingX:1,children:[(0,h.jsx)(I,{children:"How do you want to proceed?"}),(0,h.jsx)(Fb,{options:fmo(),onFocus:f,focusValue:p,onChange:r})]})]}),_.pending?(0,h.jsx)(x,{marginLeft:3,children:(0,h.jsxs)(I,{dimColor:!0,children:["Press ",_.keyName," again to exit"]})}):(0,h.jsx)(I,{children:" "})]})}function acr({m1:e,m2:t,resolve:r,debug:n,erroredToolUseIDs:o,inProgressToolUseIDs:i,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c}){let u=(0,scr.useCallback)(d=>{nzt(e,t,d),r(szt(e,t,d))},[e,t,r]);return Sce("${PRODUCT_NAME} needs your input on a response comparison"),(0,h.jsx)(icr,{debug:n,erroredToolUseIDs:o,inProgressToolUseIDs:i,m1:e,m2:t,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c,onChoose:u})}td();Om();Kt();ji();Eu();var Dce=Ie(Ve(),1);we();function AP({logs:e,onSelect:t}){let{rows:r,columns:n}=zo();if(e.length===0)return null;let o=r-3,i=Math.max(0,e.length-o),s=7,a=21,l=21,c=9,u=e.map((d,f)=>{let p=`[${f}]`.padEnd(s),A=PD(d.modified).padEnd(a),_=PD(d.created).padEnd(l),E=`${d.messageCount}`.padStart(c),S=d.firstPrompt,C="";d.sidechainNumber&&(C+=` (sidechain #${d.sidechainNumber})`);let v=`${p}${A}${_}${E} ${S}${C}`;return{label:v.length>n-2?`${v.slice(0,n-5)}...`:v,value:d.value.toString()}});return(0,h.jsxs)(x,{flexDirection:"column",height:"100%",width:"100%",children:[(0,h.jsxs)(x,{paddingLeft:9,children:[(0,h.jsx)(I,{bold:!0,color:re().text,children:"Modified"}),(0,h.jsx)(I,{children:" "}),(0,h.jsx)(I,{bold:!0,color:re().text,children:"Created"}),(0,h.jsx)(I,{children:" "}),(0,h.jsx)(I,{bold:!0,color:re().text,children:"# Messages"}),(0,h.jsx)(I,{children:" "}),(0,h.jsx)(I,{bold:!0,color:re().text,children:"First message"})]}),(0,h.jsx)(fa,{options:u,onChange:d=>t(parseInt(d,10)),visibleOptionCount:o}),i>0&&(0,h.jsx)(x,{paddingLeft:2,children:(0,h.jsxs)(I,{color:re().secondaryText,children:["and ",i," more\u2026"]})})]})}we();A1();Pe();function Nce(e,t){try{let r=e||[];return gmo(r),r}catch(r){return console.error("Error deserializing messages:",r),e||[]}}function gmo(e){for(let t of e){if(!t||t.type!=="goal_set"&&t.type!=="goal_cleared")continue;let r=t;if(r.type==="goal_set"){let n=r.content;if(!n||!n.condition)continue;dl.setGoal(n.condition,n.agentId);let o=dl.getGoal(n.agentId);o&&typeof n.setAt=="number"&&(o.setAt=n.setAt)}else{let n=r.content;dl.clearGoal(n?.agentId)}}}function lcr({onSelect:e,onClose:t,verbose:r}){let[n,o]=(0,Dce.useState)([]);(0,Dce.useEffect)(()=>{async function s(){let a=await Nv(Kn.messages());o(a)}return s(),()=>{}},[]),ft((s,a)=>{a.escape&&t()});function i(s){let a=n[s].messages;for(let c=a.length-1;c>=0;c--){let u=a[c];if(u.type==="assistant"&&u.message&&u.message.content){let d=u.message.content;if(Array.isArray(d)){let f=d.find(p=>p.type==="tool_use"&&p.name===$l&&p.input&&p.input.todos);if(f){let p=f.input.todos;p.every(_=>_.status==="completed")?od.setTodos([]):od.setTodos(p);break}}}}let l=n[s];l&&e&&e(Nce(l.messages),l.date)}return(0,h.jsxs)(x,{flexDirection:"column",alignItems:"flex-start",children:[(0,h.jsx)(AP,{logs:n,onSelect:i}),(0,h.jsx)(x,{marginTop:1,children:(0,h.jsx)(I,{children:"ESC to exit"})})]})}po();Pe();Eg();A1();qh();bS();Uf();var su=Ie(Ve(),1);Uf();po();ji();var a3e=Ie(Ve(),1);function Oce({items:e,children:t}){let r=(0,a3e.useRef)([]),n=(0,a3e.useRef)(0),o=new Map(e.map(d=>[d.uuid,d]));if(r.current.some(d=>!o.has(d)))return setImmediate(()=>ts()),n.current+=1,r.current=e.map(d=>d.uuid),(0,h.jsx)(ZF,{items:e,children:t},n.current);let s=r.current.filter(d=>o.has(d)),a=new Set(s),l=e.map(d=>d.uuid).filter(d=>!a.has(d)),c=[...s,...l];r.current=c;let u=c.map(d=>o.get(d));return(0,h.jsx)(ZF,{items:u,children:t},n.current)}function hmo(e,t){switch(e.type){case"user":case"assistant":{let r=D$(e);return r?!t.has(r):!0}case"reminder":return!0;case"goal_status":return!0;case"progress":return!t.has(e.toolUseID);default:return!0}}function ccr({debug:e=!1,verbose:t=!1,tools:r,memberName:n,showSpinner:o=!0}){let[i,s]=(0,su.useState)([]),[a,l]=(0,su.useState)(""),[c,u]=(0,su.useState)(void 0),[d,f]=(0,su.useState)(""),[p,A]=(0,su.useState)(0),_=re(),{columns:E}=zo(),S=c?qe.getSessionContext(c):qe.getSessionContext(),C=S.getPendingPrompts(),v=(0,su.useCallback)(K=>{K.trim()&&(S.addPendingPrompt(K.trim()),f(""),A(0))},[S]),R=(0,su.useCallback)(K=>{f(K)},[]),D=(0,su.useCallback)(K=>{A(K)},[]);(0,su.useEffect)(()=>{if(!n)return;let K=fn.getCurrentTeamName(),k=`${K}:${n}:change`;fn.getMember(K,n).then(se=>{if(se?.taskId){let X=qe.getInQueryContext(se.taskId).getData(K+":"+n)||[];s([...X]),u(se.taskId)}l(se.state)});let ie=Qt.on(k,se=>{s([...se])}),Z=Qt.on("team:change",({teamName:se,eventType:X})=>{X==="member_state_updated"&&fn.getMember(se,n).then(ee=>{l(ee.state)})});return()=>{ie(),Z()}},[n]);let O=(0,su.useMemo)(()=>Ln(i).filter(cP),[i]),F=(0,su.useMemo)(()=>Hle(O),[O]),{unresolvedToolUseIDs:G}=(0,su.useMemo)(()=>N$(F),[F]),P=(0,su.useMemo)(()=>[{type:"static",uuid:"logo",jsx:(0,h.jsx)(x,{flexDirection:"column",children:(0,h.jsx)(Qj,{isDefaultModel:!1})})},...F.filter(K=>K.type!=="progress").map(K=>{let k=K.type==="reminder"?(0,h.jsx)(x,{flexDirection:"column",width:"100%",marginLeft:0,children:(0,h.jsxs)(x,{flexDirection:"row",children:[(0,h.jsx)(I,{children:"\xA0\xA0\u23BF \xA0"}),(0,h.jsx)(I,{children:K.content})]})}):K.type==="goal_status"?(0,h.jsx)(x,{flexDirection:"column",width:"100%",marginLeft:0,children:(0,h.jsx)(x,{flexDirection:"row",children:K.content.met?(0,h.jsxs)(I,{color:"green",children:["\xA0\xA0\u2714 Goal achieved",H7(K.content.elapsedMs,K.content.turns,K.content.tokens)]}):(0,h.jsx)(I,{color:"yellow",children:"\xA0\xA0\u25EF Goal not yet met\u2026 continuing"})})}):(0,h.jsx)(wE,{message:K,messages:F,addMargin:!0,tools:r,verbose:t,debug:e,erroredToolUseIDs:new Set,inProgressToolUseIDs:new Set,unresolvedToolUseIDs:new Set,shouldAnimate:!1,shouldShowDot:!0});return{type:hmo(K,G)?"static":"transient",uuid:K.uuid,jsx:(0,h.jsx)(x,{width:"100%",children:k},K.uuid)}})],[F,t,r,G]),$=P.filter(K=>K.type==="static"),U=P.filter(K=>K.type==="transient"),le=n?`Message @${n}...`:"Message...";return(0,h.jsxs)(x,{flexDirection:"column",width:"100%",children:[(0,h.jsx)(Oce,{items:$,children:K=>K.jsx}),U.map(K=>K.jsx),(0,h.jsx)(x,{marginTop:1,children:(0,h.jsx)(I,{children:a})}),C.length>0&&(0,h.jsx)(x,{flexDirection:"column",marginTop:1,children:C.map((K,k)=>(0,h.jsxs)(I,{color:_.text,children:["> ",Zle(K.replace(/\r\n|\r|\n/g," "),E-6)]},k))}),o&&(0,h.jsx)(tB,{}),(0,h.jsxs)(x,{flexDirection:"column",marginTop:1,width:"100%",children:[(0,h.jsxs)(x,{flexDirection:"row",width:"100%",children:[(0,h.jsx)(I,{color:_.secondaryBorder,children:"\u2500".repeat(Math.max(0,E-(n?n.length+3:0)))}),n&&(0,h.jsxs)(I,{color:_.secondaryText,children:[" @",n," "]})]}),(0,h.jsxs)(x,{flexDirection:"row",alignItems:"center",width:"100%",children:[(0,h.jsx)(I,{color:_.text,children:"\xA0\u276F\xA0"}),(0,h.jsx)(Kh,{value:d,onChange:R,onSubmit:v,placeholder:le,multiline:!1,columns:E-4,cursorOffset:p,onChangeCursorOffset:D})]}),(0,h.jsx)(x,{flexDirection:"row",width:"100%",children:(0,h.jsx)(I,{color:_.secondaryBorder,children:"\u2500".repeat(E)})})]})]})}import{writeFile as dcr,mkdir as Amo,readFile as _mo}from"fs/promises";vUe();function ucr(e){let t=[],r=!1;async function n(){if(!r&&t.length!==0){for(r=!0;t.length>0;){let{args:o,resolve:i,reject:s,context:a}=t.shift();try{let l=await e.apply(a,o);i(l)}catch(l){s(l)}}r=!1,t.length>0&&n()}}return function(...o){return new Promise((i,s)=>{t.push({args:o,resolve:i,reject:s,context:this}),n()})}}we();Kt();we();Pe();function Emo(){return Je().sessionSummary?.enabled??!1}function bmo(){return Je().sessionSummary?.config??{}}var pcr;function Smo(e,t){let r=0,n=t==null;for(let o of e){if(!n){o.uuid===t&&(n=!0);continue}if(o.type==="assistant"){let i=o.message.content;Array.isArray(i)&&(r+=i.filter(s=>s.type==="tool_use").length)}}return r}function mcr(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.type==="assistant"){let n=r.message.content;return Array.isArray(n)?n.some(o=>o.type==="tool_use"):!1}}return!1}function ymo(e){let t=ks(e);if(!aIt()){if(!cIt(t))return!1;lIt()}let r=uIt(t),o=Smo(e,pcr)>=dIt(),i=mcr(e);if(r&&o||r&&!i){let a=e[e.length-1];return a?.uuid&&(pcr=a.uuid),!0}return!1}async function Cmo(e){let t=URe();await Amo(t,{recursive:!0,mode:448});let r=G4();try{await dcr(r,"",{encoding:"utf-8",mode:384,flag:"wx"});let o=await GRe();await dcr(r,o,{encoding:"utf-8",mode:384})}catch(o){if(o.code!=="EEXIST")throw o}let n="";try{n=await _mo(r,{encoding:"utf-8"}),e.readFileTimestamps[r]=Date.now()}catch{n=""}return{memoryPath:r,currentMemory:n}}var Tmo=(()=>{let e=!1;return()=>{if(e)return;let t=bmo(),r={minimumMessageTokensToInit:t.minimumMessageTokensToInit&&t.minimumMessageTokensToInit>0?t.minimumMessageTokensToInit:U4.minimumMessageTokensToInit,minimumTokensBetweenUpdate:t.minimumTokensBetweenUpdate&&t.minimumTokensBetweenUpdate>0?t.minimumTokensBetweenUpdate:U4.minimumTokensBetweenUpdate,toolCallsBetweenUpdates:t.toolCallsBetweenUpdates&&t.toolCallsBetweenUpdates>0?t.toolCallsBetweenUpdates:U4.toolCallsBetweenUpdates};oIt(r),e=!0}})();var Imo=ucr(async function(e){let{messages:t,toolUseContext:r,querySource:n}=e;if(!(n!=="repl_main_thread"||!Emo()||!Je().autoCompactEnabled)&&(Tmo(),!!ymo(t))){eIt();try{let i=xUe(r),{memoryPath:s,currentMemory:a}=await Cmo(i),l=await bIt(a,s);await RL({promptMessages:[At(l)],cacheSafeParams:hR(e),canUseTool:vmo(s),querySource:"session_memory",forkLabel:"session_memory",overrides:{readFileTimestamps:i.readFileTimestamps,agentId:"asession_memory_extractor"}});let c=iIt();sIt(ks(t)),xmo(t),ae("Session memory extraction completed")}catch(i){ae("Session memory extraction failed:",i)}finally{tIt()}}});function fcr(){mzt(Imo)}function vmo(e){return async(t,r)=>{if(t.name===Xo&&typeof r=="object"&&r!==null&&"file_path"in r){let n=r.file_path;if(typeof n=="string"&&n===e)return{result:!0}}return{result:!1,message:`Only FileEdit on ${e} is allowed for session memory extraction`}}}function xmo(e){if(!mcr(e)){let t=e[e.length-1];t?.uuid&&sT(t.uuid)}}process.on("unhandledRejection",(e,t)=>{te("Unhandled Rejection at:",t,"reason:",e)});function wmo(){let{frame:e}=Kp({interval:1e3}),t=dl.getGoal();return t?(0,h.jsx)(I,{children:` goal active (${BAe(Date.now()-t.setAt)})`}):null}function Y$({commands:e,dangerouslySkipPermissions:t,debug:r=!1,initialForkNumber:n=0,initialPrompt:o,shouldShowPromptInput:i,tools:s,verbose:a,initialMessages:l,isDefaultModel:c=!0}){(0,Jt.useEffect)(()=>{fcr();let Re=Qt.on("switchConversation",()=>{hr(!0)});return Je().webServer?.enabled&&Promise.resolve().then(()=>(Z4(),hre)).then(({webServerService:Yt})=>{Yt.start().then(()=>{Dt(`WebServer started: ${Yt.getUrl()}`)}).catch(Er=>{Dt(`WebServer \u542F\u52A8\u5931\u8D25: ${Er.message}`)})}),()=>{Re(),Promise.resolve().then(()=>(Z4(),hre)).then(({webServerService:Yt})=>{Yt.stop()})}},[]);let u=a??Qr().verbose,[d,f]=(0,Jt.useState)(n??0),[p,A]=(0,Jt.useState)(0),[_,E]=(0,Jt.useState)(null),[S,C]=(0,Jt.useState)(null),[v,R]=(0,Jt.useState)(null),[D,O]=(0,Jt.useState)(!1),[F,G]=(0,Jt.useState)(null),[P,$]=(0,Jt.useState)(null),U=(0,Jt.useRef)(!0);(0,Jt.useEffect)(()=>{if(U.current){U.current=!1;return}P===null&&ts().then(()=>{A(Re=>Re+1)})},[P]);let{columns:le,rows:K}=c3(),k=(0,Jt.useRef)(!0);(0,Jt.useEffect)(()=>{if(k.current){k.current=!1;return}let Re=setTimeout(()=>{ts().then(()=>{A(Mt=>Mt+1)})},200);return()=>clearTimeout(Re)},[le,K]),(0,Jt.useEffect)(()=>Qt.on("repl:refresh",()=>{A(Re=>Re+1)}),[]);let[ie,Z]=(0,Jt.useState)(null),se=(0,Jt.useRef)(null),X=(0,Jt.useRef)(null),ee=()=>{X.current&&(clearTimeout(X.current),X.current=null)},ne=(0,Jt.useCallback)((Re,Mt=!1)=>{try{let Yt=qe.getSessionContext(),Er=Yt.getData("_toolUseConfirms");if(Er||(Er=[],Yt.setData("_toolUseConfirms",Er)),Re)se.current?Er.push(Re):(se.current=Re,Z(()=>Re));else{if(Mt){Yt.setData("_toolUseConfirms",[]),se.current=null,ee(),Z(()=>null);return}if(Er.length>0){let Wn=Er.shift();se.current=Wn,Z(()=>null),ee(),X.current=setTimeout(()=>{X.current=null,se.current===Wn&&Z(()=>Wn)},0)}else se.current=null,ee(),Z(()=>null)}}catch(Yt){te("\u8BBE\u7F6E\u5DE5\u5177\u7528\u6237\u786E\u8BA4\u7A97\u53E3\u5F02\u5E38\uFF1A",Yt)}},[]),[ue,Se]=(0,Jt.useState)(l??[]),[W,j]=(0,Jt.useState)(""),[Te,Ke]=(0,Jt.useState)("prompt"),Ze=(0,Jt.useRef)(),je=Re=>{Re==="bash"?(Ze.current=Te,Ke(Re)):Ze.current&&(Ke(Ze.current),Ze.current=null)};(0,Jt.useEffect)(()=>{Fn.setModeUI=Re=>{Ke(Re)}},[]);let tt=(0,Jt.useCallback)(()=>{Ke(Re=>{switch(Re){case"prompt":return Fn.setMode("plan"),"plan";case"plan":return Fn.setMode("edit"),"edit";case"edit":return Je().autoMode?.enabled?(Fn.setMode("auto"),"auto"):(Fn.setMode("prompt"),"prompt");case"auto":return Fn.setMode("prompt"),"prompt";default:return Fn.setMode("prompt"),"prompt"}})},[]),[yt,Sr]=(0,Jt.useState)(0),[Ar,Un]=(0,Jt.useState)(!1),[Yr,Mr]=(0,Jt.useState)(!1),[Wt,An]=(0,Jt.useState)(Qr().hasAcknowledgedCostThreshold),[Ct,eo]=(0,Jt.useState)(null),[xr,wr]=(0,Jt.useState)(()=>s),[Bt,hr]=(0,Jt.useState)(!1),[dn,Gr]=(0,Jt.useState)([]),[lt,Tt]=(0,Jt.useState)(-1),[jt,Rr]=(0,Jt.useState)(-1),[at,Qe]=(0,Jt.useState)(!1),xe=(0,Jt.useCallback)((Re,Mt)=>new Promise(Yt=>{eo({m1:Re,m2:Mt,resolve:Yt})}),[]),_e=(0,Jt.useRef)({}),{status:rt,reverify:nt}={status:"valid",reverify:()=>Promise},[Vn,ar]=(0,Jt.useState)(void 0),[zr,Cn]=(0,Jt.useState)(_1());(0,Jt.useEffect)(()=>{let Re=Qt.on("token:change",Mt=>{Cn(Yt=>Mt)});return()=>{Re()}},[]);function Gt(){D&&(O(!1),ie?ie.onAbort():v?.abort())}Vlr($,ne,eo,Gt,D,Ar,P,v?.signal),(0,Jt.useEffect)(()=>{_&&(f(Re=>Re+1),E(Re=>null),Se(Re=>_))},[_]),(0,Jt.useEffect)(()=>{S&&(Se(Re=>S.messages),f(Re=>Re+1),C(Re=>null))},[S]),(0,Jt.useEffect)(()=>{VO()>=5&&!Yr&&!Wt&&(Ue("tengu_cost_threshold_reached",{}),Mr(!0))},[ue,Yr,Wt]);let ua=jlr();(0,Jt.useEffect)(()=>km.addListener(Re=>{let Mt=Re.toolUseID,Yt={toolUseID:Mt,hookWarning:Re.hookWarning,assistantMessage:Re.assistantMessage,tool:Re.tool,description:Re.description,input:Re.input,commandPrefix:Re.commandPrefix,riskScore:Re.riskScore,onAbort(){km.respondConfirmation(Mt,"reject")},onAllow(Er){if(Er==="permanent"){let Wn=Mp(Yt);Dp(Re.tool,Re.input,Wn)}km.respondConfirmation(Mt,Er==="permanent"?"allow_permanent":"allow")},onReject(){km.respondConfirmation(Mt,"reject")}};Re.onDone=()=>{let Er=qe.getSessionContext().getData("_toolUseConfirms")??[];qe.getSessionContext().setData("_toolUseConfirms",Er.filter(Wn=>Wn.toolUseID!==Mt)),se.current?.toolUseID===Mt&&ne(null)},ne(Yt)}),[ne]),(0,Jt.useEffect)(()=>Qt.on("webserver:tool_confirm_permanent",Re=>{Dp(Re.tool,Re.input,Re.prefix)}),[]),(0,Jt.useEffect)(()=>Gs.addListener(Re=>{let Mt=Re.context;if(Mt?.setToolJSX){if(Re.toolName==="AskUserQuestion")Mt.setToolJSX({jsx:(0,h.jsx)(Klr,{questions:Re.payload.questions??[],context:Mt,onComplete:Yt=>{Gs.respondResponse(Re.toolUseID,{answers:Yt})},onCancel:()=>{Gs.respondResponse(Re.toolUseID,{cancelled:!0})}},Re.toolUseID),shouldHidePromptInput:!0,disableCancel:!0});else if(Re.toolName==="EnterPlanMode")Re.context.setToolJSX({jsx:(0,h.jsx)(Zlr,{onApprove:Yt=>{Gs.respondResponse(Re.toolUseID,{approved:Yt})}},Re.toolUseID),shouldHidePromptInput:!0,disableCancel:!0});else if(Re.toolName==="ExitPlanMode"){let Yt=Re.payload;Yt?.plan?Re.context.setToolJSX({jsx:(0,h.jsx)(ecr,{plan:Yt.plan,context:Re.context,onApprove:Er=>{Gs.respondResponse(Re.toolUseID,{approved:!0,manualApproval:Er,cancelled:!1})},onReject:()=>{Gs.respondResponse(Re.toolUseID,{approved:!1,manualApproval:!1,cancelled:!0})}},Re.toolUseID),shouldHidePromptInput:!0,disableCancel:!0}):Re.context.setToolJSX({jsx:(0,h.jsx)(rcr,{onConfirm:()=>{Gs.respondResponse(Re.toolUseID,{approved:!0,cancelled:!1})},onCancel:()=>{Gs.respondResponse(Re.toolUseID,{approved:!1,cancelled:!0})}},Re.toolUseID),shouldHidePromptInput:!0,disableCancel:!0})}}}),[]),(0,Jt.useEffect)(()=>Gs.addDoneListener(()=>{$(null)}),[]);async function zs(){if(nt(),!o)return;O(!0);let Re=new AbortController;R(Re);let Mt=await la(),Yt=await R$(o,"prompt",$,{abortController:Re,options:{commands:e,tools:xr,verbose:u,slowAndCapableModel:Mt,thinking:Je().thinking},setForkConvoWithMessagesOnTheNextRender:E,readFileTimestamps:_e.current,messages:ue},null);if(Yt.length){for(let js of Yt)js.type==="user"&&NI(o);if(Se(js=>[...js,...Yt]),Yt[Yt.length-1].type==="assistant"){R(null),O(!1);return}let[Wn,Ql,Ws]=await Promise.all([Vh(),qo(),la()]);for await(let js of x$([...ue,...Yt],Wn,Ql,ua,{options:{commands:e,tools:xr,slowAndCapableModel:Ws,verbose:u,dangerouslySkipPermissions:t,thinking:Je().thinking},readFileTimestamps:_e.current,abortController:Re,setToolJSX:$,lazyToolMode:Ge.getLazyToolMode()},xe))Se(cu=>[...cu,js])}else NI(o);An(Qr().hasAcknowledgedCostThreshold||!1),O(!1)}async function Li(Re,Mt){Se(Ws=>[...Ws,...Re]),oC();let Yt=Re[Re.length-1];if(Yt.type==="user"&&typeof Yt.message.content=="string"&&JIt(Yt.message.content,Mt?.signal),Yt.type==="assistant"){R(null),O(!1);return}let[Er,Wn,Ql]=await Promise.all([Vh(),qo(),la()]);for await(let Ws of x$([...ue,...Re],Er,Wn,ua,{options:{commands:e,tools:xr,slowAndCapableModel:Ql,verbose:u,dangerouslySkipPermissions:t,thinking:Je().thinking},readFileTimestamps:_e.current,abortController:Mt,setToolJSX:$,lazyToolMode:Ge.getLazyToolMode()},xe))Se(js=>[...js,Ws]);O(!1)}Xtt(),(0,Jt.useEffect)(()=>Qt.on("repl:clearMessages",()=>{ts(),Se([]),f(Re=>Re+1),A(Re=>Re+1)}),[]),ocr(ue),zlr(),ft((Re,Mt)=>{let Yt=!1;switch(jr.platform){case"windows":Yt=Mt.meta&&(Re==="m"||Re==="M");break;case"macos":Yt=Mt.shift&&Mt.tab;break;case"linux":Yt=Mt.shift&&Mt.tab;break;default:Yt=Mt.meta&&(Re==="m"||Re==="M")}if(Yt&&tt(),Mt.ctrl&&Re==="s"&&(Bt||hr(!0)),Mt.ctrl&&Re==="b"&&(aa.runInBackgroud(),oi.runInBackgroud()),dn.length>0){if(Mt.downArrow&&!at&&!Bt){Qe(!0),Rr(lt);return}if(at){if(Mt.leftArrow){Rr(Er=>{let Wn=Er-1;return Wn<-1?dn.length-1:Wn});return}if(Mt.rightArrow){Rr(Er=>{let Wn=Er+1;return Wn>=dn.length?-1:Wn});return}if(Mt.return){ts(),A(Er=>Er+1),Tt(jt),Qe(!1);return}if(Mt.escape){Rr(lt),Qe(!1);return}}}}),(0,Jt.useEffect)(()=>{zs()},[]),(0,Jt.useEffect)(()=>{let Re=async()=>{let Yt=xi.getCurrentTeamName();if(Yt)try{let Wn=(await xi.getAllMembers(Yt)).filter(Ql=>Ql.name!=="team-lead");Gr(Wn)}catch(Er){Dt("\u52A0\u8F7D Team \u6210\u5458\u5931\u8D25:",Er)}};Re();let Mt=Qt.on("team:change",()=>{Re()});return()=>{Mt()}},[]),(0,Jt.useEffect)(()=>{let Re=Qt.on("repl:reloadtools",()=>{(async()=>{let Mt=await an.getTools(!0);wr(Mt)})()});return()=>{Re()}},[]);let hl=(0,Jt.useRef)(Li);hl.current=Li;let Ku=(0,Jt.useRef)(Gt);Ku.current=Gt;let da=(0,Jt.useRef)(D);da.current=D;let zg=(0,Jt.useRef)(ue);zg.current=ue;let Lp=(0,Jt.useRef)(xr);Lp.current=xr;async function zi({text:Re,requestId:Mt}){try{Qt.emit("webserver:prompt_status",{status:"executing",requestId:Mt});let Yt=new AbortController;R(Yt),O(!0);let Er=await la(),Wn=await R$(Re,"prompt",$,{options:{commands:e,tools:Lp.current,verbose:u,slowAndCapableModel:Er,thinking:Je().thinking},abortController:Yt,readFileTimestamps:_e.current,setForkConvoWithMessagesOnTheNextRender:()=>{},messages:zg.current},null);Wn.length?await hl.current(Wn,Yt):(O(!1),R(null)),Qt.emit("webserver:prompt_status",{status:"completed",requestId:Mt})}catch(Yt){te("processWebPrompt error:",Yt),O(!1),R(null),Qt.emit("webserver:prompt_status",{status:"rejected",message:Yt instanceof Error?Yt.message:String(Yt),requestId:Mt})}}(0,Jt.useEffect)(()=>{let Re=Qt.on("webserver:prompt",Mt=>{(async()=>{if(!da.current){await zi({text:Mt.text,requestId:Mt.requestId});return}qe.getSessionContext().addPendingPrompt(Mt.text),Qt.emit("webserver:prompt_status",{status:"queued",requestId:Mt.requestId})})()});return()=>Re()},[]),(0,Jt.useEffect)(()=>{let Re=Qt.on("webserver:interrupt",Mt=>{Mt.agentId==="main"&&Ku.current()});return()=>Re()},[]),(0,Jt.useEffect)(()=>{let Re=Qt.on(hf,Mt=>{(async()=>{if(da.current)return;if(Mt&&Mt.eventType==="loop"){try{if(!qe.isQuerying()){let Er=new AbortController;R(Er),O(!0);let Wn=Mt.data?.prompt||"Loop task triggered";hl.current([At(Wn)],Er)}}catch(Er){te(Er)}return}let Yt=Mt;if(Yt){let Er=await xi.takeMailInbox(Yt,Yy);if(Er&&Er.length>0){let Wn=new AbortController;R(Wn),O(!0),hl.current([At(xi.formatMessagesForContext(Er))],Wn)}}else try{let Er=Qn.needNotification(),Wn=oi.needNotification();if((Er||Wn)&&!qe.isQuerying()){let Ql=new AbortController;R(Ql);let Ws=[];if(Er){let js=await Qn.takeNotificationMessages();js&&Ws.push(...js)}if(Wn){let js=await oi.takeNotificationMessages();js&&Ws.push(...js)}Ws.length>0&&(O(!0),hl.current([At(Ws)],Ql))}}catch(Er){te(Er)}})()});return()=>{Re()}},[]),(0,Jt.useEffect)(()=>{let Re=k_(),Mt=Er=>{ar(Er)};Re.setStatusChangeCallback(Mt),Re.onToolsReload=Er=>{wr(Er)};let Yt=async()=>{try{Dt("\u{1F680} Initiating auto-connect to IDE..."),await Re.autoConnectToMatchingServer()?Dt("\u2705 Auto-connect completed successfully"):Dt("\u2139\uFE0F No matching IDE server found for auto-connect, or connection failed")}catch(Er){be("\u274C Error during auto-connect attempt:"+Er)}};return Re.getCurrentConnection()||Yt(),()=>{Re.setStatusChangeCallback(()=>{}),Re.onToolsReload=Er=>{}}},[]);let vo=(0,Jt.useMemo)(()=>Ln(ue).filter(cP),[ue]),{unresolvedToolUseIDs:au,unresolvedGroupToolUseIDs:DE}=(0,Jt.useMemo)(()=>N$(vo),[vo]),Jo=(0,Jt.useMemo)(()=>TXt(vo),[vo]),Xt=(0,Jt.useMemo)(()=>new Set(IXt(vo).map(Re=>Re.message.content[0].id)),[vo]),en=(0,Jt.useMemo)(()=>[{type:"static",uuid:"logo",jsx:(0,h.jsxs)(x,{flexDirection:"column",children:[(0,h.jsx)(Qj,{isDefaultModel:c}),(0,h.jsx)(x_e,{workspaceDir:ei()})]},`logo${d}-${p}`)},...Hle(vo).map(Re=>{let Mt=D$(Re),Yt=Re.type==="reminder"?(0,h.jsx)(x,{flexDirection:"column",width:"100%",marginLeft:0,children:(0,h.jsxs)(x,{flexDirection:"row",children:[(0,h.jsx)(I,{children:"\xA0\xA0\u23BF \xA0"}),(0,h.jsx)(I,{children:Re.content})]})}):Re.type==="goal_status"?(0,h.jsx)(x,{flexDirection:"column",width:"100%",marginTop:1,marginLeft:0,children:(0,h.jsx)(x,{flexDirection:"row",children:Re.content.met?(0,h.jsxs)(I,{color:"green",children:["\u2714 Goal achieved",H7(Re.content.elapsedMs,Re.content.turns,Re.content.tokens)]}):(0,h.jsx)(I,{color:"yellow",children:"\u25EF Goal not yet met\u2026 continuing"})})}):Re.type==="progress"?Re.content.message.content[0]?.type==="text"&&Re.content.message.content[0].text===Na?(0,h.jsx)(wE,{message:Re.content,messages:Re.normalizedMessages,addMargin:!1,tools:Re.tools,verbose:u??!1,debug:r,erroredToolUseIDs:new Set,inProgressToolUseIDs:new Set,unresolvedToolUseIDs:new Set,shouldAnimate:!1,shouldShowDot:!1}):(0,h.jsx)(per,{meta:Re.meta,children:(0,h.jsx)(wE,{message:Re.content,messages:Re.normalizedMessages,addMargin:!1,tools:Re.tools,verbose:u??!1,debug:r,erroredToolUseIDs:new Set,inProgressToolUseIDs:new Set,unresolvedToolUseIDs:new Set([Re.content.message.content[0].id]),shouldAnimate:!1,shouldShowDot:!1})}):(0,h.jsx)(wE,{message:Re,messages:vo,addMargin:!0,tools:xr,verbose:u,debug:r,erroredToolUseIDs:Xt,inProgressToolUseIDs:Jo,shouldAnimate:!P&&!ie&&!Ar&&(!Mt||Jo.has(Mt)),shouldShowDot:!0,unresolvedToolUseIDs:au}),Er=Rmo(Re,vo,au)?"static":"transient";return r?{type:Er,jsx:(0,h.jsx)(x,{borderStyle:"single",borderColor:Er==="static"?"green":"red",width:"100%",children:Yt},Re.uuid)}:{type:Er,uuid:Re.uuid,jsx:(0,h.jsx)(x,{width:"100%",children:Yt},Re.uuid)}})],[d,p,vo,xr,u,r,Xt,Jo,P,ie,Ar,au,c]),is=!D&&Yr,za=lt>=0&&dn[lt],Vs=za?dn[lt]:null,lu=(0,Jt.useRef)(!0);(0,Jt.useEffect)(()=>(lu.current?lu.current=!0:(ts(),A(Re=>Re+1)),()=>{}),[za,Vs]);let rf=Re=>at&&jt===Re?"green":lt===Re?"cyan":"gray",hc=Re=>!!(at&&jt===Re||lt===Re),[Fl,Pp]=(0,Jt.useState)(!0);return(0,Jt.useEffect)(()=>{Pp(D&&!P&&!ie&&!Ct)},[P,ie,Ct,D]),(0,h.jsxs)(h.Fragment,{children:[za?(0,h.jsx)(ccr,{debug:r,verbose:u,tools:xr,memberName:Vs.name,showSpinner:Fl},`AgentTeamREPL-messages-${Vs}-${d}-${p}`):(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(Oce,{items:en.filter(Re=>Re.type==="static"),children:Re=>Re.jsx},`static-messages-${d}-${p}`),en.filter(Re=>Re.type==="transient").map(Re=>Re.jsx)]}),(0,h.jsxs)(x,{borderColor:"red",borderStyle:r?"single":void 0,flexDirection:"column",width:"100%",children:[Fl&&!za&&(0,h.jsx)(tB,{}),P?P.jsx:null,!P&&Ct&&!Ar&&(0,h.jsx)(acr,{m1:Ct.m1,m2:Ct.m2,resolve:Re=>{Ct.resolve(Re),setTimeout(()=>eo(null),0)},verbose:u,normalizedMessages:vo,tools:xr,debug:r,erroredToolUseIDs:Xt,inProgressToolUseIDs:Jo,unresolvedToolUseIDs:au}),!P&&ie&&!Ar&&!Ct&&(0,h.jsx)(Blr,{toolUseConfirm:ie,onDone:()=>ne(null),verbose:u}),!P&&!ie&&!Ar&&!Ct&&is&&(0,h.jsx)(mit,{onDone:()=>{Mr(!1),An(!0);let Re=Qr();Ho({...Re,hasAcknowledgedCostThreshold:!0}),Ue("tengu_cost_threshold_acknowledged",{})}}),!Bt&&!ie&&!P?.shouldHidePromptInput&&i&&!Ar&&!Ct&&!is&&!za&&(0,h.jsx)(h.Fragment,{children:(0,h.jsx)(qlr,{commands:e,tools:xr,isDisabled:rt==="invalid",isLoading:D,onQuery:Li,debug:r,verbose:u,messages:ue,setToolJSX:$,onAutoUpdaterResult:G,autoUpdaterResult:F,input:W,onInputChange:j,mode:Te,onModeChange:je,submitCount:yt,onSubmitCountChange:Sr,setIsLoading:O,setAbortController:R,onShowMessageSelector:()=>Un(Re=>!Re),setForkConvoWithMessagesOnTheNextRender:E,readFileTimestamps:_e.current,reminderText:Vn})})]}),Ar&&(0,h.jsx)(mer,{erroredToolUseIDs:Xt,unresolvedToolUseIDs:au,messages:Du(ue),onSelect:async Re=>{Un(!1),ue.includes(Re)&&(Gt(),setImmediate(async()=>{await ts(),E(Mt=>ue.slice(0,ue.indexOf(Re))),typeof Re.message.content=="string"&&j(Re.message.content)}))},onEscape:()=>Un(!1),tools:xr}),dn.length>0&&!ie&&(0,h.jsx)(x,{flexDirection:"column",width:"100%",children:(0,h.jsxs)(x,{borderStyle:at?"single":void 0,borderColor:"green",paddingLeft:1,paddingRight:1,children:[(0,h.jsx)(I,{bold:at,color:at?"green":void 0,children:"Team Members:"}),(0,h.jsxs)(I,{color:rf(-1),bold:hc(-1),children:[" ","team-lead"," "]}),dn.map((Re,Mt)=>(0,h.jsxs)(I,{color:rf(Mt),bold:hc(Mt),children:[Re.name," "]},Re.agentId)),at&&(0,h.jsx)(I,{color:"yellow",children:" [\u2190\u2192Switch Enter Confirm ESC Cancel]"})]})}),(0,h.jsxs)(x,{justifyContent:"flex-end",children:[(0,h.jsxs)(I,{dimColor:!0,children:["\u2191 "+zr.inputTokens+" \u2193 "+zr.outputTokens," tokens"]}),Je().showWindowTokens&&(()=>{let Re=ks(ue),Mt=P_(),Yt=Mt>0?Math.round(Re/Mt*100):0;return(0,h.jsx)(I,{dimColor:!0,children:` \xB7 ${Re} (${Yt}%) window`})})(),(0,h.jsx)(wmo,{}),(0,h.jsx)(I,{children:" "})]}),(0,h.jsx)(el,{}),Bt&&(0,h.jsx)(lcr,{onClose:()=>hr(Re=>!1),onSelect:async(Re,Mt)=>{hr(!1),Gt(),setImmediate(async()=>{await ts(),iT(),od.clearTodos(),dl.clearGoal(),qe.getInQueryContext()[oh]=0,qe.getSessionContext().switchSessionId(Mt),Ol.loadSession(Mt),C({messages:Re})})}})]})}function Rmo(e,t,r){switch(e.type){case"user":case"assistant":{let n=D$(e);return n?!r.has(n):!0}case"reminder":return!0;case"goal_status":return!0;case"progress":return!r.has(e.toolUseID)}}Kx();var Aur=Ie(wcr(),1);er();lr();we();Kt();async function Rcr({commands:e,dangerouslySkipPermissions:t,hasPermissionsToUseTool:r,prompt:n,cwd:o,tools:i,verbose:s=!1}){await Ki(o);let l=[At(n)],[c,u,d]=await Promise.all([Vh(),qo(),la()]);for await(let A of x$(l,c,u,r,{options:{commands:e,tools:i,verbose:s,dangerouslySkipPermissions:t,slowAndCapableModel:d,thinking:Je().thinking},abortController:new AbortController,readFileTimestamps:{},agentDepth:0,lazyToolMode:Ge.getLazyToolMode()}))l.push(A);let f=yc(l);if(!f||f.type!=="assistant")throw new Error("Expected content to be an assistant message");if(f.message.content[0]?.type!=="text")throw new Error(`Expected first content item to be text, but got ${JSON.stringify(f.message.content[0],null,2)}`);let p=Fa();return tm(l),{resultText:f.message.content[0].text,totalCost:VO(),messageHistoryFile:p}}we();import{cwd as kp}from"process";var Ncr=Ie(Ve(),1);Pe();we();lr();import{homedir as Ymo}from"os";function Dcr({onDone:e}){let t=re();Ncr.default.useEffect(()=>{Ue("trust_dialog_shown",{})},[]);function r(o){let i=Nn();switch(o){case"yes":{let s=Ymo()===Oe();Ue("trust_dialog_accept",{isHomeDir:String(s)}),s||ti({...i,hasTrustDialogAccepted:!0}),e();break}case"no":{process.exit(1);break}}}let n=rs(()=>process.exit(0));return ft((o,i)=>{if(i.escape){process.exit(0);return}}),(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(x,{flexDirection:"column",gap:1,padding:1,borderStyle:"round",borderColor:t.warning,children:[(0,h.jsx)(I,{bold:!0,color:t.warning,children:"Do you trust the files in this folder?"}),(0,h.jsx)(I,{bold:!0,children:process.cwd()}),(0,h.jsxs)(x,{flexDirection:"column",gap:1,children:[(0,h.jsxs)(I,{children:[it," may read files in this folder. Reading untrusted files may lead to ",it," to behave in an unexpected ways."]}),(0,h.jsxs)(I,{children:["With your permission ",it," may execute files in this folder. Executing untrusted code is unsafe."]})]}),(0,h.jsx)(fa,{options:[{label:"Yes, proceed",value:"yes"},{label:"No, exit",value:"no"}],onChange:o=>r(o)})]}),(0,h.jsx)(x,{marginLeft:3,children:(0,h.jsx)(I,{dimColor:!0,children:n.pending?(0,h.jsxs)(h.Fragment,{children:["Press ",n.keyName," again to exit"]}):(0,h.jsx)(h.Fragment,{children:"Enter to confirm \xB7 Esc to exit"})})})]})}var V$=Ie(Ve(),1);we();we();we();function C3e({context:e,type:t,logNumber:r}){let[n,o]=(0,V$.useState)([]),[i,s]=(0,V$.useState)(!1);(0,V$.useEffect)(()=>{Nv(t==="messages"?Kn.messages():Kn.errors()).then(l=>{if(r!==void 0){let c=l[r>=0?r:0];c?(console.log(JSON.stringify(c.messages,null,2)),process.exit(0)):(console.error("No log found at index",r),process.exit(1))}o(l)}).catch(l=>{be(l),r!==void 0?process.exit(1):e.unmount?.()})},[e,t,r]);function a(l){let c=n[l];c&&(s(!0),setTimeout(()=>{console.log(JSON.stringify(c.messages,null,2)),process.exit(0)},100))}return r!==void 0||i?null:(0,h.jsx)(AP,{logs:n,onSelect:a})}we();po();function Ocr({context:e,commands:t,logs:r,tools:n,verbose:o}){async function i(s){let a=r[s];if(a)try{e.unmount?.();let l=await F4();qe.getSessionContext().switchSessionId(a.date),Ol.loadSession(a.date),Sl((0,h.jsx)(Y$,{initialPrompt:"",shouldShowPromptInput:!0,verbose:o,commands:t,tools:n,initialMessages:Nce(a.messages,n),initialForkNumber:0,isDefaultModel:l}),{exitOnCtrlC:!1})}catch(l){throw be(`Failed to load conversation: ${l}`),l}}return(0,h.jsx)(AP,{logs:r,onSelect:i})}vxe();dg();ERe();YM();var kce=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};bRe();var Lce=class extends JM{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(e4.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new fk,this.setRequestHandler(Eee,n=>this._oninitialize(n)),this.setNotificationHandler(bee,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Q1e,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=e4.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new kce(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=zee(this._capabilities,t)}setRequestHandler(t,r){let o=v_(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(hp(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(l,c)=>{let u=fd(jM,l);if(!u.success){let A=u.error instanceof Error?u.error.message:String(u.error);throw new Ht(or.InvalidParams,`Invalid tools/call request: ${A}`)}let{params:d}=u.data,f=await Promise.resolve(r(l,c));if(d.task){let A=fd(mS,f);if(!A.success){let _=A.error instanceof Error?A.error.message:String(A.error);throw new Ht(or.InvalidParams,`Invalid task creation result: ${_}`)}return A.data}let p=fd(Dm,f);if(!p.success){let A=p.error instanceof Error?p.error.message:String(p.error);throw new Ht(or.InvalidParams,`Invalid tools/call result: ${A}`)}return p.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Dte(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Nte(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:Fx.includes(r)?r:zC,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},pS)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(c=>c.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],l=a.some(c=>c.type==="tool_use");if(i){if(o.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let c=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(c.size!==u.size||![...c].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},r4,r):this.request({method:"sampling/createMessage",params:t},t4,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},KM,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},KM,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new Ht(or.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof Ht?s:new Ht(or.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},$1e,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};YM();Ixe();dg();var Mcr=Symbol.for("mcp.completable");function T3e(e){return!!e&&typeof e=="object"&&Mcr in e}function kcr(e){return e[Mcr]?.complete}var Bcr;(function(e){e.Completable="McpCompletable"})(Bcr||(Bcr={}));var zmo=/^[A-Za-z0-9._-]{1,128}$/;function Vmo(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!zmo.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Wmo(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function I3e(e){let t=Vmo(e);return Wmo(e,t.warnings),t.isValid}var Pce=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};sn();var Fce=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Lce(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Pce(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(OI(Mee)),this.server.assertCanSetRequestHandler(OI(jM)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Mee,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=qM(r.inputSchema);return o?yxe(o,{strictUnions:!0,pipeStrategy:"input"}):jmo})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=qM(r.outputSchema);o&&(n.outputSchema=yxe(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(jM,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new Ht(or.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new Ht(or.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new Ht(or.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new Ht(or.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof Ht&&n.code===or.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=qM(t.inputSchema)??t.inputSchema,s=await aee(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",l=lee(a);throw new Ht(or.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Ht(or.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=qM(t.outputSchema),i=await aee(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=lee(s);throw new Ht(or.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),l=a.task.taskId,c=a.task,u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let d=await n.taskStore.getTask(l);if(!d)throw new Ht(or.InternalError,`Task ${l} not found during polling`);c=d}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(OI(kee)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(kee,async t=>{switch(t.params.ref.type){case"ref/prompt":return cyt(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return uyt(t),this.handleResourceCompletion(t,t.params.ref);default:throw new Ht(or.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new Ht(or.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Ht(or.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return W$;let i=v_(n.argsSchema)?.[t.params.argument.name];if(!T3e(i))return W$;let s=kcr(i);if(!s)return W$;let a=await s(t.params.argument.value,t.params.context);return Pcr(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return W$;throw new Ht(or.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return W$;let i=await o(t.params.argument.value,t.params.context);return Pcr(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(OI(Ree)),this.server.assertCanSetRequestHandler(OI(Nee)),this.server.assertCanSetRequestHandler(OI(Dee)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ree,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Nee,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Dee,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Ht(or.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new Ht(or.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(OI(Oee)),this.server.assertCanSetRequestHandler(OI(Bee)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Oee,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?Jmo(r.argsSchema):void 0}))})),this.server.setRequestHandler(Bee,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new Ht(or.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new Ht(or.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=qM(n.argsSchema),i=await aee(o,t.params.arguments);if(!i.success){let l="error"in i?i.error:"Unknown error",c=lee(l);throw new Ht(or.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=s)),typeof c.title<"u"&&(s.title=c.title),typeof c.template<"u"&&(s.resourceTemplate=c.template),typeof c.metadata<"u"&&(s.metadata=c.metadata),typeof c.callback<"u"&&(s.readCallback=c.callback),typeof c.enabled<"u"&&(s.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Px(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Px(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(l=>{let c=l instanceof Wd?l._def?.innerType:l;return T3e(c)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,l,c){I3e(t);let u={title:r,description:n,inputSchema:Lcr(o),outputSchema:Lcr(i),annotations:s,execution:a,_meta:l,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&I3e(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=Px(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=Px(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];v3e(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!v3e(r[0])&&(s=r.shift())):typeof l=="object"&&l!==null&&(s=r.shift())}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:l,_meta:c}=r;return this._createRegisteredTool(t,o,i,s,a,l,{taskSupport:"forbidden"},c,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var jmo={type:"object",properties:{}};function Fcr(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Kmo(e){return"_def"in e||"_zod"in e||Fcr(e)}function v3e(e){return typeof e!="object"||e===null||Kmo(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Fcr)}function Lcr(e){if(e)return v3e(e)?Px(e):e}function Jmo(e){let t=v_(e);return t?Object.entries(t).map(([r,n])=>{let o=mSt(n),i=fSt(n);return{name:r,description:o,required:!i}}):[]}function OI(e){let r=v_(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=cee(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Pcr(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var W$={completion:{values:[],hasMore:!1}};import Qcr from"node:process";var Qce=class{constructor(t=Qcr.stdin,r=Qcr.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new qk,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=ine(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{Http2ServerRequest as Zmo}from"http2";import{Http2ServerRequest as x3e}from"http2";import{Readable as Ucr}from"stream";import ufo from"crypto";var $R=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},Xmo=e=>e instanceof $R?e:new $R(e.message,{cause:e}),efo=global.Request,j$=class extends efo{constructor(e,t){typeof e=="object"&&bP in e&&(e=e[bP]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},tfo=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:i}=r;o.charCodeAt(0)!==58&&t.push([o,i])}return new Headers(t)},Hcr=Symbol("wrapBodyStream"),rfo=(e,t,r,n,o)=>{let i={method:e,headers:r,signal:o.signal};if(e==="TRACE"){i.method="GET";let s=new j$(t,i);return Object.defineProperty(s,"method",{get(){return"TRACE"}}),s}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)i.body=new ReadableStream({start(s){s.enqueue(n.rawBody),s.close()}});else if(n[Hcr]){let s;i.body=new ReadableStream({async pull(a){try{s||=Ucr.toWeb(n).getReader();let{done:l,value:c}=await s.read();l?a.close():a.enqueue(c)}catch(l){a.error(l)}}})}else i.body=Ucr.toWeb(n);return new j$(t,i)},bP=Symbol("getRequestCache"),nfo=Symbol("requestCache"),Uce=Symbol("incomingKey"),Gce=Symbol("urlKey"),ofo=Symbol("headersKey"),EP=Symbol("abortControllerKey"),ifo=Symbol("getAbortController"),Hce={get method(){return this[Uce].method||"GET"},get url(){return this[Gce]},get headers(){return this[ofo]||=tfo(this[Uce])},[ifo](){return this[bP](),this[EP]},[bP](){return this[EP]||=new AbortController,this[nfo]||=rfo(this.method,this[Gce],this.headers,this[Uce],this[EP])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(Hce,e,{get(){return this[bP]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(Hce,e,{value:function(){return this[bP]()[e]()}})});Object.setPrototypeOf(Hce,j$.prototype);var sfo=(e,t)=>{let r=Object.create(Hce);r[Uce]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof x3e)throw new $R("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[Gce]=a.href}catch(a){throw new $R("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof x3e?e.authority:e.headers.host)||t;if(!o)throw new $R("Missing host header");let i;if(e instanceof x3e){if(i=e.scheme,!(i==="http"||i==="https"))throw new $R("Unsupported scheme")}else i=e.socket&&e.socket.encrypted?"https":"http";let s=new URL(`${i}://${o}${n}`);if(s.hostname.length!==o.length&&s.hostname!==o.replace(/:\d+$/,""))throw new $R("Invalid host header");return r[Gce]=s.href,r},Gcr=Symbol("responseCache"),_P=Symbol("getResponseCache"),qR=Symbol("cache"),R3e=global.Response,K$=class $cr{#e;#t;[_P](){return delete this[qR],this[Gcr]||=new R3e(this.#e,this.#t)}constructor(t,r){let n;if(this.#e=t,r instanceof $cr){let o=r[Gcr];if(o){this.#t=o,this[_P]();return}else this.#t=r.#t,n=new Headers(r.#t.headers)}else this.#t=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(n||=r?.headers||{"content-type":"text/plain; charset=UTF-8"},this[qR]=[r?.status||200,t,n])}get headers(){let t=this[qR];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2])),t[2]):this[_P]().headers}get status(){return this[qR]?.[0]??this[_P]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(K$.prototype,e,{get(){return this[_P]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(K$.prototype,e,{value:function(){return this[_P]()[e]()}})});Object.setPrototypeOf(K$,R3e);Object.setPrototypeOf(K$.prototype,R3e.prototype);async function afo(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function qcr(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(s,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function i(){e.read().then(s,o)}function s({done:a,value:l}){try{if(a)t.end();else if(!t.write(l))t.once("drain",i);else return e.read().then(s,o)}catch(c){o(c)}}}function lfo(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:qcr(e.getReader(),t)}var Ycr=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let r=[];for(let[n,o]of e)n==="set-cookie"?r.push(o):t[n]=o;return r.length>0&&(t["set-cookie"]=r),t["content-type"]??="text/plain; charset=UTF-8",t},cfo="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=ufo);var N3e=Symbol("outgoingEnded"),dfo=()=>new Response(null,{status:400}),zcr=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),w3e=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},Vcr=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Wcr=async(e,t)=>{let[r,n,o]=e[qR];o instanceof Headers&&(o=Ycr(o)),typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size),t.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(Vcr(t),await lfo(n,t)?.catch(i=>w3e(i,t))),t[N3e]?.()},pfo=e=>typeof e.then=="function",mfo=async(e,t,r={})=>{if(pfo(e))if(r.errorHandler)try{e=await e}catch(o){let i=await r.errorHandler(o);if(!i)return;e=i}else e=await e.catch(zcr);if(qR in e)return Wcr(e,t);let n=Ycr(e.headers);if(e.body){let o=e.body.getReader(),i=[],s=!1,a;if(n["transfer-encoding"]!=="chunked"){let l=2;for(let c=0;c<l;c++){a||=o.read();let u=await afo(a).catch(d=>{console.error(d),s=!0});if(!u){if(c===1){await new Promise(d=>setTimeout(d)),l=3;continue}break}if(a=void 0,u.value&&i.push(u.value),u.done){s=!0;break}}s&&!("content-length"in n)&&(n["content-length"]=i.reduce((c,u)=>c+u.length,0))}t.writeHead(e.status,n),i.forEach(l=>{t.write(l)}),s?t.end():(i.length===0&&Vcr(t),await qcr(o,t,a))}else n[cfo]||(t.writeHead(e.status,n),t.end());t[N3e]?.()},D3e=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==j$&&(Object.defineProperty(global,"Request",{value:j$}),Object.defineProperty(global,"Response",{value:K$})),async(n,o)=>{let i,s;try{s=sfo(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[Hcr]=!0,n.on("end",()=>{a=!0}),n instanceof Zmo&&(o[N3e]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),o.destroy()})})})),o.on("close",()=>{s[EP]&&(n.errored?s[EP].abort(n.errored.toString()):o.writableFinished||s[EP].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),i=e(s,{incoming:n,outgoing:o}),qR in i)return Wcr(i,o)}catch(a){if(i)return w3e(a,o);if(t.errorHandler){if(i=await t.errorHandler(s?a:Xmo(a)),!i)return}else s?i=zcr(a):i=dfo()}try{return await mfo(i,o,t)}catch(a){return w3e(a,o)}}};dg();var $ce=class{constructor(t={}){this._started=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=t.sessionIdGenerator,this._enableJsonResponse=t.enableJsonResponse??!1,this._eventStore=t.eventStore,this._onsessioninitialized=t.onsessioninitialized,this._onsessionclosed=t.onsessionclosed,this._allowedHosts=t.allowedHosts,this._allowedOrigins=t.allowedOrigins,this._enableDnsRebindingProtection=t.enableDnsRebindingProtection??!1,this._retryInterval=t.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(t,r,n,o){let i={code:r,message:n};return o?.data!==void 0&&(i.data=o.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:t,headers:{"Content-Type":"application/json",...o?.headers}})}validateRequestHeaders(t){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=t.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=t.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(t,r){let n=this.validateRequestHeaders(t);if(n)return n;switch(t.method){case"POST":return this.handlePostRequest(t,r);case"GET":return this.handleGetRequest(t);case"DELETE":return this.handleDeleteRequest(t);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(t,r,n,o){if(!this._eventStore||o<"2025-11-25")return;let i=await this._eventStore.storeEvent(n,{}),s=`id: ${i}
3487
+ No code changes will be made until you approve the plan.`})}),xce.map((o,i)=>(0,h.jsx)(x,{flexDirection:"row",marginLeft:2,children:(0,h.jsxs)(I,{color:t===i?n.highlight:n.text,children:[t===i?"\u276F":" "," ",o.label]})},o.value))]})};var Xlr=Ie(Ve(),1);Pe();Om();var wce=[{label:"Yes, and auto-accept edits",value:"auto",description:"Proceed with the plan and auto-accept all edits"},{label:"Yes, and manually approve edits",value:"manual",description:"Proceed with the plan but manually approve each edit"},{label:"No, keep planning",value:"reject",description:"Reject the plan and continue planning"}],ecr=({plan:e,context:t,onApprove:r,onReject:n})=>{let[o,i]=Xlr.useState(0),s=Fn.getCurrentPlanFilePath();ft((l,c)=>{if(c.upArrow)i(u=>u>0?u-1:wce.length-1);else if(c.downArrow)i(u=>u<wce.length-1?u+1:0);else if(c.return){let u=wce[o];u.value==="auto"?r(!1):u.value==="manual"?r(!0):n()}else c.ctrl&&l==="o"&&s?Kk(s,{wait:!1}):c.escape&&n()});let a=re();return(0,h.jsxs)(x,{flexDirection:"column",marginY:1,children:[(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:a.info,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:a.info,children:"Ready to code?"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsxs)(I,{bold:!0,color:a.info,children:["Here is ",it,"'s plan:"]})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{color:a.info,children:"\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{color:a.text,children:e})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{color:a.info,children:"\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C\u254C"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:a.info,children:"Would you like to proceed?"})}),wce.map((l,c)=>(0,h.jsxs)(x,{flexDirection:"row",marginLeft:2,children:[(0,h.jsxs)(I,{color:o===c?a.highlight:a.text,children:[o===c?"\u276F":" "," ",l.label]}),(0,h.jsxs)(I,{dimColor:!0,children:[" - ",l.description]})]},l.value)),s&&(0,h.jsx)(x,{marginTop:1,children:(0,h.jsxs)(I,{dimColor:!0,children:["ctrl-o to edit \xB7 ",s]})})]})};var tcr=Ie(Ve(),1);Pe();var Rce=[{label:"Yes",value:"yes"},{label:"No",value:"no"}],rcr=({onConfirm:e,onCancel:t})=>{let[r,n]=tcr.useState(0);ft((s,a)=>{a.upArrow?n(l=>l>0?l-1:Rce.length-1):a.downArrow?n(l=>l<Rce.length-1?l+1:0):a.return?Rce[r].value==="yes"?e():t():a.escape&&t()});let o=re(),{columns:i}=zo();return(0,h.jsxs)(x,{flexDirection:"column",marginY:1,children:[(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:o.info,children:"\u2500".repeat(Math.max(i-2,10))})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsx)(I,{bold:!0,color:o.info,children:"Exit plan mode?"})}),(0,h.jsx)(x,{marginBottom:1,children:(0,h.jsxs)(I,{color:o.text,children:[it," wants to exit plan mode"]})}),Rce.map((s,a)=>(0,h.jsx)(x,{flexDirection:"row",marginLeft:2,children:(0,h.jsxs)(I,{color:r===a?o.highlight:o.text,children:[r===a?"\u276F":" "," ",a+1,". ",s.label]})},s.value))]})};var ncr=Ie(Ve(),1);we();function ocr(e){(0,ncr.useEffect)(()=>{tm(e.filter(t=>t.type!=="progress"))},[e])}ra();gk();we();var scr=Ie(Ve(),1);var s3e=Ie(Ve(),1);function i3e({debug:e,erroredToolUseIDs:t,inProgressToolUseIDs:r,message:n,normalizedMessages:o,tools:i,unresolvedToolUseIDs:s,verbose:a}){let{columns:l}=zo();return Ln([n]).filter(c=>c.type==="assistant").map((c,u)=>(0,h.jsxs)(x,{flexDirection:"column",children:[(0,h.jsx)(wE,{addMargin:!1,erroredToolUseIDs:t,debug:e,inProgressToolUseIDs:r,message:c,messages:o,shouldAnimate:!1,shouldShowDot:!0,tools:i,unresolvedToolUseIDs:s,verbose:a,width:l/2-6}),(0,h.jsx)(pmo,{message:c,verbose:a})]},u))}function pmo({message:e,verbose:t}){let{columns:r}=zo();if(e.type!=="assistant")return null;let n=e.message.content[0];switch(n.type){case"tool_use":switch(n.name){case Xc.name:{let o=Xc.inputSchema.safeParse(n.input);return o.success?(0,h.jsx)(rce,{file_path:o.data.file_path,new_string:o.data.new_string,old_string:o.data.old_string,verbose:t,width:r/2-12}):null}case $u.name:{let o=$u.inputSchema.safeParse(n.input);return o.success?(0,h.jsx)(Cce,{file_path:o.data.file_path,content:o.data.content,verbose:t,width:r/2-12}):null}default:return null}default:return null}}Pe();var mmo="https://go/cli-feedback";function fmo(){return[{label:"Choose for me",value:"no-preference"},{label:"Left option looks better",value:"prefer-left"},{label:"Right option looks better",value:"prefer-right"},{label:`Neither, and tell ${it} what to do differently (${mt.bold.hex(re().warning)("esc")})`,value:"neither"}]}function icr({m1:e,m2:t,onChoose:r,debug:n,erroredToolUseIDs:o,inProgressToolUseIDs:i,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c}){let u=re(),[d,f]=(0,s3e.useState)("no-preference"),[p,A]=(0,s3e.useState)(void 0),_=rs(()=>process.exit(1));return ft((E,S)=>{S.leftArrow?A("prefer-left"):S.rightArrow?A("prefer-right"):S.escape&&r?.("neither")}),(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(x,{flexDirection:"column",height:"100%",width:"100%",borderStyle:"round",borderColor:u.permission,children:[(0,h.jsxs)(x,{width:"100%",justifyContent:"space-between",paddingX:1,children:[(0,h.jsxs)(I,{bold:!0,color:u.permission,children:["[ANT-ONLY] Help train ",it]}),(0,h.jsx)(I,{children:(0,h.jsx)(Qk,{url:mmo,children:"[?]"})})]}),(0,h.jsxs)(x,{flexDirection:"row",width:"100%",flexGrow:1,paddingTop:1,children:[(0,h.jsx)(x,{flexDirection:"column",flexGrow:1,flexBasis:1,gap:1,borderStyle:d==="prefer-left"?"bold":"single",borderColor:d==="prefer-left"?u.success:u.secondaryBorder,marginRight:1,padding:1,children:(0,h.jsx)(i3e,{erroredToolUseIDs:o,debug:n,inProgressToolUseIDs:i,message:e,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c})}),(0,h.jsx)(x,{flexDirection:"column",flexGrow:1,flexBasis:1,gap:1,borderStyle:d==="prefer-right"?"bold":"single",borderColor:d==="prefer-right"?u.success:u.secondaryBorder,marginLeft:1,padding:1,children:(0,h.jsx)(i3e,{erroredToolUseIDs:o,debug:n,inProgressToolUseIDs:i,message:t,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c})})]}),(0,h.jsxs)(x,{flexDirection:"column",paddingTop:1,paddingX:1,children:[(0,h.jsx)(I,{children:"How do you want to proceed?"}),(0,h.jsx)(Fb,{options:fmo(),onFocus:f,focusValue:p,onChange:r})]})]}),_.pending?(0,h.jsx)(x,{marginLeft:3,children:(0,h.jsxs)(I,{dimColor:!0,children:["Press ",_.keyName," again to exit"]})}):(0,h.jsx)(I,{children:" "})]})}function acr({m1:e,m2:t,resolve:r,debug:n,erroredToolUseIDs:o,inProgressToolUseIDs:i,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c}){let u=(0,scr.useCallback)(d=>{nzt(e,t,d),r(szt(e,t,d))},[e,t,r]);return Sce("${PRODUCT_NAME} needs your input on a response comparison"),(0,h.jsx)(icr,{debug:n,erroredToolUseIDs:o,inProgressToolUseIDs:i,m1:e,m2:t,normalizedMessages:s,tools:a,unresolvedToolUseIDs:l,verbose:c,onChoose:u})}td();Om();Kt();ji();Eu();var Dce=Ie(Ve(),1);we();function AP({logs:e,onSelect:t}){let{rows:r,columns:n}=zo();if(e.length===0)return null;let o=r-3,i=Math.max(0,e.length-o),s=7,a=21,l=21,c=9,u=e.map((d,f)=>{let p=`[${f}]`.padEnd(s),A=PD(d.modified).padEnd(a),_=PD(d.created).padEnd(l),E=`${d.messageCount}`.padStart(c),S=d.firstPrompt,C="";d.sidechainNumber&&(C+=` (sidechain #${d.sidechainNumber})`);let v=`${p}${A}${_}${E} ${S}${C}`;return{label:v.length>n-2?`${v.slice(0,n-5)}...`:v,value:d.value.toString()}});return(0,h.jsxs)(x,{flexDirection:"column",height:"100%",width:"100%",children:[(0,h.jsxs)(x,{paddingLeft:9,children:[(0,h.jsx)(I,{bold:!0,color:re().text,children:"Modified"}),(0,h.jsx)(I,{children:" "}),(0,h.jsx)(I,{bold:!0,color:re().text,children:"Created"}),(0,h.jsx)(I,{children:" "}),(0,h.jsx)(I,{bold:!0,color:re().text,children:"# Messages"}),(0,h.jsx)(I,{children:" "}),(0,h.jsx)(I,{bold:!0,color:re().text,children:"First message"})]}),(0,h.jsx)(fa,{options:u,onChange:d=>t(parseInt(d,10)),visibleOptionCount:o}),i>0&&(0,h.jsx)(x,{paddingLeft:2,children:(0,h.jsxs)(I,{color:re().secondaryText,children:["and ",i," more\u2026"]})})]})}we();A1();Pe();function Nce(e,t){try{let r=e||[];return gmo(r),r}catch(r){return console.error("Error deserializing messages:",r),e||[]}}function gmo(e){for(let t of e){if(!t||t.type!=="goal_set"&&t.type!=="goal_cleared")continue;let r=t;if(r.type==="goal_set"){let n=r.content;if(!n||!n.condition)continue;dl.setGoal(n.condition,n.agentId);let o=dl.getGoal(n.agentId);o&&typeof n.setAt=="number"&&(o.setAt=n.setAt)}else{let n=r.content;dl.clearGoal(n?.agentId)}}}function lcr({onSelect:e,onClose:t,verbose:r}){let[n,o]=(0,Dce.useState)([]);(0,Dce.useEffect)(()=>{async function s(){let a=await Nv(Kn.messages());o(a)}return s(),()=>{}},[]),ft((s,a)=>{a.escape&&t()});function i(s){let a=n[s].messages;for(let c=a.length-1;c>=0;c--){let u=a[c];if(u.type==="assistant"&&u.message&&u.message.content){let d=u.message.content;if(Array.isArray(d)){let f=d.find(p=>p.type==="tool_use"&&p.name===$l&&p.input&&p.input.todos);if(f){let p=f.input.todos;p.every(_=>_.status==="completed")?od.setTodos([]):od.setTodos(p);break}}}}let l=n[s];l&&e&&e(Nce(l.messages),l.date)}return(0,h.jsxs)(x,{flexDirection:"column",alignItems:"flex-start",children:[(0,h.jsx)(AP,{logs:n,onSelect:i}),(0,h.jsx)(x,{marginTop:1,children:(0,h.jsx)(I,{children:"ESC to exit"})})]})}po();Pe();Eg();A1();qh();bS();Uf();var su=Ie(Ve(),1);Uf();po();ji();var a3e=Ie(Ve(),1);function Oce({items:e,children:t}){let r=(0,a3e.useRef)([]),n=(0,a3e.useRef)(0),o=new Map(e.map(d=>[d.uuid,d]));if(r.current.some(d=>!o.has(d)))return setImmediate(()=>ts()),n.current+=1,r.current=e.map(d=>d.uuid),(0,h.jsx)(ZF,{items:e,children:t},n.current);let s=r.current.filter(d=>o.has(d)),a=new Set(s),l=e.map(d=>d.uuid).filter(d=>!a.has(d)),c=[...s,...l];r.current=c;let u=c.map(d=>o.get(d));return(0,h.jsx)(ZF,{items:u,children:t},n.current)}function hmo(e,t){switch(e.type){case"user":case"assistant":{let r=D$(e);return r?!t.has(r):!0}case"reminder":return!0;case"goal_status":return!0;case"progress":return!t.has(e.toolUseID);default:return!0}}function ccr({debug:e=!1,verbose:t=!1,tools:r,memberName:n,showSpinner:o=!0}){let[i,s]=(0,su.useState)([]),[a,l]=(0,su.useState)(""),[c,u]=(0,su.useState)(void 0),[d,f]=(0,su.useState)(""),[p,A]=(0,su.useState)(0),_=re(),{columns:E}=zo(),S=c?qe.getSessionContext(c):qe.getSessionContext(),C=S.getPendingPrompts(),v=(0,su.useCallback)(K=>{K.trim()&&(S.addPendingPrompt(K.trim()),f(""),A(0))},[S]),R=(0,su.useCallback)(K=>{f(K)},[]),D=(0,su.useCallback)(K=>{A(K)},[]);(0,su.useEffect)(()=>{if(!n)return;let K=fn.getCurrentTeamName(),k=`${K}:${n}:change`;fn.getMember(K,n).then(se=>{if(se?.taskId){let X=qe.getInQueryContext(se.taskId).getData(K+":"+n)||[];s([...X]),u(se.taskId)}l(se.state)});let ie=Qt.on(k,se=>{s([...se])}),Z=Qt.on("team:change",({teamName:se,eventType:X})=>{X==="member_state_updated"&&fn.getMember(se,n).then(ee=>{l(ee.state)})});return()=>{ie(),Z()}},[n]);let O=(0,su.useMemo)(()=>Ln(i).filter(cP),[i]),F=(0,su.useMemo)(()=>Hle(O),[O]),{unresolvedToolUseIDs:G}=(0,su.useMemo)(()=>N$(F),[F]),P=(0,su.useMemo)(()=>[{type:"static",uuid:"logo",jsx:(0,h.jsx)(x,{flexDirection:"column",children:(0,h.jsx)(Qj,{isDefaultModel:!1})})},...F.filter(K=>K.type!=="progress").map(K=>{let k=K.type==="reminder"?(0,h.jsx)(x,{flexDirection:"column",width:"100%",marginLeft:0,children:(0,h.jsxs)(x,{flexDirection:"row",children:[(0,h.jsx)(I,{children:"\xA0\xA0\u23BF \xA0"}),(0,h.jsx)(I,{children:K.content})]})}):K.type==="goal_status"?(0,h.jsx)(x,{flexDirection:"column",width:"100%",marginLeft:0,children:(0,h.jsx)(x,{flexDirection:"row",children:K.content.met?(0,h.jsxs)(I,{color:"green",children:["\xA0\xA0\u2714 Goal achieved",H7(K.content.elapsedMs,K.content.turns,K.content.tokens)]}):(0,h.jsx)(I,{color:"yellow",children:"\xA0\xA0\u25EF Goal not yet met\u2026 continuing"})})}):(0,h.jsx)(wE,{message:K,messages:F,addMargin:!0,tools:r,verbose:t,debug:e,erroredToolUseIDs:new Set,inProgressToolUseIDs:new Set,unresolvedToolUseIDs:new Set,shouldAnimate:!1,shouldShowDot:!0});return{type:hmo(K,G)?"static":"transient",uuid:K.uuid,jsx:(0,h.jsx)(x,{width:"100%",children:k},K.uuid)}})],[F,t,r,G]),$=P.filter(K=>K.type==="static"),U=P.filter(K=>K.type==="transient"),le=n?`Message @${n}...`:"Message...";return(0,h.jsxs)(x,{flexDirection:"column",width:"100%",children:[(0,h.jsx)(Oce,{items:$,children:K=>K.jsx}),U.map(K=>K.jsx),(0,h.jsx)(x,{marginTop:1,children:(0,h.jsx)(I,{children:a})}),C.length>0&&(0,h.jsx)(x,{flexDirection:"column",marginTop:1,children:C.map((K,k)=>(0,h.jsxs)(I,{color:_.text,children:["> ",Zle(K.replace(/\r\n|\r|\n/g," "),E-6)]},k))}),o&&(0,h.jsx)(tB,{}),(0,h.jsxs)(x,{flexDirection:"column",marginTop:1,width:"100%",children:[(0,h.jsxs)(x,{flexDirection:"row",width:"100%",children:[(0,h.jsx)(I,{color:_.secondaryBorder,children:"\u2500".repeat(Math.max(0,E-(n?n.length+3:0)))}),n&&(0,h.jsxs)(I,{color:_.secondaryText,children:[" @",n," "]})]}),(0,h.jsxs)(x,{flexDirection:"row",alignItems:"center",width:"100%",children:[(0,h.jsx)(I,{color:_.text,children:"\xA0\u276F\xA0"}),(0,h.jsx)(Kh,{value:d,onChange:R,onSubmit:v,placeholder:le,multiline:!1,columns:E-4,cursorOffset:p,onChangeCursorOffset:D})]}),(0,h.jsx)(x,{flexDirection:"row",width:"100%",children:(0,h.jsx)(I,{color:_.secondaryBorder,children:"\u2500".repeat(E)})})]})]})}import{writeFile as dcr,mkdir as Amo,readFile as _mo}from"fs/promises";vUe();function ucr(e){let t=[],r=!1;async function n(){if(!r&&t.length!==0){for(r=!0;t.length>0;){let{args:o,resolve:i,reject:s,context:a}=t.shift();try{let l=await e.apply(a,o);i(l)}catch(l){s(l)}}r=!1,t.length>0&&n()}}return function(...o){return new Promise((i,s)=>{t.push({args:o,resolve:i,reject:s,context:this}),n()})}}we();Kt();we();Pe();function Emo(){return Je().sessionSummary?.enabled??!1}function bmo(){return Je().sessionSummary?.config??{}}var pcr;function Smo(e,t){let r=0,n=t==null;for(let o of e){if(!n){o.uuid===t&&(n=!0);continue}if(o.type==="assistant"){let i=o.message.content;Array.isArray(i)&&(r+=i.filter(s=>s.type==="tool_use").length)}}return r}function mcr(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.type==="assistant"){let n=r.message.content;return Array.isArray(n)?n.some(o=>o.type==="tool_use"):!1}}return!1}function ymo(e){let t=ks(e);if(!aIt()){if(!cIt(t))return!1;lIt()}let r=uIt(t),o=Smo(e,pcr)>=dIt(),i=mcr(e);if(r&&o||r&&!i){let a=e[e.length-1];return a?.uuid&&(pcr=a.uuid),!0}return!1}async function Cmo(e){let t=URe();await Amo(t,{recursive:!0,mode:448});let r=G4();try{await dcr(r,"",{encoding:"utf-8",mode:384,flag:"wx"});let o=await GRe();await dcr(r,o,{encoding:"utf-8",mode:384})}catch(o){if(o.code!=="EEXIST")throw o}let n="";try{n=await _mo(r,{encoding:"utf-8"}),e.readFileTimestamps[r]=Date.now()}catch{n=""}return{memoryPath:r,currentMemory:n}}var Tmo=(()=>{let e=!1;return()=>{if(e)return;let t=bmo(),r={minimumMessageTokensToInit:t.minimumMessageTokensToInit&&t.minimumMessageTokensToInit>0?t.minimumMessageTokensToInit:U4.minimumMessageTokensToInit,minimumTokensBetweenUpdate:t.minimumTokensBetweenUpdate&&t.minimumTokensBetweenUpdate>0?t.minimumTokensBetweenUpdate:U4.minimumTokensBetweenUpdate,toolCallsBetweenUpdates:t.toolCallsBetweenUpdates&&t.toolCallsBetweenUpdates>0?t.toolCallsBetweenUpdates:U4.toolCallsBetweenUpdates};oIt(r),e=!0}})();var Imo=ucr(async function(e){let{messages:t,toolUseContext:r,querySource:n}=e;if(!(n!=="repl_main_thread"||!Emo()||!Je().autoCompactEnabled)&&(Tmo(),!!ymo(t))){eIt();try{let i=xUe(r),{memoryPath:s,currentMemory:a}=await Cmo(i),l=await bIt(a,s);await RL({promptMessages:[At(l)],cacheSafeParams:hR(e),canUseTool:vmo(s),querySource:"session_memory",forkLabel:"session_memory",overrides:{readFileTimestamps:i.readFileTimestamps,agentId:"asession_memory_extractor"}});let c=iIt();sIt(ks(t)),xmo(t),ae("Session memory extraction completed")}catch(i){ae("Session memory extraction failed:",i)}finally{tIt()}}});function fcr(){mzt(Imo)}function vmo(e){return async(t,r)=>{if(t.name===Xo&&typeof r=="object"&&r!==null&&"file_path"in r){let n=r.file_path;if(typeof n=="string"&&n===e)return{result:!0}}return{result:!1,message:`Only FileEdit on ${e} is allowed for session memory extraction`}}}function xmo(e){if(!mcr(e)){let t=e[e.length-1];t?.uuid&&sT(t.uuid)}}process.on("unhandledRejection",(e,t)=>{te("Unhandled Rejection at:",t,"reason:",e)});function wmo(){let{frame:e}=Kp({interval:1e3}),t=dl.getGoal();return t?(0,h.jsx)(I,{children:` goal active (${BAe(Date.now()-t.setAt)})`}):null}function Y$({commands:e,dangerouslySkipPermissions:t,debug:r=!1,initialForkNumber:n=0,initialPrompt:o,shouldShowPromptInput:i,tools:s,verbose:a,initialMessages:l,isDefaultModel:c=!0}){(0,Jt.useEffect)(()=>{fcr();let Re=Qt.on("switchConversation",()=>{hr(!0)});return Je().webServer?.enabled&&Promise.resolve().then(()=>(Z4(),hre)).then(({webServerService:Yt})=>{Yt.start().then(()=>{Dt(`WebServer started: ${Yt.getUrl()}`)}).catch(Er=>{Dt(`WebServer \u542F\u52A8\u5931\u8D25: ${Er.message}`)})}),()=>{Re(),Promise.resolve().then(()=>(Z4(),hre)).then(({webServerService:Yt})=>{Yt.stop()})}},[]);let u=a??Qr().verbose,[d,f]=(0,Jt.useState)(n??0),[p,A]=(0,Jt.useState)(0),[_,E]=(0,Jt.useState)(null),[S,C]=(0,Jt.useState)(null),[v,R]=(0,Jt.useState)(null),[D,O]=(0,Jt.useState)(!1),[F,G]=(0,Jt.useState)(null),[P,$]=(0,Jt.useState)(null),U=(0,Jt.useRef)(!0);(0,Jt.useEffect)(()=>{if(U.current){U.current=!1;return}P===null&&ts().then(()=>{A(Re=>Re+1)})},[P]);let{columns:le,rows:K}=c3(),k=(0,Jt.useRef)(!0);(0,Jt.useEffect)(()=>{if(k.current){k.current=!1;return}let Re=setTimeout(()=>{ts().then(()=>{A(Mt=>Mt+1)})},200);return()=>clearTimeout(Re)},[le,K]),(0,Jt.useEffect)(()=>Qt.on("repl:refresh",()=>{A(Re=>Re+1)}),[]);let[ie,Z]=(0,Jt.useState)(null),se=(0,Jt.useRef)(null),X=(0,Jt.useRef)(null),ee=()=>{X.current&&(clearTimeout(X.current),X.current=null)},ne=(0,Jt.useCallback)((Re,Mt=!1)=>{try{let Yt=qe.getSessionContext(),Er=Yt.getData("_toolUseConfirms");if(Er||(Er=[],Yt.setData("_toolUseConfirms",Er)),Re)se.current?Er.push(Re):(se.current=Re,Z(()=>Re));else{if(Mt){Yt.setData("_toolUseConfirms",[]),se.current=null,ee(),Z(()=>null);return}if(X.current)return;if(Er.length>0){let Wn=Er.shift();se.current=Wn,Z(()=>null),ee(),X.current=setTimeout(()=>{X.current=null,se.current===Wn&&Z(()=>Wn)},0)}else se.current=null,ee(),Z(()=>null)}}catch(Yt){te("\u8BBE\u7F6E\u5DE5\u5177\u7528\u6237\u786E\u8BA4\u7A97\u53E3\u5F02\u5E38\uFF1A",Yt)}},[]),[ue,Se]=(0,Jt.useState)(l??[]),[W,j]=(0,Jt.useState)(""),[Te,Ke]=(0,Jt.useState)("prompt"),Ze=(0,Jt.useRef)(),je=Re=>{Re==="bash"?(Ze.current=Te,Ke(Re)):Ze.current&&(Ke(Ze.current),Ze.current=null)};(0,Jt.useEffect)(()=>{Fn.setModeUI=Re=>{Ke(Re)}},[]);let tt=(0,Jt.useCallback)(()=>{Ke(Re=>{switch(Re){case"prompt":return Fn.setMode("plan"),"plan";case"plan":return Fn.setMode("edit"),"edit";case"edit":return Je().autoMode?.enabled?(Fn.setMode("auto"),"auto"):(Fn.setMode("prompt"),"prompt");case"auto":return Fn.setMode("prompt"),"prompt";default:return Fn.setMode("prompt"),"prompt"}})},[]),[yt,Sr]=(0,Jt.useState)(0),[Ar,Un]=(0,Jt.useState)(!1),[Yr,Mr]=(0,Jt.useState)(!1),[Wt,An]=(0,Jt.useState)(Qr().hasAcknowledgedCostThreshold),[Ct,eo]=(0,Jt.useState)(null),[xr,wr]=(0,Jt.useState)(()=>s),[Bt,hr]=(0,Jt.useState)(!1),[dn,Gr]=(0,Jt.useState)([]),[lt,Tt]=(0,Jt.useState)(-1),[jt,Rr]=(0,Jt.useState)(-1),[at,Qe]=(0,Jt.useState)(!1),xe=(0,Jt.useCallback)((Re,Mt)=>new Promise(Yt=>{eo({m1:Re,m2:Mt,resolve:Yt})}),[]),_e=(0,Jt.useRef)({}),{status:rt,reverify:nt}={status:"valid",reverify:()=>Promise},[Vn,ar]=(0,Jt.useState)(void 0),[zr,Cn]=(0,Jt.useState)(_1());(0,Jt.useEffect)(()=>{let Re=Qt.on("token:change",Mt=>{Cn(Yt=>Mt)});return()=>{Re()}},[]);function Gt(){D&&(O(!1),ie?ie.onAbort():v?.abort())}Vlr($,ne,eo,Gt,D,Ar,P,v?.signal),(0,Jt.useEffect)(()=>{_&&(f(Re=>Re+1),E(Re=>null),Se(Re=>_))},[_]),(0,Jt.useEffect)(()=>{S&&(Se(Re=>S.messages),f(Re=>Re+1),C(Re=>null))},[S]),(0,Jt.useEffect)(()=>{VO()>=5&&!Yr&&!Wt&&(Ue("tengu_cost_threshold_reached",{}),Mr(!0))},[ue,Yr,Wt]);let ua=jlr();(0,Jt.useEffect)(()=>km.addListener(Re=>{let Mt=Re.toolUseID,Yt={toolUseID:Mt,hookWarning:Re.hookWarning,assistantMessage:Re.assistantMessage,tool:Re.tool,description:Re.description,input:Re.input,commandPrefix:Re.commandPrefix,riskScore:Re.riskScore,onAbort(){km.respondConfirmation(Mt,"reject")},onAllow(Er){if(Er==="permanent"){let Wn=Mp(Yt);Dp(Re.tool,Re.input,Wn)}km.respondConfirmation(Mt,Er==="permanent"?"allow_permanent":"allow")},onReject(){km.respondConfirmation(Mt,"reject")}};Re.onDone=()=>{let Er=qe.getSessionContext().getData("_toolUseConfirms")??[];qe.getSessionContext().setData("_toolUseConfirms",Er.filter(Wn=>Wn.toolUseID!==Mt)),se.current?.toolUseID===Mt&&ne(null)},ne(Yt)}),[ne]),(0,Jt.useEffect)(()=>Qt.on("webserver:tool_confirm_permanent",Re=>{Dp(Re.tool,Re.input,Re.prefix)}),[]),(0,Jt.useEffect)(()=>Gs.addListener(Re=>{let Mt=Re.context;if(Mt?.setToolJSX){if(Re.toolName==="AskUserQuestion")Mt.setToolJSX({jsx:(0,h.jsx)(Klr,{questions:Re.payload.questions??[],context:Mt,onComplete:Yt=>{Gs.respondResponse(Re.toolUseID,{answers:Yt})},onCancel:()=>{Gs.respondResponse(Re.toolUseID,{cancelled:!0})}},Re.toolUseID),shouldHidePromptInput:!0,disableCancel:!0});else if(Re.toolName==="EnterPlanMode")Re.context.setToolJSX({jsx:(0,h.jsx)(Zlr,{onApprove:Yt=>{Gs.respondResponse(Re.toolUseID,{approved:Yt})}},Re.toolUseID),shouldHidePromptInput:!0,disableCancel:!0});else if(Re.toolName==="ExitPlanMode"){let Yt=Re.payload;Yt?.plan?Re.context.setToolJSX({jsx:(0,h.jsx)(ecr,{plan:Yt.plan,context:Re.context,onApprove:Er=>{Gs.respondResponse(Re.toolUseID,{approved:!0,manualApproval:Er,cancelled:!1})},onReject:()=>{Gs.respondResponse(Re.toolUseID,{approved:!1,manualApproval:!1,cancelled:!0})}},Re.toolUseID),shouldHidePromptInput:!0,disableCancel:!0}):Re.context.setToolJSX({jsx:(0,h.jsx)(rcr,{onConfirm:()=>{Gs.respondResponse(Re.toolUseID,{approved:!0,cancelled:!1})},onCancel:()=>{Gs.respondResponse(Re.toolUseID,{approved:!1,cancelled:!0})}},Re.toolUseID),shouldHidePromptInput:!0,disableCancel:!0})}}}),[]),(0,Jt.useEffect)(()=>Gs.addDoneListener(()=>{$(null)}),[]);async function zs(){if(nt(),!o)return;O(!0);let Re=new AbortController;R(Re);let Mt=await la(),Yt=await R$(o,"prompt",$,{abortController:Re,options:{commands:e,tools:xr,verbose:u,slowAndCapableModel:Mt,thinking:Je().thinking},setForkConvoWithMessagesOnTheNextRender:E,readFileTimestamps:_e.current,messages:ue},null);if(Yt.length){for(let js of Yt)js.type==="user"&&NI(o);if(Se(js=>[...js,...Yt]),Yt[Yt.length-1].type==="assistant"){R(null),O(!1);return}let[Wn,Ql,Ws]=await Promise.all([Vh(),qo(),la()]);for await(let js of x$([...ue,...Yt],Wn,Ql,ua,{options:{commands:e,tools:xr,slowAndCapableModel:Ws,verbose:u,dangerouslySkipPermissions:t,thinking:Je().thinking},readFileTimestamps:_e.current,abortController:Re,setToolJSX:$,lazyToolMode:Ge.getLazyToolMode()},xe))Se(cu=>[...cu,js])}else NI(o);An(Qr().hasAcknowledgedCostThreshold||!1),O(!1)}async function Li(Re,Mt){Se(Ws=>[...Ws,...Re]),oC();let Yt=Re[Re.length-1];if(Yt.type==="user"&&typeof Yt.message.content=="string"&&JIt(Yt.message.content,Mt?.signal),Yt.type==="assistant"){R(null),O(!1);return}let[Er,Wn,Ql]=await Promise.all([Vh(),qo(),la()]);for await(let Ws of x$([...ue,...Re],Er,Wn,ua,{options:{commands:e,tools:xr,slowAndCapableModel:Ql,verbose:u,dangerouslySkipPermissions:t,thinking:Je().thinking},readFileTimestamps:_e.current,abortController:Mt,setToolJSX:$,lazyToolMode:Ge.getLazyToolMode()},xe))Se(js=>[...js,Ws]);O(!1)}Xtt(),(0,Jt.useEffect)(()=>Qt.on("repl:clearMessages",()=>{ts(),Se([]),f(Re=>Re+1),A(Re=>Re+1)}),[]),ocr(ue),zlr(),ft((Re,Mt)=>{let Yt=!1;switch(jr.platform){case"windows":Yt=Mt.meta&&(Re==="m"||Re==="M");break;case"macos":Yt=Mt.shift&&Mt.tab;break;case"linux":Yt=Mt.shift&&Mt.tab;break;default:Yt=Mt.meta&&(Re==="m"||Re==="M")}if(Yt&&tt(),Mt.ctrl&&Re==="s"&&(Bt||hr(!0)),Mt.ctrl&&Re==="b"&&(aa.runInBackgroud(),oi.runInBackgroud()),dn.length>0){if(Mt.downArrow&&!at&&!Bt){Qe(!0),Rr(lt);return}if(at){if(Mt.leftArrow){Rr(Er=>{let Wn=Er-1;return Wn<-1?dn.length-1:Wn});return}if(Mt.rightArrow){Rr(Er=>{let Wn=Er+1;return Wn>=dn.length?-1:Wn});return}if(Mt.return){ts(),A(Er=>Er+1),Tt(jt),Qe(!1);return}if(Mt.escape){Rr(lt),Qe(!1);return}}}}),(0,Jt.useEffect)(()=>{zs()},[]),(0,Jt.useEffect)(()=>{let Re=async()=>{let Yt=xi.getCurrentTeamName();if(Yt)try{let Wn=(await xi.getAllMembers(Yt)).filter(Ql=>Ql.name!=="team-lead");Gr(Wn)}catch(Er){Dt("\u52A0\u8F7D Team \u6210\u5458\u5931\u8D25:",Er)}};Re();let Mt=Qt.on("team:change",()=>{Re()});return()=>{Mt()}},[]),(0,Jt.useEffect)(()=>{let Re=Qt.on("repl:reloadtools",()=>{(async()=>{let Mt=await an.getTools(!0);wr(Mt)})()});return()=>{Re()}},[]);let hl=(0,Jt.useRef)(Li);hl.current=Li;let Ku=(0,Jt.useRef)(Gt);Ku.current=Gt;let da=(0,Jt.useRef)(D);da.current=D;let zg=(0,Jt.useRef)(ue);zg.current=ue;let Lp=(0,Jt.useRef)(xr);Lp.current=xr;async function zi({text:Re,requestId:Mt}){try{Qt.emit("webserver:prompt_status",{status:"executing",requestId:Mt});let Yt=new AbortController;R(Yt),O(!0);let Er=await la(),Wn=await R$(Re,"prompt",$,{options:{commands:e,tools:Lp.current,verbose:u,slowAndCapableModel:Er,thinking:Je().thinking},abortController:Yt,readFileTimestamps:_e.current,setForkConvoWithMessagesOnTheNextRender:()=>{},messages:zg.current},null);Wn.length?await hl.current(Wn,Yt):(O(!1),R(null)),Qt.emit("webserver:prompt_status",{status:"completed",requestId:Mt})}catch(Yt){te("processWebPrompt error:",Yt),O(!1),R(null),Qt.emit("webserver:prompt_status",{status:"rejected",message:Yt instanceof Error?Yt.message:String(Yt),requestId:Mt})}}(0,Jt.useEffect)(()=>{let Re=Qt.on("webserver:prompt",Mt=>{(async()=>{if(!da.current){await zi({text:Mt.text,requestId:Mt.requestId});return}qe.getSessionContext().addPendingPrompt(Mt.text),Qt.emit("webserver:prompt_status",{status:"queued",requestId:Mt.requestId})})()});return()=>Re()},[]),(0,Jt.useEffect)(()=>{let Re=Qt.on("webserver:interrupt",Mt=>{Mt.agentId==="main"&&Ku.current()});return()=>Re()},[]),(0,Jt.useEffect)(()=>{let Re=Qt.on(hf,Mt=>{(async()=>{if(da.current)return;if(Mt&&Mt.eventType==="loop"){try{if(!qe.isQuerying()){let Er=new AbortController;R(Er),O(!0);let Wn=Mt.data?.prompt||"Loop task triggered";hl.current([At(Wn)],Er)}}catch(Er){te(Er)}return}let Yt=Mt;if(Yt){let Er=await xi.takeMailInbox(Yt,Yy);if(Er&&Er.length>0){let Wn=new AbortController;R(Wn),O(!0),hl.current([At(xi.formatMessagesForContext(Er))],Wn)}}else try{let Er=Qn.needNotification(),Wn=oi.needNotification();if((Er||Wn)&&!qe.isQuerying()){let Ql=new AbortController;R(Ql);let Ws=[];if(Er){let js=await Qn.takeNotificationMessages();js&&Ws.push(...js)}if(Wn){let js=await oi.takeNotificationMessages();js&&Ws.push(...js)}Ws.length>0&&(O(!0),hl.current([At(Ws)],Ql))}}catch(Er){te(Er)}})()});return()=>{Re()}},[]),(0,Jt.useEffect)(()=>{let Re=k_(),Mt=Er=>{ar(Er)};Re.setStatusChangeCallback(Mt),Re.onToolsReload=Er=>{wr(Er)};let Yt=async()=>{try{Dt("\u{1F680} Initiating auto-connect to IDE..."),await Re.autoConnectToMatchingServer()?Dt("\u2705 Auto-connect completed successfully"):Dt("\u2139\uFE0F No matching IDE server found for auto-connect, or connection failed")}catch(Er){be("\u274C Error during auto-connect attempt:"+Er)}};return Re.getCurrentConnection()||Yt(),()=>{Re.setStatusChangeCallback(()=>{}),Re.onToolsReload=Er=>{}}},[]);let vo=(0,Jt.useMemo)(()=>Ln(ue).filter(cP),[ue]),{unresolvedToolUseIDs:au,unresolvedGroupToolUseIDs:DE}=(0,Jt.useMemo)(()=>N$(vo),[vo]),Jo=(0,Jt.useMemo)(()=>TXt(vo),[vo]),Xt=(0,Jt.useMemo)(()=>new Set(IXt(vo).map(Re=>Re.message.content[0].id)),[vo]),en=(0,Jt.useMemo)(()=>[{type:"static",uuid:"logo",jsx:(0,h.jsxs)(x,{flexDirection:"column",children:[(0,h.jsx)(Qj,{isDefaultModel:c}),(0,h.jsx)(x_e,{workspaceDir:ei()})]},`logo${d}-${p}`)},...Hle(vo).map(Re=>{let Mt=D$(Re),Yt=Re.type==="reminder"?(0,h.jsx)(x,{flexDirection:"column",width:"100%",marginLeft:0,children:(0,h.jsxs)(x,{flexDirection:"row",children:[(0,h.jsx)(I,{children:"\xA0\xA0\u23BF \xA0"}),(0,h.jsx)(I,{children:Re.content})]})}):Re.type==="goal_status"?(0,h.jsx)(x,{flexDirection:"column",width:"100%",marginTop:1,marginLeft:0,children:(0,h.jsx)(x,{flexDirection:"row",children:Re.content.met?(0,h.jsxs)(I,{color:"green",children:["\u2714 Goal achieved",H7(Re.content.elapsedMs,Re.content.turns,Re.content.tokens)]}):(0,h.jsx)(I,{color:"yellow",children:"\u25EF Goal not yet met\u2026 continuing"})})}):Re.type==="progress"?Re.content.message.content[0]?.type==="text"&&Re.content.message.content[0].text===Na?(0,h.jsx)(wE,{message:Re.content,messages:Re.normalizedMessages,addMargin:!1,tools:Re.tools,verbose:u??!1,debug:r,erroredToolUseIDs:new Set,inProgressToolUseIDs:new Set,unresolvedToolUseIDs:new Set,shouldAnimate:!1,shouldShowDot:!1}):(0,h.jsx)(per,{meta:Re.meta,children:(0,h.jsx)(wE,{message:Re.content,messages:Re.normalizedMessages,addMargin:!1,tools:Re.tools,verbose:u??!1,debug:r,erroredToolUseIDs:new Set,inProgressToolUseIDs:new Set,unresolvedToolUseIDs:new Set([Re.content.message.content[0].id]),shouldAnimate:!1,shouldShowDot:!1})}):(0,h.jsx)(wE,{message:Re,messages:vo,addMargin:!0,tools:xr,verbose:u,debug:r,erroredToolUseIDs:Xt,inProgressToolUseIDs:Jo,shouldAnimate:!P&&!ie&&!Ar&&(!Mt||Jo.has(Mt)),shouldShowDot:!0,unresolvedToolUseIDs:au}),Er=Rmo(Re,vo,au)?"static":"transient";return r?{type:Er,jsx:(0,h.jsx)(x,{borderStyle:"single",borderColor:Er==="static"?"green":"red",width:"100%",children:Yt},Re.uuid)}:{type:Er,uuid:Re.uuid,jsx:(0,h.jsx)(x,{width:"100%",children:Yt},Re.uuid)}})],[d,p,vo,xr,u,r,Xt,Jo,P,ie,Ar,au,c]),is=!D&&Yr,za=lt>=0&&dn[lt],Vs=za?dn[lt]:null,lu=(0,Jt.useRef)(!0);(0,Jt.useEffect)(()=>(lu.current?lu.current=!0:(ts(),A(Re=>Re+1)),()=>{}),[za,Vs]);let rf=Re=>at&&jt===Re?"green":lt===Re?"cyan":"gray",hc=Re=>!!(at&&jt===Re||lt===Re),[Fl,Pp]=(0,Jt.useState)(!0);return(0,Jt.useEffect)(()=>{Pp(D&&!P&&!ie&&!Ct)},[P,ie,Ct,D]),(0,h.jsxs)(h.Fragment,{children:[za?(0,h.jsx)(ccr,{debug:r,verbose:u,tools:xr,memberName:Vs.name,showSpinner:Fl},`AgentTeamREPL-messages-${Vs}-${d}-${p}`):(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(Oce,{items:en.filter(Re=>Re.type==="static"),children:Re=>Re.jsx},`static-messages-${d}-${p}`),en.filter(Re=>Re.type==="transient").map(Re=>Re.jsx)]}),(0,h.jsxs)(x,{borderColor:"red",borderStyle:r?"single":void 0,flexDirection:"column",width:"100%",children:[Fl&&!za&&(0,h.jsx)(tB,{}),P?P.jsx:null,!P&&Ct&&!Ar&&(0,h.jsx)(acr,{m1:Ct.m1,m2:Ct.m2,resolve:Re=>{Ct.resolve(Re),setTimeout(()=>eo(null),0)},verbose:u,normalizedMessages:vo,tools:xr,debug:r,erroredToolUseIDs:Xt,inProgressToolUseIDs:Jo,unresolvedToolUseIDs:au}),!P&&ie&&!Ar&&!Ct&&(0,h.jsx)(Blr,{toolUseConfirm:ie,onDone:()=>ne(null),verbose:u}),!P&&!ie&&!Ar&&!Ct&&is&&(0,h.jsx)(mit,{onDone:()=>{Mr(!1),An(!0);let Re=Qr();Ho({...Re,hasAcknowledgedCostThreshold:!0}),Ue("tengu_cost_threshold_acknowledged",{})}}),!Bt&&!ie&&!P?.shouldHidePromptInput&&i&&!Ar&&!Ct&&!is&&!za&&(0,h.jsx)(h.Fragment,{children:(0,h.jsx)(qlr,{commands:e,tools:xr,isDisabled:rt==="invalid",isLoading:D,onQuery:Li,debug:r,verbose:u,messages:ue,setToolJSX:$,onAutoUpdaterResult:G,autoUpdaterResult:F,input:W,onInputChange:j,mode:Te,onModeChange:je,submitCount:yt,onSubmitCountChange:Sr,setIsLoading:O,setAbortController:R,onShowMessageSelector:()=>Un(Re=>!Re),setForkConvoWithMessagesOnTheNextRender:E,readFileTimestamps:_e.current,reminderText:Vn})})]}),Ar&&(0,h.jsx)(mer,{erroredToolUseIDs:Xt,unresolvedToolUseIDs:au,messages:Du(ue),onSelect:async Re=>{Un(!1),ue.includes(Re)&&(Gt(),setImmediate(async()=>{await ts(),E(Mt=>ue.slice(0,ue.indexOf(Re))),typeof Re.message.content=="string"&&j(Re.message.content)}))},onEscape:()=>Un(!1),tools:xr}),dn.length>0&&!ie&&(0,h.jsx)(x,{flexDirection:"column",width:"100%",children:(0,h.jsxs)(x,{borderStyle:at?"single":void 0,borderColor:"green",paddingLeft:1,paddingRight:1,children:[(0,h.jsx)(I,{bold:at,color:at?"green":void 0,children:"Team Members:"}),(0,h.jsxs)(I,{color:rf(-1),bold:hc(-1),children:[" ","team-lead"," "]}),dn.map((Re,Mt)=>(0,h.jsxs)(I,{color:rf(Mt),bold:hc(Mt),children:[Re.name," "]},Re.agentId)),at&&(0,h.jsx)(I,{color:"yellow",children:" [\u2190\u2192Switch Enter Confirm ESC Cancel]"})]})}),(0,h.jsxs)(x,{justifyContent:"flex-end",children:[(0,h.jsxs)(I,{dimColor:!0,children:["\u2191 "+zr.inputTokens+" \u2193 "+zr.outputTokens," tokens"]}),Je().showWindowTokens&&(()=>{let Re=ks(ue),Mt=P_(),Yt=Mt>0?Math.round(Re/Mt*100):0;return(0,h.jsx)(I,{dimColor:!0,children:` \xB7 ${Re} (${Yt}%) window`})})(),(0,h.jsx)(wmo,{}),(0,h.jsx)(I,{children:" "})]}),(0,h.jsx)(el,{}),Bt&&(0,h.jsx)(lcr,{onClose:()=>hr(Re=>!1),onSelect:async(Re,Mt)=>{hr(!1),Gt(),setImmediate(async()=>{await ts(),iT(),od.clearTodos(),dl.clearGoal(),qe.getInQueryContext()[oh]=0,qe.getSessionContext().switchSessionId(Mt),Ol.loadSession(Mt),C({messages:Re})})}})]})}function Rmo(e,t,r){switch(e.type){case"user":case"assistant":{let n=D$(e);return n?!r.has(n):!0}case"reminder":return!0;case"goal_status":return!0;case"progress":return!r.has(e.toolUseID)}}Kx();var Aur=Ie(wcr(),1);er();lr();we();Kt();async function Rcr({commands:e,dangerouslySkipPermissions:t,hasPermissionsToUseTool:r,prompt:n,cwd:o,tools:i,verbose:s=!1}){await Ki(o);let l=[At(n)],[c,u,d]=await Promise.all([Vh(),qo(),la()]);for await(let A of x$(l,c,u,r,{options:{commands:e,tools:i,verbose:s,dangerouslySkipPermissions:t,slowAndCapableModel:d,thinking:Je().thinking},abortController:new AbortController,readFileTimestamps:{},agentDepth:0,lazyToolMode:Ge.getLazyToolMode()}))l.push(A);let f=yc(l);if(!f||f.type!=="assistant")throw new Error("Expected content to be an assistant message");if(f.message.content[0]?.type!=="text")throw new Error(`Expected first content item to be text, but got ${JSON.stringify(f.message.content[0],null,2)}`);let p=Fa();return tm(l),{resultText:f.message.content[0].text,totalCost:VO(),messageHistoryFile:p}}we();import{cwd as kp}from"process";var Ncr=Ie(Ve(),1);Pe();we();lr();import{homedir as Ymo}from"os";function Dcr({onDone:e}){let t=re();Ncr.default.useEffect(()=>{Ue("trust_dialog_shown",{})},[]);function r(o){let i=Nn();switch(o){case"yes":{let s=Ymo()===Oe();Ue("trust_dialog_accept",{isHomeDir:String(s)}),s||ti({...i,hasTrustDialogAccepted:!0}),e();break}case"no":{process.exit(1);break}}}let n=rs(()=>process.exit(0));return ft((o,i)=>{if(i.escape){process.exit(0);return}}),(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(x,{flexDirection:"column",gap:1,padding:1,borderStyle:"round",borderColor:t.warning,children:[(0,h.jsx)(I,{bold:!0,color:t.warning,children:"Do you trust the files in this folder?"}),(0,h.jsx)(I,{bold:!0,children:process.cwd()}),(0,h.jsxs)(x,{flexDirection:"column",gap:1,children:[(0,h.jsxs)(I,{children:[it," may read files in this folder. Reading untrusted files may lead to ",it," to behave in an unexpected ways."]}),(0,h.jsxs)(I,{children:["With your permission ",it," may execute files in this folder. Executing untrusted code is unsafe."]})]}),(0,h.jsx)(fa,{options:[{label:"Yes, proceed",value:"yes"},{label:"No, exit",value:"no"}],onChange:o=>r(o)})]}),(0,h.jsx)(x,{marginLeft:3,children:(0,h.jsx)(I,{dimColor:!0,children:n.pending?(0,h.jsxs)(h.Fragment,{children:["Press ",n.keyName," again to exit"]}):(0,h.jsx)(h.Fragment,{children:"Enter to confirm \xB7 Esc to exit"})})})]})}var V$=Ie(Ve(),1);we();we();we();function C3e({context:e,type:t,logNumber:r}){let[n,o]=(0,V$.useState)([]),[i,s]=(0,V$.useState)(!1);(0,V$.useEffect)(()=>{Nv(t==="messages"?Kn.messages():Kn.errors()).then(l=>{if(r!==void 0){let c=l[r>=0?r:0];c?(console.log(JSON.stringify(c.messages,null,2)),process.exit(0)):(console.error("No log found at index",r),process.exit(1))}o(l)}).catch(l=>{be(l),r!==void 0?process.exit(1):e.unmount?.()})},[e,t,r]);function a(l){let c=n[l];c&&(s(!0),setTimeout(()=>{console.log(JSON.stringify(c.messages,null,2)),process.exit(0)},100))}return r!==void 0||i?null:(0,h.jsx)(AP,{logs:n,onSelect:a})}we();po();function Ocr({context:e,commands:t,logs:r,tools:n,verbose:o}){async function i(s){let a=r[s];if(a)try{e.unmount?.();let l=await F4();qe.getSessionContext().switchSessionId(a.date),Ol.loadSession(a.date),Sl((0,h.jsx)(Y$,{initialPrompt:"",shouldShowPromptInput:!0,verbose:o,commands:t,tools:n,initialMessages:Nce(a.messages,n),initialForkNumber:0,isDefaultModel:l}),{exitOnCtrlC:!1})}catch(l){throw be(`Failed to load conversation: ${l}`),l}}return(0,h.jsx)(AP,{logs:r,onSelect:i})}vxe();dg();ERe();YM();var kce=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};bRe();var Lce=class extends JM{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(e4.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new fk,this.setRequestHandler(Eee,n=>this._oninitialize(n)),this.setNotificationHandler(bee,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Q1e,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=e4.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new kce(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=zee(this._capabilities,t)}setRequestHandler(t,r){let o=v_(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(hp(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(l,c)=>{let u=fd(jM,l);if(!u.success){let A=u.error instanceof Error?u.error.message:String(u.error);throw new Ht(or.InvalidParams,`Invalid tools/call request: ${A}`)}let{params:d}=u.data,f=await Promise.resolve(r(l,c));if(d.task){let A=fd(mS,f);if(!A.success){let _=A.error instanceof Error?A.error.message:String(A.error);throw new Ht(or.InvalidParams,`Invalid task creation result: ${_}`)}return A.data}let p=fd(Dm,f);if(!p.success){let A=p.error instanceof Error?p.error.message:String(p.error);throw new Ht(or.InvalidParams,`Invalid tools/call result: ${A}`)}return p.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Dte(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Nte(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:Fx.includes(r)?r:zC,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},pS)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(c=>c.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],l=a.some(c=>c.type==="tool_use");if(i){if(o.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let c=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(c.size!==u.size||![...c].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},r4,r):this.request({method:"sampling/createMessage",params:t},t4,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},KM,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},KM,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new Ht(or.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof Ht?s:new Ht(or.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},$1e,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};YM();Ixe();dg();var Mcr=Symbol.for("mcp.completable");function T3e(e){return!!e&&typeof e=="object"&&Mcr in e}function kcr(e){return e[Mcr]?.complete}var Bcr;(function(e){e.Completable="McpCompletable"})(Bcr||(Bcr={}));var zmo=/^[A-Za-z0-9._-]{1,128}$/;function Vmo(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!zmo.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Wmo(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function I3e(e){let t=Vmo(e);return Wmo(e,t.warnings),t.isValid}var Pce=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};sn();var Fce=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Lce(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Pce(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(OI(Mee)),this.server.assertCanSetRequestHandler(OI(jM)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Mee,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=qM(r.inputSchema);return o?yxe(o,{strictUnions:!0,pipeStrategy:"input"}):jmo})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=qM(r.outputSchema);o&&(n.outputSchema=yxe(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(jM,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new Ht(or.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new Ht(or.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new Ht(or.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new Ht(or.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof Ht&&n.code===or.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=qM(t.inputSchema)??t.inputSchema,s=await aee(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",l=lee(a);throw new Ht(or.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Ht(or.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=qM(t.outputSchema),i=await aee(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=lee(s);throw new Ht(or.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),l=a.task.taskId,c=a.task,u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let d=await n.taskStore.getTask(l);if(!d)throw new Ht(or.InternalError,`Task ${l} not found during polling`);c=d}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(OI(kee)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(kee,async t=>{switch(t.params.ref.type){case"ref/prompt":return cyt(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return uyt(t),this.handleResourceCompletion(t,t.params.ref);default:throw new Ht(or.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new Ht(or.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Ht(or.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return W$;let i=v_(n.argsSchema)?.[t.params.argument.name];if(!T3e(i))return W$;let s=kcr(i);if(!s)return W$;let a=await s(t.params.argument.value,t.params.context);return Pcr(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return W$;throw new Ht(or.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return W$;let i=await o(t.params.argument.value,t.params.context);return Pcr(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(OI(Ree)),this.server.assertCanSetRequestHandler(OI(Nee)),this.server.assertCanSetRequestHandler(OI(Dee)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ree,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Nee,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Dee,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Ht(or.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new Ht(or.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(OI(Oee)),this.server.assertCanSetRequestHandler(OI(Bee)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Oee,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?Jmo(r.argsSchema):void 0}))})),this.server.setRequestHandler(Bee,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new Ht(or.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new Ht(or.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=qM(n.argsSchema),i=await aee(o,t.params.arguments);if(!i.success){let l="error"in i?i.error:"Unknown error",c=lee(l);throw new Ht(or.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=s)),typeof c.title<"u"&&(s.title=c.title),typeof c.template<"u"&&(s.resourceTemplate=c.template),typeof c.metadata<"u"&&(s.metadata=c.metadata),typeof c.callback<"u"&&(s.readCallback=c.callback),typeof c.enabled<"u"&&(s.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Px(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Px(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(l=>{let c=l instanceof Wd?l._def?.innerType:l;return T3e(c)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,l,c){I3e(t);let u={title:r,description:n,inputSchema:Lcr(o),outputSchema:Lcr(i),annotations:s,execution:a,_meta:l,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&I3e(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=Px(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=Px(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];v3e(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!v3e(r[0])&&(s=r.shift())):typeof l=="object"&&l!==null&&(s=r.shift())}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:l,_meta:c}=r;return this._createRegisteredTool(t,o,i,s,a,l,{taskSupport:"forbidden"},c,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var jmo={type:"object",properties:{}};function Fcr(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Kmo(e){return"_def"in e||"_zod"in e||Fcr(e)}function v3e(e){return typeof e!="object"||e===null||Kmo(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Fcr)}function Lcr(e){if(e)return v3e(e)?Px(e):e}function Jmo(e){let t=v_(e);return t?Object.entries(t).map(([r,n])=>{let o=mSt(n),i=fSt(n);return{name:r,description:o,required:!i}}):[]}function OI(e){let r=v_(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=cee(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Pcr(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var W$={completion:{values:[],hasMore:!1}};import Qcr from"node:process";var Qce=class{constructor(t=Qcr.stdin,r=Qcr.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new qk,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=ine(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{Http2ServerRequest as Zmo}from"http2";import{Http2ServerRequest as x3e}from"http2";import{Readable as Ucr}from"stream";import ufo from"crypto";var $R=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},Xmo=e=>e instanceof $R?e:new $R(e.message,{cause:e}),efo=global.Request,j$=class extends efo{constructor(e,t){typeof e=="object"&&bP in e&&(e=e[bP]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},tfo=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:i}=r;o.charCodeAt(0)!==58&&t.push([o,i])}return new Headers(t)},Hcr=Symbol("wrapBodyStream"),rfo=(e,t,r,n,o)=>{let i={method:e,headers:r,signal:o.signal};if(e==="TRACE"){i.method="GET";let s=new j$(t,i);return Object.defineProperty(s,"method",{get(){return"TRACE"}}),s}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)i.body=new ReadableStream({start(s){s.enqueue(n.rawBody),s.close()}});else if(n[Hcr]){let s;i.body=new ReadableStream({async pull(a){try{s||=Ucr.toWeb(n).getReader();let{done:l,value:c}=await s.read();l?a.close():a.enqueue(c)}catch(l){a.error(l)}}})}else i.body=Ucr.toWeb(n);return new j$(t,i)},bP=Symbol("getRequestCache"),nfo=Symbol("requestCache"),Uce=Symbol("incomingKey"),Gce=Symbol("urlKey"),ofo=Symbol("headersKey"),EP=Symbol("abortControllerKey"),ifo=Symbol("getAbortController"),Hce={get method(){return this[Uce].method||"GET"},get url(){return this[Gce]},get headers(){return this[ofo]||=tfo(this[Uce])},[ifo](){return this[bP](),this[EP]},[bP](){return this[EP]||=new AbortController,this[nfo]||=rfo(this.method,this[Gce],this.headers,this[Uce],this[EP])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(Hce,e,{get(){return this[bP]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(Hce,e,{value:function(){return this[bP]()[e]()}})});Object.setPrototypeOf(Hce,j$.prototype);var sfo=(e,t)=>{let r=Object.create(Hce);r[Uce]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof x3e)throw new $R("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[Gce]=a.href}catch(a){throw new $R("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof x3e?e.authority:e.headers.host)||t;if(!o)throw new $R("Missing host header");let i;if(e instanceof x3e){if(i=e.scheme,!(i==="http"||i==="https"))throw new $R("Unsupported scheme")}else i=e.socket&&e.socket.encrypted?"https":"http";let s=new URL(`${i}://${o}${n}`);if(s.hostname.length!==o.length&&s.hostname!==o.replace(/:\d+$/,""))throw new $R("Invalid host header");return r[Gce]=s.href,r},Gcr=Symbol("responseCache"),_P=Symbol("getResponseCache"),qR=Symbol("cache"),R3e=global.Response,K$=class $cr{#e;#t;[_P](){return delete this[qR],this[Gcr]||=new R3e(this.#e,this.#t)}constructor(t,r){let n;if(this.#e=t,r instanceof $cr){let o=r[Gcr];if(o){this.#t=o,this[_P]();return}else this.#t=r.#t,n=new Headers(r.#t.headers)}else this.#t=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(n||=r?.headers||{"content-type":"text/plain; charset=UTF-8"},this[qR]=[r?.status||200,t,n])}get headers(){let t=this[qR];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2])),t[2]):this[_P]().headers}get status(){return this[qR]?.[0]??this[_P]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(K$.prototype,e,{get(){return this[_P]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(K$.prototype,e,{value:function(){return this[_P]()[e]()}})});Object.setPrototypeOf(K$,R3e);Object.setPrototypeOf(K$.prototype,R3e.prototype);async function afo(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function qcr(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(s,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function i(){e.read().then(s,o)}function s({done:a,value:l}){try{if(a)t.end();else if(!t.write(l))t.once("drain",i);else return e.read().then(s,o)}catch(c){o(c)}}}function lfo(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:qcr(e.getReader(),t)}var Ycr=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let r=[];for(let[n,o]of e)n==="set-cookie"?r.push(o):t[n]=o;return r.length>0&&(t["set-cookie"]=r),t["content-type"]??="text/plain; charset=UTF-8",t},cfo="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=ufo);var N3e=Symbol("outgoingEnded"),dfo=()=>new Response(null,{status:400}),zcr=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),w3e=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},Vcr=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Wcr=async(e,t)=>{let[r,n,o]=e[qR];o instanceof Headers&&(o=Ycr(o)),typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size),t.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(Vcr(t),await lfo(n,t)?.catch(i=>w3e(i,t))),t[N3e]?.()},pfo=e=>typeof e.then=="function",mfo=async(e,t,r={})=>{if(pfo(e))if(r.errorHandler)try{e=await e}catch(o){let i=await r.errorHandler(o);if(!i)return;e=i}else e=await e.catch(zcr);if(qR in e)return Wcr(e,t);let n=Ycr(e.headers);if(e.body){let o=e.body.getReader(),i=[],s=!1,a;if(n["transfer-encoding"]!=="chunked"){let l=2;for(let c=0;c<l;c++){a||=o.read();let u=await afo(a).catch(d=>{console.error(d),s=!0});if(!u){if(c===1){await new Promise(d=>setTimeout(d)),l=3;continue}break}if(a=void 0,u.value&&i.push(u.value),u.done){s=!0;break}}s&&!("content-length"in n)&&(n["content-length"]=i.reduce((c,u)=>c+u.length,0))}t.writeHead(e.status,n),i.forEach(l=>{t.write(l)}),s?t.end():(i.length===0&&Vcr(t),await qcr(o,t,a))}else n[cfo]||(t.writeHead(e.status,n),t.end());t[N3e]?.()},D3e=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==j$&&(Object.defineProperty(global,"Request",{value:j$}),Object.defineProperty(global,"Response",{value:K$})),async(n,o)=>{let i,s;try{s=sfo(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[Hcr]=!0,n.on("end",()=>{a=!0}),n instanceof Zmo&&(o[N3e]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),o.destroy()})})})),o.on("close",()=>{s[EP]&&(n.errored?s[EP].abort(n.errored.toString()):o.writableFinished||s[EP].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),i=e(s,{incoming:n,outgoing:o}),qR in i)return Wcr(i,o)}catch(a){if(i)return w3e(a,o);if(t.errorHandler){if(i=await t.errorHandler(s?a:Xmo(a)),!i)return}else s?i=zcr(a):i=dfo()}try{return await mfo(i,o,t)}catch(a){return w3e(a,o)}}};dg();var $ce=class{constructor(t={}){this._started=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=t.sessionIdGenerator,this._enableJsonResponse=t.enableJsonResponse??!1,this._eventStore=t.eventStore,this._onsessioninitialized=t.onsessioninitialized,this._onsessionclosed=t.onsessionclosed,this._allowedHosts=t.allowedHosts,this._allowedOrigins=t.allowedOrigins,this._enableDnsRebindingProtection=t.enableDnsRebindingProtection??!1,this._retryInterval=t.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(t,r,n,o){let i={code:r,message:n};return o?.data!==void 0&&(i.data=o.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:t,headers:{"Content-Type":"application/json",...o?.headers}})}validateRequestHeaders(t){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=t.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=t.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(t,r){let n=this.validateRequestHeaders(t);if(n)return n;switch(t.method){case"POST":return this.handlePostRequest(t,r);case"GET":return this.handleGetRequest(t);case"DELETE":return this.handleDeleteRequest(t);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(t,r,n,o){if(!this._eventStore||o<"2025-11-25")return;let i=await this._eventStore.storeEvent(n,{}),s=`id: ${i}
3488
3488
  data:
3489
3489
 
3490
3490
  `;this._retryInterval!==void 0&&(s=`id: ${i}
package/hands.js CHANGED
@@ -623,7 +623,7 @@ data: ${JSON.stringify(z)}
623
623
  `);a=M.pop()||"";for(let z of M){let j=z.trim();if(!(!j||j==="data: [DONE]"))if(j.startsWith("data: ")){let L=j.slice(6);try{let V=JSON.parse(L);D(V)}catch(V){this.logger&&this.logger.error({err:V,line:j},"Failed to parse Gemini SSE chunk")}}else try{let L=JSON.parse(j);D(L)}catch{}}};(async()=>{try{for(;;){let{value:M,done:z}=await s.read();if(z)break;a+=n.decode(M,{stream:!0}),N()}T()}catch(M){o.error(M)}})()}})}convertGeminiResponseToAnthropic(t){this.logger&&this.logger.debug({response:t},"Original Gemini response");try{if(!t.candidates||!t.candidates[0])throw new Error("No candidates found in Gemini response");let r=t.candidates[0],n=[];r.content&&r.content.parts&&r.content.parts.forEach(o=>{if(o.text&&n.push({type:"text",text:o.text}),o.functionCall){let s=`toolu_${YN()}`,a=o.functionCall.thoughtSignature||o.functionCall.thought_signature||null;n.push({type:"tool_use",id:s,name:o.functionCall.name,input:o.functionCall.args||{},thought_signature:a})}}),r.groundingMetadata&&(this.logger&&this.logger.debug({groundingMetadata:r.groundingMetadata},"Processing grounding metadata"),r.groundingMetadata.webSearchQueries&&n.push({type:"text",text:`
624
624
 
625
625
  [Search queries used: ${r.groundingMetadata.webSearchQueries.join(", ")}]`}));let i={id:`msg_${Math.random().toString(36).slice(2)}`,type:"message",role:"assistant",model:t.modelVersion||"gemini",content:n,stop_reason:r.finishReason?r.finishReason==="STOP"&&n.some(o=>o.type==="tool_use")?"tool_use":this.mapGeminiFinishReason(r.finishReason):"end_turn",stop_sequence:null,usage:{input_tokens:t.usageMetadata?.promptTokenCount||0,output_tokens:t.usageMetadata?.candidatesTokenCount||0}};return this.logger&&this.logger.debug({result:i},"Conversion complete, final Anthropic response"),i}catch{throw H3r(`Provider error: ${JSON.stringify(t)}`,500,"provider_error")}}mapGeminiFinishReason(t){switch(t){case"STOP":return"end_turn";case"MAX_TOKENS":return"max_tokens";case"SAFETY":case"RECITATION":return"stop_sequence";default:return"end_turn"}}},z_e=new G_e;var Rpt=Re(xpt(),1);Wt();ps();function cg(e){return e?typeof e.entries=="function"?Object.fromEntries(e.entries()):{...e}:{}}function wpt(e){let t=String(e?.["x-thinking-level"]??"medium").toLowerCase();return["off","low","medium","high"].includes(t)?t:"medium"}function ren(e,t){if(t==="off"){delete e.reasoning;return}e.reasoning={effort:t}}function nen(e,t){if(t==="off"){delete e.reasoning;return}e.reasoning={effort:t,summary:"auto"}}function ien(e,t="chat"){let r={request:{},response:{},openai:{request:{},response:{}}};return r.request.model=e.request.body.model,r.request.messages=e.request.body.messages,r.request.system=e.request.body.system,r.response.content=e.response.body.content,r.response.usage=e.response.body?.usage,t==="responses"?(r.openai.request.model=e.openai.request.body.model,r.openai.request.input=e.openai.request.body.input,r.openai.response.output=e.openai.response.body?.output,r.openai.response.usage=e.openai.response.body?.usage):(r.openai.request.model=e.openai.request.body.model,r.openai.request.messages=e.openai.request.body.messages,r.openai.response.choices=e.openai.response.body.choices,r.openai.response.usage=e.openai.response.body?.usage),r}function NU(e,t,r){TG(t,e),vG(t,ien(e,r),r)}function MB(e){let t=[],r=e.getReader(),n,i=new Promise(l=>n=l),o=!1,s=()=>{o||(o=!0,n(Buffer.concat(t).toString("utf8")))};return{stream:new ReadableStream({async pull(l){try{let{done:c,value:u}=await r.read();if(c){l.close(),s();return}t.push(u),l.enqueue(u)}catch(c){l.error(c),s()}},cancel(l){r.cancel(l).catch(()=>{}),s()}}),done:i}}function BU(e){let t=new Headers(e);return t.delete("content-encoding"),t.delete("content-length"),t.delete("transfer-encoding"),t}function _1e(e,t,r,n,i){let o;try{o={type:"error",error:{type:"api_error",message:JSON.parse(i).error?.message??`${e}: ${n}`,code:`${t}_${r}_ERROR`}}}catch{o={type:"error",error:{type:"api_error",message:`${e}: ${n}`,code:`${t}_${r}_ERROR`}}}return new Response(JSON.stringify(o),{status:r,statusText:n,headers:{"Content-Type":"application/json"}})}var Dpt=["/v1/messages"];function y1e(e){let t;try{typeof e=="string"?t=new QT(e):e instanceof QT?t=e:t=new QT(e.url)}catch{return""}let r=t.pathname;for(let n of Dpt){let i=r.indexOf(n);if(i!==-1)return t.origin+r.slice(0,i)}return t.origin}function MJ(e,t){let r=typeof e=="string"?e:e instanceof QT?e.toString():e.url,n;try{n=new QT(r).pathname}catch{return!1}return Dpt.some(i=>n.includes(i))&&(t.method==="POST"||t.method==="post")}function oen(e){return async(t,r)=>{if(!MJ(t,r))return e(t,r);let n=JSON.parse(r.body),i=await QW.transformRequestOut(n),o=y1e(t)+"/chat/completions",s=cg(r.headers),a=s.authorization??s.Authorization??"";ren(i,wpt(s));let l=await e(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:a},body:JSON.stringify(i),signal:r.signal});if(!l.ok){let y=await l.text();return K(`OpenAI Chat Completions API error: ${l.status}`,{url:o,errorResponse:y}),_1e("OpenAI Chat Completions API error","OPENROUTER",l.status,l.statusText,y)}let c=n.stream===!0,u=s["x-agent-id"],d={request:{url:o,method:r.method,headers:s,body:n},response:{status:l.status,statusText:l.statusText,headers:cg(l.headers)},openai:{request:{body:i},response:{}}};if(!c){let y=await l.text(),C=new Response(y,{status:l.status,statusText:l.statusText,headers:BU(l.headers)}),I=await QW.transformResponseIn(C,n),T=await I.text();try{NU({...d,openai:{...d.openai,response:{body:JSON.parse(y)}},response:{...d.response,body:JSON.parse(T)}},u)}catch(D){K("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Chat \u975E\u6D41\u5F0F):",D)}return new Response(T,{status:I.status,statusText:I.statusText,headers:I.headers})}let g=MB(l.body),m=new Response(g.stream,{status:l.status,statusText:l.statusText,headers:BU(l.headers)}),A=await QW.transformResponseIn(m,n),h=MB(A.body);return Promise.all([g.done,h.done]).then(async([y,C])=>{try{NU({...d,openai:{...d.openai,response:{body:await nit(y)}},response:{...d.response,body:await SF(C)}},u)}catch(I){K("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Chat \u6D41\u5F0F):"+I?.stack)}}).catch(y=>K("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Chat):"+y)),new Response(h.stream,{status:A.status,statusText:A.statusText,headers:A.headers})}}function sen(e){return async(t,r)=>{if(!MJ(t,r))return e(t,r);let n=JSON.parse(r.body),i=await PW.transformRequestOut(n),o=cg(r.headers);nen(i,wpt(o));let s=JSON.stringify(i),l=y1e(t)+"/responses",c=o.authorization??o.Authorization??"";if(!c)return new Response(JSON.stringify({type:"error",error:{type:"api_error",message:"Missing Authorization header",code:"RESPONSES_AUTH_MISSING"}}),{status:401,headers:{"Content-Type":"application/json"}});let u=await e(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:c,"x-api-key":c.replace(/^Bearer\s+/i,"").trim()},body:s,signal:r.signal});if(!u.ok){let I=await u.text();return K(`OpenAI Responses API error: ${u.status} ${u.statusText}`,{url:l,status:u.status,errorResponse:I}),_1e("OpenAI Responses API error","RESPONSES",u.status,u.statusText,I)}let d=n.stream===!0,g=o["x-agent-id"],m={request:{url:l,method:r.method,headers:o,body:n},response:{status:u.status,statusText:u.statusText,headers:cg(u.headers)},openai:{request:{body:i},response:{}}};if(!d){let I=await u.text(),T=new Response(I,{status:u.status,statusText:u.statusText,headers:BU(u.headers)}),D=await PW.transformResponseIn(T,n),N=await D.text();try{NU({...m,openai:{...m.openai,response:{body:JSON.parse(I)}},response:{...m.response,body:JSON.parse(N)}},g,"responses")}catch(M){K("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Responses \u975E\u6D41\u5F0F):",M)}return new Response(N,{status:D.status,statusText:D.statusText,headers:D.headers})}let A=MB(u.body),h=new Response(A.stream,{status:u.status,statusText:u.statusText,headers:BU(u.headers)}),y=await PW.transformResponseIn(h,n),C=MB(y.body);return Promise.all([A.done,C.done]).then(async([I,T])=>{try{NU({...m,openai:{...m.openai,response:{body:await rit(I)}},response:{...m.response,body:await SF(T)}},g,"responses")}catch(D){K("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Responses \u6D41\u5F0F):"+D?.stack)}}).catch(I=>K("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Responses):"+I)),new Response(C.stream,{status:y.status,statusText:y.statusText,headers:y.headers})}}function aen(e){return async(t,r)=>{if(!MJ(t,r))return e(t,r);let n=JSON.parse(r.body),i=cg(r.headers),o=await z_e.transformRequestOut(n),s=JSON.stringify(o),a=y1e(t)+`/models/${n.model}:streamGenerateContent?alt=sse`,l=i.authorization??i.Authorization??"",c;try{c=await e(a,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":String(l).replace(/^Bearer\s+/i,"").trim()},body:s,signal:r.signal})}catch(C){throw K("gemini request error:",C),C}if(!c.ok){let C=await c.text();return K(`Gemini API error response: ${c.status} ${c.statusText}`,{url:a,status:c.status,errorResponse:C}),_1e("Gemini API error","Gemini",c.status,c.statusText,C)}let u=n.stream===!0,d=i["x-agent-id"],g={request:{url:a,method:r.method,headers:cg(r.headers),body:n},response:{status:c.status,statusText:c.statusText,headers:cg(c.headers)},openai:{request:{body:o},response:{}}},m=MB(c.body),A=new Response(m.stream,{status:c.status,statusText:c.statusText,headers:BU(c.headers)}),h=await z_e.transformResponseIn(A),y=MB(h.body);return Promise.all([m.done,y.done]).then(async([C,I])=>{try{let T=u?iit(C):JSON.parse(C),D=u?await SF(I):JSON.parse(I);NU({...g,openai:{...g.openai,response:{body:T}},response:{...g.response,body:D}},d)}catch(T){K("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Gemini):"+T?.stack)}}).catch(C=>K("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Gemini):"+C)),new Response(y.stream,{status:h.status,statusText:h.statusText,headers:h.headers})}}function len(e){return async(t,r)=>{if(!MJ(t,r))return e(t,r);let n=r.body;if(r.body)try{let d=JSON.parse(r.body);n=JSON.stringify(d)}catch{}let i=cg(r.headers);["1","true"].includes(String(process.env.HAWA_CODE_X_API_KEY_DISABLED??"").toLowerCase())&&(delete i["x-api-key"],delete i["X-API-Key"]),["1","true"].includes(String(process.env.HAWA_CODE_AUTH_DISABLED??"").toLowerCase())&&(delete i.authorization,delete i.Authorization),delete i["content-length"];let a=await e(t,{method:r.method,headers:i,body:n,signal:r.signal});if(!a.ok){let d=await a.text();K(`API error response: ${a.status} ${a.statusText}`,{url:typeof t=="string"?t:t instanceof QT?t.toString():t.url,status:a.status,errorResponse:d});let g;try{let m=JSON.parse(d);g={type:"error",error:{type:"api_error",message:m.error?.message||m.message||`API error: ${a.statusText}`,code:m.error?.code||m.code||`API_${a.status}_ERROR`}},m.error?.details&&(g.error.details=m.error.details)}catch{g={type:"error",error:{type:"api_error",message:`API error: ${a.statusText}`,code:`API_${a.status}_ERROR`}}}return new Response(JSON.stringify(g),{status:a.status,statusText:a.statusText,headers:{"Content-Type":"application/json"}})}let l=a.clone(),c=!(Object.hasOwn(JSON.parse(n),"stream")&&!JSON.parse(n).stream),u={request:{url:typeof t=="string"?t:t instanceof QT?t.toString():t.url,method:r.method,headers:cg(r.headers),body:JSON.parse(n)},response:{status:a.status,statusText:a.statusText,headers:cg(a.headers)}};return(async()=>{if(c){let m=await a.text();u.response.body=await SF(m)}else u.response.body=await a.json();let g=cg(r.headers)["x-agent-id"];TG(g,u),vG(g,{request:u.request.body.messages,response:u.response.body.content,usage:u.response.body?.usage})})().catch(d=>K(`\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF:
626
- Stack trace: `+d.stack)),new Response(l.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}var kJ=null,E1e=!1;function cen(){kJ=null,E1e=!1}_r.on("proxy:changed",cen);function uen(){if(E1e)return kJ;if(E1e=!0,tt().proxy!==!0)return null;let e=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;return e&&(kJ=new Rpt.ProxyAgent({uri:e}),Ct(`[proxy] using proxy: ${e}`)),kJ}function den(){let e=uen();return e?((t,r={})=>global.fetch(t,{...r,dispatcher:e})):global.fetch}function QJ(e){let t=e||process.env.API_TYPE,r=den();switch(t){case"openai":return oen(r);case"openai-responses":return sen(r);case"gemini":return aen(r);default:return len(r)}}kA();var gen=Re(it(),1);function Npt(e,t){let r=[],n=Math.max(1,Math.floor(t)),i="",o=0;for(let s of e){let a=fen(s);i&&o+a>n?(r.push(i),i=s,o=a):(i+=s,o+=a)}return i&&r.push(i),r}function fen(e){if(e===" ")return 4;let t=e.codePointAt(0);return t===void 0||t===0||t<32||t>=127&&t<160||pen(t)?0:men(t)?2:1}function pen(e){return e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071}function men(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=127744&&e<=128591||e>=129280&&e<=129535||e>=131072&&e<=262141)}function O0(e){if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),n=(e%6e4/1e3).toFixed(1);return t>0?`${t}h ${r}m ${n}s`:r>0?`${r}m ${n}s`:`${n}s`}function AC(e){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(e).toLowerCase()}Oe();ps();var Gl={totalCost:0,totalAPIDuration:0,startTime:Date.now(),inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,currentContextTokens:0};function PJ(e,t){Gl.totalCost+=e,Gl.totalAPIDuration+=t}function LJ(e,t){Gl.inputTokens+=e,Gl.outputTokens+=t,_r.emit("token:change",{inputTokens:Gl.inputTokens,outputTokens:Gl.outputTokens})}function FJ(e,t){Gl.cacheCreationTokens+=e,Gl.cacheReadTokens+=t}function b1e(){return{inputTokens:Gl.inputTokens,outputTokens:Gl.outputTokens,cacheCreationTokens:Gl.cacheCreationTokens,cacheReadTokens:Gl.cacheReadTokens}}function Bpt(){return Gl.totalCost}function Opt(){return Date.now()-Gl.startTime}function kpt(){return Gl.totalAPIDuration}function Mpt(e){Gl.currentContextTokens=e}function Qpt(){return Gl.currentContextTokens}Oe();He();He();var C1e="2.7.18";globalThis.MACRO={VERSION:C1e,PACKAGE_URL:`@dahawa/${Fi}`,README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var UJ=process.env.HAWA_CODE_USER_AGENT||`${Fi}/${C1e} (${process.env.USER_TYPE})`;import{randomUUID as jh}from"crypto";ps();Oe();er();Ar();Oe();He();import{existsSync as L0,readdirSync as qin,statSync as Gin}from"fs";import{join as yC,relative as zin}from"path";import{homedir as xAt}from"os";import{platform as jin}from"process";import{readFile as bC}from"fs/promises";Ar();qp();Wt();import{join as yen,sep as ben}from"path";function Gp(){if(!au())return!1;try{let e=tt();if(e.autoMemory?.teamMemoryEnabled!==void 0)return e.autoMemory.teamMemoryEnabled}catch{}return!1}function Cf(){return(yen(Be(),".hcode","team-memory")+ben).normalize("NFC")}function M0(e){let t=e.normalize("NFC"),r=Cf();return t.startsWith(r)}qp();var wAt=Re($U(),1);Ci();var F1e=(e,t,r)=>{let n=e instanceof RegExp?tAt(e,r):e,i=t instanceof RegExp?tAt(t,r):t,o=n!==null&&i!=null&&Onn(n,i,r);return o&&{start:o[0],end:o[1],pre:r.slice(0,o[0]),body:r.slice(o[0]+n.length,o[1]),post:r.slice(o[1]+i.length)}},tAt=(e,t)=>{let r=t.match(e);return r?r[0]:null},Onn=(e,t,r)=>{let n,i,o,s,a,l=r.indexOf(e),c=r.indexOf(t,l+1),u=l;if(l>=0&&c>0){if(e===t)return[l,c];for(n=[],o=r.length;u>=0&&!a;){if(u===l)n.push(u),l=r.indexOf(e,u+1);else if(n.length===1){let d=n.pop();d!==void 0&&(a=[d,c])}else i=n.pop(),i!==void 0&&i<o&&(o=i,s=c),c=r.indexOf(t,u+1);u=l<c&&l>=0?l:c}n.length&&s!==void 0&&(a=[o,s])}return a};var rAt="\0SLASH"+Math.random()+"\0",nAt="\0OPEN"+Math.random()+"\0",H1e="\0CLOSE"+Math.random()+"\0",iAt="\0COMMA"+Math.random()+"\0",oAt="\0PERIOD"+Math.random()+"\0",knn=new RegExp(rAt,"g"),Mnn=new RegExp(nAt,"g"),Qnn=new RegExp(H1e,"g"),Pnn=new RegExp(iAt,"g"),Lnn=new RegExp(oAt,"g"),Fnn=/\\\\/g,Unn=/\\{/g,$nn=/\\}/g,Hnn=/\\,/g,qnn=/\\\./g,Gnn=1e5,znn=4e6;function U1e(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function jnn(e){return e.replace(Fnn,rAt).replace(Unn,nAt).replace($nn,H1e).replace(Hnn,iAt).replace(qnn,oAt)}function Ynn(e){return e.replace(knn,"\\").replace(Mnn,"{").replace(Qnn,"}").replace(Pnn,",").replace(Lnn,".")}function sAt(e){if(!e)return[""];let t=[],r=F1e("{","}",e);if(!r)return e.split(",");let{pre:n,body:i,post:o}=r,s=n.split(",");s[s.length-1]+="{"+i+"}";let a=sAt(o);return o.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),t.push.apply(t,s),t}function aAt(e,t={}){if(!e)return[];let{max:r=Gnn,maxLength:n=znn}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),$1e(jnn(e),r,n,!0).map(Ynn)}function Vnn(e){return"{"+e+"}"}function Wnn(e){return/^-?0\d/.test(e)}function Knn(e,t){return e<=t}function Jnn(e,t){return e>=t}function HU(e,t,r,n,i,o){let s=[],a=0;for(let l=0;l<e.length;l++)for(let c=0;c<r.length;c++){if(s.length>=n)return s;let u=e[l]+t+r[c];if(!(o&&!u)){if(a+u.length>i)return s;s.push(u),a+=u.length}}return s}function Znn(e,t,r,n){let i=e.split(/\.\./),o=[];if(i[0]===void 0||i[1]===void 0)return o;let s=U1e(i[0]),a=U1e(i[1]),l=Math.max(i[0].length,i[1].length),c=i.length===3&&i[2]!==void 0?Math.max(Math.abs(U1e(i[2])),1):1,u=Knn;a<s&&(c*=-1,u=Jnn);let g=i.some(Wnn),m=0;for(let A=s;u(A,a)&&o.length<r;A+=c){let h;if(t)h=String.fromCharCode(A),h==="\\"&&(h="");else if(h=String(A),g){let y=l-h.length;if(y>0){let C=new Array(y+1).join("0");A<0?h="-"+C+h.slice(1):h=C+h}}if(m+h.length>n)break;o.push(h),m+=h.length}return o}function $1e(e,t,r,n){let i=[""],o=!1,s=!0;for(;;){let a=F1e("{","}",e);if(!a)return HU(i,e,[""],t,r,o);let l=a.pre;if(/\$$/.test(l)){if(i=HU(i,l+"{"+a.body+"}",[""],t,r,o&&!a.post.length),s=!1,!a.post.length)break;e=a.post;continue}let c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(a.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(a.body),d=c||u,g=a.body.indexOf(",")>=0;if(!d&&!g){if(a.post.match(/,(?!,).*\}/)){e=a.pre+"{"+a.body+H1e+a.post,n=!0;continue}return HU(i,l+"{"+a.body+"}"+a.post,[""],t,r,o)}s&&(o=n&&!d,s=!1);let m;if(d)m=Znn(a.body,u,t,r);else{let A=sAt(a.body);if(A.length===1&&A[0]!==void 0&&(A=$1e(A[0],t,r,!1).map(Vnn),A.length===1)){if(i=HU(i,l+A[0],[""],t,r,o&&!a.post.length),!a.post.length)break;e=a.post;continue}let h=o&&!a.post.length&&!l;for(let C=0;h&&C<i.length;C++)i[C]&&(h=!1);m=[];let y=0;e:for(let C=0;C<A.length;C++){let I=$1e(A[C],t,r,!1);for(let T=0;T<I.length;T++){let D=I[T];if(!(h&&!D)){if(m.length>=t||y+D.length>r)break e;m.push(D),y+=D.length}}}}if(i=HU(i,l,m,t,r,o&&!a.post.length),!a.post.length)break;e=a.post}return i}var qU=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")};var Xnn={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},GU=e=>e.replace(/[[\]\\-]/g,"\\$&"),ein=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),lAt=e=>e.join(""),cAt=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],i=[],o=r+1,s=!1,a=!1,l=!1,c=!1,u=r,d="";e:for(;o<e.length;){let h=e.charAt(o);if((h==="!"||h==="^")&&o===r+1){c=!0,o++;continue}if(h==="]"&&s&&!l){u=o+1;break}if(s=!0,h==="\\"&&!l){l=!0,o++;continue}if(h==="["&&!l){for(let[y,[C,I,T]]of Object.entries(Xnn))if(e.startsWith(y,o)){if(d)return["$.",!1,e.length-r,!0];o+=y.length,T?i.push(C):n.push(C),a=a||I;continue e}}if(l=!1,d){h>d?n.push(GU(d)+"-"+GU(h)):h===d&&n.push(GU(h)),d="",o++;continue}if(e.startsWith("-]",o+1)){n.push(GU(h+"-")),o+=2;continue}if(e.startsWith("-",o+1)){d=h,o+=2;continue}n.push(GU(h)),o++}if(u<o)return["",!1,0,!1];if(!n.length&&!i.length)return["$.",!1,e.length-r,!0];if(i.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let h=n[0].length===2?n[0].slice(-1):n[0];return[ein(h),!1,u-r,!1]}let g="["+(c?"^":"")+lAt(n)+"]",m="["+(c?"":"^")+lAt(i)+"]";return[n.length&&i.length?"("+g+"|"+m+")":n.length?g:m,a,u-r,!0]};var _C=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!0}={})=>r?t?e.replace(/\[([^/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):t?e.replace(/\[([^/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var fd,tin=new Set(["!","?","+","*","@"]),q1e=e=>tin.has(e),uAt=e=>q1e(e.type),rin=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),nin=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),iin=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),dAt=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),oin="(?!(?:^|/)\\.\\.?(?:$|/))",XJ="(?!\\.)",sin=new Set(["[","."]),ain=new Set(["..","."]),lin=new Set("().*{}+?[]^$\\!"),cin=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),G1e="[^/]",fAt=G1e+"*?",pAt=G1e+"+?",uin=0,GT=class{type;#e;#t;#n=!1;#r=[];#o;#i;#l;#s=!1;#a;#d;#p=!1;id=++uin;get depth(){return(this.#o?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#e.id,parent:this.#o?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(t,r,n={}){this.type=t,t&&(this.#t=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#l=this.#e===this?[]:this.#e.#l,t==="!"&&!this.#e.#s&&this.#l.push(this),this.#i=this.#o?this.#o.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#d=this.#r.map(t=>String(t)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#s)return this;this.toString(),this.#s=!0;let t;for(;t=this.#l.pop();){if(t.type!=="!")continue;let r=t,n=r.#o;for(;n;){for(let i=r.#i+1;!n.type&&i<n.#r.length;i++)for(let o of t.#r){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(n.#r[i])}r=n,n=r.#o}}return this}push(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof fd&&r.#o===this))throw new Error("invalid part: "+r);this.#r.push(r)}}toJSON(){let t=this.type===null?this.#r.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#r.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#i===0)return!0;let t=this.#o;for(let r=0;r<this.#i;r++){let n=t.#r[r];if(!(n instanceof fd&&n.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let t=this.#o?this.#o.#r.length:0;return this.#i===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let r=new fd(this.type,t);for(let n of this.#r)r.copyIn(n);return r}static#c(t,r,n,i,o){let s=i.maxExtglobRecursion??2,a=!1,l=!1,c=-1,u=!1;if(r.type===null){let h=n,y="";for(;h<t.length;){let C=t.charAt(h++);if(a||C==="\\"){a=!a,y+=C;continue}if(l){h===c+1?(C==="^"||C==="!")&&(u=!0):C==="]"&&!(h===c+2&&u)&&(l=!1),y+=C;continue}else if(C==="["){l=!0,c=h,u=!1,y+=C;continue}if(!i.noext&&q1e(C)&&t.charAt(h)==="("&&o<=s){r.push(y),y="";let T=new fd(C,r);h=fd.#c(t,T,h,i,o+1),r.push(T);continue}y+=C}return r.push(y),h}let d=n+1,g=new fd(null,r),m=[],A="";for(;d<t.length;){let h=t.charAt(d++);if(a||h==="\\"){a=!a,A+=h;continue}if(l){d===c+1?(h==="^"||h==="!")&&(u=!0):h==="]"&&!(d===c+2&&u)&&(l=!1),A+=h;continue}else if(h==="["){l=!0,c=d,u=!1,A+=h;continue}if(!i.noext&&q1e(h)&&t.charAt(d)==="("&&(o<=s||r&&r.#E(h))){let C=r&&r.#E(h)?0:1;g.push(A),A="";let I=new fd(h,g);g.push(I),d=fd.#c(t,I,d,i,o+C);continue}if(h==="|"){g.push(A),A="",m.push(g),g=new fd(null,r);continue}if(h===")")return A===""&&r.#r.length===0&&(r.#p=!0),g.push(A),A="",r.push(...m,g),d;A+=h}return r.type=null,r.#t=void 0,r.#r=[t.substring(n-1)],d}#g(t){return this.#h(t,nin)}#h(t,r=rin){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null)return!1;let n=t.#r[0];return!n||typeof n!="object"||n.type===null?!1:this.#E(n.type,r)}#E(t,r=iin){return!!r.get(this.type)?.includes(t)}#A(t,r){let n=t.#r[0],i=new fd(null,n,this.options);i.#r.push(""),n.push(i),this.#v(t,r)}#v(t,r){let n=t.#r[0];this.#r.splice(r,1,...n.#r);for(let i of n.#r)typeof i=="object"&&(i.#o=this);this.#d=void 0}#y(t){return!!dAt.get(this.type)?.has(t)}#S(t){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let r=t.#r[0];return!r||typeof r!="object"||r.type===null?!1:this.#y(r.type)}#I(t){let r=dAt.get(this.type),n=t.#r[0],i=r?.get(n.type);if(!i)return!1;this.#r=n.#r;for(let o of this.#r)typeof o=="object"&&(o.#o=this);this.type=i,this.#d=void 0,this.#p=!1}static fromGlob(t,r={}){let n=new fd(null,void 0,r);return fd.#c(t,n,0,r,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let t=this.toString(),[r,n,i,o]=this.toRegExpSource();if(!(i||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){let r=t??!!this.#a.dot;if(this.#e===this&&(this.#_(),this.#f()),!uAt(this)){let l=this.isStart()&&this.isEnd()&&!this.#r.some(m=>typeof m!="string"),c=this.#r.map(m=>{let[A,h,y,C]=typeof m=="string"?fd.#C(m,this.#t,l):m.toRegExpSource(t);return this.#t=this.#t||y,this.#n=this.#n||C,A}).join(""),u="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&ain.has(this.#r[0]))){let A=sin,h=r&&A.has(c.charAt(0))||c.startsWith("\\.")&&A.has(c.charAt(2))||c.startsWith("\\.\\.")&&A.has(c.charAt(4)),y=!r&&!t&&A.has(c.charAt(0));u=h?oin:y?XJ:""}let d="";return this.isEnd()&&this.#e.#s&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,_C(c),this.#t=!!this.#t,this.#n]}let n=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",o=this.#b(r);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let l=this.toString(),c=this;return c.#r=[l],c.type=null,c.#t=void 0,[l,_C(this.toString()),!1,!1]}let s=!n||t||r||!XJ?"":this.#b(!0);s===o&&(s=""),s&&(o=`(?:${o})(?:${s})*?`);let a="";if(this.type==="!"&&this.#p)a=(this.isStart()&&!r?XJ:"")+pAt;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?XJ:"")+fAt+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=i+o+l}return[a,_C(o),this.#t=!!this.#t,this.#n]}#_(){if(uAt(this)){let t=0,r=!1;do{r=!0;for(let n=0;n<this.#r.length;n++){let i=this.#r[n];typeof i=="object"&&(i.#_(),this.#h(i)?(r=!1,this.#v(i,n)):this.#g(i)?(r=!1,this.#A(i,n)):this.#S(i)&&(r=!1,this.#I(i)))}}while(!r&&++t<10)}else for(let t of this.#r)typeof t=="object"&&t.#_();this.#d=void 0}#b(t){return this.#r.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,i,o,s]=r.toRegExpSource(t);return this.#n=this.#n||s,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#C(t,r,n=!1){let i=!1,o="",s=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(i){i=!1,o+=(lin.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,o+=n&&/^[*]+$/.test(t)?pAt:fAt,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?o+="\\\\":i=!0;continue}if(c==="["){let[u,d,g,m]=cAt(t,l);if(g){o+=u,s=s||d,l+=g-1,r=r||m;continue}}if(c==="?"){o+=G1e,r=!0;continue}o+=cin(c)}return[o,_C(t),!!r,s]}};fd=GT;var z1e=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!1}={})=>r?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&");var jl=(e,t,r={})=>(qU(t),!r.nocomment&&t.charAt(0)==="#"?!1:new zB(t,r).match(e)),din=/^\*+([^+@!?*[(]*)$/,fin=e=>t=>!t.startsWith(".")&&t.endsWith(e),pin=e=>t=>t.endsWith(e),min=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),gin=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Ain=/^\*+\.\*+$/,hin=e=>!e.startsWith(".")&&e.includes("."),Ein=e=>e!=="."&&e!==".."&&e.includes("."),_in=/^\.\*+$/,yin=e=>e!=="."&&e!==".."&&e.startsWith("."),bin=/^\*+$/,Cin=e=>e.length!==0&&!e.startsWith("."),Sin=e=>e.length!==0&&e!=="."&&e!=="..",Iin=/^\?+([^+@!?*[(]*)?$/,Tin=([e,t=""])=>{let r=AAt([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},vin=([e,t=""])=>{let r=hAt([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},xin=([e,t=""])=>{let r=hAt([e]);return t?n=>r(n)&&n.endsWith(t):r},win=([e,t=""])=>{let r=AAt([e]);return t?n=>r(n)&&n.endsWith(t):r},AAt=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},hAt=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},EAt=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",mAt={win32:{sep:"\\"},posix:{sep:"/"}},Din=EAt==="win32"?mAt.win32.sep:mAt.posix.sep;jl.sep=Din;var vc=Symbol("globstar **");jl.GLOBSTAR=vc;var Rin="[^/]",Nin=Rin+"*?",Bin="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Oin="(?:(?!(?:\\/|^)\\.).)*?",kin=(e,t={})=>r=>jl(r,e,t);jl.filter=kin;var zp=(e,t={})=>Object.assign({},e,t),Min=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return jl;let t=jl;return Object.assign((n,i,o={})=>t(n,i,zp(e,o)),{Minimatch:class extends t.Minimatch{constructor(i,o={}){super(i,zp(e,o))}static defaults(i){return t.defaults(zp(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,o,s={}){super(i,o,zp(e,s))}static fromGlob(i,o={}){return t.AST.fromGlob(i,zp(e,o))}},unescape:(n,i={})=>t.unescape(n,zp(e,i)),escape:(n,i={})=>t.escape(n,zp(e,i)),filter:(n,i={})=>t.filter(n,zp(e,i)),defaults:n=>t.defaults(zp(e,n)),makeRe:(n,i={})=>t.makeRe(n,zp(e,i)),braceExpand:(n,i={})=>t.braceExpand(n,zp(e,i)),match:(n,i,o={})=>t.match(n,i,zp(e,o)),sep:t.sep,GLOBSTAR:vc})};jl.defaults=Min;var _At=(e,t={})=>(qU(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:aAt(e,{max:t.braceExpandMax}));jl.braceExpand=_At;var Qin=(e,t={})=>new zB(e,t).makeRe();jl.makeRe=Qin;var Pin=(e,t,r={})=>{let n=new zB(t,r);return e=e.filter(i=>n.match(i)),n.options.nonull&&!e.length&&e.push(t),e};jl.match=Pin;var gAt=/[?*]|[+@!]\(.*?\)|\[|\]/,Lin=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zB=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,r={}){qU(t),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=t,this.platform=r.platform||EAt,this.isWindows=this.platform==="win32";let n="allowWindowsEscape";this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r[n]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let r of t)if(typeof r!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,r=this.options;if(!r.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...o)=>console.error(...o)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(o=>this.slashSplit(o));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let i=this.globParts.map((o,s,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=o[0]===""&&o[1]===""&&(o[2]==="?"||!gAt.test(o[2]))&&!gAt.test(o[3]),c=/^[a-z]:/i.test(o[0]);if(l)return[...o.slice(0,4),...o.slice(4).map(u=>this.parse(u))];if(c)return[o[0],...o.slice(1).map(u=>this.parse(u))]}return o.map(l=>this.parse(l))});if(this.debug(this.pattern,i),this.set=i.filter(o=>o.indexOf(!1)===-1),this.isWindows)for(let o=0;o<this.set.length;o++){let s=this.set[o];s[0]===""&&s[1]===""&&this.globParts[o][2]==="?"&&typeof s[3]=="string"&&/^[a-z]:$/i.test(s[3])&&(s[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let n of t)for(let i=0;i<n.length;i++)n[i]==="**"&&(n[i]="*");let{optimizationLevel:r=1}=this.options;return r>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):r>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let i=n;for(;r[i+1]==="**";)i++;i!==n&&r.splice(n,i-n)}return r})}levelOneOptimize(t){return t.map(r=>(r=r.reduce((n,i)=>{let o=n[n.length-1];return i==="**"&&o==="**"?n:i===".."&&o&&o!==".."&&o!=="."&&o!=="**"?(n.pop(),n):(n.push(i),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let i=1;i<t.length-1;i++){let o=t[i];i===1&&o===""&&t[0]===""||(o==="."||o==="")&&(r=!0,t.splice(i,1),i--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(r=!0,t.pop())}let n=0;for(;(n=t.indexOf("..",n+1))!==-1;){let i=t[n-1];i&&i!=="."&&i!==".."&&i!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(i))&&(r=!0,t.splice(n-1,2),n-=2)}}while(r);return t.length===0?[""]:t}firstPhasePreProcess(t){let r=!1;do{r=!1;for(let n of t){let i=-1;for(;(i=n.indexOf("**",i+1))!==-1;){let s=i;for(;n[s+1]==="**";)s++;s>i&&n.splice(i+1,s-i);let a=n[i+1],l=n[i+2],c=n[i+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;r=!0,n.splice(i,1);let u=n.slice(0);u[i]="**",t.push(u),i--}if(!this.preserveMultipleSlashes){for(let s=1;s<n.length-1;s++){let a=n[s];s===1&&a===""&&n[0]===""||(a==="."||a==="")&&(r=!0,n.splice(s,1),s--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(r=!0,n.pop())}let o=0;for(;(o=n.indexOf("..",o+1))!==-1;){let s=n[o-1];if(s&&s!=="."&&s!==".."&&s!=="**"){r=!0;let l=o===1&&n[o+1]==="**"?["."]:[];n.splice(o-1,2,...l),n.length===0&&n.push(""),o-=2}}}}while(r);return t}secondPhasePreProcess(t){for(let r=0;r<t.length-1;r++)for(let n=r+1;n<t.length;n++){let i=this.partsMatch(t[r],t[n],!this.preserveMultipleSlashes);if(i){t[r]=[],t[n]=i;break}}return t.filter(r=>r.length)}partsMatch(t,r,n=!1){let i=0,o=0,s=[],a="";for(;i<t.length&&o<r.length;)if(t[i]===r[o])s.push(a==="b"?r[o]:t[i]),i++,o++;else if(n&&t[i]==="**"&&r[o]===t[i+1])s.push(t[i]),i++;else if(n&&r[o]==="**"&&t[i]===r[o+1])s.push(r[o]),o++;else if(t[i]==="*"&&r[o]&&(this.options.dot||!r[o].startsWith("."))&&r[o]!=="**"){if(a==="b")return!1;a="a",s.push(t[i]),i++,o++}else if(r[o]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="a")return!1;a="b",s.push(r[o]),i++,o++}else return!1;return t.length===r.length&&s}parseNegate(){if(this.nonegate)return;let t=this.pattern,r=!1,n=0;for(let i=0;i<t.length&&t.charAt(i)==="!";i++)r=!r,n++;n&&(this.pattern=t.slice(n)),this.negate=r}matchOne(t,r,n=!1){let i=0,o=0;if(this.isWindows){let a=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),l=!a&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),c=typeof r[0]=="string"&&/^[a-z]:$/i.test(r[0]),u=!c&&r[0]===""&&r[1]===""&&r[2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3]),d=l?3:a?0:void 0,g=u?3:c?0:void 0;if(typeof d=="number"&&typeof g=="number"){let[m,A]=[t[d],r[g]];m.toLowerCase()===A.toLowerCase()&&(r[g]=m,o=g,i=d)}}let{optimizationLevel:s=1}=this.options;return s>=2&&(t=this.levelTwoFileOptimize(t)),r.includes(vc)?this.#e(t,r,n,i,o):this.#n(t,r,n,i,o)}#e(t,r,n,i,o){let s=r.indexOf(vc,o),a=r.lastIndexOf(vc),[l,c,u]=n?[r.slice(o,s),r.slice(s+1),[]]:[r.slice(o,s),r.slice(s+1,a),r.slice(a+1)];if(l.length){let I=t.slice(i,i+l.length);if(!this.#n(I,l,n,0,0))return!1;i+=l.length,o+=l.length}let d=0;if(u.length){if(u.length+i>t.length)return!1;let I=t.length-u.length;if(this.#n(t,u,n,I,0))d=u.length;else{if(t[t.length-1]!==""||i+u.length===t.length||(I--,!this.#n(t,u,n,I,0)))return!1;d=u.length+1}}if(!c.length){let I=!!d;for(let T=i;T<t.length-d;T++){let D=String(t[T]);if(I=!0,D==="."||D===".."||!this.options.dot&&D.startsWith("."))return!1}return n||I}let g=[[[],0]],m=g[0],A=0,h=[0];for(let I of c)I===vc?(h.push(A),m=[[],0],g.push(m)):(m[0].push(I),A++);let y=g.length-1,C=t.length-d;for(let I of g)I[1]=C-(h[y--]+I[0].length);return!!this.#t(t,g,i,0,n,0,!!d)}#t(t,r,n,i,o,s,a){let l=r[i];if(!l){for(let d=n;d<t.length;d++){a=!0;let g=t[d];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1}return a}let[c,u]=l;for(;n<=u;){if(this.#n(t.slice(0,n+c.length),c,o,n,0)&&s<this.maxGlobstarRecursion){let m=this.#t(t,r,n+c.length,i+1,o,s+1,a);if(m!==!1)return m}let g=t[n];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1;n++}return o||null}#n(t,r,n,i,o){let s,a,l,c;for(s=i,a=o,c=t.length,l=r.length;s<c&&a<l;s++,a++){this.debug("matchOne loop");let u=r[a],d=t[s];if(this.debug(r,u,d),u===!1||u===vc)return!1;let g;if(typeof u=="string"?(g=d===u,this.debug("string match",u,d,g)):(g=u.test(d),this.debug("pattern match",u,d,g)),!g)return!1}if(s===c&&a===l)return!0;if(s===c)return n;if(a===l)return s===c-1&&t[s]==="";throw new Error("wtf?")}braceExpand(){return _At(this.pattern,this.options)}parse(t){qU(t);let r=this.options;if(t==="**")return vc;if(t==="")return"";let n,i=null;(n=t.match(bin))?i=r.dot?Sin:Cin:(n=t.match(din))?i=(r.nocase?r.dot?gin:min:r.dot?pin:fin)(n[1]):(n=t.match(Iin))?i=(r.nocase?r.dot?vin:Tin:r.dot?xin:win)(n):(n=t.match(Ain))?i=r.dot?Ein:hin:(n=t.match(_in))&&(i=yin);let o=GT.fromGlob(t,this.options).toMMPattern();return i&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:i}),o}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?Nin:r.dot?Bin:Oin,i=new Set(r.nocase?["i"]:[]),o=t.map(l=>{let c=l.map(d=>{if(d instanceof RegExp)for(let g of d.flags.split(""))i.add(g);return typeof d=="string"?Lin(d):d===vc?vc:d._src});c.forEach((d,g)=>{let m=c[g+1],A=c[g-1];d!==vc||A===vc||(A===void 0?m!==void 0&&m!==vc?c[g+1]="(?:\\/|"+n+"\\/)?"+m:c[g]=n:m===void 0?c[g-1]=A+"(?:\\/|\\/"+n+")?":m!==vc&&(c[g-1]=A+"(?:\\/|\\/"+n+"\\/)"+m,c[g+1]=vc))});let u=c.filter(d=>d!==vc);if(this.partial&&u.length>=1){let d=[];for(let g=1;g<=u.length;g++)d.push(u.slice(0,g).join("/"));return"(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[s,a]=t.length>1?["(?:",")"]:["",""];o="^"+s+o+a+"$",this.partial&&(o="^(?:\\/|"+s+o.slice(1,-1)+a+")$"),this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,r=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&r)return!0;let n=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let o=this.set;this.debug(this.pattern,"set",o);let s=i[i.length-1];if(!s)for(let a=i.length-2;!s&&a>=0;a--)s=i[a];for(let a of o){let l=i;if(n.matchBase&&a.length===1&&(l=[s]),this.matchOne(l,a,r))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(t){return jl.defaults(t).Minimatch}};jl.AST=GT;jl.Minimatch=zB;jl.escape=z1e;jl.unescape=_C;var CAt=Re($U(),1);Ar();He();Oe();Xc();import{readFile as yAt}from"fs/promises";import{existsSync as j1e,readdirSync as Fin,statSync as Uin}from"fs";import{join as Y1e,relative as SAt}from"path";import{homedir as $in}from"os";function bAt(e){try{let t=(0,CAt.default)(e),r=t.data.paths,n=[];return typeof r=="string"?n=r.split(",").map(i=>i.trim()).filter(Boolean):Array.isArray(r)&&(n=r.filter(i=>typeof i=="string")),{paths:n,content:t.content.trim()}}catch(t){return ve(t),{paths:[],content:e.trim()}}}function Hin(e,t){return t.length===0?!0:t.some(r=>{try{return jl(e,r,{matchBase:!0,dot:!0})}catch(n){return ve(n),!1}})}function V1e(e){let t=[];try{if(!j1e(e))return t;let r=Fin(e);for(let n of r){let i=Y1e(e,n),o=Uin(i);o.isDirectory()?t.push(...V1e(i)):o.isFile()&&n.endsWith(".md")&&t.push(i)}}catch(r){ve(r)}return t}async function eZ(){let e=[];try{let t=Y1e($in(),Jr,"rules");if(j1e(t)){let r=V1e(t);for(let n of r)try{let i=await yAt(n,"utf-8"),{paths:o,content:s}=bAt(i);o.length>0&&e.push({filePath:n,content:s,paths:o,isProjectRule:!1})}catch(i){ve(i)}}}catch(t){ve(t)}try{let t=Y1e(Be(),Jr,"rules");if(j1e(t)){let r=V1e(t);for(let n of r)try{let i=await yAt(n,"utf-8"),{paths:o,content:s}=bAt(i);o.length>0&&e.push({filePath:SAt(Be(),n),content:s,paths:o,isProjectRule:!0})}catch(i){ve(i)}}}catch(t){ve(t)}return e}function IAt(e,t){e=yY(e);let r=yY(Be()),n=e.startsWith(r)?SAt(r,e):e;return t.filter(i=>Hin(n,i.paths))}function TAt(e){return e.length===0?"":e.map(r=>{let n=r.isProjectRule?"project instructions, checked into the codebase":"user's private global instructions for all projects";return`Contents of ${r.filePath} (${n}):
626
+ Stack trace: `+d.stack)),new Response(l.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}var kJ=null,E1e=!1;function cen(){kJ=null,E1e=!1}_r.on("proxy:changed",cen);function uen(){if(E1e)return kJ;if(E1e=!0,tt().proxy!==!0)return null;let e=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;return e&&(kJ=new Rpt.ProxyAgent({uri:e}),Ct(`[proxy] using proxy: ${e}`)),kJ}function den(){let e=uen();return e?((t,r={})=>global.fetch(t,{...r,dispatcher:e})):global.fetch}function QJ(e){let t=e||process.env.API_TYPE,r=den();switch(t){case"openai":return oen(r);case"openai-responses":return sen(r);case"gemini":return aen(r);default:return len(r)}}kA();var gen=Re(it(),1);function Npt(e,t){let r=[],n=Math.max(1,Math.floor(t)),i="",o=0;for(let s of e){let a=fen(s);i&&o+a>n?(r.push(i),i=s,o=a):(i+=s,o+=a)}return i&&r.push(i),r}function fen(e){if(e===" ")return 4;let t=e.codePointAt(0);return t===void 0||t===0||t<32||t>=127&&t<160||pen(t)?0:men(t)?2:1}function pen(e){return e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071}function men(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=127744&&e<=128591||e>=129280&&e<=129535||e>=131072&&e<=262141)}function O0(e){if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),n=(e%6e4/1e3).toFixed(1);return t>0?`${t}h ${r}m ${n}s`:r>0?`${r}m ${n}s`:`${n}s`}function AC(e){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(e).toLowerCase()}Oe();ps();var Gl={totalCost:0,totalAPIDuration:0,startTime:Date.now(),inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,currentContextTokens:0};function PJ(e,t){Gl.totalCost+=e,Gl.totalAPIDuration+=t}function LJ(e,t){Gl.inputTokens+=e,Gl.outputTokens+=t,_r.emit("token:change",{inputTokens:Gl.inputTokens,outputTokens:Gl.outputTokens})}function FJ(e,t){Gl.cacheCreationTokens+=e,Gl.cacheReadTokens+=t}function b1e(){return{inputTokens:Gl.inputTokens,outputTokens:Gl.outputTokens,cacheCreationTokens:Gl.cacheCreationTokens,cacheReadTokens:Gl.cacheReadTokens}}function Bpt(){return Gl.totalCost}function Opt(){return Date.now()-Gl.startTime}function kpt(){return Gl.totalAPIDuration}function Mpt(e){Gl.currentContextTokens=e}function Qpt(){return Gl.currentContextTokens}Oe();He();He();var C1e="2.7.19";globalThis.MACRO={VERSION:C1e,PACKAGE_URL:`@dahawa/${Fi}`,README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var UJ=process.env.HAWA_CODE_USER_AGENT||`${Fi}/${C1e} (${process.env.USER_TYPE})`;import{randomUUID as jh}from"crypto";ps();Oe();er();Ar();Oe();He();import{existsSync as L0,readdirSync as qin,statSync as Gin}from"fs";import{join as yC,relative as zin}from"path";import{homedir as xAt}from"os";import{platform as jin}from"process";import{readFile as bC}from"fs/promises";Ar();qp();Wt();import{join as yen,sep as ben}from"path";function Gp(){if(!au())return!1;try{let e=tt();if(e.autoMemory?.teamMemoryEnabled!==void 0)return e.autoMemory.teamMemoryEnabled}catch{}return!1}function Cf(){return(yen(Be(),".hcode","team-memory")+ben).normalize("NFC")}function M0(e){let t=e.normalize("NFC"),r=Cf();return t.startsWith(r)}qp();var wAt=Re($U(),1);Ci();var F1e=(e,t,r)=>{let n=e instanceof RegExp?tAt(e,r):e,i=t instanceof RegExp?tAt(t,r):t,o=n!==null&&i!=null&&Onn(n,i,r);return o&&{start:o[0],end:o[1],pre:r.slice(0,o[0]),body:r.slice(o[0]+n.length,o[1]),post:r.slice(o[1]+i.length)}},tAt=(e,t)=>{let r=t.match(e);return r?r[0]:null},Onn=(e,t,r)=>{let n,i,o,s,a,l=r.indexOf(e),c=r.indexOf(t,l+1),u=l;if(l>=0&&c>0){if(e===t)return[l,c];for(n=[],o=r.length;u>=0&&!a;){if(u===l)n.push(u),l=r.indexOf(e,u+1);else if(n.length===1){let d=n.pop();d!==void 0&&(a=[d,c])}else i=n.pop(),i!==void 0&&i<o&&(o=i,s=c),c=r.indexOf(t,u+1);u=l<c&&l>=0?l:c}n.length&&s!==void 0&&(a=[o,s])}return a};var rAt="\0SLASH"+Math.random()+"\0",nAt="\0OPEN"+Math.random()+"\0",H1e="\0CLOSE"+Math.random()+"\0",iAt="\0COMMA"+Math.random()+"\0",oAt="\0PERIOD"+Math.random()+"\0",knn=new RegExp(rAt,"g"),Mnn=new RegExp(nAt,"g"),Qnn=new RegExp(H1e,"g"),Pnn=new RegExp(iAt,"g"),Lnn=new RegExp(oAt,"g"),Fnn=/\\\\/g,Unn=/\\{/g,$nn=/\\}/g,Hnn=/\\,/g,qnn=/\\\./g,Gnn=1e5,znn=4e6;function U1e(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function jnn(e){return e.replace(Fnn,rAt).replace(Unn,nAt).replace($nn,H1e).replace(Hnn,iAt).replace(qnn,oAt)}function Ynn(e){return e.replace(knn,"\\").replace(Mnn,"{").replace(Qnn,"}").replace(Pnn,",").replace(Lnn,".")}function sAt(e){if(!e)return[""];let t=[],r=F1e("{","}",e);if(!r)return e.split(",");let{pre:n,body:i,post:o}=r,s=n.split(",");s[s.length-1]+="{"+i+"}";let a=sAt(o);return o.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),t.push.apply(t,s),t}function aAt(e,t={}){if(!e)return[];let{max:r=Gnn,maxLength:n=znn}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),$1e(jnn(e),r,n,!0).map(Ynn)}function Vnn(e){return"{"+e+"}"}function Wnn(e){return/^-?0\d/.test(e)}function Knn(e,t){return e<=t}function Jnn(e,t){return e>=t}function HU(e,t,r,n,i,o){let s=[],a=0;for(let l=0;l<e.length;l++)for(let c=0;c<r.length;c++){if(s.length>=n)return s;let u=e[l]+t+r[c];if(!(o&&!u)){if(a+u.length>i)return s;s.push(u),a+=u.length}}return s}function Znn(e,t,r,n){let i=e.split(/\.\./),o=[];if(i[0]===void 0||i[1]===void 0)return o;let s=U1e(i[0]),a=U1e(i[1]),l=Math.max(i[0].length,i[1].length),c=i.length===3&&i[2]!==void 0?Math.max(Math.abs(U1e(i[2])),1):1,u=Knn;a<s&&(c*=-1,u=Jnn);let g=i.some(Wnn),m=0;for(let A=s;u(A,a)&&o.length<r;A+=c){let h;if(t)h=String.fromCharCode(A),h==="\\"&&(h="");else if(h=String(A),g){let y=l-h.length;if(y>0){let C=new Array(y+1).join("0");A<0?h="-"+C+h.slice(1):h=C+h}}if(m+h.length>n)break;o.push(h),m+=h.length}return o}function $1e(e,t,r,n){let i=[""],o=!1,s=!0;for(;;){let a=F1e("{","}",e);if(!a)return HU(i,e,[""],t,r,o);let l=a.pre;if(/\$$/.test(l)){if(i=HU(i,l+"{"+a.body+"}",[""],t,r,o&&!a.post.length),s=!1,!a.post.length)break;e=a.post;continue}let c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(a.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(a.body),d=c||u,g=a.body.indexOf(",")>=0;if(!d&&!g){if(a.post.match(/,(?!,).*\}/)){e=a.pre+"{"+a.body+H1e+a.post,n=!0;continue}return HU(i,l+"{"+a.body+"}"+a.post,[""],t,r,o)}s&&(o=n&&!d,s=!1);let m;if(d)m=Znn(a.body,u,t,r);else{let A=sAt(a.body);if(A.length===1&&A[0]!==void 0&&(A=$1e(A[0],t,r,!1).map(Vnn),A.length===1)){if(i=HU(i,l+A[0],[""],t,r,o&&!a.post.length),!a.post.length)break;e=a.post;continue}let h=o&&!a.post.length&&!l;for(let C=0;h&&C<i.length;C++)i[C]&&(h=!1);m=[];let y=0;e:for(let C=0;C<A.length;C++){let I=$1e(A[C],t,r,!1);for(let T=0;T<I.length;T++){let D=I[T];if(!(h&&!D)){if(m.length>=t||y+D.length>r)break e;m.push(D),y+=D.length}}}}if(i=HU(i,l,m,t,r,o&&!a.post.length),!a.post.length)break;e=a.post}return i}var qU=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")};var Xnn={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},GU=e=>e.replace(/[[\]\\-]/g,"\\$&"),ein=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),lAt=e=>e.join(""),cAt=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],i=[],o=r+1,s=!1,a=!1,l=!1,c=!1,u=r,d="";e:for(;o<e.length;){let h=e.charAt(o);if((h==="!"||h==="^")&&o===r+1){c=!0,o++;continue}if(h==="]"&&s&&!l){u=o+1;break}if(s=!0,h==="\\"&&!l){l=!0,o++;continue}if(h==="["&&!l){for(let[y,[C,I,T]]of Object.entries(Xnn))if(e.startsWith(y,o)){if(d)return["$.",!1,e.length-r,!0];o+=y.length,T?i.push(C):n.push(C),a=a||I;continue e}}if(l=!1,d){h>d?n.push(GU(d)+"-"+GU(h)):h===d&&n.push(GU(h)),d="",o++;continue}if(e.startsWith("-]",o+1)){n.push(GU(h+"-")),o+=2;continue}if(e.startsWith("-",o+1)){d=h,o+=2;continue}n.push(GU(h)),o++}if(u<o)return["",!1,0,!1];if(!n.length&&!i.length)return["$.",!1,e.length-r,!0];if(i.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let h=n[0].length===2?n[0].slice(-1):n[0];return[ein(h),!1,u-r,!1]}let g="["+(c?"^":"")+lAt(n)+"]",m="["+(c?"":"^")+lAt(i)+"]";return[n.length&&i.length?"("+g+"|"+m+")":n.length?g:m,a,u-r,!0]};var _C=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!0}={})=>r?t?e.replace(/\[([^/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):t?e.replace(/\[([^/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var fd,tin=new Set(["!","?","+","*","@"]),q1e=e=>tin.has(e),uAt=e=>q1e(e.type),rin=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),nin=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),iin=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),dAt=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),oin="(?!(?:^|/)\\.\\.?(?:$|/))",XJ="(?!\\.)",sin=new Set(["[","."]),ain=new Set(["..","."]),lin=new Set("().*{}+?[]^$\\!"),cin=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),G1e="[^/]",fAt=G1e+"*?",pAt=G1e+"+?",uin=0,GT=class{type;#e;#t;#n=!1;#r=[];#o;#i;#l;#s=!1;#a;#d;#p=!1;id=++uin;get depth(){return(this.#o?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#e.id,parent:this.#o?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(t,r,n={}){this.type=t,t&&(this.#t=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#l=this.#e===this?[]:this.#e.#l,t==="!"&&!this.#e.#s&&this.#l.push(this),this.#i=this.#o?this.#o.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#d=this.#r.map(t=>String(t)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#s)return this;this.toString(),this.#s=!0;let t;for(;t=this.#l.pop();){if(t.type!=="!")continue;let r=t,n=r.#o;for(;n;){for(let i=r.#i+1;!n.type&&i<n.#r.length;i++)for(let o of t.#r){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(n.#r[i])}r=n,n=r.#o}}return this}push(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof fd&&r.#o===this))throw new Error("invalid part: "+r);this.#r.push(r)}}toJSON(){let t=this.type===null?this.#r.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#r.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#i===0)return!0;let t=this.#o;for(let r=0;r<this.#i;r++){let n=t.#r[r];if(!(n instanceof fd&&n.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let t=this.#o?this.#o.#r.length:0;return this.#i===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let r=new fd(this.type,t);for(let n of this.#r)r.copyIn(n);return r}static#c(t,r,n,i,o){let s=i.maxExtglobRecursion??2,a=!1,l=!1,c=-1,u=!1;if(r.type===null){let h=n,y="";for(;h<t.length;){let C=t.charAt(h++);if(a||C==="\\"){a=!a,y+=C;continue}if(l){h===c+1?(C==="^"||C==="!")&&(u=!0):C==="]"&&!(h===c+2&&u)&&(l=!1),y+=C;continue}else if(C==="["){l=!0,c=h,u=!1,y+=C;continue}if(!i.noext&&q1e(C)&&t.charAt(h)==="("&&o<=s){r.push(y),y="";let T=new fd(C,r);h=fd.#c(t,T,h,i,o+1),r.push(T);continue}y+=C}return r.push(y),h}let d=n+1,g=new fd(null,r),m=[],A="";for(;d<t.length;){let h=t.charAt(d++);if(a||h==="\\"){a=!a,A+=h;continue}if(l){d===c+1?(h==="^"||h==="!")&&(u=!0):h==="]"&&!(d===c+2&&u)&&(l=!1),A+=h;continue}else if(h==="["){l=!0,c=d,u=!1,A+=h;continue}if(!i.noext&&q1e(h)&&t.charAt(d)==="("&&(o<=s||r&&r.#E(h))){let C=r&&r.#E(h)?0:1;g.push(A),A="";let I=new fd(h,g);g.push(I),d=fd.#c(t,I,d,i,o+C);continue}if(h==="|"){g.push(A),A="",m.push(g),g=new fd(null,r);continue}if(h===")")return A===""&&r.#r.length===0&&(r.#p=!0),g.push(A),A="",r.push(...m,g),d;A+=h}return r.type=null,r.#t=void 0,r.#r=[t.substring(n-1)],d}#g(t){return this.#h(t,nin)}#h(t,r=rin){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null)return!1;let n=t.#r[0];return!n||typeof n!="object"||n.type===null?!1:this.#E(n.type,r)}#E(t,r=iin){return!!r.get(this.type)?.includes(t)}#A(t,r){let n=t.#r[0],i=new fd(null,n,this.options);i.#r.push(""),n.push(i),this.#v(t,r)}#v(t,r){let n=t.#r[0];this.#r.splice(r,1,...n.#r);for(let i of n.#r)typeof i=="object"&&(i.#o=this);this.#d=void 0}#y(t){return!!dAt.get(this.type)?.has(t)}#S(t){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let r=t.#r[0];return!r||typeof r!="object"||r.type===null?!1:this.#y(r.type)}#I(t){let r=dAt.get(this.type),n=t.#r[0],i=r?.get(n.type);if(!i)return!1;this.#r=n.#r;for(let o of this.#r)typeof o=="object"&&(o.#o=this);this.type=i,this.#d=void 0,this.#p=!1}static fromGlob(t,r={}){let n=new fd(null,void 0,r);return fd.#c(t,n,0,r,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let t=this.toString(),[r,n,i,o]=this.toRegExpSource();if(!(i||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){let r=t??!!this.#a.dot;if(this.#e===this&&(this.#_(),this.#f()),!uAt(this)){let l=this.isStart()&&this.isEnd()&&!this.#r.some(m=>typeof m!="string"),c=this.#r.map(m=>{let[A,h,y,C]=typeof m=="string"?fd.#C(m,this.#t,l):m.toRegExpSource(t);return this.#t=this.#t||y,this.#n=this.#n||C,A}).join(""),u="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&ain.has(this.#r[0]))){let A=sin,h=r&&A.has(c.charAt(0))||c.startsWith("\\.")&&A.has(c.charAt(2))||c.startsWith("\\.\\.")&&A.has(c.charAt(4)),y=!r&&!t&&A.has(c.charAt(0));u=h?oin:y?XJ:""}let d="";return this.isEnd()&&this.#e.#s&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,_C(c),this.#t=!!this.#t,this.#n]}let n=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",o=this.#b(r);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let l=this.toString(),c=this;return c.#r=[l],c.type=null,c.#t=void 0,[l,_C(this.toString()),!1,!1]}let s=!n||t||r||!XJ?"":this.#b(!0);s===o&&(s=""),s&&(o=`(?:${o})(?:${s})*?`);let a="";if(this.type==="!"&&this.#p)a=(this.isStart()&&!r?XJ:"")+pAt;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?XJ:"")+fAt+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=i+o+l}return[a,_C(o),this.#t=!!this.#t,this.#n]}#_(){if(uAt(this)){let t=0,r=!1;do{r=!0;for(let n=0;n<this.#r.length;n++){let i=this.#r[n];typeof i=="object"&&(i.#_(),this.#h(i)?(r=!1,this.#v(i,n)):this.#g(i)?(r=!1,this.#A(i,n)):this.#S(i)&&(r=!1,this.#I(i)))}}while(!r&&++t<10)}else for(let t of this.#r)typeof t=="object"&&t.#_();this.#d=void 0}#b(t){return this.#r.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,i,o,s]=r.toRegExpSource(t);return this.#n=this.#n||s,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#C(t,r,n=!1){let i=!1,o="",s=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(i){i=!1,o+=(lin.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,o+=n&&/^[*]+$/.test(t)?pAt:fAt,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?o+="\\\\":i=!0;continue}if(c==="["){let[u,d,g,m]=cAt(t,l);if(g){o+=u,s=s||d,l+=g-1,r=r||m;continue}}if(c==="?"){o+=G1e,r=!0;continue}o+=cin(c)}return[o,_C(t),!!r,s]}};fd=GT;var z1e=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!1}={})=>r?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&");var jl=(e,t,r={})=>(qU(t),!r.nocomment&&t.charAt(0)==="#"?!1:new zB(t,r).match(e)),din=/^\*+([^+@!?*[(]*)$/,fin=e=>t=>!t.startsWith(".")&&t.endsWith(e),pin=e=>t=>t.endsWith(e),min=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),gin=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Ain=/^\*+\.\*+$/,hin=e=>!e.startsWith(".")&&e.includes("."),Ein=e=>e!=="."&&e!==".."&&e.includes("."),_in=/^\.\*+$/,yin=e=>e!=="."&&e!==".."&&e.startsWith("."),bin=/^\*+$/,Cin=e=>e.length!==0&&!e.startsWith("."),Sin=e=>e.length!==0&&e!=="."&&e!=="..",Iin=/^\?+([^+@!?*[(]*)?$/,Tin=([e,t=""])=>{let r=AAt([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},vin=([e,t=""])=>{let r=hAt([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},xin=([e,t=""])=>{let r=hAt([e]);return t?n=>r(n)&&n.endsWith(t):r},win=([e,t=""])=>{let r=AAt([e]);return t?n=>r(n)&&n.endsWith(t):r},AAt=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},hAt=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},EAt=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",mAt={win32:{sep:"\\"},posix:{sep:"/"}},Din=EAt==="win32"?mAt.win32.sep:mAt.posix.sep;jl.sep=Din;var vc=Symbol("globstar **");jl.GLOBSTAR=vc;var Rin="[^/]",Nin=Rin+"*?",Bin="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Oin="(?:(?!(?:\\/|^)\\.).)*?",kin=(e,t={})=>r=>jl(r,e,t);jl.filter=kin;var zp=(e,t={})=>Object.assign({},e,t),Min=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return jl;let t=jl;return Object.assign((n,i,o={})=>t(n,i,zp(e,o)),{Minimatch:class extends t.Minimatch{constructor(i,o={}){super(i,zp(e,o))}static defaults(i){return t.defaults(zp(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,o,s={}){super(i,o,zp(e,s))}static fromGlob(i,o={}){return t.AST.fromGlob(i,zp(e,o))}},unescape:(n,i={})=>t.unescape(n,zp(e,i)),escape:(n,i={})=>t.escape(n,zp(e,i)),filter:(n,i={})=>t.filter(n,zp(e,i)),defaults:n=>t.defaults(zp(e,n)),makeRe:(n,i={})=>t.makeRe(n,zp(e,i)),braceExpand:(n,i={})=>t.braceExpand(n,zp(e,i)),match:(n,i,o={})=>t.match(n,i,zp(e,o)),sep:t.sep,GLOBSTAR:vc})};jl.defaults=Min;var _At=(e,t={})=>(qU(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:aAt(e,{max:t.braceExpandMax}));jl.braceExpand=_At;var Qin=(e,t={})=>new zB(e,t).makeRe();jl.makeRe=Qin;var Pin=(e,t,r={})=>{let n=new zB(t,r);return e=e.filter(i=>n.match(i)),n.options.nonull&&!e.length&&e.push(t),e};jl.match=Pin;var gAt=/[?*]|[+@!]\(.*?\)|\[|\]/,Lin=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zB=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,r={}){qU(t),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=t,this.platform=r.platform||EAt,this.isWindows=this.platform==="win32";let n="allowWindowsEscape";this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r[n]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let r of t)if(typeof r!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,r=this.options;if(!r.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...o)=>console.error(...o)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(o=>this.slashSplit(o));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let i=this.globParts.map((o,s,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=o[0]===""&&o[1]===""&&(o[2]==="?"||!gAt.test(o[2]))&&!gAt.test(o[3]),c=/^[a-z]:/i.test(o[0]);if(l)return[...o.slice(0,4),...o.slice(4).map(u=>this.parse(u))];if(c)return[o[0],...o.slice(1).map(u=>this.parse(u))]}return o.map(l=>this.parse(l))});if(this.debug(this.pattern,i),this.set=i.filter(o=>o.indexOf(!1)===-1),this.isWindows)for(let o=0;o<this.set.length;o++){let s=this.set[o];s[0]===""&&s[1]===""&&this.globParts[o][2]==="?"&&typeof s[3]=="string"&&/^[a-z]:$/i.test(s[3])&&(s[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let n of t)for(let i=0;i<n.length;i++)n[i]==="**"&&(n[i]="*");let{optimizationLevel:r=1}=this.options;return r>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):r>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let i=n;for(;r[i+1]==="**";)i++;i!==n&&r.splice(n,i-n)}return r})}levelOneOptimize(t){return t.map(r=>(r=r.reduce((n,i)=>{let o=n[n.length-1];return i==="**"&&o==="**"?n:i===".."&&o&&o!==".."&&o!=="."&&o!=="**"?(n.pop(),n):(n.push(i),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let i=1;i<t.length-1;i++){let o=t[i];i===1&&o===""&&t[0]===""||(o==="."||o==="")&&(r=!0,t.splice(i,1),i--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(r=!0,t.pop())}let n=0;for(;(n=t.indexOf("..",n+1))!==-1;){let i=t[n-1];i&&i!=="."&&i!==".."&&i!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(i))&&(r=!0,t.splice(n-1,2),n-=2)}}while(r);return t.length===0?[""]:t}firstPhasePreProcess(t){let r=!1;do{r=!1;for(let n of t){let i=-1;for(;(i=n.indexOf("**",i+1))!==-1;){let s=i;for(;n[s+1]==="**";)s++;s>i&&n.splice(i+1,s-i);let a=n[i+1],l=n[i+2],c=n[i+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;r=!0,n.splice(i,1);let u=n.slice(0);u[i]="**",t.push(u),i--}if(!this.preserveMultipleSlashes){for(let s=1;s<n.length-1;s++){let a=n[s];s===1&&a===""&&n[0]===""||(a==="."||a==="")&&(r=!0,n.splice(s,1),s--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(r=!0,n.pop())}let o=0;for(;(o=n.indexOf("..",o+1))!==-1;){let s=n[o-1];if(s&&s!=="."&&s!==".."&&s!=="**"){r=!0;let l=o===1&&n[o+1]==="**"?["."]:[];n.splice(o-1,2,...l),n.length===0&&n.push(""),o-=2}}}}while(r);return t}secondPhasePreProcess(t){for(let r=0;r<t.length-1;r++)for(let n=r+1;n<t.length;n++){let i=this.partsMatch(t[r],t[n],!this.preserveMultipleSlashes);if(i){t[r]=[],t[n]=i;break}}return t.filter(r=>r.length)}partsMatch(t,r,n=!1){let i=0,o=0,s=[],a="";for(;i<t.length&&o<r.length;)if(t[i]===r[o])s.push(a==="b"?r[o]:t[i]),i++,o++;else if(n&&t[i]==="**"&&r[o]===t[i+1])s.push(t[i]),i++;else if(n&&r[o]==="**"&&t[i]===r[o+1])s.push(r[o]),o++;else if(t[i]==="*"&&r[o]&&(this.options.dot||!r[o].startsWith("."))&&r[o]!=="**"){if(a==="b")return!1;a="a",s.push(t[i]),i++,o++}else if(r[o]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="a")return!1;a="b",s.push(r[o]),i++,o++}else return!1;return t.length===r.length&&s}parseNegate(){if(this.nonegate)return;let t=this.pattern,r=!1,n=0;for(let i=0;i<t.length&&t.charAt(i)==="!";i++)r=!r,n++;n&&(this.pattern=t.slice(n)),this.negate=r}matchOne(t,r,n=!1){let i=0,o=0;if(this.isWindows){let a=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),l=!a&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),c=typeof r[0]=="string"&&/^[a-z]:$/i.test(r[0]),u=!c&&r[0]===""&&r[1]===""&&r[2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3]),d=l?3:a?0:void 0,g=u?3:c?0:void 0;if(typeof d=="number"&&typeof g=="number"){let[m,A]=[t[d],r[g]];m.toLowerCase()===A.toLowerCase()&&(r[g]=m,o=g,i=d)}}let{optimizationLevel:s=1}=this.options;return s>=2&&(t=this.levelTwoFileOptimize(t)),r.includes(vc)?this.#e(t,r,n,i,o):this.#n(t,r,n,i,o)}#e(t,r,n,i,o){let s=r.indexOf(vc,o),a=r.lastIndexOf(vc),[l,c,u]=n?[r.slice(o,s),r.slice(s+1),[]]:[r.slice(o,s),r.slice(s+1,a),r.slice(a+1)];if(l.length){let I=t.slice(i,i+l.length);if(!this.#n(I,l,n,0,0))return!1;i+=l.length,o+=l.length}let d=0;if(u.length){if(u.length+i>t.length)return!1;let I=t.length-u.length;if(this.#n(t,u,n,I,0))d=u.length;else{if(t[t.length-1]!==""||i+u.length===t.length||(I--,!this.#n(t,u,n,I,0)))return!1;d=u.length+1}}if(!c.length){let I=!!d;for(let T=i;T<t.length-d;T++){let D=String(t[T]);if(I=!0,D==="."||D===".."||!this.options.dot&&D.startsWith("."))return!1}return n||I}let g=[[[],0]],m=g[0],A=0,h=[0];for(let I of c)I===vc?(h.push(A),m=[[],0],g.push(m)):(m[0].push(I),A++);let y=g.length-1,C=t.length-d;for(let I of g)I[1]=C-(h[y--]+I[0].length);return!!this.#t(t,g,i,0,n,0,!!d)}#t(t,r,n,i,o,s,a){let l=r[i];if(!l){for(let d=n;d<t.length;d++){a=!0;let g=t[d];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1}return a}let[c,u]=l;for(;n<=u;){if(this.#n(t.slice(0,n+c.length),c,o,n,0)&&s<this.maxGlobstarRecursion){let m=this.#t(t,r,n+c.length,i+1,o,s+1,a);if(m!==!1)return m}let g=t[n];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1;n++}return o||null}#n(t,r,n,i,o){let s,a,l,c;for(s=i,a=o,c=t.length,l=r.length;s<c&&a<l;s++,a++){this.debug("matchOne loop");let u=r[a],d=t[s];if(this.debug(r,u,d),u===!1||u===vc)return!1;let g;if(typeof u=="string"?(g=d===u,this.debug("string match",u,d,g)):(g=u.test(d),this.debug("pattern match",u,d,g)),!g)return!1}if(s===c&&a===l)return!0;if(s===c)return n;if(a===l)return s===c-1&&t[s]==="";throw new Error("wtf?")}braceExpand(){return _At(this.pattern,this.options)}parse(t){qU(t);let r=this.options;if(t==="**")return vc;if(t==="")return"";let n,i=null;(n=t.match(bin))?i=r.dot?Sin:Cin:(n=t.match(din))?i=(r.nocase?r.dot?gin:min:r.dot?pin:fin)(n[1]):(n=t.match(Iin))?i=(r.nocase?r.dot?vin:Tin:r.dot?xin:win)(n):(n=t.match(Ain))?i=r.dot?Ein:hin:(n=t.match(_in))&&(i=yin);let o=GT.fromGlob(t,this.options).toMMPattern();return i&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:i}),o}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?Nin:r.dot?Bin:Oin,i=new Set(r.nocase?["i"]:[]),o=t.map(l=>{let c=l.map(d=>{if(d instanceof RegExp)for(let g of d.flags.split(""))i.add(g);return typeof d=="string"?Lin(d):d===vc?vc:d._src});c.forEach((d,g)=>{let m=c[g+1],A=c[g-1];d!==vc||A===vc||(A===void 0?m!==void 0&&m!==vc?c[g+1]="(?:\\/|"+n+"\\/)?"+m:c[g]=n:m===void 0?c[g-1]=A+"(?:\\/|\\/"+n+")?":m!==vc&&(c[g-1]=A+"(?:\\/|\\/"+n+"\\/)"+m,c[g+1]=vc))});let u=c.filter(d=>d!==vc);if(this.partial&&u.length>=1){let d=[];for(let g=1;g<=u.length;g++)d.push(u.slice(0,g).join("/"));return"(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[s,a]=t.length>1?["(?:",")"]:["",""];o="^"+s+o+a+"$",this.partial&&(o="^(?:\\/|"+s+o.slice(1,-1)+a+")$"),this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,r=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&r)return!0;let n=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let o=this.set;this.debug(this.pattern,"set",o);let s=i[i.length-1];if(!s)for(let a=i.length-2;!s&&a>=0;a--)s=i[a];for(let a of o){let l=i;if(n.matchBase&&a.length===1&&(l=[s]),this.matchOne(l,a,r))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(t){return jl.defaults(t).Minimatch}};jl.AST=GT;jl.Minimatch=zB;jl.escape=z1e;jl.unescape=_C;var CAt=Re($U(),1);Ar();He();Oe();Xc();import{readFile as yAt}from"fs/promises";import{existsSync as j1e,readdirSync as Fin,statSync as Uin}from"fs";import{join as Y1e,relative as SAt}from"path";import{homedir as $in}from"os";function bAt(e){try{let t=(0,CAt.default)(e),r=t.data.paths,n=[];return typeof r=="string"?n=r.split(",").map(i=>i.trim()).filter(Boolean):Array.isArray(r)&&(n=r.filter(i=>typeof i=="string")),{paths:n,content:t.content.trim()}}catch(t){return ve(t),{paths:[],content:e.trim()}}}function Hin(e,t){return t.length===0?!0:t.some(r=>{try{return jl(e,r,{matchBase:!0,dot:!0})}catch(n){return ve(n),!1}})}function V1e(e){let t=[];try{if(!j1e(e))return t;let r=Fin(e);for(let n of r){let i=Y1e(e,n),o=Uin(i);o.isDirectory()?t.push(...V1e(i)):o.isFile()&&n.endsWith(".md")&&t.push(i)}}catch(r){ve(r)}return t}async function eZ(){let e=[];try{let t=Y1e($in(),Jr,"rules");if(j1e(t)){let r=V1e(t);for(let n of r)try{let i=await yAt(n,"utf-8"),{paths:o,content:s}=bAt(i);o.length>0&&e.push({filePath:n,content:s,paths:o,isProjectRule:!1})}catch(i){ve(i)}}}catch(t){ve(t)}try{let t=Y1e(Be(),Jr,"rules");if(j1e(t)){let r=V1e(t);for(let n of r)try{let i=await yAt(n,"utf-8"),{paths:o,content:s}=bAt(i);o.length>0&&e.push({filePath:SAt(Be(),n),content:s,paths:o,isProjectRule:!0})}catch(i){ve(i)}}}catch(t){ve(t)}return e}function IAt(e,t){e=yY(e);let r=yY(Be()),n=e.startsWith(r)?SAt(r,e):e;return t.filter(i=>Hin(n,i.paths))}function TAt(e){return e.length===0?"":e.map(r=>{let n=r.isProjectRule?"project instructions, checked into the codebase":"user's private global instructions for all projects";return`Contents of ${r.filePath} (${n}):
627
627
 
628
628
  ${r.content}`}).join(`
629
629
 
@@ -818,7 +818,7 @@ try {
818
818
  `],{encoding:"utf8",maxBuffer:XEt,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function uln(){try{let e=C5("where",["pwsh.exe"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0];if(e)return e}catch{}return"powershell.exe"}var dln="[Image pasted]";function n0t(e){return function(t){return(new Map(e).get(t)??(()=>{}))(t)}}function o0t({value:e,onChange:t,onSubmit:r,onExit:n,onExitMessage:i,onMessage:o,onHistoryUp:s,onHistoryDown:a,onHistoryReset:l,onCancel:c,onEscape:u,mask:d="",multiline:g=!1,cursorChar:m,invert:A,columns:h,onImagePaste:y,disableCursorMovementForUpDownKeys:C=!1,externalOffset:I,onOffsetChange:T}){let D=I,N=T,M=b5.fromText(e,h,D),[z,j]=(0,i0t.useState)(null);function L(){z&&(clearTimeout(z),j(null),o?.(!1))}let V=sv(Z=>{L(),i?.(Z,"Ctrl-C")},()=>n?.(),()=>{e&&(t(""),l?.())}),G=sv(Z=>{if(u&&!e){u();return}if(c){L(),o?.(!!e&&Z,"Press Escape again to cancel");return}L(),o?.(!!e&&Z,"Press Escape again to clear")},()=>{if(!(u&&!e)){if(c){c();return}e&&t("")}});function ae(){return b5.fromText("",h,0)}let ee=sv(Z=>i?.(Z,"Ctrl-D"),()=>n?.());function P(){return L(),M.text===""?(ee(),M):M.del()}function le(){if(d)return M;let Z=r0t();return Z===null?(t0t()&&(o?.(!0,e0t),L(),j(setTimeout(()=>{o?.(!1)},4e3))),M):(y?.(Z),M.insert(dln))}let Ee=n0t([["a",()=>M.startOfLine()],["b",()=>M.left()],["c",V],["d",P],["e",()=>M.endOfLine()],["f",()=>M.right()],["h",()=>(L(),M.backspace())],["k",()=>M.deleteToLineEnd()],["l",()=>ae()],["n",()=>se()],["p",()=>oe()],["u",()=>M.deleteToLineStart()],["v",le],["w",()=>M.deleteWordBefore()],["o",le]]),Se=n0t([["b",()=>M.prevWord()],["f",()=>M.nextWord()],["d",()=>M.deleteWordAfter()]]);function de(Z){if(g&&M.offset>0&&M.text[M.offset-1]==="\\")return M.backspace().insert(`
819
819
  `);if(Z.meta||Z.shift)return M.insert(`
820
820
  `);r?.(e)}function oe(){if(C)return s?.(),M;let Z=M.up();return Z.equals(M)&&s?.(),Z}function se(){if(C)return a?.(),M;let Z=M.down();return Z.equals(M)&&a?.(),Z}function _e(Z,W){if(W.tab)return;if(W.backspace||W.delete||Z==="\b"||Z==="\x7F"||Z==="\b"){let nt=M.backspace();M.equals(nt)||(N(nt.offset),M.text!==nt.text&&t(nt.text));return}if(!W.ctrl&&!W.meta&&Z.length>1){let nt=M.insert(Z);M.equals(nt)||(N(nt.offset),M.text!==nt.text&&t(nt.text));return}let Ne=je(W)(Z);Ne&&(M.equals(Ne)||(N(Ne.offset),M.text!==Ne.text&&t(Ne.text)))}function je(Z){if(Z.backspace||Z.delete)return L(),()=>M.backspace();switch(!0){case Z.escape:return u&&!e?()=>(u(),M):G;case(Z.leftArrow&&(Z.ctrl||Z.meta||"fn"in Z&&Z.fn)):return()=>M.prevWord();case(Z.rightArrow&&(Z.ctrl||Z.meta||"fn"in Z&&Z.fn)):return()=>M.nextWord();case Z.ctrl:return Ee;case("home"in Z&&Z.home):return()=>M.startOfLine();case("end"in Z&&Z.end):return()=>M.endOfLine();case Z.pageDown:return()=>M.endOfLine();case Z.pageUp:return()=>M.startOfLine();case Z.return:return()=>de(Z);case Z.meta:return Se;case Z.upArrow:return oe;case Z.downArrow:return se;case Z.leftArrow:return()=>M.left();case Z.rightArrow:return()=>M.right()}return function(W){switch(!0){case(W=="\x1B[H"||W=="\x1B[1~"):return M.startOfLine();case(W=="\x1B[F"||W=="\x1B[4~"):return M.endOfLine();case(W==="\b"||W==="\x7F"||W==="\b"):return L(),M.backspace();default:return M.insert(W.replace(/\r/g,`
821
- `))}}}return{onInput:_e,renderedValue:M.render(m,d,A),offset:D,setOffset:N}}function S5({value:e,placeholder:t="",focus:r=!0,mask:n,multiline:i=!1,highlightPastedText:o=!1,showCursor:s=!0,onChange:a,onSubmit:l,onExit:c,onHistoryUp:u,onHistoryDown:d,onExitMessage:g,onMessage:m,onHistoryReset:A,onCancel:h,onEscape:y,columns:C,onImagePaste:I,onPaste:T,isDimmed:D=!1,disableCursorMovementForUpDownKeys:N=!1,cursorOffset:M,onChangeCursorOffset:z}){let{onInput:j,renderedValue:L}=o0t({value:e,onChange:a,onSubmit:l,onExit:c,onExitMessage:g,onMessage:m,onHistoryReset:A,onHistoryUp:u,onHistoryDown:d,onCancel:h,onEscape:y,focus:r,mask:n,multiline:i,cursorChar:s?" ":"",highlightPastedText:o,invert:Se=>Jt.bgHex("#ffffff").hex("#000000")(Se),themeText:Se=>Jt.hex(Me().text)(Se),columns:C,onImagePaste:I,disableCursorMovementForUpDownKeys:N,externalOffset:M,onOffsetChange:z}),[V,G]=s0t.default.useState({chunks:[],timeoutId:null}),ae=Se=>(Se&&clearTimeout(Se),setTimeout(()=>{G(({chunks:de})=>{let oe=de.join("");return Promise.resolve().then(()=>T(oe)),{chunks:[],timeoutId:null}})},100));or((Se,de)=>{if(T&&(Se.length>10||V.timeoutId)){G(({chunks:oe,timeoutId:se})=>({chunks:[...oe,Se],timeoutId:ae(se)}));return}j(Se,de)},{isActive:r});let P=t?Jt.hex(Me().secondaryText)(t):void 0,le=Se=>Jt.bgHex("#ffffff").hex("#000000")(Se);s&&r&&(P=t.length>0?le(t[0])+Jt.hex(Me().secondaryText)(t.slice(1)):le(" "));let Ee=e.length==0&&t;return(0,_.jsx)(x,{wrap:"truncate-end",dimColor:D,children:Ee?P:L})}var fln=["General","Context"];function a0t({onClose:e}){let[t,r]=(0,Mo.useState)(ri()),n=Kl.useRef(ri()),[i,o]=(0,Mo.useState)(0),[s,a]=(0,Mo.useState)("General"),l=md(()=>process.exit(0)),[c,u]=(0,Mo.useState)(tt().webServer?.enabled??!1),[d,g]=(0,Mo.useState)(tt().proxy??!1),m=Kl.useRef(tt().proxy??!1),[A,h]=(0,Mo.useState)(Ue.getLazyToolMode()),y=Kl.useRef(Ue.getLazyToolMode()),[C,I]=(0,Mo.useState)(Ue.getProxyToolSchemaFormat()),T=Kl.useRef(Ue.getProxyToolSchemaFormat()),[D,N]=(0,Mo.useState)(tt().autoMode?.enabled??!0),M=Kl.useRef(tt().autoMode?.enabled??!0),[z,j]=(0,Mo.useState)(tt().memo??!1),L=Kl.useRef(tt().memo??!1),[V,G]=(0,Mo.useState)(tt().headlessBrowser??!1),[ae,ee]=(0,Mo.useState)("not_installed"),[P,le]=(0,Mo.useState)(tt().showWindowTokens??!1),Ee=Kl.useRef(tt().showWindowTokens??!1),[Se,de]=(0,Mo.useState)(tt().messageArchiving??!1),oe=Kl.useRef(tt().messageArchiving??!1),[se,_e]=(0,Mo.useState)(tt().archiveToolUseInputs??!1),je=Kl.useRef(tt().archiveToolUseInputs??!1),[Z,W]=(0,Mo.useState)(tt().archiveThinking??!1),Ne=Kl.useRef(tt().archiveThinking??!1),[nt,Je]=(0,Mo.useState)(tt().planDirectory??""),Ve=Kl.useRef(tt().planDirectory??""),[Ze,xt]=(0,Mo.useState)(String(tt().agentDepth??1)),Dr=Kl.useRef(String(tt().agentDepth??1)),[Pr,uo]=(0,Mo.useState)(String(Ue.getCodemodeMethodsMax())),an=Kl.useRef(String(Ue.getCodemodeMethodsMax())),[yn,mn]=(0,Mo.useState)(tt().codemodeSession??!1),fo=Kl.useRef(tt().codemodeSession??!1),[Mi,po]=(0,Mo.useState)(tt().disableSuggestion??!1),Wi=Kl.useRef(tt().disableSuggestion??!1),[Ki,kt]=(0,Mo.useState)(tt().plugins?.pluginClaudeCompat??!1),Mr=Kl.useRef(tt().plugins?.pluginClaudeCompat??!1),[pi,qr]=(0,Mo.useState)(null),[Co,Ji]=(0,Mo.useState)(""),[Zi,_s]=(0,Mo.useState)(0),bt=[...process.env.ANTHROPIC_API_KEY?[{id:"apiKey",label:`Use custom API key: ${Jt.bold(kb(process.env.ANTHROPIC_API_KEY))}`,value:!!(process.env.ANTHROPIC_API_KEY&&t.customApiKeyResponses?.approved?.includes(kb(process.env.ANTHROPIC_API_KEY))),type:"boolean",onChange(ye){let ge={...ri()};if(ge.customApiKeyResponses||(ge.customApiKeyResponses={approved:[],rejected:[]}),ge.customApiKeyResponses.approved||(ge.customApiKeyResponses.approved=[]),ge.customApiKeyResponses.rejected||(ge.customApiKeyResponses.rejected=[]),process.env.ANTHROPIC_API_KEY){let Ye=kb(process.env.ANTHROPIC_API_KEY);ye?(ge.customApiKeyResponses.approved=[...ge.customApiKeyResponses.approved.filter(Ke=>Ke!==Ye),Ye],ge.customApiKeyResponses.rejected=ge.customApiKeyResponses.rejected.filter(Ke=>Ke!==Ye)):(ge.customApiKeyResponses.approved=ge.customApiKeyResponses.approved.filter(Ke=>Ke!==Ye),ge.customApiKeyResponses.rejected=[...ge.customApiKeyResponses.rejected.filter(Ke=>Ke!==Ye),Ye])}ua(ge),r(ge)}}]:[],{id:"verbose",label:"Verbose output",value:t.verbose,type:"boolean",onChange(ye){let ge={...ri(),verbose:ye};ua(ge),r(ge)}},{id:"theme",label:"Theme",value:t.theme,options:["light","dark","light-daltonized","dark-daltonized"],type:"enum",onChange(ye){let ge={...ri(),theme:ye};ua(ge),r(ge)}},{id:"notifChannel",label:"Notifications",value:t.preferredNotifChannel,options:["iterm2","terminal_bell","iterm2_with_bell","notifications_disabled"],type:"enum",onChange(ye){let ge={...ri(),preferredNotifChannel:ye};ua(ge),r(ge)}},{id:"webServer",label:"Web Server",value:c?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";u(ge);let Ye=tt(),Ke={...Ye.webServer,enabled:ge,port:Ye.webServer?.port||3210,host:Ye.webServer?.host||"127.0.0.1"};yr.updateSetting("webServer",Ke),ge?E5.start().catch(()=>{}):E5.stop().catch(()=>{})}},{id:"proxy",label:"Proxy",tab:"Context",value:d?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";g(ge),yr.updateSetting("proxy",ge),_r.emit("proxy:changed")}},{id:"lazyTool",label:"Lazy Tool",tab:"Context",value:A,options:["off","loading","proxy"],type:"enum",onChange(ye){let ge=ye;h(ge),yr.updateSetting("lazyTool",ge)}},{id:"proxyToolSchemaFormat",label:"Proxy Tool Schema Format",tab:"Context",value:C,options:["ts","json","xml"],type:"enum",onChange(ye){let ge=ye==="ts"?"ts":ye==="xml"?"xml":"json";I(ge),yr.updateSetting("proxyToolSchemaFormat",ge)}},{id:"autoMode",label:"Auto Mode",value:D?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";N(ge);let Ke={...tt().autoMode,enabled:ge};yr.updateSetting("autoMode",Ke)}},{id:"memo",label:"Memo",tab:"Context",value:z?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";j(ge),yr.updateSetting("memo",ge)}},{id:"headlessBrowser",label:"Headless Browser (JS pages)",value:V?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";G(ge),yr.updateSetting("headlessBrowser",ge),ge?(ee("installing"),dv().then(Ye=>{ee(Ye?"installed":"failed")})):ee("not_installed")}},{id:"showWindowTokens",label:"Window tokens usage",value:P?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";le(ge),yr.updateSetting("showWindowTokens",ge)}},{id:"messageArchiving",label:"Message Archiving",tab:"Context",value:Se?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";de(ge),yr.updateSetting("messageArchiving",ge)}},{id:"archiveToolUseInputs",label:"Archive Tool Use Inputs",tab:"Context",value:se?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";_e(ge),yr.updateSetting("archiveToolUseInputs",ge)}},{id:"archiveThinking",label:"Archive Thinking",tab:"Context",value:Z?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";W(ge),yr.updateSetting("archiveThinking",ge)}},{id:"pluginClaudeCompat",label:"Claude Code plugin compatibility",value:Ki?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";kt(ge);let Ke={...tt().plugins,pluginClaudeCompat:ge};yr.updateSetting("plugins",Ke)}},{id:"planDirectory",label:"Plan directory",value:nt,placeholder:"Leave empty for default",type:"string",onChange(ye){Je(ye),yr.updateSetting("planDirectory",ye||void 0)}},{id:"agentDepth",label:"Agent depth",value:Ze,placeholder:"1-5",type:"string",onChange(ye){let ge=parseInt(ye,10),Ye=Number.isNaN(ge)?1:Math.min(5,Math.max(1,ge)),Ke=String(Ye);xt(Ke),yr.updateSetting("agentDepth",Ye)}},{id:"codemodeMethodsMax",label:"Codemode methods max",value:Pr,placeholder:"1-100",type:"string",onChange(ye){let ge=parseInt(ye,10),Ye=Number.isNaN(ge)?20:Math.min(100,Math.max(1,ge)),Ke=String(Ye);uo(Ke),yr.updateSetting("codemodeMethodsMax",Ye)}},{id:"codemodeSession",label:"Codemode Session Storage",value:yn?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";mn(ge),yr.updateSetting("codemodeSession",ge)}},{id:"disableSuggestion",label:"Suggestion",value:Mi?"off":"on",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="off";po(ge),yr.updateSetting("disableSuggestion",ge)}}],$e=bt.filter(ye=>(ye.tab??"General")===s);return or((ye,ge)=>{if(ge.escape){let Ke=[],Xn=!!(process.env.ANTHROPIC_API_KEY&&n.current.customApiKeyResponses?.approved?.includes(kb(process.env.ANTHROPIC_API_KEY))),So=!!(process.env.ANTHROPIC_API_KEY&&t.customApiKeyResponses?.approved?.includes(kb(process.env.ANTHROPIC_API_KEY)));Xn!==So&&Ke.push(` \u23BF ${So?"Enabled":"Disabled"} custom API key`),t.verbose!==n.current.verbose&&Ke.push(` \u23BF Set verbose to ${Jt.bold(t.verbose)}`),t.theme!==n.current.theme&&Ke.push(` \u23BF Set theme to ${Jt.bold(t.theme)}`),t.preferredNotifChannel!==n.current.preferredNotifChannel&&Ke.push(` \u23BF Set notifications to ${Jt.bold(t.preferredNotifChannel)}`),d!==m.current&&Ke.push(` \u23BF Set proxy to ${Jt.bold(d?"on":"off")}`),A!==y.current&&Ke.push(` \u23BF Set lazy tool to ${Jt.bold(A)}`),C!==T.current&&Ke.push(` \u23BF Set proxy tool schema format to ${Jt.bold(C)}`),D!==M.current&&Ke.push(` \u23BF Set auto mode to ${Jt.bold(D?"on":"off")}`),z!==L.current&&Ke.push(` \u23BF Set memo to ${Jt.bold(z?"on":"off")}`),V!==tt().headlessBrowser&&Ke.push(` \u23BF Set headless browser to ${Jt.bold(V?"on":"off")}`),P!==Ee.current&&Ke.push(` \u23BF Set window tokens usage to ${Jt.bold(P?"on":"off")}`),Se!==oe.current&&Ke.push(` \u23BF Set message archiving to ${Jt.bold(Se?"on":"off")}`),se!==je.current&&Ke.push(` \u23BF Set archive tool use inputs to ${Jt.bold(se?"on":"off")}`),Z!==Ne.current&&Ke.push(` \u23BF Set archive thinking to ${Jt.bold(Z?"on":"off")}`),Ki!==Mr.current&&Ke.push(` \u23BF Set Claude Code plugin compatibility to ${Jt.bold(Ki?"on":"off")}`),nt!==Ve.current&&Ke.push(` \u23BF Set plan directory to ${Jt.bold(nt||"default")}`),Ze!==Dr.current&&Ke.push(` \u23BF Set agent depth to ${Jt.bold(Ze)}`),Pr!==an.current&&Ke.push(` \u23BF Set codemode methods max to ${Jt.bold(Pr)}`),yn!==fo.current&&Ke.push(` \u23BF Set codemode session storage to ${Jt.bold(yn?"on":"off")}`),Mi!==Wi.current&&Ke.push(` \u23BF Set suggestion to ${Jt.bold(Mi?"off":"on")}`),Ke.length>0&&console.log(Jt.gray(Ke.join(`
821
+ `))}}}return{onInput:_e,renderedValue:M.render(m,d,A),offset:D,setOffset:N}}function S5({value:e,placeholder:t="",focus:r=!0,mask:n,multiline:i=!1,highlightPastedText:o=!1,showCursor:s=!0,onChange:a,onSubmit:l,onExit:c,onHistoryUp:u,onHistoryDown:d,onExitMessage:g,onMessage:m,onHistoryReset:A,onCancel:h,onEscape:y,columns:C,onImagePaste:I,onPaste:T,isDimmed:D=!1,disableCursorMovementForUpDownKeys:N=!1,cursorOffset:M,onChangeCursorOffset:z}){let{onInput:j,renderedValue:L}=o0t({value:e,onChange:a,onSubmit:l,onExit:c,onExitMessage:g,onMessage:m,onHistoryReset:A,onHistoryUp:u,onHistoryDown:d,onCancel:h,onEscape:y,focus:r,mask:n,multiline:i,cursorChar:s?" ":"",highlightPastedText:o,invert:Se=>Jt.bgHex("#ffffff").hex("#000000")(Se),themeText:Se=>Jt.hex(Me().text)(Se),columns:C,onImagePaste:I,disableCursorMovementForUpDownKeys:N,externalOffset:M,onOffsetChange:z}),[V,G]=s0t.default.useState({chunks:[],timeoutId:null}),ae=Se=>(Se&&clearTimeout(Se),setTimeout(()=>{G(({chunks:de})=>{let oe=de.join("");return Promise.resolve().then(()=>T(oe)),{chunks:[],timeoutId:null}})},100));or((Se,de)=>{if(T&&(Se.length>10||V.timeoutId)){G(({chunks:oe,timeoutId:se})=>({chunks:[...oe,Se],timeoutId:ae(se)}));return}j(Se,de)},{isActive:r});let P=t?Jt.hex(Me().secondaryText)(t):void 0,le=Se=>Jt.bgHex("#ffffff").hex("#000000")(Se);s&&r&&(P=t.length>0?le(t[0])+Jt.hex(Me().secondaryText)(t.slice(1)):le(" "));let Ee=e.length==0&&t;return(0,_.jsx)(x,{wrap:"truncate-end",dimColor:D,children:Ee?P:L})}var fln=["General","Context"];function a0t({onClose:e}){let[t,r]=(0,Mo.useState)(ri()),n=Kl.useRef(ri()),[i,o]=(0,Mo.useState)(0),[s,a]=(0,Mo.useState)("General"),l=md(()=>process.exit(0)),[c,u]=(0,Mo.useState)(tt().webServer?.enabled??!1),[d,g]=(0,Mo.useState)(tt().proxy??!1),m=Kl.useRef(tt().proxy??!1),[A,h]=(0,Mo.useState)(Ue.getLazyToolMode()),y=Kl.useRef(Ue.getLazyToolMode()),[C,I]=(0,Mo.useState)(Ue.getProxyToolSchemaFormat()),T=Kl.useRef(Ue.getProxyToolSchemaFormat()),[D,N]=(0,Mo.useState)(tt().autoMode?.enabled??!0),M=Kl.useRef(tt().autoMode?.enabled??!0),[z,j]=(0,Mo.useState)(tt().memo??!1),L=Kl.useRef(tt().memo??!1),[V,G]=(0,Mo.useState)(tt().headlessBrowser??!1),[ae,ee]=(0,Mo.useState)("not_installed"),[P,le]=(0,Mo.useState)(tt().showWindowTokens??!1),Ee=Kl.useRef(tt().showWindowTokens??!1),[Se,de]=(0,Mo.useState)(tt().messageArchiving??!1),oe=Kl.useRef(tt().messageArchiving??!1),[se,_e]=(0,Mo.useState)(tt().archiveToolUseInputs??!1),je=Kl.useRef(tt().archiveToolUseInputs??!1),[Z,W]=(0,Mo.useState)(tt().archiveThinking??!1),Ne=Kl.useRef(tt().archiveThinking??!1),[nt,Je]=(0,Mo.useState)(tt().planDirectory??""),Ve=Kl.useRef(tt().planDirectory??""),[Ze,xt]=(0,Mo.useState)(String(tt().agentDepth??1)),Dr=Kl.useRef(String(tt().agentDepth??1)),[Pr,uo]=(0,Mo.useState)(String(Ue.getCodemodeMethodsMax())),an=Kl.useRef(String(Ue.getCodemodeMethodsMax())),[yn,mn]=(0,Mo.useState)(tt().codemodeSession??!1),fo=Kl.useRef(tt().codemodeSession??!1),[Mi,po]=(0,Mo.useState)(tt().disableSuggestion??!1),Wi=Kl.useRef(tt().disableSuggestion??!1),[Ki,kt]=(0,Mo.useState)(tt().plugins?.pluginClaudeCompat??!1),Mr=Kl.useRef(tt().plugins?.pluginClaudeCompat??!1),[pi,qr]=(0,Mo.useState)(null),[Co,Ji]=(0,Mo.useState)(""),[Zi,_s]=(0,Mo.useState)(0),bt=[...process.env.ANTHROPIC_API_KEY?[{id:"apiKey",label:`Use custom API key: ${Jt.bold(kb(process.env.ANTHROPIC_API_KEY))}`,value:!!(process.env.ANTHROPIC_API_KEY&&t.customApiKeyResponses?.approved?.includes(kb(process.env.ANTHROPIC_API_KEY))),type:"boolean",onChange(ye){let ge={...ri()};if(ge.customApiKeyResponses||(ge.customApiKeyResponses={approved:[],rejected:[]}),ge.customApiKeyResponses.approved||(ge.customApiKeyResponses.approved=[]),ge.customApiKeyResponses.rejected||(ge.customApiKeyResponses.rejected=[]),process.env.ANTHROPIC_API_KEY){let Ye=kb(process.env.ANTHROPIC_API_KEY);ye?(ge.customApiKeyResponses.approved=[...ge.customApiKeyResponses.approved.filter(Ke=>Ke!==Ye),Ye],ge.customApiKeyResponses.rejected=ge.customApiKeyResponses.rejected.filter(Ke=>Ke!==Ye)):(ge.customApiKeyResponses.approved=ge.customApiKeyResponses.approved.filter(Ke=>Ke!==Ye),ge.customApiKeyResponses.rejected=[...ge.customApiKeyResponses.rejected.filter(Ke=>Ke!==Ye),Ye])}ua(ge),r(ge)}}]:[],{id:"verbose",label:"Verbose output",value:t.verbose,type:"boolean",onChange(ye){let ge={...ri(),verbose:ye};ua(ge),r(ge)}},{id:"theme",label:"Theme",value:t.theme,options:["light","dark","light-daltonized","dark-daltonized"],type:"enum",onChange(ye){let ge={...ri(),theme:ye};ua(ge),r(ge)}},{id:"notifChannel",label:"Notifications",value:t.preferredNotifChannel,options:["iterm2","terminal_bell","iterm2_with_bell","notifications_disabled"],type:"enum",onChange(ye){let ge={...ri(),preferredNotifChannel:ye};ua(ge),r(ge)}},{id:"webServer",label:"Web Server",value:c?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";u(ge);let Ye=tt(),Ke={...Ye.webServer,enabled:ge,port:Ye.webServer?.port||3210,host:Ye.webServer?.host||"127.0.0.1"};yr.updateSetting("webServer",Ke),ge?E5.start().catch(()=>{}):E5.stop().catch(()=>{})}},{id:"proxy",label:"Proxy",value:d?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";g(ge),yr.updateSetting("proxy",ge),_r.emit("proxy:changed")}},{id:"lazyTool",label:"Lazy Tool",tab:"Context",value:A,options:["off","loading","proxy"],type:"enum",onChange(ye){let ge=ye;h(ge),yr.updateSetting("lazyTool",ge)}},{id:"proxyToolSchemaFormat",label:"Proxy Tool Schema Format",tab:"Context",value:C,options:["ts","json","xml"],type:"enum",onChange(ye){let ge=ye==="ts"?"ts":ye==="xml"?"xml":"json";I(ge),yr.updateSetting("proxyToolSchemaFormat",ge)}},{id:"autoMode",label:"Auto Mode",value:D?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";N(ge);let Ke={...tt().autoMode,enabled:ge};yr.updateSetting("autoMode",Ke)}},{id:"headlessBrowser",label:"Headless Browser (JS pages)",value:V?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";G(ge),yr.updateSetting("headlessBrowser",ge),ge?(ee("installing"),dv().then(Ye=>{ee(Ye?"installed":"failed")})):ee("not_installed")}},{id:"showWindowTokens",label:"Window tokens usage",value:P?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";le(ge),yr.updateSetting("showWindowTokens",ge)}},{id:"messageArchiving",label:"Message Archiving",tab:"Context",value:Se?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";de(ge),yr.updateSetting("messageArchiving",ge)}},{id:"archiveToolUseInputs",label:"Archive Tool Use Inputs",tab:"Context",value:se?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";_e(ge),yr.updateSetting("archiveToolUseInputs",ge)}},{id:"archiveThinking",label:"Archive Thinking",tab:"Context",value:Z?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";W(ge),yr.updateSetting("archiveThinking",ge)}},{id:"pluginClaudeCompat",label:"Claude Code plugin compatibility",value:Ki?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";kt(ge);let Ke={...tt().plugins,pluginClaudeCompat:ge};yr.updateSetting("plugins",Ke)}},{id:"planDirectory",label:"Plan directory",value:nt,placeholder:"Leave empty for default",type:"string",onChange(ye){Je(ye),yr.updateSetting("planDirectory",ye||void 0)}},{id:"agentDepth",label:"Agent depth",value:Ze,placeholder:"1-5",type:"string",onChange(ye){let ge=parseInt(ye,10),Ye=Number.isNaN(ge)?1:Math.min(5,Math.max(1,ge)),Ke=String(Ye);xt(Ke),yr.updateSetting("agentDepth",Ye)}},{id:"codemodeMethodsMax",label:"Codemode methods max",value:Pr,placeholder:"1-100",type:"string",onChange(ye){let ge=parseInt(ye,10),Ye=Number.isNaN(ge)?20:Math.min(100,Math.max(1,ge)),Ke=String(Ye);uo(Ke),yr.updateSetting("codemodeMethodsMax",Ye)}},{id:"codemodeSession",label:"Codemode Session Storage",value:yn?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";mn(ge),yr.updateSetting("codemodeSession",ge)}},{id:"disableSuggestion",label:"Suggestion",value:Mi?"off":"on",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="off";po(ge),yr.updateSetting("disableSuggestion",ge)}},{id:"memo",label:"Memo",tab:"Context",value:z?"on":"off",options:["off","on"],type:"enum",onChange(ye){let ge=ye==="on";j(ge),yr.updateSetting("memo",ge)}}],$e=bt.filter(ye=>(ye.tab??"General")===s);return or((ye,ge)=>{if(ge.escape){let Ke=[],Xn=!!(process.env.ANTHROPIC_API_KEY&&n.current.customApiKeyResponses?.approved?.includes(kb(process.env.ANTHROPIC_API_KEY))),So=!!(process.env.ANTHROPIC_API_KEY&&t.customApiKeyResponses?.approved?.includes(kb(process.env.ANTHROPIC_API_KEY)));Xn!==So&&Ke.push(` \u23BF ${So?"Enabled":"Disabled"} custom API key`),t.verbose!==n.current.verbose&&Ke.push(` \u23BF Set verbose to ${Jt.bold(t.verbose)}`),t.theme!==n.current.theme&&Ke.push(` \u23BF Set theme to ${Jt.bold(t.theme)}`),t.preferredNotifChannel!==n.current.preferredNotifChannel&&Ke.push(` \u23BF Set notifications to ${Jt.bold(t.preferredNotifChannel)}`),d!==m.current&&Ke.push(` \u23BF Set proxy to ${Jt.bold(d?"on":"off")}`),A!==y.current&&Ke.push(` \u23BF Set lazy tool to ${Jt.bold(A)}`),C!==T.current&&Ke.push(` \u23BF Set proxy tool schema format to ${Jt.bold(C)}`),D!==M.current&&Ke.push(` \u23BF Set auto mode to ${Jt.bold(D?"on":"off")}`),z!==L.current&&Ke.push(` \u23BF Set memo to ${Jt.bold(z?"on":"off")}`),V!==tt().headlessBrowser&&Ke.push(` \u23BF Set headless browser to ${Jt.bold(V?"on":"off")}`),P!==Ee.current&&Ke.push(` \u23BF Set window tokens usage to ${Jt.bold(P?"on":"off")}`),Se!==oe.current&&Ke.push(` \u23BF Set message archiving to ${Jt.bold(Se?"on":"off")}`),se!==je.current&&Ke.push(` \u23BF Set archive tool use inputs to ${Jt.bold(se?"on":"off")}`),Z!==Ne.current&&Ke.push(` \u23BF Set archive thinking to ${Jt.bold(Z?"on":"off")}`),Ki!==Mr.current&&Ke.push(` \u23BF Set Claude Code plugin compatibility to ${Jt.bold(Ki?"on":"off")}`),nt!==Ve.current&&Ke.push(` \u23BF Set plan directory to ${Jt.bold(nt||"default")}`),Ze!==Dr.current&&Ke.push(` \u23BF Set agent depth to ${Jt.bold(Ze)}`),Pr!==an.current&&Ke.push(` \u23BF Set codemode methods max to ${Jt.bold(Pr)}`),yn!==fo.current&&Ke.push(` \u23BF Set codemode session storage to ${Jt.bold(yn?"on":"off")}`),Mi!==Wi.current&&Ke.push(` \u23BF Set suggestion to ${Jt.bold(Mi?"off":"on")}`),Ke.length>0&&console.log(Jt.gray(Ke.join(`
822
822
  `))),e();return}function Ye(){let Ke=$e[i];if(!(!Ke||!Ke.onChange)){if(Ke.type==="boolean"){Ke.onChange(!Ke.value);return}if(Ke.type==="enum"){let So=(Ke.options.indexOf(Ke.value)+1)%Ke.options.length;Ke.onChange(Ke.options[So]);return}if(Ke.type==="string"){qr(Ke.id),Ji(Ke.value);return}}}if(ge.return||ye===" "){Ye();return}ge.upArrow&&o(Ke=>Math.max(0,Ke-1)),ge.downArrow&&o(Ke=>Math.min($e.length-1,Ke+1)),(ge.leftArrow||ge.rightArrow)&&(a(Ke=>Ke==="General"?"Context":"General"),o(0))},{isActive:pi===null}),(0,_.jsxs)(_.Fragment,{children:[(0,_.jsxs)(B,{flexDirection:"column",borderStyle:"round",borderColor:Me().secondaryBorder,paddingX:1,marginTop:1,children:[(0,_.jsxs)(B,{flexDirection:"column",minHeight:2,marginBottom:1,children:[(0,_.jsx)(x,{bold:!0,children:"Settings"}),(0,_.jsxs)(x,{dimColor:!0,children:["Configure ",Rt," preferences"]})]}),(0,_.jsx)(B,{gap:3,marginBottom:1,children:fln.map(ye=>(0,_.jsx)(x,{bold:ye===s,color:ye===s?"blue":void 0,children:ye===s?`[ ${ye} ]`:` ${ye} `},ye))}),$e.map((ye,ge)=>{let Ye=ge===i;return(0,_.jsxs)(B,{height:2,minHeight:2,children:[(0,_.jsx)(B,{width:44,children:(0,_.jsxs)(x,{color:Ye?"blue":void 0,children:[Ye?Zt.pointer:" "," ",ye.label]})}),(0,_.jsxs)(B,{children:[ye.type==="boolean"?(0,_.jsx)(x,{color:Ye?"blue":void 0,children:ye.value.toString()}):ye.type==="string"&&pi===ye.id?(0,_.jsx)(S5,{value:Co,onChange:Ji,onSubmit:Ke=>{let Xn=bt.find(So=>So.id===ye.id);Xn&&Xn.type==="string"&&Xn.onChange(Ke),qr(null),_s(0)},onCancel:()=>{qr(null),Ji(""),_s(0)},placeholder:ye.placeholder,columns:Math.max(20,process.stdout.columns-50),cursorOffset:Zi,onChangeCursorOffset:_s}):(0,_.jsxs)(x,{color:(ye.id==="webServer"||ye.id==="proxy"||ye.id==="autoMode"||ye.id==="memo"||ye.id==="headlessBrowser"||ye.id==="showWindowTokens"||ye.id==="messageArchiving"||ye.id==="archiveToolUseInputs"||ye.id==="archiveThinking"||ye.id==="codemodeSession"||ye.id==="pluginClaudeCompat"||ye.id==="disableSuggestion")&&ye.value==="on"||ye.id==="lazyTool"&&ye.value!=="off"?"green":Ye?"blue":void 0,children:[ye.id==="lazyTool"&&ye.value==="loading"?"load":ye.id==="headlessBrowser"&&ye.value==="on"&&ae==="installing"?"installing...":ye.id==="headlessBrowser"&&ye.value==="on"&&ae==="failed"?"on (install failed)":ye.value.toString(),ye.id==="webServer"&&ye.value==="on"?` (${E5.getUrl()})`:""]}),ye.id==="headlessBrowser"&&ye.value==="on"&&ae!=="installed"&&(0,_.jsx)(x,{dimColor:!0,children:" manual install: npx -y playwright-core@1.64.1 install chromium"})]})]},ye.id)})]}),(0,_.jsx)(B,{marginLeft:3,children:(0,_.jsx)(x,{dimColor:!0,children:l.pending?(0,_.jsxs)(_.Fragment,{children:["Press ",l.keyName," again to exit"]}):pi?(0,_.jsx)(_.Fragment,{children:"Enter to save \xB7 Esc to cancel"}):(0,_.jsx)(_.Fragment,{children:"\u2190/\u2192 switch tab \xB7 \u2191/\u2193 to select \xB7 Enter/Space to change \xB7 Esc to close"})})})]})}var pln={type:"local-jsx",name:"config",description:()=>"Open config panel",isEnabled:!0,isHidden:!1,async call(e){return(0,_.jsx)(a0t,{onClose:e})},userFacingName(){return"config"}},l0t=pln;function fv(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function c0t(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let r=Math.floor(t/60),n=t%60;return`${r}m ${n.toFixed(0)}s`}function u0t(e){return`${e.toFixed(1)}%`}function d0t({costUSD:e,durationMs:t,apiDurationMs:r,inputTokens:n,outputTokens:i,cacheCreationTokens:o,cacheReadTokens:s,currentContextTokens:a,contextLimit:l,onDone:c}){let u=Me();or((A,h)=>{h.escape&&c()});let d=n+o+s,g=d>0?s/d*100:0,m=l>0?a/l*100:0;return(0,_.jsxs)(B,{flexDirection:"column",borderStyle:"round",paddingLeft:1,paddingRight:1,borderColor:u.secondaryBorder,children:[(0,_.jsx)(B,{marginBottom:1,flexDirection:"column",children:(0,_.jsx)(x,{bold:!0,children:"Session Cost & Usage"})}),(0,_.jsx)(B,{flexDirection:"column",marginBottom:1,children:(0,_.jsxs)(x,{children:[(0,_.jsx)(x,{dimColor:!0,children:"Cost: "}),(0,_.jsxs)(x,{children:["$",e.toFixed(4)]})]})}),(0,_.jsxs)(B,{flexDirection:"column",marginBottom:1,children:[(0,_.jsx)(x,{dimColor:!0,children:"Session Tokens"}),(0,_.jsxs)(B,{marginLeft:2,flexDirection:"column",children:[(0,_.jsxs)(x,{children:[(0,_.jsx)(x,{children:"Input: "}),(0,_.jsx)(x,{bold:!0,children:fv(d)}),(0,_.jsxs)(x,{dimColor:!0,children:[" (uncached: ",fv(n),")"]})]}),(0,_.jsxs)(x,{children:[(0,_.jsx)(x,{children:"Output: "}),(0,_.jsx)(x,{bold:!0,children:fv(i)})]})]})]}),(0,_.jsx)(B,{flexDirection:"column",marginBottom:1,children:(0,_.jsxs)(x,{children:[(0,_.jsx)(x,{dimColor:!0,children:"Context Window: "}),(0,_.jsx)(x,{bold:!0,children:u0t(m)}),(0,_.jsxs)(x,{dimColor:!0,children:[" (",fv(a)," / ",fv(l)," tokens)"]})]})}),(0,_.jsx)(B,{flexDirection:"column",marginBottom:1,children:(0,_.jsxs)(x,{children:[(0,_.jsx)(x,{dimColor:!0,children:"Cache Hit Rate: "}),(0,_.jsx)(x,{bold:!0,children:u0t(g)}),(0,_.jsxs)(x,{dimColor:!0,children:[" ","(read: ",fv(s),", creation:"," ",fv(o),")"]})]})}),(0,_.jsxs)(B,{flexDirection:"column",marginBottom:1,children:[(0,_.jsx)(x,{dimColor:!0,children:"Duration"}),(0,_.jsxs)(B,{marginLeft:2,flexDirection:"column",children:[(0,_.jsxs)(x,{children:[(0,_.jsx)(x,{children:"API: "}),(0,_.jsx)(x,{bold:!0,children:c0t(r)})]}),(0,_.jsxs)(x,{children:[(0,_.jsx)(x,{children:"Wall: "}),(0,_.jsx)(x,{bold:!0,children:c0t(t)})]})]})]}),(0,_.jsx)(B,{marginTop:1,children:(0,_.jsx)(x,{dimColor:!0,children:"Esc to close"})})]})}_Te();kA();Oe();Wt();Ci();Wd();gI();er();He();Oe();Wt();import{existsSync as m0t,mkdirSync as yln,readFileSync as bln,writeFileSync as Cln}from"fs";import{dirname as Sln,join as Iln}from"path";import{homedir as Tln}from"os";function Kp(e){if(!e)return 0;let t=e.match(/[\u2E80-\u2FDF\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF]|[\p{L}\p{N}]+(?:['’\-][\p{L}\p{N}]+)*/gu);return t?t.length:0}function p0t(e,t){if(!e||t<=0)return"";let r=/[\u2E80-\u2FDF\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF]|[\p{L}\p{N}]+(?:['’\-][\p{L}\p{N}]+)*/gu,n=0,i=0;for(let o of e.matchAll(r))if(n++,i=(o.index??0)+o[0].length,n>=t)break;return n===0?"":n<t?e:e.slice(0,i)+"..."}var Oa="__tool_result__",Jp="__thinking__",j0="__tool_input__",Ag="THK_",pu=100;function vln(){return Ue.isArchiveToolUseInputsEnable()}function STe(){return Ue.isArchiveThinkingEnable()}var xln=new Set(["Cwd",zm,Yd,aa,lR,Bl,Ol,mI,pG,mG,sR,Zy,Ome,kme]);function wln(e){return e.replace(/[^a-zA-Z0-9]/g,"-")}function Dln(e,t=process.cwd()){return Iln(Tln(),Jr,"projects",wln(t),"archive",`${e}.json`)}function Rln(e){m0t(e)||yln(e,{recursive:!0})}function Nln(e){let t={toolUseInputFields:new Map,thinkingUuids:new Set};if(!m0t(e))return t;try{let r=bln(e,"utf8");if(!r.trim())return t;let n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))return t;let i=new Map,o=new Set;for(let[s,a]of Object.entries(n)){if(!Array.isArray(a))continue;let l=a.filter(c=>typeof c=="string");if(l.length!==0){if(l.length===1&&l[0]===Jp){o.add(s);continue}i.set(s,new Set(l))}}return{toolUseInputFields:i,thinkingUuids:o}}catch(r){return ve(`Failed to read archive state from ${e}:`,r),t}}function Bln(e,t,r){Rln(Sln(e));try{let n={};for(let[i,o]of t)o.size>0&&(n[i]=[...o]);for(let i of r)n[i]=[Jp];Cln(e,JSON.stringify(n,null,2),"utf8")}catch(n){throw ve(`Failed to write archive state to ${e}:`,n),n}}function Oln(e){return`<system>Archived result [tool_use_id: ${e}]. Unarchive via MessageArchiving.</system>`}function kln(e,t){return`<system>Archived input field "${t}" [tool_use_id: ${e}]. Unarchive via MessageArchiving.</system>`}function Mln(e){let t=e.content;return typeof t=="string"?Kp(t):Array.isArray(t)?t.reduce((r,n)=>typeof n=="string"?r+Kp(n):typeof n=="object"&&n!==null&&"text"in n&&typeof n.text=="string"?r+Kp(n.text):r,0):0}function g0t(e){return Mln(e)<=pu}function Qln(e){return{type:"text",text:`<system>[tool_use_id: ${e}]</system>`}}function yTe(e){if(typeof e=="string")return Kp(e);if(typeof e!="object"||e===null)return 0;if(Array.isArray(e))return e.reduce((n,i)=>Math.max(n,yTe(i)),0);let t=Object.values(e),r=0;for(let n of t)r=Math.max(r,yTe(n));return r}function eX(e){return typeof e=="string"?Kp(e):typeof e=="number"||typeof e=="boolean"?Kp(String(e)):Array.isArray(e)?e.reduce((t,r)=>t+eX(r),0):typeof e=="object"&&e!==null?Object.values(e).reduce((t,r)=>t+eX(r),0):0}function A0t(e){if(typeof e!="object"||e===null)return[];let t=[],r=(n,i)=>{if(typeof n=="string"){let o=Kp(n);o>pu&&t.push({path:i,words:o});return}if(Array.isArray(n)){n.forEach((o,s)=>r(o,`${i}[${s}]`));return}if(typeof n=="object"&&n!==null)for(let[o,s]of Object.entries(n)){let a=i===""?o:`${i}.${o}`;r(s,a)}};return r(e,""),t.sort((n,i)=>i.words-n.words).map(n=>n.path)}function bTe(e){return yTe(e)<=pu}function ITe(e){let t=new Map;for(let r of e){if(r.type!=="assistant")continue;let n=r.message.content;if(Array.isArray(n))for(let i of n)vTe(i)&&t.set(i.id,i.input)}return t}function Pln(e){let t=new Map;for(let r of e){if(r.type!=="assistant")continue;let n=r.message.content;if(Array.isArray(n)){for(let i of n)if(typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"&&"id"in i&&typeof i.id=="string"&&"name"in i&&typeof i.name=="string"){let o=i;t.set(o.id,o.name)}}}return t}function TTe(e){return xln.has(e)}function Lln(e,t){let r=t.get(e.tool_use_id);return r?TTe(r):!1}function h0t(e,t){let r;for(let s of t)if(s.type==="assistant"&&s.uuid===e){r=s;break}if(!r)return{archivable:!1,reason:"thinking block not found"};let n=r.message.content;if(!Array.isArray(n))return{archivable:!1,reason:"message has no thinking block"};let i=0,o=!1;for(let s of n)typeof s=="object"&&s!==null&&"type"in s&&s.type==="thinking"&&"thinking"in s&&typeof s.thinking=="string"?(o=!0,i+=Kp(s.thinking)):typeof s=="object"&&s!==null&&"type"in s&&s.type==="redacted_thinking"&&"data"in s&&typeof s.data=="string"&&(o=!0,i+=Kp(s.data));return o?i<=pu?{archivable:!1,reason:`thinking block is ${i} words, which is ${pu} words or fewer`}:STe()?{archivable:!0}:{archivable:!1,reason:"thinking archiving is disabled (enable by setting archiveThinking to true)"}:{archivable:!1,reason:"message has no thinking block"}}function Fln(e){let t=e.message.content;if(!Array.isArray(t))return 0;let r=0;for(let n of t)typeof n=="object"&&n!==null&&"type"in n&&n.type==="thinking"&&"thinking"in n&&typeof n.thinking=="string"?r+=Kp(n.thinking):typeof n=="object"&&n!==null&&"type"in n&&n.type==="redacted_thinking"&&"data"in n&&typeof n.data=="string"&&(r+=Kp(n.data));return r}function Uln(e){return typeof e=="object"&&e!==null&&"type"in e&&(e.type==="thinking"||e.type==="redacted_thinking")}function $ln(e){return{type:"text",text:`<system>[thinking_id: ${Ag}${e}]</system>`}}function Hln(e){return`<system-thinking>Archived thinking [thinking_id: ${Ag}${e}]. Unarchive via MessageArchiving.</system-thinking>`}function E0t(e,t){let r,n;for(let s of t){if(s.type!=="assistant")continue;let a=s.message.content;if(Array.isArray(a)){for(let l of a)if(vTe(l)&&l.id===e){r=l.input,n=l.name;break}if(n!==void 0)break}}if(!n)return{archivable:!1,reason:"no matching tool_use block found in the conversation history"};if(TTe(n))return{archivable:!1,reason:`tool "${n}" is blacklisted from archiving`};let i=!1,o=!1;for(let s of t){if(s.type!=="user")continue;let a=s.message.content;if(Array.isArray(a))for(let l of a)_0t(l)&&l.tool_use_id===e&&(i=!0,g0t(l)||(o=!0))}return i?o||!bTe(r)?{archivable:!0}:{archivable:!1,reason:`tool result and tool_use input are both ${pu} words or fewer`}:bTe(r)?{archivable:!1,reason:`tool_use input is ${pu} words or fewer`}:{archivable:!0}}function qln(e,t,r,n){let i=e.tool_use_id;if(Lln(e,r))return e;let o=n.get(i);if(g0t(e)&&bTe(o))return e;if(t.get(i)?.has(Oa)??!1)return{...e,content:[{type:"text",text:Oln(i)}]};let l;typeof e.content=="string"?l=[{type:"text",text:e.content}]:l=[...e.content];let c=Array.isArray(l)?l:[{type:"text",text:l}];return c.push(Qln(i)),{...e,content:c}}function _0t(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="tool_result"&&"tool_use_id"in e&&typeof e.tool_use_id=="string"}function vTe(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="tool_use"&&"id"in e&&typeof e.id=="string"&&"name"in e&&typeof e.name=="string"}function Gln(e,t,r,n){let i=e.message.content;if(!Array.isArray(i))return e;let o=i.map(s=>_0t(s)?qln(s,t,r,n):s);return{...e,message:{...e.message,content:o}}}function zln(e,t,r,n){let i=e.message.content;if(!Array.isArray(i))return e;let o=STe(),s=vln();if(!o&&!s)return e;let a=e.uuid,l=o&&r.has(a),c=!1,u=[];for(let d of i){if(Uln(d)){if(!o){u.push(d);continue}if(l){c=!0;continue}u.push(d);continue}if(vTe(d)){if(!s){u.push(d);continue}let g=d.id,m=n.get(g)??d.name;if(TTe(m)){u.push(d);continue}let A=t.get(g);if(!A){u.push(d);continue}let h=[...A].filter(C=>C!==Oa);if(h.length===0){u.push(d);continue}if(typeof d.input!="object"||d.input===null){u.push(d);continue}let y=GE(d.input);for(let C of h)xme(y,C)?Rme(y,C,kln(g,C)):ve(`Archived input field path does not exist: ${C} for tool_use_id ${g}`);c=!0,u.push({...d,input:y});continue}u.push(d)}return c?{...e,message:{...e.message,content:u}}:e}var CTe=class e{static instance;archivedToolUseInputFields=new Map;archivedThinkingUuids=new Set;currentSessionId=null;currentArchiveFilePath=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadSession(t,r){if(!Ue.isMessageArchivingEnable()){this.archivedToolUseInputFields.clear(),this.archivedThinkingUuids.clear(),this.currentSessionId=t,this.currentArchiveFilePath=null;return}this.currentSessionId=t,this.currentArchiveFilePath=Dln(t,r);let n=Nln(this.currentArchiveFilePath);this.archivedToolUseInputFields=n.toolUseInputFields,this.archivedThinkingUuids=n.thinkingUuids}archive(t){if(Ue.isMessageArchivingEnable()){for(let[r,n]of Object.entries(t)){this.archivedToolUseInputFields.has(r)||this.archivedToolUseInputFields.set(r,new Set);let i=this.archivedToolUseInputFields.get(r);for(let o of n)i.add(o)}this.persist()}}unarchive(t){if(Ue.isMessageArchivingEnable()){for(let[r,n]of Object.entries(t)){let i=this.archivedToolUseInputFields.get(r);if(i){for(let o of n)i.delete(o);i.size===0&&this.archivedToolUseInputFields.delete(r)}}this.persist()}}archiveThinkingUuids(t){if(Ue.isMessageArchivingEnable()){for(let r of t)this.archivedThinkingUuids.add(r);this.persist()}}unarchiveThinkingUuids(t){if(Ue.isMessageArchivingEnable()){for(let r of t)this.archivedThinkingUuids.delete(r);this.persist()}}getArchivedThinkingUuids(){return new Set(this.archivedThinkingUuids)}isArchived(t){return this.archivedToolUseInputFields.get(t)?.has(Oa)??!1}getArchivedIds(){let t=new Set;for(let[r,n]of this.archivedToolUseInputFields)n.has(Oa)&&t.add(r);return t}getArchivedToolUseInputFields(t){return new Set(this.archivedToolUseInputFields.get(t)??[])}applyToMessages(t){if(!Ue.isMessageArchivingEnable())return t;let r=Pln(t),n=ITe(t),i=STe(),o=[];return t.map(s=>{if(s.type==="assistant")return i&&Array.isArray(s.message.content)&&(this.archivedThinkingUuids.has(s.uuid)?o.push({type:"text",text:Hln(s.uuid)}):Fln(s)>pu&&o.push($ln(s.uuid))),zln(s,this.archivedToolUseInputFields,this.archivedThinkingUuids,r);if(s.type==="user"){let a=Gln(s,this.archivedToolUseInputFields,r,n);if(o.length===0)return a;let l=o.splice(0,o.length),c=a.message.content,u=Array.isArray(c)?c:[{type:"text",text:c}],d=u.findIndex(m=>m.isReminder),g=d===-1?[...u,...l]:[...u.slice(0,d),...l,...u.slice(d)];return{...a,message:{...a.message,content:g}}}return s})}getCurrentArchiveFilePath(){return this.currentArchiveFilePath}persist(){this.currentArchiveFilePath&&Bln(this.currentArchiveFilePath,this.archivedToolUseInputFields,this.archivedThinkingUuids)}},vf=CTe.getInstance();He();async function y0t(){let e=tt();if(!(!e.hooks?.SessionStart||e.hooks.SessionStart.length===0))try{let t=new mg(e.hooks),r={session_id:Date.now().toString(),transcript_path:"",cwd:ms(),permission_mode:"default",hook_event_name:"SessionStart",source:"compact",model:process.env.ANTHROPIC_MODEL||"default"},n=await t.execute(r),i=[...n.additionalContext];n.asyncAdditionalContext&&n.getAsyncAdditionalContext().then(o=>{if(o.length>0){let s=et.getSessionContext(),l=[...s.getData("sessionStartAdditionalContexts")||[],...o];s.setData("sessionStartAdditionalContexts",l)}}).catch(o=>{K("SessionStart async hook execution error:",o)}),i.length>0&&et.getSessionContext().setData("sessionStartAdditionalContexts",i)}catch(t){K("SessionStart hook execution error in auto-compact:",t)}}var jln={"claude-3-7-sonnet-20250219":2e5,"claude-3-5-sonnet-20241022":2e5,"claude-3-5-haiku-20241022":2e5,"claude-3-haiku-20240307":2e5,"us.anthropic.claude-3-7-sonnet-20250219-v1:0":2e5,"us.anthropic.claude-3-5-haiku-20241022-v1:0":2e5,"claude-3-7-sonnet@20250219":2e5,"claude-3-5-haiku@20241022":2e5,"kimi-k2.5":15e4,"kimi-k2.6":15e4,"k2.5":15e4,"k2.6":15e4};function Yln(e){return jln[e.toLowerCase()]||2e5}function p2(){let e=Nn.getModelRoutingModels();if(e.length===0)throw new Error("No MODEL routing configuration found");let t=e.map(Yln);return Math.min(...t)}var Vln=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
823
823
  This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
824
824
 
@@ -1016,7 +1016,7 @@ You are powered by the model ${e}.`}async function hv(){return!["1","true"].incl
1016
1016
  <context name="${c}">${u}</context>`;let s=i.map(c=>{let u=c.prompt({},t),d=JSON.stringify("inputJSONSchema"in c&&c.inputJSONSchema?c.inputJSONSchema:TE(c.inputSchema));return{name:c.name,description:`${u}
1017
1017
 
1018
1018
  Schema:
1019
- ${d}`}}),{messages:a}=t,l=Fcn(o);return Ucn(o,l,s,a)}},B_t=$cn;fg();var y2=Re(it(),1);Oe();Oe();import{existsSync as Hcn,readdirSync as qcn,statSync as Gcn}from"fs";import{join as zcn}from"path";function jcn(){let e=$i.plan();if(!Hcn(e))return[];try{return qcn(e).filter(r=>r.endsWith(".md")).map(r=>{let n=zcn(e,r),i=Gcn(n);return{name:r,path:n,modified:i.mtime}}).sort((r,n)=>n.modified.getTime()-r.modified.getTime())}catch{return[]}}var O_t=({onSelect:e})=>{let[t,r]=(0,y2.useState)([]),[n,i]=(0,y2.useState)(0),[o,s]=(0,y2.useState)(!1);(0,y2.useEffect)(()=>{let c=jcn();r(c),s(!0)},[]);let a=[{label:"New plan",value:"__NEW_PLAN__",isNew:!0},...t.map(c=>({label:c.name,value:c.path,isNew:!1,modified:c.modified}))];or((c,u)=>{if(u.upArrow)i(d=>d>0?d-1:a.length-1);else if(u.downArrow)i(d=>d<a.length-1?d+1:0);else if(u.return){let d=a[n];d&&e(d.value)}else u.escape&&e("__CANCELLED__")});let l=Me();return o?(0,_.jsxs)(B,{flexDirection:"column",marginY:1,children:[(0,_.jsx)(B,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:l.claude,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"})}),(0,_.jsx)(B,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:l.claude,children:" Select a plan to continue, or create a new one"})}),a.map((c,u)=>{let d=u===n;return(0,_.jsxs)(B,{flexDirection:"row",marginLeft:2,children:[(0,_.jsx)(x,{color:d?l.claude:l.text,children:d?"\u276F":" "}),(0,_.jsx)(x,{color:d?l.claude:l.text,children:" "}),(0,_.jsx)(x,{color:d?l.claude:l.text,bold:c.isNew,children:c.isNew?c.label:c.label.replace(".md","")}),!c.isNew&&c.modified&&(0,_.jsxs)(x,{dimColor:!0,children:[" ","(",$me(c.modified),")"]})]},c.isNew?"new":c.value)}),(0,_.jsx)(B,{marginTop:1,marginLeft:2,children:(0,_.jsx)(x,{dimColor:!0,children:"\u2191/\u2193 to select \xB7 Enter to confirm \xB7 Esc to cancel"})})]}):(0,_.jsx)(B,{flexDirection:"column",marginY:1,children:(0,_.jsx)(x,{children:"Loading plan history..."})})};var Ycn={type:"local-jsx",name:"plan",description:()=>"Enable plan mode",isEnabled:!0,isHidden:!1,disableCancel:!0,async call(e){return Ai.isPlanMode()?(e("Already in plan mode."),null):(0,_.jsx)(O_t,{onSelect:t=>{if(t==="__CANCELLED__"){e("Cancelled.");return}t&&t!=="__NEW_PLAN__"?Ai.setCurrentPlanFilePath(t):Ai.generatePlanFilePath(),Ai.setMode("plan",!0,!1),e("Enabled plan mode")}})},userFacingName(){return"plan"}},k_t=Ycn;fg();var Vcn={type:"local",name:"auto",description:()=>"Enable auto mode",isEnabled:!0,isHidden:!1,async call(){return Ai.isAutoMode()?"Already in auto mode.":(Ai.setMode("auto",!0),"Enabled auto mode")},userFacingName(){return"auto"}},M_t=Vcn;Ar();import{resolve as Wcn}from"path";var Kcn={type:"local",name:"cd",description:()=>"Move this session to a new working directory",isEnabled:!0,isHidden:!1,argNames:["path"],async call(e){let t=e.trim();if(t==="")throw new Error("Missing directory path. Usage: /cd <path>");let r=Be(),n=Wcn(r,t);zs(n);let i=Be();return i===r?`Already in ${i}.`:`Changed directory to ${i}/`},userFacingName(){return"cd"}},Q_t=Kcn;var pCt=Re(it(),1);var ch=Re(it(),1);var wun=Re(it(),1);var N5=Re(it(),1),Tun=Re(U_t(),1);var $_t={info:"blue",success:"green",error:"red",warning:"yellow"},uun={styles:{container:({variant:e})=>({flexGrow:1,borderStyle:"round",borderColor:$_t[e],gap:1,paddingX:1}),iconContainer:()=>({flexShrink:0}),icon:({variant:e})=>({color:$_t[e]}),content:()=>({flexShrink:1,flexGrow:1,minWidth:0,flexDirection:"column",gap:1}),title:()=>({bold:!0}),message:()=>({})},config({variant:e}){let t;return e==="info"&&(t=Zt.info),e==="success"&&(t=Zt.tick),e==="error"&&(t=Zt.cross),e==="warning"&&(t=Zt.warning),{icon:t}}},H_t=uun;var dun={styles:{container:({color:e})=>({backgroundColor:e}),label:()=>({color:"black"})}},q_t=dun;var fun={styles:{input:({isFocused:e})=>({dimColor:!e})}},G_t=fun;var pun={styles:{container:()=>({flexDirection:"column"}),option:({isFocused:e})=>({gap:1,paddingLeft:e?0:2}),selectedIndicator:()=>({color:"green"}),focusIndicator:()=>({color:"blue"}),label({isFocused:e,isSelected:t}){let r;return t&&(r="green"),e&&(r="blue"),{color:r}},highlightedText:()=>({bold:!0})}},z_t=pun;var mun={styles:{list:()=>({flexDirection:"column"}),listItem:()=>({gap:1}),marker:()=>({dimColor:!0}),content:()=>({flexDirection:"column"})}},j_t=mun;var gun={styles:{container:()=>({flexGrow:1,minWidth:0}),completed:()=>({color:"magenta"}),remaining:()=>({dimColor:!0})},config:()=>({completedCharacter:Zt.square,remainingCharacter:Zt.squareLightShade})},Y_t=gun;var Aun={styles:{container:()=>({flexDirection:"column"}),option:({isFocused:e})=>({gap:1,paddingLeft:e?0:2}),selectedIndicator:()=>({color:"green"}),focusIndicator:()=>({color:"blue"}),label({isFocused:e,isSelected:t}){let r;return t&&(r="green"),e&&(r="blue"),{color:r}},highlightedText:()=>({bold:!0})}},V_t=Aun;var hun={styles:{container:()=>({gap:1}),frame:()=>({color:"blue"}),label:()=>({})}},W_t=hun;var Eun={success:"green",error:"red",warning:"yellow",info:"blue"},_un={success:Zt.tick,error:Zt.cross,warning:Zt.warning,info:Zt.info},yun={styles:{container:()=>({gap:1}),iconContainer:()=>({flexShrink:0}),icon:({variant:e})=>({color:Eun[e]}),message:()=>({})},config:({variant:e})=>({icon:_un[e]})},K_t=yun;var bun={styles:{list:()=>({flexDirection:"column"}),listItem:()=>({gap:1}),marker:()=>({dimColor:!0}),content:()=>({flexDirection:"column"})},config:()=>({marker:Zt.line})},J_t=bun;var Cun={styles:{value:()=>({})}},Z_t=Cun;var Sun={styles:{value:()=>({})}},X_t=Sun;var Iun={styles:{value:()=>({})}},eyt=Iun;var vun={components:{Alert:H_t,Badge:q_t,ConfirmInput:G_t,MultiSelect:z_t,OrderedList:j_t,ProgressBar:Y_t,Select:V_t,Spinner:W_t,StatusMessage:K_t,UnorderedList:J_t,TextInput:Z_t,EmailInput:X_t,PasswordInput:eyt}},xun=(0,N5.createContext)(vun);var oo=e=>(0,N5.useContext)(xun).components[e];var Dun=Re(it(),1);var V0=Re(it(),1);var C2=Re(it(),1);var tyt=Re(it(),1);var B5=Zt.line;var sX=(0,tyt.createContext)({marker:B5});function ryt({children:e}){let{marker:t}=(0,C2.useContext)(sX),{styles:r}=oo("UnorderedList");return C2.default.createElement(B,{...r.listItem()},C2.default.createElement(x,{...r.marker()},t),C2.default.createElement(B,{...r.content()},e))}var nyt=Re(it(),1),HTe=(0,nyt.createContext)({depth:0});function Run({children:e}){let{depth:t}=(0,V0.useContext)(HTe),{styles:r,config:n}=oo("UnorderedList"),i=(0,V0.useMemo)(()=>({depth:t+1}),[t]),o=(0,V0.useMemo)(()=>{let{marker:s}=n();return typeof s=="string"?{marker:s}:Array.isArray(s)?{marker:s[t]??s.at(-1)??B5}:{marker:B5}},[n,t]);return V0.default.createElement(HTe.Provider,{value:i},V0.default.createElement(sX.Provider,{value:o},V0.default.createElement(B,{...r.list()},e)))}Run.Item=ryt;var Bun=Re(it(),1);var Nun=Re(it(),1);var O5=Re(it(),1);var S2=class extends Map{first;constructor(t){let r=[],n,i,o=0;for(let s of t){let a={...s,previous:i,next:void 0,index:o};i&&(i.next=a),n||=a,r.push([s.value,a]),o++,i=a}super(r),this.first=n}};var iyt=Re(it(),1);var I2=Re(it(),1);var k5=Re(it(),1);function oyt({isFocused:e,isSelected:t,children:r}){let{styles:n}=oo("Select");return k5.default.createElement(B,{...n.option({isFocused:e})},e&&k5.default.createElement(x,{...n.focusIndicator()},Zt.pointer),k5.default.createElement(x,{...n.label({isFocused:e,isSelected:t})},r),t&&k5.default.createElement(x,{...n.selectedIndicator()},Zt.tick))}var Zp=Re(it(),1);import{isDeepStrictEqual as Oun}from"node:util";var kun=(e,t)=>{switch(t.type){case"focus-next-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.next;if(!n)return e;if(!(n.index>=e.visibleToIndex))return{...e,focusedValue:n.value};let o=Math.min(e.optionMap.size,e.visibleToIndex+1),s=o-e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:s,visibleToIndex:o}}case"focus-previous-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.previous;if(!n)return e;if(!(n.index<=e.visibleFromIndex))return{...e,focusedValue:n.value};let o=Math.max(0,e.visibleFromIndex-1),s=o+e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:o,visibleToIndex:s}}case"select-focused-option":return{...e,previousValue:e.value,value:e.focusedValue};case"reset":return t.state}},syt=({visibleOptionCount:e,defaultValue:t,options:r})=>{let n=typeof e=="number"?Math.min(e,r.length):r.length,i=new S2(r);return{optionMap:i,visibleOptionCount:n,focusedValue:i.first?.value,visibleFromIndex:0,visibleToIndex:n,previousValue:t,value:t}},ayt=({visibleOptionCount:e=5,options:t,defaultValue:r,onChange:n})=>{let[i,o]=(0,Zp.useReducer)(kun,{visibleOptionCount:e,defaultValue:r,options:t},syt),[s,a]=(0,Zp.useState)(t);t!==s&&!Oun(t,s)&&(o({type:"reset",state:syt({visibleOptionCount:e,defaultValue:r,options:t})}),a(t));let l=(0,Zp.useCallback)(()=>{o({type:"focus-next-option"})},[]),c=(0,Zp.useCallback)(()=>{o({type:"focus-previous-option"})},[]),u=(0,Zp.useCallback)(()=>{o({type:"select-focused-option"})},[]),d=(0,Zp.useMemo)(()=>t.map((g,m)=>({...g,index:m})).slice(i.visibleFromIndex,i.visibleToIndex),[t,i.visibleFromIndex,i.visibleToIndex]);return(0,Zp.useEffect)(()=>{i.value&&i.previousValue!==i.value&&n?.(i.value)},[i.previousValue,i.value,t,n]),{focusedValue:i.focusedValue,visibleFromIndex:i.visibleFromIndex,visibleToIndex:i.visibleToIndex,value:i.value,visibleOptions:d,focusNextOption:l,focusPreviousOption:c,selectFocusedOption:u}};var lyt=({isDisabled:e=!1,state:t})=>{or((r,n)=>{n.downArrow&&t.focusNextOption(),n.upArrow&&t.focusPreviousOption(),n.return&&t.selectFocusedOption()},{isActive:!e})};function T2({isDisabled:e=!1,visibleOptionCount:t=5,highlightText:r,options:n,defaultValue:i,onChange:o}){let s=ayt({visibleOptionCount:t,options:n,defaultValue:i,onChange:o});lyt({isDisabled:e,state:s});let{styles:a}=oo("Select");return I2.default.createElement(B,{...a.container()},s.visibleOptions.map(l=>{let c=l.label;if(r&&l.label.includes(r)){let u=l.label.indexOf(r);c=I2.default.createElement(I2.default.Fragment,null,l.label.slice(0,u),I2.default.createElement(x,{...a.highlightedText()},r),l.label.slice(u+r.length))}return I2.default.createElement(oyt,{key:l.value,isFocused:!e&&s.focusedValue===l.value,isSelected:s.value===l.value},c)}))}var Mun=Re(it(),1);var cyt=Re(it(),1);var Pun=Re(it(),1);var aX=Re(it(),1);var Qun=Re(it(),1);var aki=Jt.inverse(" ");var Eg=Re(it(),1);var v2=Re(it(),1);var uyt=Re(it(),1);var lX=(0,uyt.createContext)({marker:Zt.line});function cX({children:e}){let{marker:t}=(0,v2.useContext)(lX),{styles:r}=oo("OrderedList");return v2.default.createElement(B,{...r.listItem()},v2.default.createElement(x,{...r.marker()},t),v2.default.createElement(B,{...r.content()},e))}var dyt=Re(it(),1),qTe=(0,dyt.createContext)({marker:""});function _g({children:e}){let{marker:t}=(0,Eg.useContext)(qTe),{styles:r}=oo("OrderedList"),n=0;for(let o of Eg.default.Children.toArray(e))!(0,Eg.isValidElement)(o)||o.type!==cX||n++;let i=String(n).length;return Eg.default.createElement(B,{...r.list()},Eg.default.Children.map(e,(o,s)=>{if(!(0,Eg.isValidElement)(o)||o.type!==cX)return o;let a=`${String(s+1).padStart(i)}.`,l=`${t}${a}`;return Eg.default.createElement(qTe.Provider,{value:{marker:l}},Eg.default.createElement(lX.Provider,{value:{marker:l}},o))}))}_g.Item=cX;var Fun=Re(it(),1);var GTe=Re(it(),1);var Lun=Re(it(),1);var Qki=Jt.inverse(" ");var Uun=Re(it(),1);var $un=Re(it(),1);var qun=Re(it(),1);var uX=Re(it(),1);var Hun=Re(it(),1);var sMi=Jt.inverse(" ");var R2=Re(it(),1);var zTe=Re(it(),1);YU();ps();Ci();iv();Wt();var Gun=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function DC(){let e=Gun,{frame:t}=OD({interval:120});return(0,_.jsx)(B,{flexWrap:"nowrap",height:1,width:2,children:(0,_.jsx)(x,{color:Me().claude,children:e[t%e.length]})})}var pX=Re(it(),1);var Ev=null,W0=null,fX=new Set,dX=null;function YTe(e){let{columns:t,rows:r}=e;return t&&r?{columns:t,rows:r}:(dX||(dX=xfe()),{columns:t||dX.columns||80,rows:r||dX.rows||24})}function jTe(){if(!W0)return;let e=YTe(W0);Ev&&e.columns===Ev.columns&&e.rows===Ev.rows||(Ev=e,fX.forEach(t=>t(Ev)))}function zun(e,t){return W0!==e&&(W0&&W0.off("resize",jTe),W0=e,Ev=YTe(e),e.on("resize",jTe)),fX.add(t),()=>{fX.delete(t),fX.size===0&&W0&&(W0.off("resize",jTe),W0=null,Ev=null)}}function VTe(){let{stdout:e}=Uy(),[t,r]=(0,pX.useState)(()=>YTe(e));return(0,pX.useEffect)(()=>zun(e,r),[e]),t}function mX(){return VTe()}He();Xd();Oe();RA();Oe();var KQi=Re(Xbt(),1);import{homedir as q5}from"os";import{join as D2}from"path";import{existsSync as G5,mkdirSync as tCt,appendFileSync as eCt,readFileSync as rCt,constants as Hpn,writeFileSync as qpn,unlinkSync as nCt,statSync as Gpn}from"fs";import{platform as iCt}from"process";import{accessSync as zpn}from"fs";var $pn="2.7.18",H5={VERSION:$pn,PACKAGE_URL:"@dahawa/hawa-code",README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};He();var yv=D2(s0,".update.lock"),jpn=300*1e3;function oCt(){try{if(G5(s0)||tCt(s0,{recursive:!0}),G5(yv)){let e=Gpn(yv);if(Date.now()-e.mtimeMs<jpn)return!1;try{nCt(yv)}catch(r){return ve(`Failed to remove stale lock file: ${r}`),!1}}return qpn(yv,`${process.pid}`,"utf8"),!0}catch(e){return ve(`Failed to acquire lock: ${e}`),!1}}function sCt(){try{G5(yv)&&rCt(yv,"utf8")===`${process.pid}`&&nCt(yv)}catch(e){ve(`Failed to release lock: ${e}`)}}async function gve(){try{let e=await Wn("npm -g config get prefix");if(e.code!==0)return ve("Failed to check npm permissions"),{hasPermissions:!1,npmPrefix:null};let t=e.stdout.trim(),r=!1;try{zpn(t,Hpn.W_OK),r=!0}catch{r=!1}return r?{hasPermissions:!0,npmPrefix:t}:(ve("Insufficient permissions for global npm install."),{hasPermissions:!1,npmPrefix:t})}catch(e){return ve(`Failed to verify npm global install permissions: ${e}`),{hasPermissions:!1,npmPrefix:null}}}async function aCt(e){if(!oCt())throw Nt("tengu_auto_updater_prefix_lock_contention",{pid:String(process.pid),currentVersion:H5.VERSION,prefix:e}),new Error("Another process is currently setting up npm prefix");try{G5(e)||tCt(e,{recursive:!0});let t=await Wn(`npm -g config set prefix ${e}`);if(t.code!==0)throw new Error(`Failed to set npm prefix: ${t.stderr}`);let r=`
1019
+ ${d}`}}),{messages:a}=t,l=Fcn(o);return Ucn(o,l,s,a)}},B_t=$cn;fg();var y2=Re(it(),1);Oe();Oe();import{existsSync as Hcn,readdirSync as qcn,statSync as Gcn}from"fs";import{join as zcn}from"path";function jcn(){let e=$i.plan();if(!Hcn(e))return[];try{return qcn(e).filter(r=>r.endsWith(".md")).map(r=>{let n=zcn(e,r),i=Gcn(n);return{name:r,path:n,modified:i.mtime}}).sort((r,n)=>n.modified.getTime()-r.modified.getTime())}catch{return[]}}var O_t=({onSelect:e})=>{let[t,r]=(0,y2.useState)([]),[n,i]=(0,y2.useState)(0),[o,s]=(0,y2.useState)(!1);(0,y2.useEffect)(()=>{let c=jcn();r(c),s(!0)},[]);let a=[{label:"New plan",value:"__NEW_PLAN__",isNew:!0},...t.map(c=>({label:c.name,value:c.path,isNew:!1,modified:c.modified}))];or((c,u)=>{if(u.upArrow)i(d=>d>0?d-1:a.length-1);else if(u.downArrow)i(d=>d<a.length-1?d+1:0);else if(u.return){let d=a[n];d&&e(d.value)}else u.escape&&e("__CANCELLED__")});let l=Me();return o?(0,_.jsxs)(B,{flexDirection:"column",marginY:1,children:[(0,_.jsx)(B,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:l.claude,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"})}),(0,_.jsx)(B,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:l.claude,children:" Select a plan to continue, or create a new one"})}),a.map((c,u)=>{let d=u===n;return(0,_.jsxs)(B,{flexDirection:"row",marginLeft:2,children:[(0,_.jsx)(x,{color:d?l.claude:l.text,children:d?"\u276F":" "}),(0,_.jsx)(x,{color:d?l.claude:l.text,children:" "}),(0,_.jsx)(x,{color:d?l.claude:l.text,bold:c.isNew,children:c.isNew?c.label:c.label.replace(".md","")}),!c.isNew&&c.modified&&(0,_.jsxs)(x,{dimColor:!0,children:[" ","(",$me(c.modified),")"]})]},c.isNew?"new":c.value)}),(0,_.jsx)(B,{marginTop:1,marginLeft:2,children:(0,_.jsx)(x,{dimColor:!0,children:"\u2191/\u2193 to select \xB7 Enter to confirm \xB7 Esc to cancel"})})]}):(0,_.jsx)(B,{flexDirection:"column",marginY:1,children:(0,_.jsx)(x,{children:"Loading plan history..."})})};var Ycn={type:"local-jsx",name:"plan",description:()=>"Enable plan mode",isEnabled:!0,isHidden:!1,disableCancel:!0,async call(e){return Ai.isPlanMode()?(e("Already in plan mode."),null):(0,_.jsx)(O_t,{onSelect:t=>{if(t==="__CANCELLED__"){e("Cancelled.");return}t&&t!=="__NEW_PLAN__"?Ai.setCurrentPlanFilePath(t):Ai.generatePlanFilePath(),Ai.setMode("plan",!0,!1),e("Enabled plan mode")}})},userFacingName(){return"plan"}},k_t=Ycn;fg();var Vcn={type:"local",name:"auto",description:()=>"Enable auto mode",isEnabled:!0,isHidden:!1,async call(){return Ai.isAutoMode()?"Already in auto mode.":(Ai.setMode("auto",!0),"Enabled auto mode")},userFacingName(){return"auto"}},M_t=Vcn;Ar();import{resolve as Wcn}from"path";var Kcn={type:"local",name:"cd",description:()=>"Move this session to a new working directory",isEnabled:!0,isHidden:!1,argNames:["path"],async call(e){let t=e.trim();if(t==="")throw new Error("Missing directory path. Usage: /cd <path>");let r=Be(),n=Wcn(r,t);zs(n);let i=Be();return i===r?`Already in ${i}.`:`Changed directory to ${i}/`},userFacingName(){return"cd"}},Q_t=Kcn;var pCt=Re(it(),1);var ch=Re(it(),1);var wun=Re(it(),1);var N5=Re(it(),1),Tun=Re(U_t(),1);var $_t={info:"blue",success:"green",error:"red",warning:"yellow"},uun={styles:{container:({variant:e})=>({flexGrow:1,borderStyle:"round",borderColor:$_t[e],gap:1,paddingX:1}),iconContainer:()=>({flexShrink:0}),icon:({variant:e})=>({color:$_t[e]}),content:()=>({flexShrink:1,flexGrow:1,minWidth:0,flexDirection:"column",gap:1}),title:()=>({bold:!0}),message:()=>({})},config({variant:e}){let t;return e==="info"&&(t=Zt.info),e==="success"&&(t=Zt.tick),e==="error"&&(t=Zt.cross),e==="warning"&&(t=Zt.warning),{icon:t}}},H_t=uun;var dun={styles:{container:({color:e})=>({backgroundColor:e}),label:()=>({color:"black"})}},q_t=dun;var fun={styles:{input:({isFocused:e})=>({dimColor:!e})}},G_t=fun;var pun={styles:{container:()=>({flexDirection:"column"}),option:({isFocused:e})=>({gap:1,paddingLeft:e?0:2}),selectedIndicator:()=>({color:"green"}),focusIndicator:()=>({color:"blue"}),label({isFocused:e,isSelected:t}){let r;return t&&(r="green"),e&&(r="blue"),{color:r}},highlightedText:()=>({bold:!0})}},z_t=pun;var mun={styles:{list:()=>({flexDirection:"column"}),listItem:()=>({gap:1}),marker:()=>({dimColor:!0}),content:()=>({flexDirection:"column"})}},j_t=mun;var gun={styles:{container:()=>({flexGrow:1,minWidth:0}),completed:()=>({color:"magenta"}),remaining:()=>({dimColor:!0})},config:()=>({completedCharacter:Zt.square,remainingCharacter:Zt.squareLightShade})},Y_t=gun;var Aun={styles:{container:()=>({flexDirection:"column"}),option:({isFocused:e})=>({gap:1,paddingLeft:e?0:2}),selectedIndicator:()=>({color:"green"}),focusIndicator:()=>({color:"blue"}),label({isFocused:e,isSelected:t}){let r;return t&&(r="green"),e&&(r="blue"),{color:r}},highlightedText:()=>({bold:!0})}},V_t=Aun;var hun={styles:{container:()=>({gap:1}),frame:()=>({color:"blue"}),label:()=>({})}},W_t=hun;var Eun={success:"green",error:"red",warning:"yellow",info:"blue"},_un={success:Zt.tick,error:Zt.cross,warning:Zt.warning,info:Zt.info},yun={styles:{container:()=>({gap:1}),iconContainer:()=>({flexShrink:0}),icon:({variant:e})=>({color:Eun[e]}),message:()=>({})},config:({variant:e})=>({icon:_un[e]})},K_t=yun;var bun={styles:{list:()=>({flexDirection:"column"}),listItem:()=>({gap:1}),marker:()=>({dimColor:!0}),content:()=>({flexDirection:"column"})},config:()=>({marker:Zt.line})},J_t=bun;var Cun={styles:{value:()=>({})}},Z_t=Cun;var Sun={styles:{value:()=>({})}},X_t=Sun;var Iun={styles:{value:()=>({})}},eyt=Iun;var vun={components:{Alert:H_t,Badge:q_t,ConfirmInput:G_t,MultiSelect:z_t,OrderedList:j_t,ProgressBar:Y_t,Select:V_t,Spinner:W_t,StatusMessage:K_t,UnorderedList:J_t,TextInput:Z_t,EmailInput:X_t,PasswordInput:eyt}},xun=(0,N5.createContext)(vun);var oo=e=>(0,N5.useContext)(xun).components[e];var Dun=Re(it(),1);var V0=Re(it(),1);var C2=Re(it(),1);var tyt=Re(it(),1);var B5=Zt.line;var sX=(0,tyt.createContext)({marker:B5});function ryt({children:e}){let{marker:t}=(0,C2.useContext)(sX),{styles:r}=oo("UnorderedList");return C2.default.createElement(B,{...r.listItem()},C2.default.createElement(x,{...r.marker()},t),C2.default.createElement(B,{...r.content()},e))}var nyt=Re(it(),1),HTe=(0,nyt.createContext)({depth:0});function Run({children:e}){let{depth:t}=(0,V0.useContext)(HTe),{styles:r,config:n}=oo("UnorderedList"),i=(0,V0.useMemo)(()=>({depth:t+1}),[t]),o=(0,V0.useMemo)(()=>{let{marker:s}=n();return typeof s=="string"?{marker:s}:Array.isArray(s)?{marker:s[t]??s.at(-1)??B5}:{marker:B5}},[n,t]);return V0.default.createElement(HTe.Provider,{value:i},V0.default.createElement(sX.Provider,{value:o},V0.default.createElement(B,{...r.list()},e)))}Run.Item=ryt;var Bun=Re(it(),1);var Nun=Re(it(),1);var O5=Re(it(),1);var S2=class extends Map{first;constructor(t){let r=[],n,i,o=0;for(let s of t){let a={...s,previous:i,next:void 0,index:o};i&&(i.next=a),n||=a,r.push([s.value,a]),o++,i=a}super(r),this.first=n}};var iyt=Re(it(),1);var I2=Re(it(),1);var k5=Re(it(),1);function oyt({isFocused:e,isSelected:t,children:r}){let{styles:n}=oo("Select");return k5.default.createElement(B,{...n.option({isFocused:e})},e&&k5.default.createElement(x,{...n.focusIndicator()},Zt.pointer),k5.default.createElement(x,{...n.label({isFocused:e,isSelected:t})},r),t&&k5.default.createElement(x,{...n.selectedIndicator()},Zt.tick))}var Zp=Re(it(),1);import{isDeepStrictEqual as Oun}from"node:util";var kun=(e,t)=>{switch(t.type){case"focus-next-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.next;if(!n)return e;if(!(n.index>=e.visibleToIndex))return{...e,focusedValue:n.value};let o=Math.min(e.optionMap.size,e.visibleToIndex+1),s=o-e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:s,visibleToIndex:o}}case"focus-previous-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.previous;if(!n)return e;if(!(n.index<=e.visibleFromIndex))return{...e,focusedValue:n.value};let o=Math.max(0,e.visibleFromIndex-1),s=o+e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:o,visibleToIndex:s}}case"select-focused-option":return{...e,previousValue:e.value,value:e.focusedValue};case"reset":return t.state}},syt=({visibleOptionCount:e,defaultValue:t,options:r})=>{let n=typeof e=="number"?Math.min(e,r.length):r.length,i=new S2(r);return{optionMap:i,visibleOptionCount:n,focusedValue:i.first?.value,visibleFromIndex:0,visibleToIndex:n,previousValue:t,value:t}},ayt=({visibleOptionCount:e=5,options:t,defaultValue:r,onChange:n})=>{let[i,o]=(0,Zp.useReducer)(kun,{visibleOptionCount:e,defaultValue:r,options:t},syt),[s,a]=(0,Zp.useState)(t);t!==s&&!Oun(t,s)&&(o({type:"reset",state:syt({visibleOptionCount:e,defaultValue:r,options:t})}),a(t));let l=(0,Zp.useCallback)(()=>{o({type:"focus-next-option"})},[]),c=(0,Zp.useCallback)(()=>{o({type:"focus-previous-option"})},[]),u=(0,Zp.useCallback)(()=>{o({type:"select-focused-option"})},[]),d=(0,Zp.useMemo)(()=>t.map((g,m)=>({...g,index:m})).slice(i.visibleFromIndex,i.visibleToIndex),[t,i.visibleFromIndex,i.visibleToIndex]);return(0,Zp.useEffect)(()=>{i.value&&i.previousValue!==i.value&&n?.(i.value)},[i.previousValue,i.value,t,n]),{focusedValue:i.focusedValue,visibleFromIndex:i.visibleFromIndex,visibleToIndex:i.visibleToIndex,value:i.value,visibleOptions:d,focusNextOption:l,focusPreviousOption:c,selectFocusedOption:u}};var lyt=({isDisabled:e=!1,state:t})=>{or((r,n)=>{n.downArrow&&t.focusNextOption(),n.upArrow&&t.focusPreviousOption(),n.return&&t.selectFocusedOption()},{isActive:!e})};function T2({isDisabled:e=!1,visibleOptionCount:t=5,highlightText:r,options:n,defaultValue:i,onChange:o}){let s=ayt({visibleOptionCount:t,options:n,defaultValue:i,onChange:o});lyt({isDisabled:e,state:s});let{styles:a}=oo("Select");return I2.default.createElement(B,{...a.container()},s.visibleOptions.map(l=>{let c=l.label;if(r&&l.label.includes(r)){let u=l.label.indexOf(r);c=I2.default.createElement(I2.default.Fragment,null,l.label.slice(0,u),I2.default.createElement(x,{...a.highlightedText()},r),l.label.slice(u+r.length))}return I2.default.createElement(oyt,{key:l.value,isFocused:!e&&s.focusedValue===l.value,isSelected:s.value===l.value},c)}))}var Mun=Re(it(),1);var cyt=Re(it(),1);var Pun=Re(it(),1);var aX=Re(it(),1);var Qun=Re(it(),1);var aki=Jt.inverse(" ");var Eg=Re(it(),1);var v2=Re(it(),1);var uyt=Re(it(),1);var lX=(0,uyt.createContext)({marker:Zt.line});function cX({children:e}){let{marker:t}=(0,v2.useContext)(lX),{styles:r}=oo("OrderedList");return v2.default.createElement(B,{...r.listItem()},v2.default.createElement(x,{...r.marker()},t),v2.default.createElement(B,{...r.content()},e))}var dyt=Re(it(),1),qTe=(0,dyt.createContext)({marker:""});function _g({children:e}){let{marker:t}=(0,Eg.useContext)(qTe),{styles:r}=oo("OrderedList"),n=0;for(let o of Eg.default.Children.toArray(e))!(0,Eg.isValidElement)(o)||o.type!==cX||n++;let i=String(n).length;return Eg.default.createElement(B,{...r.list()},Eg.default.Children.map(e,(o,s)=>{if(!(0,Eg.isValidElement)(o)||o.type!==cX)return o;let a=`${String(s+1).padStart(i)}.`,l=`${t}${a}`;return Eg.default.createElement(qTe.Provider,{value:{marker:l}},Eg.default.createElement(lX.Provider,{value:{marker:l}},o))}))}_g.Item=cX;var Fun=Re(it(),1);var GTe=Re(it(),1);var Lun=Re(it(),1);var Qki=Jt.inverse(" ");var Uun=Re(it(),1);var $un=Re(it(),1);var qun=Re(it(),1);var uX=Re(it(),1);var Hun=Re(it(),1);var sMi=Jt.inverse(" ");var R2=Re(it(),1);var zTe=Re(it(),1);YU();ps();Ci();iv();Wt();var Gun=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function DC(){let e=Gun,{frame:t}=OD({interval:120});return(0,_.jsx)(B,{flexWrap:"nowrap",height:1,width:2,children:(0,_.jsx)(x,{color:Me().claude,children:e[t%e.length]})})}var pX=Re(it(),1);var Ev=null,W0=null,fX=new Set,dX=null;function YTe(e){let{columns:t,rows:r}=e;return t&&r?{columns:t,rows:r}:(dX||(dX=xfe()),{columns:t||dX.columns||80,rows:r||dX.rows||24})}function jTe(){if(!W0)return;let e=YTe(W0);Ev&&e.columns===Ev.columns&&e.rows===Ev.rows||(Ev=e,fX.forEach(t=>t(Ev)))}function zun(e,t){return W0!==e&&(W0&&W0.off("resize",jTe),W0=e,Ev=YTe(e),e.on("resize",jTe)),fX.add(t),()=>{fX.delete(t),fX.size===0&&W0&&(W0.off("resize",jTe),W0=null,Ev=null)}}function VTe(){let{stdout:e}=Uy(),[t,r]=(0,pX.useState)(()=>YTe(e));return(0,pX.useEffect)(()=>zun(e,r),[e]),t}function mX(){return VTe()}He();Xd();Oe();RA();Oe();var KQi=Re(Xbt(),1);import{homedir as q5}from"os";import{join as D2}from"path";import{existsSync as G5,mkdirSync as tCt,appendFileSync as eCt,readFileSync as rCt,constants as Hpn,writeFileSync as qpn,unlinkSync as nCt,statSync as Gpn}from"fs";import{platform as iCt}from"process";import{accessSync as zpn}from"fs";var $pn="2.7.19",H5={VERSION:$pn,PACKAGE_URL:"@dahawa/hawa-code",README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};He();var yv=D2(s0,".update.lock"),jpn=300*1e3;function oCt(){try{if(G5(s0)||tCt(s0,{recursive:!0}),G5(yv)){let e=Gpn(yv);if(Date.now()-e.mtimeMs<jpn)return!1;try{nCt(yv)}catch(r){return ve(`Failed to remove stale lock file: ${r}`),!1}}return qpn(yv,`${process.pid}`,"utf8"),!0}catch(e){return ve(`Failed to acquire lock: ${e}`),!1}}function sCt(){try{G5(yv)&&rCt(yv,"utf8")===`${process.pid}`&&nCt(yv)}catch(e){ve(`Failed to release lock: ${e}`)}}async function gve(){try{let e=await Wn("npm -g config get prefix");if(e.code!==0)return ve("Failed to check npm permissions"),{hasPermissions:!1,npmPrefix:null};let t=e.stdout.trim(),r=!1;try{zpn(t,Hpn.W_OK),r=!0}catch{r=!1}return r?{hasPermissions:!0,npmPrefix:t}:(ve("Insufficient permissions for global npm install."),{hasPermissions:!1,npmPrefix:t})}catch(e){return ve(`Failed to verify npm global install permissions: ${e}`),{hasPermissions:!1,npmPrefix:null}}}async function aCt(e){if(!oCt())throw Nt("tengu_auto_updater_prefix_lock_contention",{pid:String(process.pid),currentVersion:H5.VERSION,prefix:e}),new Error("Another process is currently setting up npm prefix");try{G5(e)||tCt(e,{recursive:!0});let t=await Wn(`npm -g config set prefix ${e}`);if(t.code!==0)throw new Error(`Failed to set npm prefix: ${t.stderr}`);let r=`
1020
1020
  # npm global path
1021
1021
  export PATH="${e}/bin:$PATH"
1022
1022
  `;if(iCt==="win32"){let n=await Wn(`setx PATH "${process.env.PATH};${e}"`);if(n.code!==0)throw new Error(`Failed to update PATH on Windows: ${n.stderr}`)}else{let n=[D2(q5(),".bashrc"),D2(q5(),".bash_profile"),D2(q5(),".zshrc"),D2(q5(),".config","fish","config.fish")];for(let i of n)if(G5(i))try{if(!rCt(i,"utf8").includes(e)){if(i.includes("fish")){let s=`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dahawa/hawa-code",
3
- "version": "2.7.18",
3
+ "version": "2.7.19",
4
4
  "bin": {
5
5
  "hcode": "hawa.js"
6
6
  },