@dahawa/hawa-code 2.7.17 → 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.
- package/cli.js +5 -5
- package/hands.js +4 -4
- 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.17",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.
|
|
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>
|
|
@@ -1044,7 +1044,7 @@ ${Ge.isMessageArchivingEnable()?`
|
|
|
1044
1044
|
|
|
1045
1045
|
${await GIt()||""}`,`
|
|
1046
1046
|
${await nw()}
|
|
1047
|
-
|
|
1047
|
+
`,"# Code References\n\nWhen referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.",...Ge.isMemoEnable()?["\n\n# Memo Tool Content Placeholder\n\nWhen the Memo tool is enabled, older Memo write contents are truncated in the context window. If you see a past Memo write where the content appears as `...<first 20 characters>...(argument truncated)`, the real content is stored on disk. Use the Memo tool's `read` operation with the corresponding `key` when you need the full content again. The most recent 5 messages keep their full content unchanged."]:[],...Je().language&&Je().language!=="auto"?[`
|
|
1048
1048
|
|
|
1049
1049
|
# Language
|
|
1050
1050
|
Always respond in ${Je().language}. Use ${Je().language} for all explanations, comments, and communications with the user. Technical terms and code identifiers should remain in their original form.
|
|
@@ -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}
|