@dahawa/hawa-code 2.9.4 → 2.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/cli.js +580 -580
  2. package/hands.js +4 -4
  3. package/package.json +1 -1
  4. package/server.js +2 -2
package/hands.js CHANGED
@@ -619,7 +619,7 @@ data: ${JSON.stringify(L)}
619
619
  `);a=P.pop()||"";for(let L of P){let j=L.trim();if(!(!j||j==="data: [DONE]"))if(j.startsWith("data: ")){let z=j.slice(6);try{let J=JSON.parse(z);D(J)}catch(J){this.logger&&this.logger.error({err:J,line:j},"Failed to parse Gemini SSE chunk")}}else try{let z=JSON.parse(j);D(z)}catch{}}};(async()=>{try{for(;;){let{value:P,done:L}=await s.read();if(L)break;a+=n.decode(P,{stream:!0}),M()}T()}catch(P){o.error(P)}})()}})}convertGeminiResponseToAnthropic(t){this.logger&&this.logger.debug({response:t},"Original Gemini response");try{if(!t.candidates||!t.candidates[0])throw new Error("No candidates found in Gemini response");let r=t.candidates[0],n=[];r.content&&r.content.parts&&r.content.parts.forEach(o=>{if(o.text&&n.push({type:"text",text:o.text}),o.functionCall){let s=`toolu_${$N()}`,a=o.functionCall.thoughtSignature||o.functionCall.thought_signature||null;n.push({type:"tool_use",id:s,name:o.functionCall.name,input:o.functionCall.args||{},thought_signature:a})}}),r.groundingMetadata&&(this.logger&&this.logger.debug({groundingMetadata:r.groundingMetadata},"Processing grounding metadata"),r.groundingMetadata.webSearchQueries&&n.push({type:"text",text:`
620
620
 
621
621
  [Search queries used: ${r.groundingMetadata.webSearchQueries.join(", ")}]`}));let i={id:`msg_${Math.random().toString(36).slice(2)}`,type:"message",role:"assistant",model:t.modelVersion||"gemini",content:n,stop_reason:r.finishReason?r.finishReason==="STOP"&&n.some(o=>o.type==="tool_use")?"tool_use":this.mapGeminiFinishReason(r.finishReason):"end_turn",stop_sequence:null,usage:{input_tokens:t.usageMetadata?.promptTokenCount||0,output_tokens:t.usageMetadata?.candidatesTokenCount||0}};return this.logger&&this.logger.debug({result:i},"Conversion complete, final Anthropic response"),i}catch{throw t8r(`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"}}},_ye=new Eye;var zmt=we(Hmt(),1);Zt();os();function og(e){return e?typeof e.entries=="function"?Object.fromEntries(e.entries()):{...e}:{}}function qmt(e){let t=String(e?.["x-thinking-level"]??"medium").toLowerCase();return["off","low","medium","high"].includes(t)?t:"medium"}function gtn(e,t){if(t==="off"){delete e.reasoning;return}e.reasoning={effort:t}}function Atn(e,t){if(t==="off"){delete e.reasoning;return}e.reasoning={effort:t,summary:"auto"}}function htn(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 LU(e,t,r){BG(t,e),OG(t,htn(e,r),r)}function DB(e){let t=[],r=e.getReader(),n,i=new Promise(l=>n=l),o=!1,s=()=>{o||(o=!0,n(Buffer.concat(t).toString("utf8")))};return{stream:new ReadableStream({async pull(l){try{let{done:c,value:u}=await r.read();if(c){l.close(),s();return}t.push(u),l.enqueue(u)}catch(c){l.error(c),s()}},cancel(l){r.cancel(l).catch(()=>{}),s()}}),done:i}}function FU(e){let t=new Headers(e);return t.delete("content-encoding"),t.delete("content-length"),t.delete("transfer-encoding"),t}function Y1e(e,t,r,n,i){let o;try{o={type:"error",error:{type:"api_error",message:JSON.parse(i).error?.message??`${e}: ${n}`,code:`${t}_${r}_ERROR`}}}catch{o={type:"error",error:{type:"api_error",message:`${e}: ${n}`,code:`${t}_${r}_ERROR`}}}return new Response(JSON.stringify(o),{status:r,statusText:n,headers:{"Content-Type":"application/json"}})}var Gmt=["/v1/messages"];function V1e(e){let t;try{typeof e=="string"?t=new wT(e):e instanceof wT?t=e:t=new wT(e.url)}catch{return""}let r=t.pathname;for(let n of Gmt){let i=r.indexOf(n);if(i!==-1)return t.origin+r.slice(0,i)}return t.origin}function qJ(e,t){let r=typeof e=="string"?e:e instanceof wT?e.toString():e.url,n;try{n=new wT(r).pathname}catch{return!1}return Gmt.some(i=>n.includes(i))&&(t.method==="POST"||t.method==="post")}function Etn(e){return async(t,r)=>{if(!qJ(t,r))return e(t,r);let n=JSON.parse(r.body),i=await GW.transformRequestOut(n),o=V1e(t)+"/chat/completions",s=og(r.headers),a=s.authorization??s.Authorization??"";gtn(i,qmt(s));let l=await e(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:a},body:JSON.stringify(i),signal:r.signal});if(!l.ok){let y=await l.text();return V(`OpenAI Chat Completions API error: ${l.status}`,{url:o,errorResponse:y}),Y1e("OpenAI Chat Completions API error","OPENROUTER",l.status,l.statusText,y)}let c=n.stream===!0,u=s["x-agent-id"],d={request:{url:o,method:r.method,headers:s,body:n},response:{status:l.status,statusText:l.statusText,headers:og(l.headers)},openai:{request:{body:i},response:{}}};if(!c){let y=await l.text(),C=new Response(y,{status:l.status,statusText:l.statusText,headers:FU(l.headers)}),I=await GW.transformResponseIn(C,n),T=await I.text();try{LU({...d,openai:{...d.openai,response:{body:JSON.parse(y)}},response:{...d.response,body:JSON.parse(T)}},u)}catch(D){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Chat \u975E\u6D41\u5F0F):",D)}return new Response(T,{status:I.status,statusText:I.statusText,headers:I.headers})}let g=DB(l.body),m=new Response(g.stream,{status:l.status,statusText:l.statusText,headers:FU(l.headers)}),A=await GW.transformResponseIn(m,n),h=DB(A.body);return Promise.all([g.done,h.done]).then(async([y,C])=>{try{LU({...d,openai:{...d.openai,response:{body:await Eot(y)}},response:{...d.response,body:await RF(C)}},u)}catch(I){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Chat \u6D41\u5F0F):"+I?.stack)}}).catch(y=>V("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Chat):"+y)),new Response(h.stream,{status:A.status,statusText:A.statusText,headers:A.headers})}}function _tn(e){return async(t,r)=>{if(!qJ(t,r))return e(t,r);let n=JSON.parse(r.body),i=await zW.transformRequestOut(n),o=og(r.headers);Atn(i,qmt(o));let s=JSON.stringify(i),l=V1e(t)+"/responses",c=o.authorization??o.Authorization??"";if(!c)return new Response(JSON.stringify({type:"error",error:{type:"api_error",message:"Missing Authorization header",code:"RESPONSES_AUTH_MISSING"}}),{status:401,headers:{"Content-Type":"application/json"}});let u=await e(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:c,"x-api-key":c.replace(/^Bearer\s+/i,"").trim()},body:s,signal:r.signal});if(!u.ok){let I=await u.text();return V(`OpenAI Responses API error: ${u.status} ${u.statusText}`,{url:l,status:u.status,errorResponse:I}),Y1e("OpenAI Responses API error","RESPONSES",u.status,u.statusText,I)}let d=n.stream===!0,g=o["x-agent-id"],m={request:{url:l,method:r.method,headers:o,body:n},response:{status:u.status,statusText:u.statusText,headers:og(u.headers)},openai:{request:{body:i},response:{}}};if(!d){let I=await u.text(),T=new Response(I,{status:u.status,statusText:u.statusText,headers:FU(u.headers)}),D=await zW.transformResponseIn(T,n),M=await D.text();try{LU({...m,openai:{...m.openai,response:{body:JSON.parse(I)}},response:{...m.response,body:JSON.parse(M)}},g,"responses")}catch(P){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Responses \u975E\u6D41\u5F0F):",P)}return new Response(M,{status:D.status,statusText:D.statusText,headers:D.headers})}let A=DB(u.body),h=new Response(A.stream,{status:u.status,statusText:u.statusText,headers:FU(u.headers)}),y=await zW.transformResponseIn(h,n),C=DB(y.body);return Promise.all([A.done,C.done]).then(async([I,T])=>{try{LU({...m,openai:{...m.openai,response:{body:await hot(I)}},response:{...m.response,body:await RF(T)}},g,"responses")}catch(D){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Responses \u6D41\u5F0F):"+D?.stack)}}).catch(I=>V("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Responses):"+I)),new Response(C.stream,{status:y.status,statusText:y.statusText,headers:y.headers})}}function ytn(e){return async(t,r)=>{if(!qJ(t,r))return e(t,r);let n=JSON.parse(r.body),i=og(r.headers),o=await _ye.transformRequestOut(n),s=JSON.stringify(o),a=V1e(t)+`/models/${n.model}:streamGenerateContent?alt=sse`,l=i.authorization??i.Authorization??"",c;try{c=await e(a,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":String(l).replace(/^Bearer\s+/i,"").trim()},body:s,signal:r.signal})}catch(C){throw V("gemini request error:",C),C}if(!c.ok){let C=await c.text();return V(`Gemini API error response: ${c.status} ${c.statusText}`,{url:a,status:c.status,errorResponse:C}),Y1e("Gemini API error","Gemini",c.status,c.statusText,C)}let u=n.stream===!0,d=i["x-agent-id"],g={request:{url:a,method:r.method,headers:og(r.headers),body:n},response:{status:c.status,statusText:c.statusText,headers:og(c.headers)},openai:{request:{body:o},response:{}}},m=DB(c.body),A=new Response(m.stream,{status:c.status,statusText:c.statusText,headers:FU(c.headers)}),h=await _ye.transformResponseIn(A),y=DB(h.body);return Promise.all([m.done,y.done]).then(async([C,I])=>{try{let T=u?_ot(C):JSON.parse(C),D=u?await RF(I):JSON.parse(I);LU({...g,openai:{...g.openai,response:{body:T}},response:{...g.response,body:D}},d)}catch(T){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Gemini):"+T?.stack)}}).catch(C=>V("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Gemini):"+C)),new Response(y.stream,{status:h.status,statusText:h.statusText,headers:h.headers})}}function btn(e){return async(t,r)=>{if(!qJ(t,r))return e(t,r);let n=r.body;if(r.body)try{let d=JSON.parse(r.body);n=JSON.stringify(d)}catch{}let i=og(r.headers);["1","true"].includes(String(process.env.HAWA_CODE_X_API_KEY_DISABLED??"").toLowerCase())&&(delete i["x-api-key"],delete i["X-API-Key"]),["1","true"].includes(String(process.env.HAWA_CODE_AUTH_DISABLED??"").toLowerCase())&&(delete i.authorization,delete i.Authorization),delete i["content-length"];let a=await e(t,{method:r.method,headers:i,body:n,signal:r.signal});if(!a.ok){let d=await a.text();V(`API error response: ${a.status} ${a.statusText}`,{url:typeof t=="string"?t:t instanceof wT?t.toString():t.url,status:a.status,errorResponse:d});let g;try{let m=JSON.parse(d);g={type:"error",error:{type:"api_error",message:m.error?.message||m.message||`API error: ${a.statusText}`,code:m.error?.code||m.code||`API_${a.status}_ERROR`}},m.error?.details&&(g.error.details=m.error.details)}catch{g={type:"error",error:{type:"api_error",message:`API error: ${a.statusText}`,code:`API_${a.status}_ERROR`}}}return new Response(JSON.stringify(g),{status:a.status,statusText:a.statusText,headers:{"Content-Type":"application/json"}})}let l=a.clone(),c=!(Object.hasOwn(JSON.parse(n),"stream")&&!JSON.parse(n).stream),u={request:{url:typeof t=="string"?t:t instanceof wT?t.toString():t.url,method:r.method,headers:og(r.headers),body:JSON.parse(n)},response:{status:a.status,statusText:a.statusText,headers:og(a.headers)}};return(async()=>{if(c){let m=await a.text();u.response.body=await RF(m)}else u.response.body=await a.json();let g=og(r.headers)["x-agent-id"];BG(g,u),OG(g,{request:u.request.body.messages,response:u.response.body.content,usage:u.response.body?.usage})})().catch(d=>V(`\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF:
622
- Stack trace: `+d.stack)),new Response(l.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}var HJ=null,j1e=!1;function Ctn(){HJ=null,j1e=!1}Yt.on("proxy:changed",Ctn);function Stn(){if(j1e)return HJ;if(j1e=!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&&(HJ=new zmt.ProxyAgent({uri:e}),nt(`[proxy] using proxy: ${e}`)),HJ}function Itn(){let e=Stn();return e?((t,r={})=>global.fetch(t,{...r,dispatcher:e})):global.fetch}function GJ(e){let t=e||process.env.API_TYPE,r=Itn();switch(t){case"openai":return Etn(r);case"openai-responses":return _tn(r);case"gemini":return ytn(r);default:return btn(r)}}NA();var wtn=we(Ze(),1);function jmt(e,t){let r=[],n=Math.max(1,Math.floor(t)),i="",o=0;for(let s of e){let a=Ttn(s);i&&o+a>n?(r.push(i),i=s,o=a):(i+=s,o+=a)}return i&&r.push(i),r}function Ttn(e){if(e===" ")return 4;let t=e.codePointAt(0);return t===void 0||t===0||t<32||t>=127&&t<160||vtn(t)?0:xtn(t)?2:1}function vtn(e){return e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071}function xtn(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=127744&&e<=128591||e>=129280&&e<=129535||e>=131072&&e<=262141)}function UU(e){if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),n=(e%6e4/1e3).toFixed(1);return t>0?`${t}h ${r}m ${n}s`:r>0?`${r}m ${n}s`:`${n}s`}function zJ(e){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(e).toLowerCase()}De();os();var Kl={totalCost:0,totalAPIDuration:0,startTime:Date.now(),inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,currentContextTokens:0};function jJ(e,t){Kl.totalCost+=e,Kl.totalAPIDuration+=t}function YJ(e,t){Kl.inputTokens+=e,Kl.outputTokens+=t,Yt.emit("token:change",{inputTokens:Kl.inputTokens,outputTokens:Kl.outputTokens})}function VJ(e,t){Kl.cacheCreationTokens+=e,Kl.cacheReadTokens+=t}function W1e(){return{inputTokens:Kl.inputTokens,outputTokens:Kl.outputTokens,cacheCreationTokens:Kl.cacheCreationTokens,cacheReadTokens:Kl.cacheReadTokens}}function Ymt(){return Kl.totalCost}function Vmt(){return Date.now()-Kl.startTime}function Wmt(){return Kl.totalAPIDuration}function Kmt(e){Kl.currentContextTokens=e}function Jmt(){return Kl.currentContextTokens}De();He();He();var K1e="2.9.4";globalThis.MACRO={VERSION:K1e,PACKAGE_URL:`@dahawa/${zi}`,README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var WJ=process.env.HAWA_CODE_USER_AGENT||`${zi}/${K1e} (${process.env.USER_TYPE})`;os();De();ar();Cr();De();He();import{existsSync as R0,readdirSync as rsn,statSync as nsn}from"fs";import{join as uC,relative as isn}from"path";import{homedir as Hht}from"os";import{platform as osn}from"process";import{readFile as dC}from"fs/promises";Cr();xf();Zt();import{join as Otn,sep as ktn}from"path";function zp(){if(!fu())return!1;try{let e=Je();if(e.autoMemory?.teamMemoryEnabled!==void 0)return e.autoMemory.teamMemoryEnabled}catch{}return!1}function pu(){return(Otn(Re(),".hcode","team-memory")+ktn).normalize("NFC")}function ag(e){let t=e.normalize("NFC"),r=pu();return t.startsWith(r)}xf();var qht=we(FB(),1);Di();var pIe=(e,t,r)=>{let n=e instanceof RegExp?Aht(e,r):e,i=t instanceof RegExp?Aht(t,r):t,o=n!==null&&i!=null&&jin(n,i,r);return o&&{start:o[0],end:o[1],pre:r.slice(0,o[0]),body:r.slice(o[0]+n.length,o[1]),post:r.slice(o[1]+i.length)}},Aht=(e,t)=>{let r=t.match(e);return r?r[0]:null},jin=(e,t,r)=>{let n,i,o,s,a,l=r.indexOf(e),c=r.indexOf(t,l+1),u=l;if(l>=0&&c>0){if(e===t)return[l,c];for(n=[],o=r.length;u>=0&&!a;){if(u===l)n.push(u),l=r.indexOf(e,u+1);else if(n.length===1){let d=n.pop();d!==void 0&&(a=[d,c])}else i=n.pop(),i!==void 0&&i<o&&(o=i,s=c),c=r.indexOf(t,u+1);u=l<c&&l>=0?l:c}n.length&&s!==void 0&&(a=[o,s])}return a};var hht="\0SLASH"+Math.random()+"\0",Eht="\0OPEN"+Math.random()+"\0",AIe="\0CLOSE"+Math.random()+"\0",_ht="\0COMMA"+Math.random()+"\0",yht="\0PERIOD"+Math.random()+"\0",Yin=new RegExp(hht,"g"),Vin=new RegExp(Eht,"g"),Win=new RegExp(AIe,"g"),Kin=new RegExp(_ht,"g"),Jin=new RegExp(yht,"g"),Zin=/\\\\/g,Xin=/\\{/g,eon=/\\}/g,ton=/\\,/g,ron=/\\\./g,non=1e5,ion=4e6;function mIe(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function oon(e){return e.replace(Zin,hht).replace(Xin,Eht).replace(eon,AIe).replace(ton,_ht).replace(ron,yht)}function son(e){return e.replace(Yin,"\\").replace(Vin,"{").replace(Win,"}").replace(Kin,",").replace(Jin,".")}function bht(e){if(!e)return[""];let t=[],r=pIe("{","}",e);if(!r)return e.split(",");let{pre:n,body:i,post:o}=r,s=n.split(",");s[s.length-1]+="{"+i+"}";let a=bht(o);return o.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),t.push.apply(t,s),t}function Cht(e,t={}){if(!e)return[];let{max:r=non,maxLength:n=ion}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),gIe(oon(e),r,n,!0).map(son)}function aon(e){return"{"+e+"}"}function lon(e){return/^-?0\d/.test(e)}function con(e,t){return e<=t}function uon(e,t){return e>=t}function WU(e,t,r,n,i,o){let s=[],a=0;for(let l=0;l<e.length;l++)for(let c=0;c<r.length;c++){if(s.length>=n)return s;let u=e[l]+t+r[c];if(!(o&&!u)){if(a+u.length>i)return s;s.push(u),a+=u.length}}return s}function don(e,t,r,n){let i=e.split(/\.\./),o=[];if(i[0]===void 0||i[1]===void 0)return o;let s=mIe(i[0]),a=mIe(i[1]),l=Math.max(i[0].length,i[1].length),c=i.length===3&&i[2]!==void 0?Math.max(Math.abs(mIe(i[2])),1):1,u=con;a<s&&(c*=-1,u=uon);let g=i.some(lon),m=0;for(let A=s;u(A,a)&&o.length<r;A+=c){let h;if(t)h=String.fromCharCode(A),h==="\\"&&(h="");else if(h=String(A),g){let y=l-h.length;if(y>0){let C=new Array(y+1).join("0");A<0?h="-"+C+h.slice(1):h=C+h}}if(m+h.length>n)break;o.push(h),m+=h.length}return o}function gIe(e,t,r,n){let i=[""],o=!1,s=!0;for(;;){let a=pIe("{","}",e);if(!a)return WU(i,e,[""],t,r,o);let l=a.pre;if(/\$$/.test(l)){if(i=WU(i,l+"{"+a.body+"}",[""],t,r,o&&!a.post.length),s=!1,!a.post.length)break;e=a.post;continue}let c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(a.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(a.body),d=c||u,g=a.body.indexOf(",")>=0;if(!d&&!g){if(a.post.match(/,(?!,).*\}/)){e=a.pre+"{"+a.body+AIe+a.post,n=!0;continue}return WU(i,l+"{"+a.body+"}"+a.post,[""],t,r,o)}s&&(o=n&&!d,s=!1);let m;if(d)m=don(a.body,u,t,r);else{let A=bht(a.body);if(A.length===1&&A[0]!==void 0&&(A=gIe(A[0],t,r,!1).map(aon),A.length===1)){if(i=WU(i,l+A[0],[""],t,r,o&&!a.post.length),!a.post.length)break;e=a.post;continue}let h=o&&!a.post.length&&!l;for(let C=0;h&&C<i.length;C++)i[C]&&(h=!1);m=[];let y=0;e:for(let C=0;C<A.length;C++){let I=gIe(A[C],t,r,!1);for(let T=0;T<I.length;T++){let D=I[T];if(!(h&&!D)){if(m.length>=t||y+D.length>r)break e;m.push(D),y+=D.length}}}}if(i=WU(i,l,m,t,r,o&&!a.post.length),!a.post.length)break;e=a.post}return i}var KU=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")};var fon={"[: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]},JU=e=>e.replace(/[[\]\\-]/g,"\\$&"),pon=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Sht=e=>e.join(""),Iht=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],i=[],o=r+1,s=!1,a=!1,l=!1,c=!1,u=r,d="";e:for(;o<e.length;){let h=e.charAt(o);if((h==="!"||h==="^")&&o===r+1){c=!0,o++;continue}if(h==="]"&&s&&!l){u=o+1;break}if(s=!0,h==="\\"&&!l){l=!0,o++;continue}if(h==="["&&!l){for(let[y,[C,I,T]]of Object.entries(fon))if(e.startsWith(y,o)){if(d)return["$.",!1,e.length-r,!0];o+=y.length,T?i.push(C):n.push(C),a=a||I;continue e}}if(l=!1,d){h>d?n.push(JU(d)+"-"+JU(h)):h===d&&n.push(JU(h)),d="",o++;continue}if(e.startsWith("-]",o+1)){n.push(JU(h+"-")),o+=2;continue}if(e.startsWith("-",o+1)){d=h,o+=2;continue}n.push(JU(h)),o++}if(u<o)return["",!1,0,!1];if(!n.length&&!i.length)return["$.",!1,e.length-r,!0];if(i.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let h=n[0].length===2?n[0].slice(-1):n[0];return[pon(h),!1,u-r,!1]}let g="["+(c?"^":"")+Sht(n)+"]",m="["+(c?"":"^")+Sht(i)+"]";return[n.length&&i.length?"("+g+"|"+m+")":n.length?g:m,a,u-r,!0]};var cC=(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 Ed,mon=new Set(["!","?","+","*","@"]),hIe=e=>mon.has(e),Tht=e=>hIe(e.type),gon=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),Aon=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),hon=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),vht=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),Eon="(?!(?:^|/)\\.\\.?(?:$|/))",lZ="(?!\\.)",_on=new Set(["[","."]),yon=new Set(["..","."]),bon=new Set("().*{}+?[]^$\\!"),Con=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),EIe="[^/]",xht=EIe+"*?",wht=EIe+"+?",Son=0,QT=class{type;#e;#t;#n=!1;#r=[];#o;#i;#l;#s=!1;#a;#d;#p=!1;id=++Son;get depth(){return(this.#o?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#e.id,parent:this.#o?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(t,r,n={}){this.type=t,t&&(this.#t=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#l=this.#e===this?[]:this.#e.#l,t==="!"&&!this.#e.#s&&this.#l.push(this),this.#i=this.#o?this.#o.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#d=this.#r.map(t=>String(t)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#s)return this;this.toString(),this.#s=!0;let t;for(;t=this.#l.pop();){if(t.type!=="!")continue;let r=t,n=r.#o;for(;n;){for(let i=r.#i+1;!n.type&&i<n.#r.length;i++)for(let o of t.#r){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(n.#r[i])}r=n,n=r.#o}}return this}push(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof Ed&&r.#o===this))throw new Error("invalid part: "+r);this.#r.push(r)}}toJSON(){let t=this.type===null?this.#r.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#r.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#i===0)return!0;let t=this.#o;for(let r=0;r<this.#i;r++){let n=t.#r[r];if(!(n instanceof Ed&&n.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let t=this.#o?this.#o.#r.length:0;return this.#i===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let r=new Ed(this.type,t);for(let n of this.#r)r.copyIn(n);return r}static#c(t,r,n,i,o){let s=i.maxExtglobRecursion??2,a=!1,l=!1,c=-1,u=!1;if(r.type===null){let h=n,y="";for(;h<t.length;){let C=t.charAt(h++);if(a||C==="\\"){a=!a,y+=C;continue}if(l){h===c+1?(C==="^"||C==="!")&&(u=!0):C==="]"&&!(h===c+2&&u)&&(l=!1),y+=C;continue}else if(C==="["){l=!0,c=h,u=!1,y+=C;continue}if(!i.noext&&hIe(C)&&t.charAt(h)==="("&&o<=s){r.push(y),y="";let T=new Ed(C,r);h=Ed.#c(t,T,h,i,o+1),r.push(T);continue}y+=C}return r.push(y),h}let d=n+1,g=new Ed(null,r),m=[],A="";for(;d<t.length;){let h=t.charAt(d++);if(a||h==="\\"){a=!a,A+=h;continue}if(l){d===c+1?(h==="^"||h==="!")&&(u=!0):h==="]"&&!(d===c+2&&u)&&(l=!1),A+=h;continue}else if(h==="["){l=!0,c=d,u=!1,A+=h;continue}if(!i.noext&&hIe(h)&&t.charAt(d)==="("&&(o<=s||r&&r.#E(h))){let C=r&&r.#E(h)?0:1;g.push(A),A="";let I=new Ed(h,g);g.push(I),d=Ed.#c(t,I,d,i,o+C);continue}if(h==="|"){g.push(A),A="",m.push(g),g=new Ed(null,r);continue}if(h===")")return A===""&&r.#r.length===0&&(r.#p=!0),g.push(A),A="",r.push(...m,g),d;A+=h}return r.type=null,r.#t=void 0,r.#r=[t.substring(n-1)],d}#g(t){return this.#h(t,Aon)}#h(t,r=gon){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null)return!1;let n=t.#r[0];return!n||typeof n!="object"||n.type===null?!1:this.#E(n.type,r)}#E(t,r=hon){return!!r.get(this.type)?.includes(t)}#A(t,r){let n=t.#r[0],i=new Ed(null,n,this.options);i.#r.push(""),n.push(i),this.#v(t,r)}#v(t,r){let n=t.#r[0];this.#r.splice(r,1,...n.#r);for(let i of n.#r)typeof i=="object"&&(i.#o=this);this.#d=void 0}#y(t){return!!vht.get(this.type)?.has(t)}#S(t){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let r=t.#r[0];return!r||typeof r!="object"||r.type===null?!1:this.#y(r.type)}#I(t){let r=vht.get(this.type),n=t.#r[0],i=r?.get(n.type);if(!i)return!1;this.#r=n.#r;for(let o of this.#r)typeof o=="object"&&(o.#o=this);this.type=i,this.#d=void 0,this.#p=!1}static fromGlob(t,r={}){let n=new Ed(null,void 0,r);return Ed.#c(t,n,0,r,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let t=this.toString(),[r,n,i,o]=this.toRegExpSource();if(!(i||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){let r=t??!!this.#a.dot;if(this.#e===this&&(this.#_(),this.#f()),!Tht(this)){let l=this.isStart()&&this.isEnd()&&!this.#r.some(m=>typeof m!="string"),c=this.#r.map(m=>{let[A,h,y,C]=typeof m=="string"?Ed.#C(m,this.#t,l):m.toRegExpSource(t);return this.#t=this.#t||y,this.#n=this.#n||C,A}).join(""),u="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&yon.has(this.#r[0]))){let A=_on,h=r&&A.has(c.charAt(0))||c.startsWith("\\.")&&A.has(c.charAt(2))||c.startsWith("\\.\\.")&&A.has(c.charAt(4)),y=!r&&!t&&A.has(c.charAt(0));u=h?Eon:y?lZ:""}let d="";return this.isEnd()&&this.#e.#s&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,cC(c),this.#t=!!this.#t,this.#n]}let n=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",o=this.#b(r);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let l=this.toString(),c=this;return c.#r=[l],c.type=null,c.#t=void 0,[l,cC(this.toString()),!1,!1]}let s=!n||t||r||!lZ?"":this.#b(!0);s===o&&(s=""),s&&(o=`(?:${o})(?:${s})*?`);let a="";if(this.type==="!"&&this.#p)a=(this.isStart()&&!r?lZ:"")+wht;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?lZ:"")+xht+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=i+o+l}return[a,cC(o),this.#t=!!this.#t,this.#n]}#_(){if(Tht(this)){let t=0,r=!1;do{r=!0;for(let n=0;n<this.#r.length;n++){let i=this.#r[n];typeof i=="object"&&(i.#_(),this.#h(i)?(r=!1,this.#v(i,n)):this.#g(i)?(r=!1,this.#A(i,n)):this.#S(i)&&(r=!1,this.#I(i)))}}while(!r&&++t<10)}else for(let t of this.#r)typeof t=="object"&&t.#_();this.#d=void 0}#b(t){return this.#r.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,i,o,s]=r.toRegExpSource(t);return this.#n=this.#n||s,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#C(t,r,n=!1){let i=!1,o="",s=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(i){i=!1,o+=(bon.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,o+=n&&/^[*]+$/.test(t)?wht:xht,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?o+="\\\\":i=!0;continue}if(c==="["){let[u,d,g,m]=Iht(t,l);if(g){o+=u,s=s||d,l+=g-1,r=r||m;continue}}if(c==="?"){o+=EIe,r=!0;continue}o+=Con(c)}return[o,cC(t),!!r,s]}};Ed=QT;var _Ie=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!1}={})=>r?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&");var Jl=(e,t,r={})=>(KU(t),!r.nocomment&&t.charAt(0)==="#"?!1:new UB(t,r).match(e)),Ion=/^\*+([^+@!?*[(]*)$/,Ton=e=>t=>!t.startsWith(".")&&t.endsWith(e),von=e=>t=>t.endsWith(e),xon=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),won=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Don=/^\*+\.\*+$/,Ron=e=>!e.startsWith(".")&&e.includes("."),Non=e=>e!=="."&&e!==".."&&e.includes("."),Bon=/^\.\*+$/,Oon=e=>e!=="."&&e!==".."&&e.startsWith("."),kon=/^\*+$/,Mon=e=>e.length!==0&&!e.startsWith("."),Qon=e=>e.length!==0&&e!=="."&&e!=="..",Pon=/^\?+([^+@!?*[(]*)?$/,Lon=([e,t=""])=>{let r=Nht([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},Fon=([e,t=""])=>{let r=Bht([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},Uon=([e,t=""])=>{let r=Bht([e]);return t?n=>r(n)&&n.endsWith(t):r},$on=([e,t=""])=>{let r=Nht([e]);return t?n=>r(n)&&n.endsWith(t):r},Nht=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},Bht=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},Oht=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Dht={win32:{sep:"\\"},posix:{sep:"/"}},Hon=Oht==="win32"?Dht.win32.sep:Dht.posix.sep;Jl.sep=Hon;var Oc=Symbol("globstar **");Jl.GLOBSTAR=Oc;var qon="[^/]",Gon=qon+"*?",zon="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",jon="(?:(?!(?:\\/|^)\\.).)*?",Yon=(e,t={})=>r=>Jl(r,e,t);Jl.filter=Yon;var jp=(e,t={})=>Object.assign({},e,t),Von=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return Jl;let t=Jl;return Object.assign((n,i,o={})=>t(n,i,jp(e,o)),{Minimatch:class extends t.Minimatch{constructor(i,o={}){super(i,jp(e,o))}static defaults(i){return t.defaults(jp(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,o,s={}){super(i,o,jp(e,s))}static fromGlob(i,o={}){return t.AST.fromGlob(i,jp(e,o))}},unescape:(n,i={})=>t.unescape(n,jp(e,i)),escape:(n,i={})=>t.escape(n,jp(e,i)),filter:(n,i={})=>t.filter(n,jp(e,i)),defaults:n=>t.defaults(jp(e,n)),makeRe:(n,i={})=>t.makeRe(n,jp(e,i)),braceExpand:(n,i={})=>t.braceExpand(n,jp(e,i)),match:(n,i,o={})=>t.match(n,i,jp(e,o)),sep:t.sep,GLOBSTAR:Oc})};Jl.defaults=Von;var kht=(e,t={})=>(KU(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Cht(e,{max:t.braceExpandMax}));Jl.braceExpand=kht;var Won=(e,t={})=>new UB(e,t).makeRe();Jl.makeRe=Won;var Kon=(e,t,r={})=>{let n=new UB(t,r);return e=e.filter(i=>n.match(i)),n.options.nonull&&!e.length&&e.push(t),e};Jl.match=Kon;var Rht=/[?*]|[+@!]\(.*?\)|\[|\]/,Jon=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),UB=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,r={}){KU(t),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=t,this.platform=r.platform||Oht,this.isWindows=this.platform==="win32";let n="allowWindowsEscape";this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r[n]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let r of t)if(typeof r!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,r=this.options;if(!r.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...o)=>console.error(...o)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(o=>this.slashSplit(o));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let i=this.globParts.map((o,s,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=o[0]===""&&o[1]===""&&(o[2]==="?"||!Rht.test(o[2]))&&!Rht.test(o[3]),c=/^[a-z]:/i.test(o[0]);if(l)return[...o.slice(0,4),...o.slice(4).map(u=>this.parse(u))];if(c)return[o[0],...o.slice(1).map(u=>this.parse(u))]}return o.map(l=>this.parse(l))});if(this.debug(this.pattern,i),this.set=i.filter(o=>o.indexOf(!1)===-1),this.isWindows)for(let o=0;o<this.set.length;o++){let s=this.set[o];s[0]===""&&s[1]===""&&this.globParts[o][2]==="?"&&typeof s[3]=="string"&&/^[a-z]:$/i.test(s[3])&&(s[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let n of t)for(let i=0;i<n.length;i++)n[i]==="**"&&(n[i]="*");let{optimizationLevel:r=1}=this.options;return r>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):r>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let i=n;for(;r[i+1]==="**";)i++;i!==n&&r.splice(n,i-n)}return r})}levelOneOptimize(t){return t.map(r=>(r=r.reduce((n,i)=>{let o=n[n.length-1];return i==="**"&&o==="**"?n:i===".."&&o&&o!==".."&&o!=="."&&o!=="**"?(n.pop(),n):(n.push(i),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let i=1;i<t.length-1;i++){let o=t[i];i===1&&o===""&&t[0]===""||(o==="."||o==="")&&(r=!0,t.splice(i,1),i--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(r=!0,t.pop())}let n=0;for(;(n=t.indexOf("..",n+1))!==-1;){let i=t[n-1];i&&i!=="."&&i!==".."&&i!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(i))&&(r=!0,t.splice(n-1,2),n-=2)}}while(r);return t.length===0?[""]:t}firstPhasePreProcess(t){let r=!1;do{r=!1;for(let n of t){let i=-1;for(;(i=n.indexOf("**",i+1))!==-1;){let s=i;for(;n[s+1]==="**";)s++;s>i&&n.splice(i+1,s-i);let a=n[i+1],l=n[i+2],c=n[i+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;r=!0,n.splice(i,1);let u=n.slice(0);u[i]="**",t.push(u),i--}if(!this.preserveMultipleSlashes){for(let s=1;s<n.length-1;s++){let a=n[s];s===1&&a===""&&n[0]===""||(a==="."||a==="")&&(r=!0,n.splice(s,1),s--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(r=!0,n.pop())}let o=0;for(;(o=n.indexOf("..",o+1))!==-1;){let s=n[o-1];if(s&&s!=="."&&s!==".."&&s!=="**"){r=!0;let l=o===1&&n[o+1]==="**"?["."]:[];n.splice(o-1,2,...l),n.length===0&&n.push(""),o-=2}}}}while(r);return t}secondPhasePreProcess(t){for(let r=0;r<t.length-1;r++)for(let n=r+1;n<t.length;n++){let i=this.partsMatch(t[r],t[n],!this.preserveMultipleSlashes);if(i){t[r]=[],t[n]=i;break}}return t.filter(r=>r.length)}partsMatch(t,r,n=!1){let i=0,o=0,s=[],a="";for(;i<t.length&&o<r.length;)if(t[i]===r[o])s.push(a==="b"?r[o]:t[i]),i++,o++;else if(n&&t[i]==="**"&&r[o]===t[i+1])s.push(t[i]),i++;else if(n&&r[o]==="**"&&t[i]===r[o+1])s.push(r[o]),o++;else if(t[i]==="*"&&r[o]&&(this.options.dot||!r[o].startsWith("."))&&r[o]!=="**"){if(a==="b")return!1;a="a",s.push(t[i]),i++,o++}else if(r[o]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="a")return!1;a="b",s.push(r[o]),i++,o++}else return!1;return t.length===r.length&&s}parseNegate(){if(this.nonegate)return;let t=this.pattern,r=!1,n=0;for(let i=0;i<t.length&&t.charAt(i)==="!";i++)r=!r,n++;n&&(this.pattern=t.slice(n)),this.negate=r}matchOne(t,r,n=!1){let i=0,o=0;if(this.isWindows){let a=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),l=!a&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),c=typeof r[0]=="string"&&/^[a-z]:$/i.test(r[0]),u=!c&&r[0]===""&&r[1]===""&&r[2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3]),d=l?3:a?0:void 0,g=u?3:c?0:void 0;if(typeof d=="number"&&typeof g=="number"){let[m,A]=[t[d],r[g]];m.toLowerCase()===A.toLowerCase()&&(r[g]=m,o=g,i=d)}}let{optimizationLevel:s=1}=this.options;return s>=2&&(t=this.levelTwoFileOptimize(t)),r.includes(Oc)?this.#e(t,r,n,i,o):this.#n(t,r,n,i,o)}#e(t,r,n,i,o){let s=r.indexOf(Oc,o),a=r.lastIndexOf(Oc),[l,c,u]=n?[r.slice(o,s),r.slice(s+1),[]]:[r.slice(o,s),r.slice(s+1,a),r.slice(a+1)];if(l.length){let I=t.slice(i,i+l.length);if(!this.#n(I,l,n,0,0))return!1;i+=l.length,o+=l.length}let d=0;if(u.length){if(u.length+i>t.length)return!1;let I=t.length-u.length;if(this.#n(t,u,n,I,0))d=u.length;else{if(t[t.length-1]!==""||i+u.length===t.length||(I--,!this.#n(t,u,n,I,0)))return!1;d=u.length+1}}if(!c.length){let I=!!d;for(let T=i;T<t.length-d;T++){let D=String(t[T]);if(I=!0,D==="."||D===".."||!this.options.dot&&D.startsWith("."))return!1}return n||I}let g=[[[],0]],m=g[0],A=0,h=[0];for(let I of c)I===Oc?(h.push(A),m=[[],0],g.push(m)):(m[0].push(I),A++);let y=g.length-1,C=t.length-d;for(let I of g)I[1]=C-(h[y--]+I[0].length);return!!this.#t(t,g,i,0,n,0,!!d)}#t(t,r,n,i,o,s,a){let l=r[i];if(!l){for(let d=n;d<t.length;d++){a=!0;let g=t[d];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1}return a}let[c,u]=l;for(;n<=u;){if(this.#n(t.slice(0,n+c.length),c,o,n,0)&&s<this.maxGlobstarRecursion){let m=this.#t(t,r,n+c.length,i+1,o,s+1,a);if(m!==!1)return m}let g=t[n];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1;n++}return o||null}#n(t,r,n,i,o){let s,a,l,c;for(s=i,a=o,c=t.length,l=r.length;s<c&&a<l;s++,a++){this.debug("matchOne loop");let u=r[a],d=t[s];if(this.debug(r,u,d),u===!1||u===Oc)return!1;let g;if(typeof u=="string"?(g=d===u,this.debug("string match",u,d,g)):(g=u.test(d),this.debug("pattern match",u,d,g)),!g)return!1}if(s===c&&a===l)return!0;if(s===c)return n;if(a===l)return s===c-1&&t[s]==="";throw new Error("wtf?")}braceExpand(){return kht(this.pattern,this.options)}parse(t){KU(t);let r=this.options;if(t==="**")return Oc;if(t==="")return"";let n,i=null;(n=t.match(kon))?i=r.dot?Qon:Mon:(n=t.match(Ion))?i=(r.nocase?r.dot?won:xon:r.dot?von:Ton)(n[1]):(n=t.match(Pon))?i=(r.nocase?r.dot?Fon:Lon:r.dot?Uon:$on)(n):(n=t.match(Don))?i=r.dot?Non:Ron:(n=t.match(Bon))&&(i=Oon);let o=QT.fromGlob(t,this.options).toMMPattern();return i&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:i}),o}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?Gon:r.dot?zon:jon,i=new Set(r.nocase?["i"]:[]),o=t.map(l=>{let c=l.map(d=>{if(d instanceof RegExp)for(let g of d.flags.split(""))i.add(g);return typeof d=="string"?Jon(d):d===Oc?Oc:d._src});c.forEach((d,g)=>{let m=c[g+1],A=c[g-1];d!==Oc||A===Oc||(A===void 0?m!==void 0&&m!==Oc?c[g+1]="(?:\\/|"+n+"\\/)?"+m:c[g]=n:m===void 0?c[g-1]=A+"(?:\\/|\\/"+n+")?":m!==Oc&&(c[g-1]=A+"(?:\\/|\\/"+n+"\\/)"+m,c[g+1]=Oc))});let u=c.filter(d=>d!==Oc);if(this.partial&&u.length>=1){let d=[];for(let g=1;g<=u.length;g++)d.push(u.slice(0,g).join("/"));return"(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[s,a]=t.length>1?["(?:",")"]:["",""];o="^"+s+o+a+"$",this.partial&&(o="^(?:\\/|"+s+o.slice(1,-1)+a+")$"),this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,r=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&r)return!0;let n=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let o=this.set;this.debug(this.pattern,"set",o);let s=i[i.length-1];if(!s)for(let a=i.length-2;!s&&a>=0;a--)s=i[a];for(let a of o){let l=i;if(n.matchBase&&a.length===1&&(l=[s]),this.matchOne(l,a,r))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(t){return Jl.defaults(t).Minimatch}};Jl.AST=QT;Jl.Minimatch=UB;Jl.escape=_Ie;Jl.unescape=cC;var Pht=we(FB(),1);Cr();He();De();iu();import{readFile as Mht}from"fs/promises";import{existsSync as yIe,readdirSync as Zon,statSync as Xon}from"fs";import{join as bIe,relative as Lht}from"path";import{homedir as esn}from"os";function Qht(e){try{let t=(0,Pht.default)(e),r=t.data.paths,n=[];return typeof r=="string"?n=r.split(",").map(i=>i.trim()).filter(Boolean):Array.isArray(r)&&(n=r.filter(i=>typeof i=="string")),{paths:n,content:t.content.trim()}}catch(t){return Ie(t),{paths:[],content:e.trim()}}}function tsn(e,t){return t.length===0?!0:t.some(r=>{try{return Jl(e,r,{matchBase:!0,dot:!0})}catch(n){return Ie(n),!1}})}function CIe(e){let t=[];try{if(!yIe(e))return t;let r=Zon(e);for(let n of r){let i=bIe(e,n),o=Xon(i);o.isDirectory()?t.push(...CIe(i)):o.isFile()&&n.endsWith(".md")&&t.push(i)}}catch(r){Ie(r)}return t}async function cZ(){let e=[];try{let t=bIe(esn(),Kr,"rules");if(yIe(t)){let r=CIe(t);for(let n of r)try{let i=await Mht(n,"utf-8"),{paths:o,content:s}=Qht(i);o.length>0&&e.push({filePath:n,content:s,paths:o,isProjectRule:!1})}catch(i){Ie(i)}}}catch(t){Ie(t)}try{let t=bIe(Re(),Kr,"rules");if(yIe(t)){let r=CIe(t);for(let n of r)try{let i=await Mht(n,"utf-8"),{paths:o,content:s}=Qht(i);o.length>0&&e.push({filePath:Lht(Re(),n),content:s,paths:o,isProjectRule:!0})}catch(i){Ie(i)}}}catch(t){Ie(t)}return e}function Fht(e,t){e=xY(e);let r=xY(Re()),n=e.startsWith(r)?Lht(r,e):e;return t.filter(i=>tsn(n,i.paths))}function Uht(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}):
622
+ Stack trace: `+d.stack)),new Response(l.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}var HJ=null,j1e=!1;function Ctn(){HJ=null,j1e=!1}Yt.on("proxy:changed",Ctn);function Stn(){if(j1e)return HJ;if(j1e=!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&&(HJ=new zmt.ProxyAgent({uri:e}),nt(`[proxy] using proxy: ${e}`)),HJ}function Itn(){let e=Stn();return e?((t,r={})=>global.fetch(t,{...r,dispatcher:e})):global.fetch}function GJ(e){let t=e||process.env.API_TYPE,r=Itn();switch(t){case"openai":return Etn(r);case"openai-responses":return _tn(r);case"gemini":return ytn(r);default:return btn(r)}}NA();var wtn=we(Ze(),1);function jmt(e,t){let r=[],n=Math.max(1,Math.floor(t)),i="",o=0;for(let s of e){let a=Ttn(s);i&&o+a>n?(r.push(i),i=s,o=a):(i+=s,o+=a)}return i&&r.push(i),r}function Ttn(e){if(e===" ")return 4;let t=e.codePointAt(0);return t===void 0||t===0||t<32||t>=127&&t<160||vtn(t)?0:xtn(t)?2:1}function vtn(e){return e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071}function xtn(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=127744&&e<=128591||e>=129280&&e<=129535||e>=131072&&e<=262141)}function UU(e){if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),n=(e%6e4/1e3).toFixed(1);return t>0?`${t}h ${r}m ${n}s`:r>0?`${r}m ${n}s`:`${n}s`}function zJ(e){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(e).toLowerCase()}De();os();var Kl={totalCost:0,totalAPIDuration:0,startTime:Date.now(),inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,currentContextTokens:0};function jJ(e,t){Kl.totalCost+=e,Kl.totalAPIDuration+=t}function YJ(e,t){Kl.inputTokens+=e,Kl.outputTokens+=t,Yt.emit("token:change",{inputTokens:Kl.inputTokens,outputTokens:Kl.outputTokens})}function VJ(e,t){Kl.cacheCreationTokens+=e,Kl.cacheReadTokens+=t}function W1e(){return{inputTokens:Kl.inputTokens,outputTokens:Kl.outputTokens,cacheCreationTokens:Kl.cacheCreationTokens,cacheReadTokens:Kl.cacheReadTokens}}function Ymt(){return Kl.totalCost}function Vmt(){return Date.now()-Kl.startTime}function Wmt(){return Kl.totalAPIDuration}function Kmt(e){Kl.currentContextTokens=e}function Jmt(){return Kl.currentContextTokens}De();He();He();var K1e="2.9.5";globalThis.MACRO={VERSION:K1e,PACKAGE_URL:`@dahawa/${zi}`,README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var WJ=process.env.HAWA_CODE_USER_AGENT||`${zi}/${K1e} (${process.env.USER_TYPE})`;os();De();ar();Cr();De();He();import{existsSync as R0,readdirSync as rsn,statSync as nsn}from"fs";import{join as uC,relative as isn}from"path";import{homedir as Hht}from"os";import{platform as osn}from"process";import{readFile as dC}from"fs/promises";Cr();xf();Zt();import{join as Otn,sep as ktn}from"path";function zp(){if(!fu())return!1;try{let e=Je();if(e.autoMemory?.teamMemoryEnabled!==void 0)return e.autoMemory.teamMemoryEnabled}catch{}return!1}function pu(){return(Otn(Re(),".hcode","team-memory")+ktn).normalize("NFC")}function ag(e){let t=e.normalize("NFC"),r=pu();return t.startsWith(r)}xf();var qht=we(FB(),1);Di();var pIe=(e,t,r)=>{let n=e instanceof RegExp?Aht(e,r):e,i=t instanceof RegExp?Aht(t,r):t,o=n!==null&&i!=null&&jin(n,i,r);return o&&{start:o[0],end:o[1],pre:r.slice(0,o[0]),body:r.slice(o[0]+n.length,o[1]),post:r.slice(o[1]+i.length)}},Aht=(e,t)=>{let r=t.match(e);return r?r[0]:null},jin=(e,t,r)=>{let n,i,o,s,a,l=r.indexOf(e),c=r.indexOf(t,l+1),u=l;if(l>=0&&c>0){if(e===t)return[l,c];for(n=[],o=r.length;u>=0&&!a;){if(u===l)n.push(u),l=r.indexOf(e,u+1);else if(n.length===1){let d=n.pop();d!==void 0&&(a=[d,c])}else i=n.pop(),i!==void 0&&i<o&&(o=i,s=c),c=r.indexOf(t,u+1);u=l<c&&l>=0?l:c}n.length&&s!==void 0&&(a=[o,s])}return a};var hht="\0SLASH"+Math.random()+"\0",Eht="\0OPEN"+Math.random()+"\0",AIe="\0CLOSE"+Math.random()+"\0",_ht="\0COMMA"+Math.random()+"\0",yht="\0PERIOD"+Math.random()+"\0",Yin=new RegExp(hht,"g"),Vin=new RegExp(Eht,"g"),Win=new RegExp(AIe,"g"),Kin=new RegExp(_ht,"g"),Jin=new RegExp(yht,"g"),Zin=/\\\\/g,Xin=/\\{/g,eon=/\\}/g,ton=/\\,/g,ron=/\\\./g,non=1e5,ion=4e6;function mIe(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function oon(e){return e.replace(Zin,hht).replace(Xin,Eht).replace(eon,AIe).replace(ton,_ht).replace(ron,yht)}function son(e){return e.replace(Yin,"\\").replace(Vin,"{").replace(Win,"}").replace(Kin,",").replace(Jin,".")}function bht(e){if(!e)return[""];let t=[],r=pIe("{","}",e);if(!r)return e.split(",");let{pre:n,body:i,post:o}=r,s=n.split(",");s[s.length-1]+="{"+i+"}";let a=bht(o);return o.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),t.push.apply(t,s),t}function Cht(e,t={}){if(!e)return[];let{max:r=non,maxLength:n=ion}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),gIe(oon(e),r,n,!0).map(son)}function aon(e){return"{"+e+"}"}function lon(e){return/^-?0\d/.test(e)}function con(e,t){return e<=t}function uon(e,t){return e>=t}function WU(e,t,r,n,i,o){let s=[],a=0;for(let l=0;l<e.length;l++)for(let c=0;c<r.length;c++){if(s.length>=n)return s;let u=e[l]+t+r[c];if(!(o&&!u)){if(a+u.length>i)return s;s.push(u),a+=u.length}}return s}function don(e,t,r,n){let i=e.split(/\.\./),o=[];if(i[0]===void 0||i[1]===void 0)return o;let s=mIe(i[0]),a=mIe(i[1]),l=Math.max(i[0].length,i[1].length),c=i.length===3&&i[2]!==void 0?Math.max(Math.abs(mIe(i[2])),1):1,u=con;a<s&&(c*=-1,u=uon);let g=i.some(lon),m=0;for(let A=s;u(A,a)&&o.length<r;A+=c){let h;if(t)h=String.fromCharCode(A),h==="\\"&&(h="");else if(h=String(A),g){let y=l-h.length;if(y>0){let C=new Array(y+1).join("0");A<0?h="-"+C+h.slice(1):h=C+h}}if(m+h.length>n)break;o.push(h),m+=h.length}return o}function gIe(e,t,r,n){let i=[""],o=!1,s=!0;for(;;){let a=pIe("{","}",e);if(!a)return WU(i,e,[""],t,r,o);let l=a.pre;if(/\$$/.test(l)){if(i=WU(i,l+"{"+a.body+"}",[""],t,r,o&&!a.post.length),s=!1,!a.post.length)break;e=a.post;continue}let c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(a.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(a.body),d=c||u,g=a.body.indexOf(",")>=0;if(!d&&!g){if(a.post.match(/,(?!,).*\}/)){e=a.pre+"{"+a.body+AIe+a.post,n=!0;continue}return WU(i,l+"{"+a.body+"}"+a.post,[""],t,r,o)}s&&(o=n&&!d,s=!1);let m;if(d)m=don(a.body,u,t,r);else{let A=bht(a.body);if(A.length===1&&A[0]!==void 0&&(A=gIe(A[0],t,r,!1).map(aon),A.length===1)){if(i=WU(i,l+A[0],[""],t,r,o&&!a.post.length),!a.post.length)break;e=a.post;continue}let h=o&&!a.post.length&&!l;for(let C=0;h&&C<i.length;C++)i[C]&&(h=!1);m=[];let y=0;e:for(let C=0;C<A.length;C++){let I=gIe(A[C],t,r,!1);for(let T=0;T<I.length;T++){let D=I[T];if(!(h&&!D)){if(m.length>=t||y+D.length>r)break e;m.push(D),y+=D.length}}}}if(i=WU(i,l,m,t,r,o&&!a.post.length),!a.post.length)break;e=a.post}return i}var KU=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")};var fon={"[: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]},JU=e=>e.replace(/[[\]\\-]/g,"\\$&"),pon=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Sht=e=>e.join(""),Iht=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],i=[],o=r+1,s=!1,a=!1,l=!1,c=!1,u=r,d="";e:for(;o<e.length;){let h=e.charAt(o);if((h==="!"||h==="^")&&o===r+1){c=!0,o++;continue}if(h==="]"&&s&&!l){u=o+1;break}if(s=!0,h==="\\"&&!l){l=!0,o++;continue}if(h==="["&&!l){for(let[y,[C,I,T]]of Object.entries(fon))if(e.startsWith(y,o)){if(d)return["$.",!1,e.length-r,!0];o+=y.length,T?i.push(C):n.push(C),a=a||I;continue e}}if(l=!1,d){h>d?n.push(JU(d)+"-"+JU(h)):h===d&&n.push(JU(h)),d="",o++;continue}if(e.startsWith("-]",o+1)){n.push(JU(h+"-")),o+=2;continue}if(e.startsWith("-",o+1)){d=h,o+=2;continue}n.push(JU(h)),o++}if(u<o)return["",!1,0,!1];if(!n.length&&!i.length)return["$.",!1,e.length-r,!0];if(i.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let h=n[0].length===2?n[0].slice(-1):n[0];return[pon(h),!1,u-r,!1]}let g="["+(c?"^":"")+Sht(n)+"]",m="["+(c?"":"^")+Sht(i)+"]";return[n.length&&i.length?"("+g+"|"+m+")":n.length?g:m,a,u-r,!0]};var cC=(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 Ed,mon=new Set(["!","?","+","*","@"]),hIe=e=>mon.has(e),Tht=e=>hIe(e.type),gon=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),Aon=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),hon=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),vht=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),Eon="(?!(?:^|/)\\.\\.?(?:$|/))",lZ="(?!\\.)",_on=new Set(["[","."]),yon=new Set(["..","."]),bon=new Set("().*{}+?[]^$\\!"),Con=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),EIe="[^/]",xht=EIe+"*?",wht=EIe+"+?",Son=0,QT=class{type;#e;#t;#n=!1;#r=[];#o;#i;#l;#s=!1;#a;#d;#p=!1;id=++Son;get depth(){return(this.#o?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#e.id,parent:this.#o?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(t,r,n={}){this.type=t,t&&(this.#t=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#l=this.#e===this?[]:this.#e.#l,t==="!"&&!this.#e.#s&&this.#l.push(this),this.#i=this.#o?this.#o.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#d=this.#r.map(t=>String(t)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#s)return this;this.toString(),this.#s=!0;let t;for(;t=this.#l.pop();){if(t.type!=="!")continue;let r=t,n=r.#o;for(;n;){for(let i=r.#i+1;!n.type&&i<n.#r.length;i++)for(let o of t.#r){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(n.#r[i])}r=n,n=r.#o}}return this}push(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof Ed&&r.#o===this))throw new Error("invalid part: "+r);this.#r.push(r)}}toJSON(){let t=this.type===null?this.#r.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#r.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#i===0)return!0;let t=this.#o;for(let r=0;r<this.#i;r++){let n=t.#r[r];if(!(n instanceof Ed&&n.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let t=this.#o?this.#o.#r.length:0;return this.#i===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let r=new Ed(this.type,t);for(let n of this.#r)r.copyIn(n);return r}static#c(t,r,n,i,o){let s=i.maxExtglobRecursion??2,a=!1,l=!1,c=-1,u=!1;if(r.type===null){let h=n,y="";for(;h<t.length;){let C=t.charAt(h++);if(a||C==="\\"){a=!a,y+=C;continue}if(l){h===c+1?(C==="^"||C==="!")&&(u=!0):C==="]"&&!(h===c+2&&u)&&(l=!1),y+=C;continue}else if(C==="["){l=!0,c=h,u=!1,y+=C;continue}if(!i.noext&&hIe(C)&&t.charAt(h)==="("&&o<=s){r.push(y),y="";let T=new Ed(C,r);h=Ed.#c(t,T,h,i,o+1),r.push(T);continue}y+=C}return r.push(y),h}let d=n+1,g=new Ed(null,r),m=[],A="";for(;d<t.length;){let h=t.charAt(d++);if(a||h==="\\"){a=!a,A+=h;continue}if(l){d===c+1?(h==="^"||h==="!")&&(u=!0):h==="]"&&!(d===c+2&&u)&&(l=!1),A+=h;continue}else if(h==="["){l=!0,c=d,u=!1,A+=h;continue}if(!i.noext&&hIe(h)&&t.charAt(d)==="("&&(o<=s||r&&r.#E(h))){let C=r&&r.#E(h)?0:1;g.push(A),A="";let I=new Ed(h,g);g.push(I),d=Ed.#c(t,I,d,i,o+C);continue}if(h==="|"){g.push(A),A="",m.push(g),g=new Ed(null,r);continue}if(h===")")return A===""&&r.#r.length===0&&(r.#p=!0),g.push(A),A="",r.push(...m,g),d;A+=h}return r.type=null,r.#t=void 0,r.#r=[t.substring(n-1)],d}#g(t){return this.#h(t,Aon)}#h(t,r=gon){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null)return!1;let n=t.#r[0];return!n||typeof n!="object"||n.type===null?!1:this.#E(n.type,r)}#E(t,r=hon){return!!r.get(this.type)?.includes(t)}#A(t,r){let n=t.#r[0],i=new Ed(null,n,this.options);i.#r.push(""),n.push(i),this.#v(t,r)}#v(t,r){let n=t.#r[0];this.#r.splice(r,1,...n.#r);for(let i of n.#r)typeof i=="object"&&(i.#o=this);this.#d=void 0}#y(t){return!!vht.get(this.type)?.has(t)}#S(t){if(!t||typeof t!="object"||t.type!==null||t.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let r=t.#r[0];return!r||typeof r!="object"||r.type===null?!1:this.#y(r.type)}#I(t){let r=vht.get(this.type),n=t.#r[0],i=r?.get(n.type);if(!i)return!1;this.#r=n.#r;for(let o of this.#r)typeof o=="object"&&(o.#o=this);this.type=i,this.#d=void 0,this.#p=!1}static fromGlob(t,r={}){let n=new Ed(null,void 0,r);return Ed.#c(t,n,0,r,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let t=this.toString(),[r,n,i,o]=this.toRegExpSource();if(!(i||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){let r=t??!!this.#a.dot;if(this.#e===this&&(this.#_(),this.#f()),!Tht(this)){let l=this.isStart()&&this.isEnd()&&!this.#r.some(m=>typeof m!="string"),c=this.#r.map(m=>{let[A,h,y,C]=typeof m=="string"?Ed.#C(m,this.#t,l):m.toRegExpSource(t);return this.#t=this.#t||y,this.#n=this.#n||C,A}).join(""),u="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&yon.has(this.#r[0]))){let A=_on,h=r&&A.has(c.charAt(0))||c.startsWith("\\.")&&A.has(c.charAt(2))||c.startsWith("\\.\\.")&&A.has(c.charAt(4)),y=!r&&!t&&A.has(c.charAt(0));u=h?Eon:y?lZ:""}let d="";return this.isEnd()&&this.#e.#s&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,cC(c),this.#t=!!this.#t,this.#n]}let n=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",o=this.#b(r);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let l=this.toString(),c=this;return c.#r=[l],c.type=null,c.#t=void 0,[l,cC(this.toString()),!1,!1]}let s=!n||t||r||!lZ?"":this.#b(!0);s===o&&(s=""),s&&(o=`(?:${o})(?:${s})*?`);let a="";if(this.type==="!"&&this.#p)a=(this.isStart()&&!r?lZ:"")+wht;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?lZ:"")+xht+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=i+o+l}return[a,cC(o),this.#t=!!this.#t,this.#n]}#_(){if(Tht(this)){let t=0,r=!1;do{r=!0;for(let n=0;n<this.#r.length;n++){let i=this.#r[n];typeof i=="object"&&(i.#_(),this.#h(i)?(r=!1,this.#v(i,n)):this.#g(i)?(r=!1,this.#A(i,n)):this.#S(i)&&(r=!1,this.#I(i)))}}while(!r&&++t<10)}else for(let t of this.#r)typeof t=="object"&&t.#_();this.#d=void 0}#b(t){return this.#r.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,i,o,s]=r.toRegExpSource(t);return this.#n=this.#n||s,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#C(t,r,n=!1){let i=!1,o="",s=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(i){i=!1,o+=(bon.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,o+=n&&/^[*]+$/.test(t)?wht:xht,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?o+="\\\\":i=!0;continue}if(c==="["){let[u,d,g,m]=Iht(t,l);if(g){o+=u,s=s||d,l+=g-1,r=r||m;continue}}if(c==="?"){o+=EIe,r=!0;continue}o+=Con(c)}return[o,cC(t),!!r,s]}};Ed=QT;var _Ie=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!1}={})=>r?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&");var Jl=(e,t,r={})=>(KU(t),!r.nocomment&&t.charAt(0)==="#"?!1:new UB(t,r).match(e)),Ion=/^\*+([^+@!?*[(]*)$/,Ton=e=>t=>!t.startsWith(".")&&t.endsWith(e),von=e=>t=>t.endsWith(e),xon=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),won=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Don=/^\*+\.\*+$/,Ron=e=>!e.startsWith(".")&&e.includes("."),Non=e=>e!=="."&&e!==".."&&e.includes("."),Bon=/^\.\*+$/,Oon=e=>e!=="."&&e!==".."&&e.startsWith("."),kon=/^\*+$/,Mon=e=>e.length!==0&&!e.startsWith("."),Qon=e=>e.length!==0&&e!=="."&&e!=="..",Pon=/^\?+([^+@!?*[(]*)?$/,Lon=([e,t=""])=>{let r=Nht([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},Fon=([e,t=""])=>{let r=Bht([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},Uon=([e,t=""])=>{let r=Bht([e]);return t?n=>r(n)&&n.endsWith(t):r},$on=([e,t=""])=>{let r=Nht([e]);return t?n=>r(n)&&n.endsWith(t):r},Nht=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},Bht=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},Oht=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Dht={win32:{sep:"\\"},posix:{sep:"/"}},Hon=Oht==="win32"?Dht.win32.sep:Dht.posix.sep;Jl.sep=Hon;var Oc=Symbol("globstar **");Jl.GLOBSTAR=Oc;var qon="[^/]",Gon=qon+"*?",zon="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",jon="(?:(?!(?:\\/|^)\\.).)*?",Yon=(e,t={})=>r=>Jl(r,e,t);Jl.filter=Yon;var jp=(e,t={})=>Object.assign({},e,t),Von=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return Jl;let t=Jl;return Object.assign((n,i,o={})=>t(n,i,jp(e,o)),{Minimatch:class extends t.Minimatch{constructor(i,o={}){super(i,jp(e,o))}static defaults(i){return t.defaults(jp(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,o,s={}){super(i,o,jp(e,s))}static fromGlob(i,o={}){return t.AST.fromGlob(i,jp(e,o))}},unescape:(n,i={})=>t.unescape(n,jp(e,i)),escape:(n,i={})=>t.escape(n,jp(e,i)),filter:(n,i={})=>t.filter(n,jp(e,i)),defaults:n=>t.defaults(jp(e,n)),makeRe:(n,i={})=>t.makeRe(n,jp(e,i)),braceExpand:(n,i={})=>t.braceExpand(n,jp(e,i)),match:(n,i,o={})=>t.match(n,i,jp(e,o)),sep:t.sep,GLOBSTAR:Oc})};Jl.defaults=Von;var kht=(e,t={})=>(KU(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Cht(e,{max:t.braceExpandMax}));Jl.braceExpand=kht;var Won=(e,t={})=>new UB(e,t).makeRe();Jl.makeRe=Won;var Kon=(e,t,r={})=>{let n=new UB(t,r);return e=e.filter(i=>n.match(i)),n.options.nonull&&!e.length&&e.push(t),e};Jl.match=Kon;var Rht=/[?*]|[+@!]\(.*?\)|\[|\]/,Jon=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),UB=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,r={}){KU(t),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=t,this.platform=r.platform||Oht,this.isWindows=this.platform==="win32";let n="allowWindowsEscape";this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r[n]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let r of t)if(typeof r!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,r=this.options;if(!r.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...o)=>console.error(...o)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(o=>this.slashSplit(o));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let i=this.globParts.map((o,s,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=o[0]===""&&o[1]===""&&(o[2]==="?"||!Rht.test(o[2]))&&!Rht.test(o[3]),c=/^[a-z]:/i.test(o[0]);if(l)return[...o.slice(0,4),...o.slice(4).map(u=>this.parse(u))];if(c)return[o[0],...o.slice(1).map(u=>this.parse(u))]}return o.map(l=>this.parse(l))});if(this.debug(this.pattern,i),this.set=i.filter(o=>o.indexOf(!1)===-1),this.isWindows)for(let o=0;o<this.set.length;o++){let s=this.set[o];s[0]===""&&s[1]===""&&this.globParts[o][2]==="?"&&typeof s[3]=="string"&&/^[a-z]:$/i.test(s[3])&&(s[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let n of t)for(let i=0;i<n.length;i++)n[i]==="**"&&(n[i]="*");let{optimizationLevel:r=1}=this.options;return r>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):r>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let i=n;for(;r[i+1]==="**";)i++;i!==n&&r.splice(n,i-n)}return r})}levelOneOptimize(t){return t.map(r=>(r=r.reduce((n,i)=>{let o=n[n.length-1];return i==="**"&&o==="**"?n:i===".."&&o&&o!==".."&&o!=="."&&o!=="**"?(n.pop(),n):(n.push(i),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let i=1;i<t.length-1;i++){let o=t[i];i===1&&o===""&&t[0]===""||(o==="."||o==="")&&(r=!0,t.splice(i,1),i--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(r=!0,t.pop())}let n=0;for(;(n=t.indexOf("..",n+1))!==-1;){let i=t[n-1];i&&i!=="."&&i!==".."&&i!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(i))&&(r=!0,t.splice(n-1,2),n-=2)}}while(r);return t.length===0?[""]:t}firstPhasePreProcess(t){let r=!1;do{r=!1;for(let n of t){let i=-1;for(;(i=n.indexOf("**",i+1))!==-1;){let s=i;for(;n[s+1]==="**";)s++;s>i&&n.splice(i+1,s-i);let a=n[i+1],l=n[i+2],c=n[i+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;r=!0,n.splice(i,1);let u=n.slice(0);u[i]="**",t.push(u),i--}if(!this.preserveMultipleSlashes){for(let s=1;s<n.length-1;s++){let a=n[s];s===1&&a===""&&n[0]===""||(a==="."||a==="")&&(r=!0,n.splice(s,1),s--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(r=!0,n.pop())}let o=0;for(;(o=n.indexOf("..",o+1))!==-1;){let s=n[o-1];if(s&&s!=="."&&s!==".."&&s!=="**"){r=!0;let l=o===1&&n[o+1]==="**"?["."]:[];n.splice(o-1,2,...l),n.length===0&&n.push(""),o-=2}}}}while(r);return t}secondPhasePreProcess(t){for(let r=0;r<t.length-1;r++)for(let n=r+1;n<t.length;n++){let i=this.partsMatch(t[r],t[n],!this.preserveMultipleSlashes);if(i){t[r]=[],t[n]=i;break}}return t.filter(r=>r.length)}partsMatch(t,r,n=!1){let i=0,o=0,s=[],a="";for(;i<t.length&&o<r.length;)if(t[i]===r[o])s.push(a==="b"?r[o]:t[i]),i++,o++;else if(n&&t[i]==="**"&&r[o]===t[i+1])s.push(t[i]),i++;else if(n&&r[o]==="**"&&t[i]===r[o+1])s.push(r[o]),o++;else if(t[i]==="*"&&r[o]&&(this.options.dot||!r[o].startsWith("."))&&r[o]!=="**"){if(a==="b")return!1;a="a",s.push(t[i]),i++,o++}else if(r[o]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="a")return!1;a="b",s.push(r[o]),i++,o++}else return!1;return t.length===r.length&&s}parseNegate(){if(this.nonegate)return;let t=this.pattern,r=!1,n=0;for(let i=0;i<t.length&&t.charAt(i)==="!";i++)r=!r,n++;n&&(this.pattern=t.slice(n)),this.negate=r}matchOne(t,r,n=!1){let i=0,o=0;if(this.isWindows){let a=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),l=!a&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),c=typeof r[0]=="string"&&/^[a-z]:$/i.test(r[0]),u=!c&&r[0]===""&&r[1]===""&&r[2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3]),d=l?3:a?0:void 0,g=u?3:c?0:void 0;if(typeof d=="number"&&typeof g=="number"){let[m,A]=[t[d],r[g]];m.toLowerCase()===A.toLowerCase()&&(r[g]=m,o=g,i=d)}}let{optimizationLevel:s=1}=this.options;return s>=2&&(t=this.levelTwoFileOptimize(t)),r.includes(Oc)?this.#e(t,r,n,i,o):this.#n(t,r,n,i,o)}#e(t,r,n,i,o){let s=r.indexOf(Oc,o),a=r.lastIndexOf(Oc),[l,c,u]=n?[r.slice(o,s),r.slice(s+1),[]]:[r.slice(o,s),r.slice(s+1,a),r.slice(a+1)];if(l.length){let I=t.slice(i,i+l.length);if(!this.#n(I,l,n,0,0))return!1;i+=l.length,o+=l.length}let d=0;if(u.length){if(u.length+i>t.length)return!1;let I=t.length-u.length;if(this.#n(t,u,n,I,0))d=u.length;else{if(t[t.length-1]!==""||i+u.length===t.length||(I--,!this.#n(t,u,n,I,0)))return!1;d=u.length+1}}if(!c.length){let I=!!d;for(let T=i;T<t.length-d;T++){let D=String(t[T]);if(I=!0,D==="."||D===".."||!this.options.dot&&D.startsWith("."))return!1}return n||I}let g=[[[],0]],m=g[0],A=0,h=[0];for(let I of c)I===Oc?(h.push(A),m=[[],0],g.push(m)):(m[0].push(I),A++);let y=g.length-1,C=t.length-d;for(let I of g)I[1]=C-(h[y--]+I[0].length);return!!this.#t(t,g,i,0,n,0,!!d)}#t(t,r,n,i,o,s,a){let l=r[i];if(!l){for(let d=n;d<t.length;d++){a=!0;let g=t[d];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1}return a}let[c,u]=l;for(;n<=u;){if(this.#n(t.slice(0,n+c.length),c,o,n,0)&&s<this.maxGlobstarRecursion){let m=this.#t(t,r,n+c.length,i+1,o,s+1,a);if(m!==!1)return m}let g=t[n];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1;n++}return o||null}#n(t,r,n,i,o){let s,a,l,c;for(s=i,a=o,c=t.length,l=r.length;s<c&&a<l;s++,a++){this.debug("matchOne loop");let u=r[a],d=t[s];if(this.debug(r,u,d),u===!1||u===Oc)return!1;let g;if(typeof u=="string"?(g=d===u,this.debug("string match",u,d,g)):(g=u.test(d),this.debug("pattern match",u,d,g)),!g)return!1}if(s===c&&a===l)return!0;if(s===c)return n;if(a===l)return s===c-1&&t[s]==="";throw new Error("wtf?")}braceExpand(){return kht(this.pattern,this.options)}parse(t){KU(t);let r=this.options;if(t==="**")return Oc;if(t==="")return"";let n,i=null;(n=t.match(kon))?i=r.dot?Qon:Mon:(n=t.match(Ion))?i=(r.nocase?r.dot?won:xon:r.dot?von:Ton)(n[1]):(n=t.match(Pon))?i=(r.nocase?r.dot?Fon:Lon:r.dot?Uon:$on)(n):(n=t.match(Don))?i=r.dot?Non:Ron:(n=t.match(Bon))&&(i=Oon);let o=QT.fromGlob(t,this.options).toMMPattern();return i&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:i}),o}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?Gon:r.dot?zon:jon,i=new Set(r.nocase?["i"]:[]),o=t.map(l=>{let c=l.map(d=>{if(d instanceof RegExp)for(let g of d.flags.split(""))i.add(g);return typeof d=="string"?Jon(d):d===Oc?Oc:d._src});c.forEach((d,g)=>{let m=c[g+1],A=c[g-1];d!==Oc||A===Oc||(A===void 0?m!==void 0&&m!==Oc?c[g+1]="(?:\\/|"+n+"\\/)?"+m:c[g]=n:m===void 0?c[g-1]=A+"(?:\\/|\\/"+n+")?":m!==Oc&&(c[g-1]=A+"(?:\\/|\\/"+n+"\\/)"+m,c[g+1]=Oc))});let u=c.filter(d=>d!==Oc);if(this.partial&&u.length>=1){let d=[];for(let g=1;g<=u.length;g++)d.push(u.slice(0,g).join("/"));return"(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[s,a]=t.length>1?["(?:",")"]:["",""];o="^"+s+o+a+"$",this.partial&&(o="^(?:\\/|"+s+o.slice(1,-1)+a+")$"),this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,r=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&r)return!0;let n=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let o=this.set;this.debug(this.pattern,"set",o);let s=i[i.length-1];if(!s)for(let a=i.length-2;!s&&a>=0;a--)s=i[a];for(let a of o){let l=i;if(n.matchBase&&a.length===1&&(l=[s]),this.matchOne(l,a,r))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(t){return Jl.defaults(t).Minimatch}};Jl.AST=QT;Jl.Minimatch=UB;Jl.escape=_Ie;Jl.unescape=cC;var Pht=we(FB(),1);Cr();He();De();iu();import{readFile as Mht}from"fs/promises";import{existsSync as yIe,readdirSync as Zon,statSync as Xon}from"fs";import{join as bIe,relative as Lht}from"path";import{homedir as esn}from"os";function Qht(e){try{let t=(0,Pht.default)(e),r=t.data.paths,n=[];return typeof r=="string"?n=r.split(",").map(i=>i.trim()).filter(Boolean):Array.isArray(r)&&(n=r.filter(i=>typeof i=="string")),{paths:n,content:t.content.trim()}}catch(t){return Ie(t),{paths:[],content:e.trim()}}}function tsn(e,t){return t.length===0?!0:t.some(r=>{try{return Jl(e,r,{matchBase:!0,dot:!0})}catch(n){return Ie(n),!1}})}function CIe(e){let t=[];try{if(!yIe(e))return t;let r=Zon(e);for(let n of r){let i=bIe(e,n),o=Xon(i);o.isDirectory()?t.push(...CIe(i)):o.isFile()&&n.endsWith(".md")&&t.push(i)}}catch(r){Ie(r)}return t}async function cZ(){let e=[];try{let t=bIe(esn(),Kr,"rules");if(yIe(t)){let r=CIe(t);for(let n of r)try{let i=await Mht(n,"utf-8"),{paths:o,content:s}=Qht(i);o.length>0&&e.push({filePath:n,content:s,paths:o,isProjectRule:!1})}catch(i){Ie(i)}}}catch(t){Ie(t)}try{let t=bIe(Re(),Kr,"rules");if(yIe(t)){let r=CIe(t);for(let n of r)try{let i=await Mht(n,"utf-8"),{paths:o,content:s}=Qht(i);o.length>0&&e.push({filePath:Lht(Re(),n),content:s,paths:o,isProjectRule:!0})}catch(i){Ie(i)}}}catch(t){Ie(t)}return e}function Fht(e,t){e=xY(e);let r=xY(Re()),n=e.startsWith(r)?Lht(r,e):e;return t.filter(i=>tsn(n,i.paths))}function Uht(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}):
623
623
 
624
624
  ${r.content}`}).join(`
625
625
 
@@ -2916,7 +2916,7 @@ CREATE TABLE IF NOT EXISTS index_state (
2916
2916
  file_size INTEGER NOT NULL DEFAULT 0,
2917
2917
  file_mtime_ms INTEGER NOT NULL DEFAULT 0
2918
2918
  );
2919
- `;function W3(){if(!boe())return null;if(D_)return D_;if(CLe)return null;let e=Mzt();if(!e)return CLe=!0,kzt||(kzt=!0,Ie("hmemory: better-sqlite3 \u4E0D\u53EF\u7528\uFF0C\u6D88\u606F\u641C\u7D22\u529F\u80FD\u5DF2\u7981\u7528\uFF08JSONL \u6301\u4E45\u5316\u4E0D\u53D7\u5F71\u54CD\uFF09")),null;try{let t=Kn.searchDb();return Y4n(V4n(t),{recursive:!0}),D_=new e(t),D_.pragma("journal_mode = WAL"),D_.pragma("synchronous = NORMAL"),D_.pragma("busy_timeout = 3000"),D_.exec(W4n),D_}catch(t){return D_=null,CLe=!0,Ie("hmemory: \u6253\u5F00 search.db \u5931\u8D25\uFF0C\u6D88\u606F\u641C\u7D22\u529F\u80FD\u5DF2\u7981\u7528",t),null}}De();Gy();var dpo=256*1024,J4n=10,Z4n=50;function X4n(e){let t=e.split(/[^\p{L}\p{N}]+/u).map(r=>r.trim()).filter(r=>r.length>0);return t.length===0?null:t.map(r=>`"${r.replace(/"/g,'""')}"`).join(" AND ")}function e3n(e){return e.replace(/[\\%_]/g,t=>`\\${t}`)}var K3="id AS messageId, session_id AS sessionId, agent_id AS agentId, uuid, parent_uuid AS parentUuid, type, role, timestamp, content_text AS contentText, source_file AS sourceFile, source_line AS sourceLine";function t3n(e){let t=[],r=[];return e.sessionId&&(t.push("m.session_id = ?"),r.push(e.sessionId)),e.type&&(t.push("m.type = ?"),r.push(e.type)),e.role&&(t.push("m.role = ?"),r.push(e.role)),e.since!==void 0&&(t.push("m.timestamp >= ?"),r.push(e.since)),e.until!==void 0&&(t.push("m.timestamp <= ?"),r.push(e.until)),{where:t.length?" AND "+t.join(" AND "):"",params:r}}function SLe(e){return e===""||e===null?null:e}function ILe(e,t={}){let r=W3();if(!r)return[];let n=e.trim();if(!n)return[];let i=Math.min(t.limit??J4n,Z4n),o=t.offset??0,{where:s,params:a}=t3n(t);try{if(n.length<3)return r.prepare(`SELECT m.id AS messageId, m.session_id AS sessionId, m.agent_id AS agentId, m.uuid,
2919
+ `;function W3(){if(!boe())return null;if(D_)return D_;if(CLe)return null;let e=Mzt();if(!e)return CLe=!0,kzt||(kzt=!0,Ie("hmemory: better-sqlite3 \u4E0D\u53EF\u7528\uFF0C\u6D88\u606F\u641C\u7D22\u529F\u80FD\u5DF2\u7981\u7528\uFF08JSONL \u6301\u4E45\u5316\u4E0D\u53D7\u5F71\u54CD\uFF09")),null;try{let t=Kn.searchDb();return Y4n(V4n(t),{recursive:!0}),D_=new e(t),D_.pragma("journal_mode = WAL"),D_.pragma("synchronous = NORMAL"),D_.pragma("busy_timeout = 3000"),D_.exec(W4n),D_}catch(t){return D_=null,CLe=!0,Ie("hmemory: \u6253\u5F00 search.db \u5931\u8D25\uFF0C\u6D88\u606F\u641C\u7D22\u529F\u80FD\u5DF2\u7981\u7528",t),null}}De();Gy();var fpo=256*1024,J4n=10,Z4n=50;function X4n(e){let t=e.split(/[^\p{L}\p{N}]+/u).map(r=>r.trim()).filter(r=>r.length>0);return t.length===0?null:t.map(r=>`"${r.replace(/"/g,'""')}"`).join(" AND ")}function e3n(e){return e.replace(/[\\%_]/g,t=>`\\${t}`)}var K3="id AS messageId, session_id AS sessionId, agent_id AS agentId, uuid, parent_uuid AS parentUuid, type, role, timestamp, content_text AS contentText, source_file AS sourceFile, source_line AS sourceLine";function t3n(e){let t=[],r=[];return e.sessionId&&(t.push("m.session_id = ?"),r.push(e.sessionId)),e.type&&(t.push("m.type = ?"),r.push(e.type)),e.role&&(t.push("m.role = ?"),r.push(e.role)),e.since!==void 0&&(t.push("m.timestamp >= ?"),r.push(e.since)),e.until!==void 0&&(t.push("m.timestamp <= ?"),r.push(e.until)),{where:t.length?" AND "+t.join(" AND "):"",params:r}}function SLe(e){return e===""||e===null?null:e}function ILe(e,t={}){let r=W3();if(!r)return[];let n=e.trim();if(!n)return[];let i=Math.min(t.limit??J4n,Z4n),o=t.offset??0,{where:s,params:a}=t3n(t);try{if(n.length<3)return r.prepare(`SELECT m.id AS messageId, m.session_id AS sessionId, m.agent_id AS agentId, m.uuid,
2920
2920
  m.type, m.role, m.timestamp,
2921
2921
  substr(m.content_text, 1, 500) AS snippet,
2922
2922
  0 AS rank, m.source_file AS sourceFile, m.source_line AS sourceLine
@@ -3174,7 +3174,7 @@ Then confirm to the user: what's scheduled, the cron expression, the human-reada
3174
3174
  ## Input
3175
3175
 
3176
3176
  ${e}"`}]}]}},p7t=X3n;var e6n={type:"local",name:"dream",description:()=>"Manually trigger autoDream memory consolidation",isEnabled:!0,isHidden:!1,async call(e,t){let r={messages:[],systemPrompt:[],userContext:{},systemContext:{},toolUseContext:{...t,freezeSystemPrompt:(await hO()).join(`
3177
- `)},querySource:"dream_command"},n=await Jzt(r);return n.success?"AutoDream memory consolidation triggered successfully.":`AutoDream failed: ${n.error||"Unknown error"}`},userFacingName(){return"dream"}},m7t=e6n;var Mg=we(Ze(),1);NA();os();He();import t6n from"os";import r6n from"path";function g7t({onDone:e}){let t=Ue();(0,Mg.useEffect)(()=>{Rn.reload()},[]);let r=Rn.getAvailableModels(),n=Rn.getConfig().routing.MODEL??[],i=Rn.getConfig().routing.SMALL_FAST_MODEL??[],o=new Set(n.map(J=>`${J.source}__${J.model}`)),s=new Set(i.map(J=>`${J.source}__${J.model}`)),[a,l]=(0,Mg.useState)(o.size>0?o:new Set(r[0]?[r[0]]:[])),[c,u]=(0,Mg.useState)(s.size>0?s:new Set(r[0]?[r[0]]:[])),[d,g]=(0,Mg.useState)("model"),[m,A]=(0,Mg.useState)(!1),[h,y]=(0,Mg.useState)(!1),[C,I]=(0,Mg.useState)(0),[T,D]=(0,Mg.useState)(0),[M,P]=(0,Mg.useState)(null),L=()=>{let J=[];if(a.size===0&&J.push("MODEL must select at least one option"),c.size===0&&J.push("SMALL_FAST_MODEL must select at least one option"),J.length>0){P(J.join("; "));return}P(null);let G=Array.from(a).map(Ae=>{let k=Rn.parseModelKey(Ae);return{source:k.source,model:k.model,weight:100}}),ae=Array.from(c).map(Ae=>{let k=Rn.parseModelKey(Ae);return{source:k.source,model:k.model,weight:100}});Rn.setModelRouting(G),Rn.setSmallFastModelRouting(ae),Rn.reload(),lg().then(()=>{Yt.emit("repl:refresh");let Ae=Array.from(a).join(", ")||"N/A",k=Array.from(c).join(", ")||"N/A";e(`Switched MODEL to ${Ae}, SMALL_FAST_MODEL to ${k}`)})},j=()=>{let J=r6n.join(t6n.homedir(),Kr,"config.json");qX(J,{wait:!1}).catch(()=>{})};mr((J,G)=>{if(G.escape){if(m){A(!1);return}if(h){y(!1);return}e("Cancelled.");return}if(G.return){if(m){A(!1);return}if(h){y(!1);return}if(d==="confirm"){L();return}if(d==="openConfig"){j();return}if(d==="model"){A(!0),I(0);return}if(d==="small"){y(!0),D(0);return}return}if(G.upArrow||G.downArrow){if(m){G.upArrow?I(k=>k>0?k-1:r.length-1):I(k=>k<r.length-1?k+1:0);return}if(h){G.upArrow?D(k=>k>0?k-1:r.length-1):D(k=>k<r.length-1?k+1:0);return}let ae=["model","small","confirm","openConfig"],Ae=ae.indexOf(d);G.upArrow?g(ae[Ae>0?Ae-1:ae.length-1]):g(ae[Ae<ae.length-1?Ae+1:0]);return}if(J===" "){if(m){let ae=r[C];ae&&l(Ae=>{let k=new Set(Ae);return k.has(ae)?k.delete(ae):k.add(ae),k});return}if(h){let ae=r[T];ae&&u(Ae=>{let k=new Set(Ae);return k.has(ae)?k.delete(ae):k.add(ae),k});return}if(d==="model"){A(!0),I(0);return}if(d==="small"){y(!0),D(0);return}if(d==="confirm"){L();return}if(d==="openConfig"){j();return}}});let z=(J,G,ae,Ae,k)=>{let le=G.size>0?Array.from(G).join(", "):"Select models...";return(0,_.jsxs)(O,{flexDirection:"column",marginBottom:1,children:[(0,_.jsx)(x,{color:ae?t.claude:t.secondaryText,children:J}),(0,_.jsxs)(O,{borderStyle:"single",borderColor:ae?t.claude:t.secondaryBorder,paddingX:1,width:60,children:[(0,_.jsx)(x,{children:le}),(0,_.jsx)(x,{color:t.secondaryText,children:Ae?"\u25B2":"\u25BC"})]}),Ae&&(0,_.jsx)(O,{flexDirection:"column",borderStyle:"single",borderColor:t.claude,width:60,children:r.map((_e,he)=>{let pe=G.has(_e),ce=he===k;return(0,_.jsx)(O,{paddingX:1,children:(0,_.jsxs)(x,{color:ce?t.claude:t.text,children:[ce?"\u276F ":" ",pe?(0,_.jsx)(x,{color:"blue",children:"\u25A0 "}):"\u2610 ",_e]})},_e)})})]})};return(0,_.jsxs)(O,{flexDirection:"column",marginY:1,children:[(0,_.jsx)(O,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:t.claude,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"})}),(0,_.jsx)(O,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:t.claude,children:" Select model routing"})}),(0,_.jsxs)(O,{flexDirection:"column",marginLeft:2,children:[z("MODEL",a,d==="model"&&!m&&!h,m,C),z("SMALL_FAST_MODEL",c,d==="small"&&!m&&!h,h,T),M&&(0,_.jsx)(O,{marginTop:1,children:(0,_.jsx)(x,{color:t.error,children:M})}),(0,_.jsxs)(O,{marginTop:1,children:[(0,_.jsxs)(x,{color:d==="confirm"?t.claude:t.secondaryText,bold:d==="confirm",children:[d==="confirm"?"\u276F ":" ","[ Confirm ]"]}),(0,_.jsx)(O,{marginLeft:2,children:(0,_.jsxs)(x,{color:d==="openConfig"?t.claude:t.secondaryText,bold:d==="openConfig",children:[d==="openConfig"?"\u276F ":" ","[ Open Config ]"]})})]})]}),(0,_.jsx)(O,{marginTop:1,marginLeft:2,children:(0,_.jsx)(x,{dimColor:!0,children:"\u2191/\u2193 to navigate \xB7 Space/Enter to select \xB7 Esc to cancel"})})]})}var n6n={type:"local-jsx",name:"model",description:()=>"Switch MODEL or SMALL_FAST_MODEL routing",isEnabled:!0,isHidden:!1,disableCancel:!0,async call(e){return(0,_.jsx)(g7t,{onDone:t=>{e(t)}})},userFacingName(){return"model"}},A7t=n6n;var _7t=we(Ze(),1);Zt();var Tx=["off","low","medium","high"],i6n={low:4e3,medium:1e4,high:32e3};function Z3(e){return Tx.includes(e)?e:"medium"}function o6n(e){let t=e.toLowerCase();return t.includes("claude-opus-4-7")||t.includes("claude-mythos-preview")}function s6n(e){let t=e.toLowerCase();return t.includes("claude-opus-4-8")||t.includes("claude-opus-4-7")||t.includes("claude-opus-4-6")||t.includes("claude-sonnet-4-6")||t.includes("claude-mythos-preview")}function h7t(e,t){let r=Z3(t);if(r!=="off"){if(s6n(e)){let n={type:"adaptive"};return o6n(e)&&(n.display="summarized"),n}return{budget_tokens:i6n[r],type:"enabled"}}}function E7t(e){return e&&"budget_tokens"in e?e.budget_tokens:0}function y7t({onDone:e}){let t=Ue(),r=Z3(Je().thinking),[n,i]=(0,_7t.useState)(()=>Math.max(0,Tx.indexOf(r))),o=()=>{let s=Tx[n];gr.updateSetting("thinking",s),e(`Thinking level set to ${s}`)};return mr((s,a)=>{if(a.escape){e("Cancelled.");return}if(a.return||s===" "){o();return}if(a.upArrow){i(l=>l>0?l-1:Tx.length-1);return}a.downArrow&&i(l=>l<Tx.length-1?l+1:0)}),(0,_.jsxs)(O,{flexDirection:"column",marginY:1,children:[(0,_.jsx)(O,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:t.claude,children:" Select thinking level"})}),(0,_.jsx)(O,{flexDirection:"column",marginLeft:2,children:Tx.map((s,a)=>{let l=a===n,c=s===r;return(0,_.jsx)(O,{children:(0,_.jsxs)(x,{color:l?t.claude:t.text,children:[l?"> ":" ",s,c?" (current)":""]})},s)})}),(0,_.jsx)(O,{marginTop:1,marginLeft:2,children:(0,_.jsx)(x,{dimColor:!0,children:"Up/Down to navigate \xB7 Enter to save \xB7 Esc to cancel"})})]})}var a6n={type:"local-jsx",name:"thinking",description:()=>"Configure model thinking level",isEnabled:!0,isHidden:!1,disableCancel:!0,async call(e){return(0,_.jsx)(y7t,{onDone:t=>{e(t)}})},userFacingName(){return"thinking"}},b7t=a6n;var C7t=we(Ze(),1);function l6n(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60);if(r<60)return`${r}m`;let n=Math.floor(r/60),i=r%60;return i?`${n}h${i}m`:`${n}h`}function S7t({goal:e,onClear:t,onClose:r}){let{frame:n}=xD({interval:1e3,isActive:!!e}),i=(0,C7t.useMemo)(()=>e?l6n(Date.now()-e.setAt):"",[e,n]);mr((s,a)=>{if(a.escape||s==="q"){r();return}e&&(s==="c"||s==="C")&&t()});let o=Ue();return e?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsxs)(O,{flexDirection:"column",borderStyle:"round",borderColor:o.secondaryBorder,paddingX:1,marginTop:1,children:[(0,_.jsxs)(O,{children:[(0,_.jsx)(x,{bold:!0,color:"green",children:"\u25CE Goal active"}),(0,_.jsxs)(x,{dimColor:!0,children:[" \xB7 running ",i]})]}),(0,_.jsx)(O,{marginTop:1,children:(0,_.jsxs)(x,{children:[(0,_.jsx)(x,{bold:!0,children:"Goal: "}),e.condition]})})]}),(0,_.jsx)(O,{marginLeft:3,children:(0,_.jsxs)(x,{dimColor:!0,children:[(0,_.jsx)(x,{color:"blue",children:"c"})," clear \xB7 ",(0,_.jsx)(x,{color:"blue",children:"Esc"})," dismiss"]})})]}):(0,_.jsxs)(_.Fragment,{children:[(0,_.jsxs)(O,{flexDirection:"column",borderStyle:"round",borderColor:o.secondaryBorder,paddingX:1,marginTop:1,children:[(0,_.jsx)(x,{bold:!0,children:"\u25CE Goal"}),(0,_.jsx)(x,{dimColor:!0,children:"No active goal."}),(0,_.jsx)(O,{marginTop:1,children:(0,_.jsxs)(x,{dimColor:!0,children:["Set one with ",(0,_.jsx)(x,{color:"blue",children:"/goal <condition>"})]})})]}),(0,_.jsx)(O,{marginLeft:3,children:(0,_.jsx)(x,{dimColor:!0,children:"Esc / q to dismiss"})})]})}Di();He();var c6n={type:"local-jsx-prompt",name:"goal",description:()=>"View, set, or clear a session-scoped goal; the Stop hook keeps Hawa working until the condition is satisfied.",isEnabled:!0,isHidden:!1,argNames:["condition"],userFacingName(){return"goal"},async call(e,t,r){let n=(t||"").trim();if(!n){let o=Df.getGoal();return(0,_.jsx)(S7t,{goal:o,onClear:()=>{o?(Df.clearGoal(),pt.getInQueryContext()[UE]=0,e({resultForUser:`Goal cleared: ${o.condition}`,componentMessages:[P4({reason:"user"})]})):e()},onClose:()=>e()})}if(n.toLowerCase()==="clear"){if(Df.hasGoal()){let o=Df.getGoal().condition;Df.clearGoal(),pt.getInQueryContext()[UE]=0,e({resultForUser:`Goal cleared: ${o}`,componentMessages:[P4({reason:"user"})]})}else e({resultForUser:"No active goal to clear."});return null}Df.setGoal(n);let i=Df.getGoal().setAt;return e({resultForUser:`Goal set: ${n}`,additionalPromptForAI:`A session-scoped Stop hook is now active with condition: "${n}". Briefly acknowledge the goal, then immediately start (or continue) working toward it \u2014 treat the condition itself as your directive and do not pause to ask the user what to do. The hook will block stopping until the condition holds. It auto-clears once the condition is met \u2014 do not tell the user to run \`/goal clear\` after success; that's only for clearing a goal early.`,componentMessages:[T7t({condition:n,setAt:i})]}),null}},I7t=c6n;var u6n=[dbt,eCt],d6n=Qe(()=>[p7t,d0t,S0t,U_t,eyt,gbt,hbt,bbt,Zbt,uCt,pbt,mbt,dCt,kX,Bve,PFt,nUt,iUt,sUt,pUt,fCt,m7t,A7t,b7t,I7t,...process.env.USER_TYPE==="ant"?u6n:[]]),w0o=Qe(async()=>{let[e,t,r]=await Promise.all([Zr.getMCPCommands(),iO(),d7t()]);return[...e,...t,...r,...d6n()].filter(n=>n.isEnabled)});dN();De();ar();De();Cr();Di();He();sR();var Hh="[Request interrupted by user]",VLe="[Request interrupted by user for tool use]",v7t="The user doesn't want to take this action right now. STOP what you are doing and wait for the user to tell you how to proceed.",p6n="The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.",m6n="No response requested.",f0t=new Set([Hh,VLe,v7t,p6n,m6n]),x7t="[Tool result missing due to internal error]";function w7t(e,t){return{type:"assistant",costUSD:0,durationMs:0,uuid:so.next(),message:{id:so.next(),model:"<synthetic>",role:"assistant",stop_reason:"stop_sequence",stop_sequence:"",type:"message",container:null,stop_details:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,cache_creation:null,inference_geo:null,server_tool_use:null,service_tier:null},content:e},...t}}function Pi(e){return w7t([{type:"text",text:e===""?Vk:e,citations:[]}])}function vx(e){return w7t([{type:"text",text:e===""?Vk:e,citations:[]}],{isApiErrorMessage:!0})}function sr(e,t,r){if(e==null)throw new Error("createUserMessage Content cannot be null or undefined");if(typeof e!="string"&&!Array.isArray(e))throw new Error("createUserMessage Content must be either a string or an array of content blocks");return{type:"user",message:{role:"user",content:e},uuid:so.next(),toolUseResult:t,...r?.hideInUI?{hideInUI:!0}:{}}}function PT(e,t,r,n,i,o={multiline:!1,freeze:!1}){return{type:"progress",content:r,normalizedMessages:n,siblingToolUseIDs:t,tools:i,toolUseID:e,uuid:so.next(),meta:o}}function rk(e){return{type:"reminder",content:e,uuid:so.next()}}function s7t(e){return{type:"insert",content:{content:e},uuid:so.next()}}function jht(e){return{type:"path_rules",content:{paths:e},uuid:so.next()}}function a7t(e){return{type:"systemAutoMemory",content:{paths:e},uuid:so.next()}}function mke(e){return{type:"goal_status",content:e,uuid:so.next()}}function T7t(e){return{type:"goal_set",content:e,uuid:so.next()}}function P4(e){return{type:"goal_cleared",content:e,uuid:so.next()}}function voe(e){return{type:"tool_result",content:v7t,is_error:!0,tool_use_id:e}}function $c(e){return e.filter(t=>!(t.type==="user"&&t.hideInUI)).flatMap(t=>{if(t.type==="progress"||t.type==="reminder")return[t];if(t.type==="goal_status")return[t];if(t.type==="insert")return[{...sr(t.content.content),uuid:t.uuid}];if(t.type==="path_rules")return[];if(t.type==="systemAutoMemory")return[];if(!("message"in t))return[];if(typeof t.message?.content=="string")return[t];if(!t.message)return[];let r=t.message.content.filter(a=>!(a.type==="text"&&/<system-reminder>.*?<\/system-reminder>/s.test(a.text.trim()))),n=r.find(a=>a.type==="text"),o=t.type==="user"&&!!n&&(n.text.includes("<command-name>")||n.text.includes("<command-message>"))?r.filter((a,l)=>{if(a.type!=="text"||a===n)return!0;let c=a.text.trimStart();return c.startsWith("<local-command-stdout>")||c.startsWith("<local-command-stderr>")}):r,s=0;return o.map(a=>{switch(s++,t.type){case"assistant":{let l;if(a.type==="tool_use"){let c=t.message.content;if(c.filter(d=>d.type==="tool_use").length>1){l=new Set;for(let d of c)d.type==="tool_use"&&d.id&&l.add(d.id)}}return{type:"assistant",uuid:t.uuid+s,message:{...t.message,content:[a]},costUSD:t.costUSD/t.message.content.length,durationMs:t.durationMs,siblingToolUseIDs:l}}case"user":return a.type==="tool_result"?{...sr([a],t.toolUseResult),uuid:t.uuid+s}:{...sr([a],t.toolUseResult),uuid:t.uuid+s}}})})}var o_o=Qe(e=>Object.fromEntries(e.flatMap(t=>t.type==="user"&&t.message.content[0]?.type==="tool_result"?[[t.message.content[0].tool_use_id,t.message.content[0].is_error??!1]]:[])));De();De();ar();function _d(e,t){let r=[],n=new Set,i=new Set;return e.filter(o=>o.type!=="progress"&&o.type!=="reminder").forEach(o=>{switch(o.type){case"user":{let s=AA(r);if(s?.type==="user"){r[r.length-1]=ZLe(s,o);return}r.push(o);return}case"assistant":r.push(o);return;case"insert":{let s=AA(r);s?.type==="user"&&(r[r.length-1]=g6n(s,o));return}case"path_rules":{let s=t?.pathRules;if(!s)return;let a=o.content.paths.filter(d=>!n.has(d));if(a.length===0)return;let l=a.map(d=>s.get(d)).filter(d=>d!==void 0);if(a.forEach(d=>n.add(d)),l.length===0)return;let c=sr([{type:"text",text:`<system-rules>
3177
+ `)},querySource:"dream_command"},n=await Jzt(r);return n.success?"AutoDream memory consolidation triggered successfully.":`AutoDream failed: ${n.error||"Unknown error"}`},userFacingName(){return"dream"}},m7t=e6n;var Mg=we(Ze(),1);NA();os();He();import t6n from"os";import r6n from"path";function g7t({onDone:e}){let t=Ue();(0,Mg.useEffect)(()=>{Rn.reload()},[]);let r=Rn.getAvailableModels(),n=Rn.getConfig().routing.MODEL??[],i=Rn.getConfig().routing.SMALL_FAST_MODEL??[],o=new Set(n.map(J=>`${J.source}__${J.model}`)),s=new Set(i.map(J=>`${J.source}__${J.model}`)),[a,l]=(0,Mg.useState)(o.size>0?o:new Set(r[0]?[r[0]]:[])),[c,u]=(0,Mg.useState)(s.size>0?s:new Set(r[0]?[r[0]]:[])),[d,g]=(0,Mg.useState)("model"),[m,A]=(0,Mg.useState)(!1),[h,y]=(0,Mg.useState)(!1),[C,I]=(0,Mg.useState)(0),[T,D]=(0,Mg.useState)(0),[M,P]=(0,Mg.useState)(null),L=()=>{let J=[];if(a.size===0&&J.push("MODEL must select at least one option"),c.size===0&&J.push("SMALL_FAST_MODEL must select at least one option"),J.length>0){P(J.join("; "));return}P(null);let G=Array.from(a).map(Ae=>{let k=Rn.parseModelKey(Ae);return{source:k.source,model:k.model,weight:100}}),ae=Array.from(c).map(Ae=>{let k=Rn.parseModelKey(Ae);return{source:k.source,model:k.model,weight:100}});Rn.setModelRouting(G),Rn.setSmallFastModelRouting(ae),Rn.reload(),lg().then(()=>{Yt.emit("repl:refresh");let Ae=Array.from(a).join(", ")||"N/A",k=Array.from(c).join(", ")||"N/A";e(`Switched MODEL to ${Ae}, SMALL_FAST_MODEL to ${k}`)})},j=()=>{let J=r6n.join(t6n.homedir(),Kr,"config.json");qX(J,{wait:!1}).catch(()=>{})};mr((J,G)=>{if(G.escape){if(m){A(!1);return}if(h){y(!1);return}e("Cancelled.");return}if(G.return){if(m){A(!1);return}if(h){y(!1);return}if(d==="confirm"){L();return}if(d==="openConfig"){j();return}if(d==="model"){A(!0),I(0);return}if(d==="small"){y(!0),D(0);return}return}if(G.upArrow||G.downArrow){if(m){G.upArrow?I(k=>k>0?k-1:r.length-1):I(k=>k<r.length-1?k+1:0);return}if(h){G.upArrow?D(k=>k>0?k-1:r.length-1):D(k=>k<r.length-1?k+1:0);return}let ae=["model","small","confirm","openConfig"],Ae=ae.indexOf(d);G.upArrow?g(ae[Ae>0?Ae-1:ae.length-1]):g(ae[Ae<ae.length-1?Ae+1:0]);return}if(J===" "){if(m){let ae=r[C];ae&&l(Ae=>{let k=new Set(Ae);return k.has(ae)?k.delete(ae):k.add(ae),k});return}if(h){let ae=r[T];ae&&u(Ae=>{let k=new Set(Ae);return k.has(ae)?k.delete(ae):k.add(ae),k});return}if(d==="model"){A(!0),I(0);return}if(d==="small"){y(!0),D(0);return}if(d==="confirm"){L();return}if(d==="openConfig"){j();return}}});let z=(J,G,ae,Ae,k)=>{let le=G.size>0?Array.from(G).join(", "):"Select models...";return(0,_.jsxs)(O,{flexDirection:"column",marginBottom:1,children:[(0,_.jsx)(x,{color:ae?t.claude:t.secondaryText,children:J}),(0,_.jsxs)(O,{borderStyle:"single",borderColor:ae?t.claude:t.secondaryBorder,paddingX:1,width:60,children:[(0,_.jsx)(x,{children:le}),(0,_.jsx)(x,{color:t.secondaryText,children:Ae?"\u25B2":"\u25BC"})]}),Ae&&(0,_.jsx)(O,{flexDirection:"column",borderStyle:"single",borderColor:t.claude,width:60,children:r.map((_e,he)=>{let pe=G.has(_e),ce=he===k;return(0,_.jsx)(O,{paddingX:1,children:(0,_.jsxs)(x,{color:ce?t.claude:t.text,children:[ce?"\u276F ":" ",pe?(0,_.jsx)(x,{color:"blue",children:"\u25A0 "}):"\u2610 ",_e]})},_e)})})]})};return(0,_.jsxs)(O,{flexDirection:"column",marginY:1,children:[(0,_.jsx)(O,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:t.claude,children:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"})}),(0,_.jsx)(O,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:t.claude,children:" Select model routing"})}),(0,_.jsxs)(O,{flexDirection:"column",marginLeft:2,children:[z("MODEL",a,d==="model"&&!m&&!h,m,C),z("SMALL_FAST_MODEL",c,d==="small"&&!m&&!h,h,T),M&&(0,_.jsx)(O,{marginTop:1,children:(0,_.jsx)(x,{color:t.error,children:M})}),(0,_.jsxs)(O,{marginTop:1,children:[(0,_.jsxs)(x,{color:d==="confirm"?t.claude:t.secondaryText,bold:d==="confirm",children:[d==="confirm"?"\u276F ":" ","[ Confirm ]"]}),(0,_.jsx)(O,{marginLeft:2,children:(0,_.jsxs)(x,{color:d==="openConfig"?t.claude:t.secondaryText,bold:d==="openConfig",children:[d==="openConfig"?"\u276F ":" ","[ Open Config ]"]})})]})]}),(0,_.jsx)(O,{marginTop:1,marginLeft:2,children:(0,_.jsx)(x,{dimColor:!0,children:"\u2191/\u2193 to navigate \xB7 Space/Enter to select \xB7 Esc to cancel"})})]})}var n6n={type:"local-jsx",name:"model",description:()=>"Switch MODEL or SMALL_FAST_MODEL routing",isEnabled:!0,isHidden:!1,disableCancel:!0,async call(e){return(0,_.jsx)(g7t,{onDone:t=>{e(t)}})},userFacingName(){return"model"}},A7t=n6n;var _7t=we(Ze(),1);Zt();var Tx=["off","low","medium","high"],i6n={low:4e3,medium:1e4,high:32e3};function Z3(e){return Tx.includes(e)?e:"medium"}function o6n(e){let t=e.toLowerCase();return t.includes("claude-opus-4-7")||t.includes("claude-mythos-preview")}function s6n(e){let t=e.toLowerCase();return t.includes("claude-opus-4-8")||t.includes("claude-opus-4-7")||t.includes("claude-opus-4-6")||t.includes("claude-sonnet-4-6")||t.includes("claude-mythos-preview")}function h7t(e,t){let r=Z3(t);if(r!=="off"){if(s6n(e)){let n={type:"adaptive"};return o6n(e)&&(n.display="summarized"),n}return{budget_tokens:i6n[r],type:"enabled"}}}function E7t(e){return e&&"budget_tokens"in e?e.budget_tokens:0}function y7t({onDone:e}){let t=Ue(),r=Z3(Je().thinking),[n,i]=(0,_7t.useState)(()=>Math.max(0,Tx.indexOf(r))),o=()=>{let s=Tx[n];gr.updateSetting("thinking",s),e(`Thinking level set to ${s}`)};return mr((s,a)=>{if(a.escape){e("Cancelled.");return}if(a.return||s===" "){o();return}if(a.upArrow){i(l=>l>0?l-1:Tx.length-1);return}a.downArrow&&i(l=>l<Tx.length-1?l+1:0)}),(0,_.jsxs)(O,{flexDirection:"column",marginY:1,children:[(0,_.jsx)(O,{marginBottom:1,children:(0,_.jsx)(x,{bold:!0,color:t.claude,children:" Select thinking level"})}),(0,_.jsx)(O,{flexDirection:"column",marginLeft:2,children:Tx.map((s,a)=>{let l=a===n,c=s===r;return(0,_.jsx)(O,{children:(0,_.jsxs)(x,{color:l?t.claude:t.text,children:[l?"> ":" ",s,c?" (current)":""]})},s)})}),(0,_.jsx)(O,{marginTop:1,marginLeft:2,children:(0,_.jsx)(x,{dimColor:!0,children:"Up/Down to navigate \xB7 Enter to save \xB7 Esc to cancel"})})]})}var a6n={type:"local-jsx",name:"thinking",description:()=>"Configure model thinking level",isEnabled:!0,isHidden:!1,disableCancel:!0,async call(e){return(0,_.jsx)(y7t,{onDone:t=>{e(t)}})},userFacingName(){return"thinking"}},b7t=a6n;var C7t=we(Ze(),1);function l6n(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60);if(r<60)return`${r}m`;let n=Math.floor(r/60),i=r%60;return i?`${n}h${i}m`:`${n}h`}function S7t({goal:e,onClear:t,onClose:r}){let{frame:n}=xD({interval:1e3,isActive:!!e}),i=(0,C7t.useMemo)(()=>e?l6n(Date.now()-e.setAt):"",[e,n]);mr((s,a)=>{if(a.escape||s==="q"){r();return}e&&(s==="c"||s==="C")&&t()});let o=Ue();return e?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsxs)(O,{flexDirection:"column",borderStyle:"round",borderColor:o.secondaryBorder,paddingX:1,marginTop:1,children:[(0,_.jsxs)(O,{children:[(0,_.jsx)(x,{bold:!0,color:"green",children:"\u25CE Goal active"}),(0,_.jsxs)(x,{dimColor:!0,children:[" \xB7 running ",i]})]}),(0,_.jsx)(O,{marginTop:1,children:(0,_.jsxs)(x,{children:[(0,_.jsx)(x,{bold:!0,children:"Goal: "}),e.condition]})})]}),(0,_.jsx)(O,{marginLeft:3,children:(0,_.jsxs)(x,{dimColor:!0,children:[(0,_.jsx)(x,{color:"blue",children:"c"})," clear \xB7 ",(0,_.jsx)(x,{color:"blue",children:"Esc"})," dismiss"]})})]}):(0,_.jsxs)(_.Fragment,{children:[(0,_.jsxs)(O,{flexDirection:"column",borderStyle:"round",borderColor:o.secondaryBorder,paddingX:1,marginTop:1,children:[(0,_.jsx)(x,{bold:!0,children:"\u25CE Goal"}),(0,_.jsx)(x,{dimColor:!0,children:"No active goal."}),(0,_.jsx)(O,{marginTop:1,children:(0,_.jsxs)(x,{dimColor:!0,children:["Set one with ",(0,_.jsx)(x,{color:"blue",children:"/goal <condition>"})]})})]}),(0,_.jsx)(O,{marginLeft:3,children:(0,_.jsx)(x,{dimColor:!0,children:"Esc / q to dismiss"})})]})}Di();He();var c6n={type:"local-jsx-prompt",name:"goal",description:()=>"View, set, or clear a session-scoped goal; the Stop hook keeps Hawa working until the condition is satisfied.",isEnabled:!0,isHidden:!1,argNames:["condition"],userFacingName(){return"goal"},async call(e,t,r){let n=(t||"").trim();if(!n){let o=Df.getGoal();return(0,_.jsx)(S7t,{goal:o,onClear:()=>{o?(Df.clearGoal(),pt.getInQueryContext()[UE]=0,e({resultForUser:`Goal cleared: ${o.condition}`,componentMessages:[P4({reason:"user"})]})):e()},onClose:()=>e()})}if(n.toLowerCase()==="clear"){if(Df.hasGoal()){let o=Df.getGoal().condition;Df.clearGoal(),pt.getInQueryContext()[UE]=0,e({resultForUser:`Goal cleared: ${o}`,componentMessages:[P4({reason:"user"})]})}else e({resultForUser:"No active goal to clear."});return null}Df.setGoal(n);let i=Df.getGoal().setAt;return e({resultForUser:`Goal set: ${n}`,additionalPromptForAI:`A session-scoped Stop hook is now active with condition: "${n}". Briefly acknowledge the goal, then immediately start (or continue) working toward it \u2014 treat the condition itself as your directive and do not pause to ask the user what to do. The hook will block stopping until the condition holds. It auto-clears once the condition is met \u2014 do not tell the user to run \`/goal clear\` after success; that's only for clearing a goal early.`,componentMessages:[T7t({condition:n,setAt:i})]}),null}},I7t=c6n;var u6n=[dbt,eCt],d6n=Qe(()=>[p7t,d0t,S0t,U_t,eyt,gbt,hbt,bbt,Zbt,uCt,pbt,mbt,dCt,kX,Bve,PFt,nUt,iUt,sUt,pUt,fCt,m7t,A7t,b7t,I7t,...process.env.USER_TYPE==="ant"?u6n:[]]),D0o=Qe(async()=>{let[e,t,r]=await Promise.all([Zr.getMCPCommands(),iO(),d7t()]);return[...e,...t,...r,...d6n()].filter(n=>n.isEnabled)});dN();De();ar();De();Cr();Di();He();sR();var Hh="[Request interrupted by user]",VLe="[Request interrupted by user for tool use]",v7t="The user doesn't want to take this action right now. STOP what you are doing and wait for the user to tell you how to proceed.",p6n="The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.",m6n="No response requested.",f0t=new Set([Hh,VLe,v7t,p6n,m6n]),x7t="[Tool result missing due to internal error]";function w7t(e,t){return{type:"assistant",costUSD:0,durationMs:0,uuid:so.next(),message:{id:so.next(),model:"<synthetic>",role:"assistant",stop_reason:"stop_sequence",stop_sequence:"",type:"message",container:null,stop_details:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,cache_creation:null,inference_geo:null,server_tool_use:null,service_tier:null},content:e},...t}}function Pi(e){return w7t([{type:"text",text:e===""?Vk:e,citations:[]}])}function vx(e){return w7t([{type:"text",text:e===""?Vk:e,citations:[]}],{isApiErrorMessage:!0})}function sr(e,t,r){if(e==null)throw new Error("createUserMessage Content cannot be null or undefined");if(typeof e!="string"&&!Array.isArray(e))throw new Error("createUserMessage Content must be either a string or an array of content blocks");return{type:"user",message:{role:"user",content:e},uuid:so.next(),toolUseResult:t,...r?.hideInUI?{hideInUI:!0}:{}}}function PT(e,t,r,n,i,o={multiline:!1,freeze:!1}){return{type:"progress",content:r,normalizedMessages:n,siblingToolUseIDs:t,tools:i,toolUseID:e,uuid:so.next(),meta:o}}function rk(e){return{type:"reminder",content:e,uuid:so.next()}}function s7t(e){return{type:"insert",content:{content:e},uuid:so.next()}}function jht(e){return{type:"path_rules",content:{paths:e},uuid:so.next()}}function a7t(e){return{type:"systemAutoMemory",content:{paths:e},uuid:so.next()}}function mke(e){return{type:"goal_status",content:e,uuid:so.next()}}function T7t(e){return{type:"goal_set",content:e,uuid:so.next()}}function P4(e){return{type:"goal_cleared",content:e,uuid:so.next()}}function voe(e){return{type:"tool_result",content:v7t,is_error:!0,tool_use_id:e}}function $c(e){return e.filter(t=>!(t.type==="user"&&t.hideInUI)).flatMap(t=>{if(t.type==="progress"||t.type==="reminder")return[t];if(t.type==="goal_status")return[t];if(t.type==="insert")return[{...sr(t.content.content),uuid:t.uuid}];if(t.type==="path_rules")return[];if(t.type==="systemAutoMemory")return[];if(!("message"in t))return[];if(typeof t.message?.content=="string")return[t];if(!t.message)return[];let r=t.message.content.filter(a=>!(a.type==="text"&&/<system-reminder>.*?<\/system-reminder>/s.test(a.text.trim()))),n=r.find(a=>a.type==="text"),o=t.type==="user"&&!!n&&(n.text.includes("<command-name>")||n.text.includes("<command-message>"))?r.filter((a,l)=>{if(a.type!=="text"||a===n)return!0;let c=a.text.trimStart();return c.startsWith("<local-command-stdout>")||c.startsWith("<local-command-stderr>")}):r,s=0;return o.map(a=>{switch(s++,t.type){case"assistant":{let l;if(a.type==="tool_use"){let c=t.message.content;if(c.filter(d=>d.type==="tool_use").length>1){l=new Set;for(let d of c)d.type==="tool_use"&&d.id&&l.add(d.id)}}return{type:"assistant",uuid:t.uuid+s,message:{...t.message,content:[a]},costUSD:t.costUSD/t.message.content.length,durationMs:t.durationMs,siblingToolUseIDs:l}}case"user":return a.type==="tool_result"?{...sr([a],t.toolUseResult),uuid:t.uuid+s}:{...sr([a],t.toolUseResult),uuid:t.uuid+s}}})})}var s_o=Qe(e=>Object.fromEntries(e.flatMap(t=>t.type==="user"&&t.message.content[0]?.type==="tool_result"?[[t.message.content[0].tool_use_id,t.message.content[0].is_error??!1]]:[])));De();De();ar();function _d(e,t){let r=[],n=new Set,i=new Set;return e.filter(o=>o.type!=="progress"&&o.type!=="reminder").forEach(o=>{switch(o.type){case"user":{let s=AA(r);if(s?.type==="user"){r[r.length-1]=ZLe(s,o);return}r.push(o);return}case"assistant":r.push(o);return;case"insert":{let s=AA(r);s?.type==="user"&&(r[r.length-1]=g6n(s,o));return}case"path_rules":{let s=t?.pathRules;if(!s)return;let a=o.content.paths.filter(d=>!n.has(d));if(a.length===0)return;let l=a.map(d=>s.get(d)).filter(d=>d!==void 0);if(a.forEach(d=>n.add(d)),l.length===0)return;let c=sr([{type:"text",text:`<system-rules>
3178
3178
  ${Uht(l)}
3179
3179
  </system-rules>`}]),u=AA(r);u?.type==="user"?r[r.length-1]=ZLe(u,c,{skipTrailingSystemReminders:!0}):r.push(c);return}case"systemAutoMemory":{let s=t?.autoMemories;if(!s)return;let a=o.content.paths.filter(d=>!i.has(d));a.forEach(d=>i.add(d));let l=a.map(d=>{let g=s.get(d);return g===void 0||g.length===0?null:`## ${d.split(/[\\/]/).pop()||d}
3180
3180
  ${g}`}).filter(d=>d!==null);if(l.length===0)return;let c=sr([{type:"text",text:`<system-auto-memory>
@@ -3231,7 +3231,7 @@ ${a}
3231
3231
  Action to classify:
3232
3232
  ${s}`,c=ox(i),{model:u}=Rn.parseModelKey(i),d=Date.now();ir("tengu_auto_mode_classifier_start",{model:u,transcriptLength:String(a.length),actionLength:String(s.length)});try{let g=await TC(async y=>await c.messages.stream({model:u,max_tokens:1024,temperature:0,system:H8n,messages:[{role:"user",content:l}],tools:[$8n],tool_choice:{type:"tool",name:cFe},thinking:{type:"disabled"},stream:!0},{signal:n}).finalMessage(),{maxRetries:2}),m=Date.now()-d;nt("\u81EA\u52A8\u6821\u9A8C\uFF1A",g.content);let A=rjt(g.content,cFe);if(!A)return ir("tengu_auto_mode_classifier_parse_failure",{reason:"no_tool_use",model:u}),{shouldBlock:!0,reason:"Classifier returned no tool use block - blocking for safety",model:u,durationMs:m};let h=njt(A,U8n);return h?(ir("tengu_auto_mode_classifier_success",{model:u,shouldBlock:String(h.shouldBlock),durationMs:String(m)}),{thinking:h.thinking,shouldBlock:h.shouldBlock,reason:h.reason,model:u,durationMs:m}):(ir("tengu_auto_mode_classifier_parse_failure",{reason:"invalid_schema",model:u}),{shouldBlock:!0,reason:"Invalid classifier response - blocking for safety",model:u,durationMs:m})}catch(g){console.log(g);let m=Date.now()-d;if(n.aborted)return ir("tengu_auto_mode_classifier_interrupted",{model:u}),{shouldBlock:!0,reason:"Classifier request aborted",model:u,unavailable:!0,durationMs:m};let A=g instanceof Error&&g.message.toLowerCase().includes("prompt is too long");return Ie(g),ir("tengu_auto_mode_classifier_error",{model:u,error:g instanceof Error?g.message:String(g),tooLong:String(A),durationMs:String(m)}),{shouldBlock:!0,reason:A?"Classifier transcript exceeded context window":"Classifier unavailable - blocking for safety",model:u,unavailable:!0,transcriptTooLong:A,durationMs:m}}}He();var V8n=new Set([is,Es,hs,"LSP",GWe,zWe,jWe,$m,Kd,qE,Jd,Hm,nR,rR,iR,oI,GE,qWe,tR,EG,_G,HE,YWe]);function ljt(e){return V8n.has(e)}Zt();var cjt={maxConsecutive:3,maxTotal:20};function W8n(){let e=Je().autoMode;return{maxConsecutive:e?.maxConsecutiveDenials??cjt.maxConsecutive,maxTotal:e?.maxTotalDenials??cjt.maxTotal}}function ujt(){return{consecutiveDenials:0,totalDenials:0}}function uFe(e){return{...e,consecutiveDenials:e.consecutiveDenials+1,totalDenials:e.totalDenials+1}}function t6(e){return e.consecutiveDenials===0?e:{...e,consecutiveDenials:0}}function djt(e){let t=W8n();return e.consecutiveDenials>=t.maxConsecutive||e.totalDenials>=t.maxTotal}Zt();var K8n=!1;function fjt(){return K8n||Je().autoMode.enabled}var Rx=ujt();var Ejt=new Set([".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json",".hcode.json"]),Z8n=new Set([".git",".vscode",".idea",".hcode"]),X8n=new Set(["commands","agents","skills"]);function O_(e){return e==="~"?AFe():e.startsWith("~/")?Qoe(AFe(),e.slice(2)):J8n(e)}function e$n(e){let r=O_(e).split(Nx),n=r[r.length-1]??"";if(Ejt.has(n))return!0;for(let i=0;i<r.length-1;i++)if(Z8n.has(r[i]??""))return!0;return!1}function _jt(e){return!!(e.indexOf(":",2)!==-1||/~\d/.test(e)||e.startsWith("\\\\?\\")||e.startsWith("\\\\.\\")||/[.\s]+$/.test(e)||/\.(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(e)||/(^|\/|\\)\.{3,}(\/|\\|$)/.test(e))}function t$n(e){let t=O_(e).toLowerCase();return t.endsWith(`${Nx}.hcode${Nx}settings.json`)||t.endsWith(`${Nx}.hcode${Nx}settings.local.json`)}function r$n(e,t){if(t$n(e))return!0;let r=Qoe(t,".hcode","commands"),n=Qoe(t,".hcode","agents"),i=Qoe(t,".hcode","skills"),o=O_(e);return o.startsWith(r)||o.startsWith(n)||o.startsWith(i)}function n$n(e,t){let n=O_(e).split(Nx),i=n[n.length-1]??"";if(Ejt.has(i))return!0;for(let o=0;o<n.length-1;o++){let s=n[o]??"";if(s===".git"||s===".vscode"||s===".idea")return!0;if(s===".hcode"&&o<n.length-1){let a=n[o+1]??"";if(o+1===n.length-1||!X8n.has(a))return!0}}return!1}function i$n(e){if(e.endsWith(":*"))return!1;for(let t=0;t<e.length;t++)if(e[t]==="*"){let r=0,n=t-1;for(;n>=0&&e[n]==="\\";)r++,n--;if(r%2===0)return!0}return!1}function o$n(e){let t=e.match(/^(.+):\*$/);return t?.[1]?{type:"prefix",prefix:t[1]}:i$n(e)?{type:"wildcard",pattern:e}:{type:"exact",command:e}}function Poe(e){return e.match(/^[^(]+\((.+)\)$/)?.[1]}function pjt(e,t){let r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),i=r.replace(/[.+^${}()|[\]]/g,"\\$&").replace(/\*\*\//g,"(.+/)?").replace(/\*\*/g,"<<<DOUBLE_STAR>>>").replace(/\*/g,"[^/]*").replace(/<<<DOUBLE_STAR>>>/g,".*").replace(/\?/g,"[^/]");try{return new RegExp(`^${i}$`).test(n)}catch{return n.includes(r.replace(/\*/g,""))}}function s$n(e,t,r=!1){let n="\0ESCAPED_STAR\0",i="\0ESCAPED_BACKSLASH\0",o="",s=0;for(;s<e.length;){let u=e[s];if(u==="\\"&&s+1<e.length){let d=e[s+1];if(d==="*"){o+=n,s+=2;continue}if(d==="\\"){o+=i,s+=2;continue}}o+=u,s++}let a=o.replace(/[.+?^${}()|[\]'"]/g,"\\$&").replace(/\*/g,".*").replace(new RegExp(n,"g"),"\\*").replace(new RegExp(i,"g"),"\\\\"),l=(o.match(/\*/g)||[]).length;a.endsWith(" .*")&&l===1&&(a=a.slice(0,-3)+"( .*)?");let c="s"+(r?"i":"");return new RegExp(`^${a}$`,c).test(t)}function a$n(e,t){let r=Nx;if(e.startsWith("//")||e.startsWith("\\\\")){let i=e.slice(1);return{root:r,relativePattern:i}}if(e.startsWith("~/")||e.startsWith("~\\"))return{root:AFe(),relativePattern:e.slice(2)};if(e.startsWith(r)||e.startsWith("/"))return{root:So(),relativePattern:e.slice(1)};if(/^[A-Za-z]:[/\\]/.test(e))return{root:"__absolute__",relativePattern:e};let n=e;return(n.startsWith("./")||n.startsWith(".\\"))&&(n=n.slice(2)),{root:null,relativePattern:n}}function l$n(e,t,r,n){let{root:i,relativePattern:o}=a$n(t,r),s=O_(e);if(i==="__absolute__")return!!pjt(o,s);let l=hjt(i??n,s);return l.startsWith("..")?!1:!!pjt(o,l)}function Jk(e,t,r,n){let i=Array.isArray(t)?t:[t];for(let o of r)for(let s of i){if(o===s)return o;if(!o.startsWith(`${s}(`))continue;let a=Poe(o);if(a===void 0||l$n(e,a,n,n))return o}}function yjt(e,t){let r=O_(e);return!hjt(t,r).startsWith("..")}function c$n(e,t,r,n,i,o,s){let a=O_(e);return a.startsWith("\\\\")||a.startsWith("//")?{behavior:"ask",message:`Hcode requested permissions to read from ${e}, which appears to be a UNC path.`}:_jt(a)?{behavior:"ask",message:`Hcode requested permissions to read from ${e}, which contains a suspicious path pattern.`}:Jk(a,[is,hs,Es],r,i)?{behavior:"deny",message:"File is in a directory that is denied by your permission settings."}:Jk(a,[is,hs,Es],n,i)?{behavior:"ask",message:`Hcode requested permissions to read from ${e}, but you haven't granted it yet.`}:yjt(a,i)?{behavior:"allow"}:Jk(a,[is,hs,Es],t,i)?{behavior:"allow"}:o==="acceptEdits"?{behavior:"allow"}:Sh(a)?{behavior:"allow"}:{behavior:"ask",message:`Hcode requested permissions to read from ${e}, but you haven't granted it yet.`}}function u$n(e,t,r,n,i,o,s){let a=O_(e),l=Je().permissions?.disableBypassPermissionsMode;return o==="bypassPermissions"&&l!=="disable"?JC(a)?{behavior:"allow"}:n$n(e,i)?{message:`Hcode requested permissions to write to ${e}, but you haven't granted it yet.`,behavior:"ask"}:{behavior:"allow"}:o==="plan"?Ih(a)?{behavior:"allow"}:{message:"Plan mode cannot use tool: "+s.name,behavior:"deny"}:Jk(a,[ua,Na,Hy],r,i)?{behavior:"deny",message:"File is in a directory that is denied by your permission settings."}:_jt(a)?{behavior:"ask",message:`Hcode requested permissions to write to ${e}, which contains a suspicious path pattern.`}:Jk(a,[ua,Na,Hy],n,i)?{behavior:"ask",message:`Hcode requested permissions to write to ${e}, but you haven't granted it yet.`}:JC(a)?{behavior:"allow"}:r$n(a,i)?{behavior:"ask",message:`Hcode requested permissions to write to ${e}, but you haven't granted it yet.`}:e$n(a)?{behavior:"ask",message:`Hcode requested permissions to edit ${e} which is a sensitive file.`}:o==="acceptEdits"&&yjt(a,i)?{behavior:"allow"}:Jk(a,[ua,Na,Hy],t,i)?{behavior:"allow"}:ZC(a)?{behavior:"allow"}:{behavior:"ask",message:`Hcode requested permissions to write to ${e}, but you haven't granted it yet.`}}var d$n=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","PYTEST_DISABLE_PLUGIN_AUTOLOAD","PYTEST_DEBUG","ANTHROPIC_API_KEY","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS","GCC_COLORS","TIME_STYLE","BLOCK_SIZE","BLOCKSIZE"]),f$n=/^(LD_|DYLD_|PATH$)/,p$n=[/^timeout[ \t]+(?:(?:--(?:foreground|preserve-status|verbose)|--(?:kill-after|signal)=[A-Za-z0-9_.+-]+|--(?:kill-after|signal)[ \t]+[A-Za-z0-9_.+-]+|-v|-[ks][ \t]+[A-Za-z0-9_.+-]+|-[ks][A-Za-z0-9_.+-]+)[ \t]+)*(?:--[ \t]+)?\d+(?:\.\d+)?[smhd]?[ \t]+/,/^time[ \t]+(?:--[ \t]+)?/,/^nice(?:[ \t]+-n[ \t]+-?\d+|[ \t]+-\d+)?[ \t]+(?:--[ \t]+)?/,/^stdbuf(?:[ \t]+-[ioe][LN0-9]+)+[ \t]+(?:--[ \t]+)?/,/^nohup[ \t]+(?:--[ \t]+)?/];function hFe(e){let t=e.split(`
3233
3233
  `).filter(r=>{let n=r.trim();return n!==""&&!n.startsWith("#")});return t.length===0?e:t.join(`
3234
- `)}function bjt(e){let t=/^([A-Za-z_][A-Za-z0-9_]*)=([A-Za-z0-9_./:-]+)[ \t]+/,r=e,n="";for(;r!==n;){n=r,r=hFe(r);let i=r.match(t);if(i){let o=i[1];d$n.has(o)&&!f$n.test(o)&&(r=r.replace(t,""))}}for(n="";r!==n;){n=r,r=hFe(r);for(let i of p$n)r=r.replace(i,"")}return r.trim()}function EFe(e){let t=/^([A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?)\+?=(?:'[^'\n\r]*'|"(?:\\.|[^"$`\\\n\r])*"|\\.|[^ \t\n\r$`;|&()<>\\'"])*[ \t]+/,r=e,n="";for(;r!==n;){n=r,r=hFe(r);let i=r.match(t);i&&(r=r.slice(i[0].length))}return r.trim()}function Cjt(e){return{commandWithoutRedirections:e.replace(/\s+2>&1$/,"").replace(/\s+\d?>>?\s+\S+/g,"").replace(/\s+<<[-~]?\w+[\s\S]*$/,"").trim(),hasDangerousRedirection:!1}}function m$n(e){let t=["&&","||",";","|"],r=0,n=!1,i=!1,o=0;for(;o<e.length;){let s=e[o];if(s==="'"&&!i){n=!n,o++;continue}if(s==='"'&&!n){i=!i,o++;continue}if(s==="\\"&&!n){o+=2;continue}if(!n&&!i){if(s==="("||s==="{"){r++,o++;continue}if(s===")"||s==="}"){r--,o++;continue}if(r===0){for(let a of t)if(e.startsWith(a,o))return!0}}o++}return!1}function g$n(e,t,r){let n=e.trim(),i=o$n(t),o=new Set([n]),{commandWithoutRedirections:s}=Cjt(n);s!==n&&o.add(s);let a=bjt(n);if(a!==n&&o.add(a),r==="prefix"){let u=EFe(n);u!==n&&o.add(u);let d=EFe(a);d!==a&&d!==n&&o.add(d)}let l=Array.from(o),c=r==="prefix"?new Map(l.map(u=>[u,m$n(u)])):null;for(let u of l)switch(i.type){case"exact":if(i.command===u)return!0;break;case"prefix":{let d=i.prefix;if(r==="exact"){if(u===d)return!0}else{if(c.get(u))continue;if(u===d||u.startsWith(`${d} `)||u.startsWith(`${d} `)||u===`xargs ${d}`||u.startsWith(`xargs ${d} `))return!0}break}case"wildcard":if(r==="exact")break;if(c.get(u))continue;if(s$n(i.pattern,u))return!0;break}return!1}function Zk(e,t,r){for(let n of t){if(n===Li.name)return n;if(!n.startsWith(Li.name))continue;let i=Poe(n);if(i===void 0||g$n(e,i,r))return n}}function Sjt(e,t,r,n){return Zk(e,r,"exact")?{behavior:"deny",message:`Permission to use ${Li.name} with command "${e}" has been denied.`}:Zk(e,n,"exact")?{behavior:"ask",message:`Hawa code requested permissions to use ${Li.name} with command "${e}", but you haven't granted it yet.`}:nrt(e)?{behavior:"allow"}:Zk(e,t,"exact")?{behavior:"allow"}:{behavior:"passthrough"}}function dFe(e,t,r,n,i){let o=Sjt(e,r,n,i);if(o.behavior!=="passthrough")return o;if(Zk(e,n,"prefix"))return{behavior:"deny",message:`Permission to use ${Li.name} with command "${e}" has been denied.`};if(Zk(e,i,"prefix"))return{behavior:"ask",message:`Hawa code requested permissions to use ${Li.name} with command "${e}", but you haven't granted it yet.`};if(Zk(e,r,"prefix"))return{behavior:"allow"};if(t!==null){let s=`${Li.name}(${t}:*)`;if(n.includes(s))return{behavior:"deny",message:`Permission to use ${Li.name} with command "${e}" has been denied.`};if(i.includes(s))return{behavior:"ask",message:`Hawa code requested permissions to use ${Li.name} with command "${e}", but you haven't granted it yet.`};if(r.includes(s))return{behavior:"allow"}}return{behavior:"passthrough"}}function fFe(e){return"commandPrefix"in e?e.commandPrefix:null}var A$n=["mkdir","touch","rm","rmdir","mv","cp","sed"];function mjt(e){return A$n.includes(e)}function gjt(e){let t=bjt(EFe(e)),{commandWithoutRedirections:r}=Cjt(t),n=r.trim();if(!n)return null;let[i]=n.split(/\s+/);return i??null}function h$n(e,t){if(t!=="acceptEdits")return null;let r=Tb(e).filter(i=>i!==`cd ${Re()}`);if(r.length<2){let i=gjt(e);return i&&mjt(i)?{behavior:"allow"}:null}return r.every(i=>{let o=gjt(i);return o&&mjt(o)})?{behavior:"allow"}:null}var E$n=(e,t,r,n,i=[],o=[],s,a=Ktt)=>{if(nl.isSandboxingEnabled()&&Je().sandbox?.autoAllowBashIfSandboxed===!0)return{result:!0};if(s==="plan")return{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"};if(h$n(t,s)?.behavior==="allow")return{result:!0};let c=Sjt(t,n,i,o);if(c.behavior==="deny")return{result:!1,message:c.message,behavior:"deny"};if(c.behavior==="ask")return{result:!1,message:c.message,behavior:"ask"};if(c.behavior==="allow")return{result:!0};let u=Tb(t).filter(m=>m!==`cd ${Re()}`),d=a(t);if(d.commandInjectionDetected)return{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"};if(u.length<2){let m=dFe(t,fFe(d),n,i,o);return m.behavior==="deny"?{result:!1,message:m.message,behavior:"deny"}:m.behavior==="ask"?{result:!1,message:m.message,behavior:"ask"}:m.behavior==="allow"?{result:!0}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}for(let m of u){let A=d.subcommandPrefixes.get(m);if(A===void 0||A.commandInjectionDetected)continue;let h=dFe(m,fFe(A),n,i,o);if(h.behavior==="deny")return{result:!1,message:h.message,behavior:"deny"};if(h.behavior==="ask")return{result:!1,message:h.message,behavior:"ask"}}return u.every(m=>{let A=d.subcommandPrefixes.get(m);return A===void 0||A.commandInjectionDetected?!1:dFe(m,fFe(A),n,i,o).behavior==="allow"})?{result:!0}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}};function _$n(e){return Ea(e.agentId)?lo.isEditMode()?"acceptEdits":lo.isPlanMode()?"plan":lo.isAutoMode()?"auto":"default":e.options?.permissionMode||"default"}function pFe(e,t){return t.some(r=>r.endsWith("*")?e.startsWith(r.slice(0,-1)):r.startsWith("mcp_")&&!r.includes("*")?e.startsWith(r+"_"):!1)}function Ijt(e){try{return new URL(e).hostname}catch{return null}}function y$n(e,t){let r=t.endsWith(":*")?t.slice(0,-2):t;if(r===e)return!0;if(r.startsWith("*.")){let n=r.slice(2);return e.endsWith(n)}return t.endsWith(":*")?e===r||e.endsWith("."+r):!1}function mFe(e,t){for(let r of t){if(r===HE)return r;if(!r.startsWith(`${HE}(`))continue;let n=Poe(r);if(n===void 0)return r;let i=n.match(/^domain:(.+)$/);if(i?.[1]){let o=i[1];if(y$n(e,o))return r}}}function b$n(e,t,r,n){let i=Ijt(e);return mFe(i,r)?{behavior:"deny",message:`Fetching from ${i} has been denied by your permission settings.`}:mFe(i,n)?{behavior:"ask",message:`Hcode requested permissions to fetch from ${e}, but you haven't granted it yet.`}:mFe(i,t)?{behavior:"allow"}:{behavior:"allow"}}function gFe(e,t){for(let r of t){if(r===Dn)return r;if(!r.startsWith(`${Dn}(`))continue;let n=Poe(r);if(n===void 0||n==="*"||n===e)return r}}function C$n(e,t,r,n){return gFe(e,r)?{behavior:"deny",message:`Agent ${e?`(${e})`:""} has been denied by your permission settings.`}:gFe(e,n)?{behavior:"ask",message:`Hcode requested permissions to use Agent ${e?`(${e})`:""}, but you haven't granted it yet.`}:gFe(e,t)?{behavior:"allow"}:{behavior:"allow"}}var Ajt=async(e,t,r,n)=>{if(r.options.dangerouslySkipPermissions)return{result:!0};if(r.abortController.signal.aborted)throw new wA;let i=S$n(e,t,null),o=Je(),s=o.permissions?.allow??[],a=o.permissions?.deny??[],l=o.permissions?.ask??[],c=pt.getQueryContext(r.agentId)[$P];c&&(s=[...s,...c]);let u=pt.getQueryContext(r.agentId).planAllowedPrompts;u&&(s=[...s,...u]);let d=Re();if(e===tS||e===sS||e===oS){let g=e===oS||e===sS?t.path??Re():t.file_path,m=O_(g);if(ag(m)||sg(m))return{result:!0};let A=c$n(g,s,a,l,d,n,e);return A.behavior==="allow"?{result:!0}:A.behavior==="deny"?{result:!1,message:A.message,behavior:"deny"}:A.behavior==="ask"?{result:!1,message:A.message,behavior:"ask"}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}else if(e===eS||e===nS||e===Th){let g=t.file_path??t.notebook_path,m=u$n(g,s,a,l,d,n,e);return m.behavior==="allow"?{result:!0}:m.behavior==="deny"?{result:!1,message:m.message,behavior:"deny"}:m.behavior==="ask"?{result:!1,message:m.message,behavior:"ask"}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}else if(e===Li){let{command:g}=Li.inputSchema.parse(t);return E$n(e,g,r,s,a,l,n)}else if(e===am){let{command:g}=am.inputSchema.parse(t);return lFe(e,g,r,s,a,l,n)}else if(e===w3){let g=t.url||"",m=b$n(g,s,a,l);return m.behavior==="allow"?{result:!0}:m.behavior==="deny"?{result:!1,message:m.message,behavior:"deny"}:m.behavior==="ask"?{result:!1,message:m.message,behavior:"ask"}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}else if(e.name===Dn){let g=t.subagent_type||t.name,m=C$n(g,s,a,l);return m.behavior==="allow"?{result:!0}:m.behavior==="deny"?{result:!1,message:m.message,behavior:"deny"}:m.behavior==="ask"?{result:!1,message:m.message,behavior:"ask"}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}else{if(e.isMcp?.())return a.includes(e.name)||pFe(i,a)?{result:!0}:l.includes(e.name)||pFe(i,l)?{result:!0}:s.includes(e.name)||pFe(i,s)?{result:!0}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"};{let g;return e.needsPermissions(t)?a.includes(e.name)||a.includes(i)?g={result:!1,behavior:"deny",message:`Hcode requested permissions to ${e.name}, but you haven't granted it yet.`}:l.includes(e.name)||l.includes(i)?g={result:!1,behavior:"ask",message:`Hcode requested permissions to ${e.name}, but you haven't granted it yet.`}:s.includes(e.name)||s.includes(i)?g={result:!0}:g={result:!1,behavior:"ask",message:`Hcode requested permissions to ${e.name}, but you haven't granted it yet.`}:g={result:!0},g}}},xoe=async(e,t,r,n,i,o,s)=>{let a=_$n(r),l=await Ajt(e,t,r,a);if(a==="auto"&&fjt()){if(l.result===!0)return t6(Rx),l;if(l.behavior==="deny")return uFe(Rx),l;let c=process.env.HAWA_CODE_AUTO_MODE_ACCEPTEDITS;if((c==="1"||c==="true")&&await(async()=>(await Ajt(e,t,r,"acceptEdits")).result===!0)())return t6(Rx),{result:!0};if(ljt(e.name))return t6(Rx),{result:!0};if(djt(Rx))return l;if(s&&s.length>0)try{let u=_d(s),d=sjt(e.name,t),g=await ajt(u,d,[e],r.abortController.signal);return g.shouldBlock?(uFe(Rx),{result:!1,message:g.reason||"Auto mode denied this action.",behavior:"deny"}):(t6(Rx),{result:!0})}catch(u){if(u.name==="AbortError")throw u;return Ie(u),l}}return l};function S$n(e,t,r){switch(e){case Li:return r?`${Li.name}(${r}:*)`:`${Li.name}(${Li.renderToolUseMessage(t)})`;case am:return r?`${am.name}(${r}:*)`:`${am.name}(${am.renderToolUseMessage(t)})`;case eS:case nS:case tS:return`${e.name}(${t.file_path})`;case Th:return`${e.name}(${t.notebook_path})`;case w3:let n=t.url||"",i=Ijt(n);return i?`${e.name}(domain:${i})`:e.name;default:if(e.name===Dn){let o=t.subagent_type||t.name;return o?`${Dn}(${o})`:Dn}return e.name}}De();Cr();He();import{randomUUID as T$n}from"node:crypto";var Tjt={readFileTimestamps:{}},v$n=1800*1e3,x$n=300*1e3,w$n=[kX],vjt=vFt();async function D$n(e,t,r=Tjt.readFileTimestamps){try{if(!await e.isEnabled())throw new Error(`Tool ${e.name} is not enabled`);let n=await BA(),i={abortController:new AbortController,options:{commands:w$n,tools:vjt,slowAndCapableModel:n,thinking:"off"},readFileTimestamps:r,agentDepth:0},o=await e.validateInput?.(t??{},i);if(o&&!o.result){let u=`Tool ${e.name} input is invalid: ${o.message}`;return{isError:!0,content:[{type:"text",text:u}],_meta:{[D4]:{validationError:!0,message:o.message,resultForAssistant:u}}}}let s=e.call(t??{},i,xoe),a=await fke(s);if(a.type!=="result")throw new Error(`Tool ${e.name} did not return a result`);let l=typeof a.resultForAssistant=="string"?a.resultForAssistant:JSON.stringify(a.data),c={data:a.data,resultForAssistant:l};return{content:[{type:"text",text:l}],_meta:{[D4]:c}}}catch(n){return Ie(n),{isError:!0,content:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}async function xjt(e=Tjt.readFileTimestamps){let t=new J$({name:`${Ht}/hands`,version:MACRO.VERSION},{capabilities:{tools:{}}}),r=await Promise.all(vjt.map(async n=>({tool:n,description:n.description?await n.description():""})));for(let{tool:n,description:i}of r)t.registerTool(n.name,{description:i,inputSchema:n.inputSchema},(async o=>D$n(n,o,e)));return t}function wjt(e){let t=async()=>{try{await e()}catch(r){Ie(r)}finally{process.exit(0)}};process.on("SIGINT",t),process.on("SIGTERM",t)}async function R$n(e){let t=[];for await(let n of e)t.push(n);let r=Buffer.concat(t).toString("utf8");return r?JSON.parse(r):void 0}async function N$n(){let e=await xjt();wjt(async()=>{await e.close()});let t=new X$;await e.connect(t),console.error(`${Ht} Hands MCP server running on stdio`)}async function B$n(e){let t=new Map;function r(c){let u=c.headers["mcp-session-id"];return Array.isArray(u)?u[0]:u}async function n(c){let u=t.get(c);if(u){t.delete(c);try{await u.server.close()}catch(d){Ie(d)}}}async function i(){let c={},u=await xjt(c),d,g=new iH({sessionIdGenerator:()=>T$n(),enableJsonResponse:!0,onsessioninitialized:A=>{d=A,t.set(A,m)},onsessionclosed:A=>{n(A)}});await u.connect(g);let m={server:u,transport:g,readFileTimestamps:c,lastUsedAt:Date.now()};return d!==void 0&&!t.has(d)&&t.set(d,m),m}function o(){let c=Date.now();for(let[u,d]of t)c-d.lastUsedAt>v$n&&n(u)}let s=setInterval(o,x$n);s.unref();let a=I$n(async(c,u)=>{if(c.url!=="/mcp"){u.statusCode=404,u.setHeader("Content-Type","application/json"),u.end(JSON.stringify({error:"Not Found"}));return}if(c.method!=="GET"&&c.method!=="POST"&&c.method!=="DELETE"){u.statusCode=405,u.setHeader("Content-Type","application/json"),u.setHeader("Allow","GET, POST, DELETE"),u.end(JSON.stringify({error:"Method Not Allowed"}));return}try{let d=r(c),g;if(d!==void 0){if(g=t.get(d),!g){u.statusCode=404,u.setHeader("Content-Type","application/json"),u.end(JSON.stringify({error:"Session not found"}));return}}else g=await i();g.lastUsedAt=Date.now();let m=c.method==="POST"?await R$n(c):void 0;await g.transport.handleRequest(c,u,m)}catch(d){Ie(d),u.headersSent||(u.statusCode=500,u.setHeader("Content-Type","application/json"),u.end(JSON.stringify({error:d instanceof Error?d.message:String(d)})))}}),l=await O$n(a,e,10);console.error(`${Ht} Hands MCP server running on http://localhost:${l}/mcp`),console.error("WARNING: HTTP transport has no authentication. Only use behind a reverse proxy or in a secured setup."),wjt(async()=>{clearInterval(s),await Promise.all(Array.from(t.keys()).map(c=>n(c))),await new Promise(c=>{a.close(()=>c())})})}function O$n(e,t,r){return new Promise((n,i)=>{let o=(s,a)=>{let l=u=>{if(e.removeListener("listening",c),u.code==="EADDRINUSE"&&a>0){c9.getAvailablePort().then(d=>{if(d==null){i(new Error("No available port in range 3000-3999 after retries"));return}setImmediate(()=>o(d,a-1))}).catch(i);return}i(u)},c=()=>{e.removeListener("error",l),n(s)};e.once("error",l),e.once("listening",c),e.listen(s,"0.0.0.0")};o(t,r)})}async function _Co(e){await Ul(e);let t=(process.env.MCP_TRANSPORT||"http").toLowerCase();if(t==="stdio"){await N$n();return}if(t==="http"){let r;if(process.env.PORT)r=parseInt(process.env.PORT,10);else{let n=await c9.getAvailablePort();n==null&&(console.error("No available port in range 3000-3999. Set PORT environment variable to specify one."),process.exit(1)),r=n}await B$n(r);return}console.error(`Unknown transport: ${t}. Use MCP_TRANSPORT=stdio or MCP_TRANSPORT=http`),process.exit(1)}export{_Co as startMCPServer};
3234
+ `)}function bjt(e){let t=/^([A-Za-z_][A-Za-z0-9_]*)=([A-Za-z0-9_./:-]+)[ \t]+/,r=e,n="";for(;r!==n;){n=r,r=hFe(r);let i=r.match(t);if(i){let o=i[1];d$n.has(o)&&!f$n.test(o)&&(r=r.replace(t,""))}}for(n="";r!==n;){n=r,r=hFe(r);for(let i of p$n)r=r.replace(i,"")}return r.trim()}function EFe(e){let t=/^([A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?)\+?=(?:'[^'\n\r]*'|"(?:\\.|[^"$`\\\n\r])*"|\\.|[^ \t\n\r$`;|&()<>\\'"])*[ \t]+/,r=e,n="";for(;r!==n;){n=r,r=hFe(r);let i=r.match(t);i&&(r=r.slice(i[0].length))}return r.trim()}function Cjt(e){return{commandWithoutRedirections:e.replace(/\s+2>&1$/,"").replace(/\s+\d?>>?\s+\S+/g,"").replace(/\s+<<[-~]?\w+[\s\S]*$/,"").trim(),hasDangerousRedirection:!1}}function m$n(e){let t=["&&","||",";","|"],r=0,n=!1,i=!1,o=0;for(;o<e.length;){let s=e[o];if(s==="'"&&!i){n=!n,o++;continue}if(s==='"'&&!n){i=!i,o++;continue}if(s==="\\"&&!n){o+=2;continue}if(!n&&!i){if(s==="("||s==="{"){r++,o++;continue}if(s===")"||s==="}"){r--,o++;continue}if(r===0){for(let a of t)if(e.startsWith(a,o))return!0}}o++}return!1}function g$n(e,t,r){let n=e.trim(),i=o$n(t),o=new Set([n]),{commandWithoutRedirections:s}=Cjt(n);s!==n&&o.add(s);let a=bjt(n);if(a!==n&&o.add(a),r==="prefix"){let u=EFe(n);u!==n&&o.add(u);let d=EFe(a);d!==a&&d!==n&&o.add(d)}let l=Array.from(o),c=r==="prefix"?new Map(l.map(u=>[u,m$n(u)])):null;for(let u of l)switch(i.type){case"exact":if(i.command===u)return!0;break;case"prefix":{let d=i.prefix;if(r==="exact"){if(u===d)return!0}else{if(c.get(u))continue;if(u===d||u.startsWith(`${d} `)||u.startsWith(`${d} `)||u===`xargs ${d}`||u.startsWith(`xargs ${d} `))return!0}break}case"wildcard":if(r==="exact")break;if(c.get(u))continue;if(s$n(i.pattern,u))return!0;break}return!1}function Zk(e,t,r){for(let n of t){if(n===Li.name)return n;if(!n.startsWith(Li.name))continue;let i=Poe(n);if(i===void 0||g$n(e,i,r))return n}}function Sjt(e,t,r,n){return Zk(e,r,"exact")?{behavior:"deny",message:`Permission to use ${Li.name} with command "${e}" has been denied.`}:Zk(e,n,"exact")?{behavior:"ask",message:`Hawa code requested permissions to use ${Li.name} with command "${e}", but you haven't granted it yet.`}:nrt(e)?{behavior:"allow"}:Zk(e,t,"exact")?{behavior:"allow"}:{behavior:"passthrough"}}function dFe(e,t,r,n,i){let o=Sjt(e,r,n,i);if(o.behavior!=="passthrough")return o;if(Zk(e,n,"prefix"))return{behavior:"deny",message:`Permission to use ${Li.name} with command "${e}" has been denied.`};if(Zk(e,i,"prefix"))return{behavior:"ask",message:`Hawa code requested permissions to use ${Li.name} with command "${e}", but you haven't granted it yet.`};if(Zk(e,r,"prefix"))return{behavior:"allow"};if(t!==null){let s=`${Li.name}(${t}:*)`;if(n.includes(s))return{behavior:"deny",message:`Permission to use ${Li.name} with command "${e}" has been denied.`};if(i.includes(s))return{behavior:"ask",message:`Hawa code requested permissions to use ${Li.name} with command "${e}", but you haven't granted it yet.`};if(r.includes(s))return{behavior:"allow"}}return{behavior:"passthrough"}}function fFe(e){return"commandPrefix"in e?e.commandPrefix:null}var A$n=["mkdir","touch","rm","rmdir","mv","cp","sed"];function mjt(e){return A$n.includes(e)}function gjt(e){let t=bjt(EFe(e)),{commandWithoutRedirections:r}=Cjt(t),n=r.trim();if(!n)return null;let[i]=n.split(/\s+/);return i??null}function h$n(e,t){if(t!=="acceptEdits")return null;let r=Tb(e).filter(i=>i!==`cd ${Re()}`);if(r.length<2){let i=gjt(e);return i&&mjt(i)?{behavior:"allow"}:null}return r.every(i=>{let o=gjt(i);return o&&mjt(o)})?{behavior:"allow"}:null}var E$n=(e,t,r,n,i=[],o=[],s,a=Ktt)=>{if(nl.isSandboxingEnabled()&&Je().sandbox?.autoAllowBashIfSandboxed===!0)return{result:!0};if(s==="plan")return{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"};if(h$n(t,s)?.behavior==="allow")return{result:!0};let c=Sjt(t,n,i,o);if(c.behavior==="deny")return{result:!1,message:c.message,behavior:"deny"};if(c.behavior==="ask")return{result:!1,message:c.message,behavior:"ask"};if(c.behavior==="allow")return{result:!0};let u=Tb(t).filter(m=>m!==`cd ${Re()}`),d=a(t);if(d.commandInjectionDetected)return{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"};if(u.length<2){let m=dFe(t,fFe(d),n,i,o);return m.behavior==="deny"?{result:!1,message:m.message,behavior:"deny"}:m.behavior==="ask"?{result:!1,message:m.message,behavior:"ask"}:m.behavior==="allow"?{result:!0}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}for(let m of u){let A=d.subcommandPrefixes.get(m);if(A===void 0||A.commandInjectionDetected)continue;let h=dFe(m,fFe(A),n,i,o);if(h.behavior==="deny")return{result:!1,message:h.message,behavior:"deny"};if(h.behavior==="ask")return{result:!1,message:h.message,behavior:"ask"}}return u.every(m=>{let A=d.subcommandPrefixes.get(m);return A===void 0||A.commandInjectionDetected?!1:dFe(m,fFe(A),n,i,o).behavior==="allow"})?{result:!0}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}};function _$n(e){return Ea(e.agentId)?lo.isEditMode()?"acceptEdits":lo.isPlanMode()?"plan":lo.isAutoMode()?"auto":"default":e.options?.permissionMode||"default"}function pFe(e,t){return t.some(r=>r.endsWith("*")?e.startsWith(r.slice(0,-1)):r.startsWith("mcp_")&&!r.includes("*")?e.startsWith(r+"_"):!1)}function Ijt(e){try{return new URL(e).hostname}catch{return null}}function y$n(e,t){let r=t.endsWith(":*")?t.slice(0,-2):t;if(r===e)return!0;if(r.startsWith("*.")){let n=r.slice(2);return e.endsWith(n)}return t.endsWith(":*")?e===r||e.endsWith("."+r):!1}function mFe(e,t){for(let r of t){if(r===HE)return r;if(!r.startsWith(`${HE}(`))continue;let n=Poe(r);if(n===void 0)return r;let i=n.match(/^domain:(.+)$/);if(i?.[1]){let o=i[1];if(y$n(e,o))return r}}}function b$n(e,t,r,n){let i=Ijt(e);return mFe(i,r)?{behavior:"deny",message:`Fetching from ${i} has been denied by your permission settings.`}:mFe(i,n)?{behavior:"ask",message:`Hcode requested permissions to fetch from ${e}, but you haven't granted it yet.`}:mFe(i,t)?{behavior:"allow"}:{behavior:"allow"}}function gFe(e,t){for(let r of t){if(r===Dn)return r;if(!r.startsWith(`${Dn}(`))continue;let n=Poe(r);if(n===void 0||n==="*"||n===e)return r}}function C$n(e,t,r,n){return gFe(e,r)?{behavior:"deny",message:`Agent ${e?`(${e})`:""} has been denied by your permission settings.`}:gFe(e,n)?{behavior:"ask",message:`Hcode requested permissions to use Agent ${e?`(${e})`:""}, but you haven't granted it yet.`}:gFe(e,t)?{behavior:"allow"}:{behavior:"allow"}}var Ajt=async(e,t,r,n)=>{if(r.options.dangerouslySkipPermissions)return{result:!0};if(r.abortController.signal.aborted)throw new wA;let i=S$n(e,t,null),o=Je(),s=o.permissions?.allow??[],a=o.permissions?.deny??[],l=o.permissions?.ask??[],c=pt.getQueryContext(r.agentId)[$P];c&&(s=[...s,...c]);let u=pt.getQueryContext(r.agentId).planAllowedPrompts;u&&(s=[...s,...u]);let d=Re();if(e===tS||e===sS||e===oS){let g=e===oS||e===sS?t.path??Re():t.file_path,m=O_(g);if(ag(m)||sg(m))return{result:!0};let A=c$n(g,s,a,l,d,n,e);return A.behavior==="allow"?{result:!0}:A.behavior==="deny"?{result:!1,message:A.message,behavior:"deny"}:A.behavior==="ask"?{result:!1,message:A.message,behavior:"ask"}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}else if(e===eS||e===nS||e===Th){let g=t.file_path??t.notebook_path,m=u$n(g,s,a,l,d,n,e);return m.behavior==="allow"?{result:!0}:m.behavior==="deny"?{result:!1,message:m.message,behavior:"deny"}:m.behavior==="ask"?{result:!1,message:m.message,behavior:"ask"}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}else if(e===Li){let{command:g}=Li.inputSchema.parse(t);return E$n(e,g,r,s,a,l,n)}else if(e===am){let{command:g}=am.inputSchema.parse(t);return lFe(e,g,r,s,a,l,n)}else if(e===w3){let g=t.url||"",m=b$n(g,s,a,l);return m.behavior==="allow"?{result:!0}:m.behavior==="deny"?{result:!1,message:m.message,behavior:"deny"}:m.behavior==="ask"?{result:!1,message:m.message,behavior:"ask"}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}else if(e.name===Dn){let g=t.subagent_type||t.name,m=C$n(g,s,a,l);return m.behavior==="allow"?{result:!0}:m.behavior==="deny"?{result:!1,message:m.message,behavior:"deny"}:m.behavior==="ask"?{result:!1,message:m.message,behavior:"ask"}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"}}else{if(e.isMcp?.())return a.includes(e.name)||pFe(i,a)?{result:!0}:l.includes(e.name)||pFe(i,l)?{result:!0}:s.includes(e.name)||pFe(i,s)?{result:!0}:{result:!1,message:`Hawa code requested permissions to use ${e.name}, but you haven't granted it yet.`,behavior:"ask"};{let g;return e.needsPermissions(t)?a.includes(e.name)||a.includes(i)?g={result:!1,behavior:"deny",message:`Hcode requested permissions to ${e.name}, but you haven't granted it yet.`}:l.includes(e.name)||l.includes(i)?g={result:!1,behavior:"ask",message:`Hcode requested permissions to ${e.name}, but you haven't granted it yet.`}:s.includes(e.name)||s.includes(i)?g={result:!0}:g={result:!1,behavior:"ask",message:`Hcode requested permissions to ${e.name}, but you haven't granted it yet.`}:g={result:!0},g}}},xoe=async(e,t,r,n,i,o,s)=>{let a=_$n(r),l=await Ajt(e,t,r,a);if(a==="auto"&&fjt()){if(l.result===!0)return t6(Rx),l;if(l.behavior==="deny")return uFe(Rx),l;let c=process.env.HAWA_CODE_AUTO_MODE_ACCEPTEDITS;if((c==="1"||c==="true")&&await(async()=>(await Ajt(e,t,r,"acceptEdits")).result===!0)())return t6(Rx),{result:!0};if(ljt(e.name))return t6(Rx),{result:!0};if(djt(Rx))return l;if(s&&s.length>0)try{let u=_d(s),d=sjt(e.name,t),g=await ajt(u,d,[e],r.abortController.signal);return g.shouldBlock?(uFe(Rx),{result:!1,message:g.reason||"Auto mode denied this action.",behavior:"deny"}):(t6(Rx),{result:!0})}catch(u){if(u.name==="AbortError")throw u;return Ie(u),l}}return l};function S$n(e,t,r){switch(e){case Li:return r?`${Li.name}(${r}:*)`:`${Li.name}(${Li.renderToolUseMessage(t)})`;case am:return r?`${am.name}(${r}:*)`:`${am.name}(${am.renderToolUseMessage(t)})`;case eS:case nS:case tS:return`${e.name}(${t.file_path})`;case Th:return`${e.name}(${t.notebook_path})`;case w3:let n=t.url||"",i=Ijt(n);return i?`${e.name}(domain:${i})`:e.name;default:if(e.name===Dn){let o=t.subagent_type||t.name;return o?`${Dn}(${o})`:Dn}return e.name}}De();Cr();He();import{randomUUID as T$n}from"node:crypto";var Tjt={readFileTimestamps:{}},v$n=1800*1e3,x$n=300*1e3,w$n=[kX],vjt=vFt();async function D$n(e,t,r=Tjt.readFileTimestamps){try{if(!await e.isEnabled())throw new Error(`Tool ${e.name} is not enabled`);let n=await BA(),i={abortController:new AbortController,options:{commands:w$n,tools:vjt,slowAndCapableModel:n,thinking:"off"},readFileTimestamps:r,agentDepth:0},o=await e.validateInput?.(t??{},i);if(o&&!o.result){let u=`Tool ${e.name} input is invalid: ${o.message}`;return{isError:!0,content:[{type:"text",text:u}],_meta:{[D4]:{validationError:!0,message:o.message,resultForAssistant:u}}}}let s=e.call(t??{},i,xoe),a=await fke(s);if(a.type!=="result")throw new Error(`Tool ${e.name} did not return a result`);let l=typeof a.resultForAssistant=="string"?a.resultForAssistant:JSON.stringify(a.data),c={data:a.data,resultForAssistant:l};return{content:[{type:"text",text:l}],_meta:{[D4]:c}}}catch(n){return Ie(n),{isError:!0,content:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}async function xjt(e=Tjt.readFileTimestamps){let t=new J$({name:`${Ht}/hands`,version:MACRO.VERSION},{capabilities:{tools:{}}}),r=await Promise.all(vjt.map(async n=>({tool:n,description:n.description?await n.description():""})));for(let{tool:n,description:i}of r)t.registerTool(n.name,{description:i,inputSchema:n.inputSchema},(async o=>D$n(n,o,e)));return t}function wjt(e){let t=async()=>{try{await e()}catch(r){Ie(r)}finally{process.exit(0)}};process.on("SIGINT",t),process.on("SIGTERM",t)}async function R$n(e){let t=[];for await(let n of e)t.push(n);let r=Buffer.concat(t).toString("utf8");return r?JSON.parse(r):void 0}async function N$n(){let e=await xjt();wjt(async()=>{await e.close()});let t=new X$;await e.connect(t),console.error(`${Ht} Hands MCP server running on stdio`)}async function B$n(e){let t=new Map;function r(c){let u=c.headers["mcp-session-id"];return Array.isArray(u)?u[0]:u}async function n(c){let u=t.get(c);if(u){t.delete(c);try{await u.server.close()}catch(d){Ie(d)}}}async function i(){let c={},u=await xjt(c),d,g=new iH({sessionIdGenerator:()=>T$n(),enableJsonResponse:!0,onsessioninitialized:A=>{d=A,t.set(A,m)},onsessionclosed:A=>{n(A)}});await u.connect(g);let m={server:u,transport:g,readFileTimestamps:c,lastUsedAt:Date.now()};return d!==void 0&&!t.has(d)&&t.set(d,m),m}function o(){let c=Date.now();for(let[u,d]of t)c-d.lastUsedAt>v$n&&n(u)}let s=setInterval(o,x$n);s.unref();let a=I$n(async(c,u)=>{if(c.url!=="/mcp"){u.statusCode=404,u.setHeader("Content-Type","application/json"),u.end(JSON.stringify({error:"Not Found"}));return}if(c.method!=="GET"&&c.method!=="POST"&&c.method!=="DELETE"){u.statusCode=405,u.setHeader("Content-Type","application/json"),u.setHeader("Allow","GET, POST, DELETE"),u.end(JSON.stringify({error:"Method Not Allowed"}));return}try{let d=r(c),g;if(d!==void 0){if(g=t.get(d),!g){u.statusCode=404,u.setHeader("Content-Type","application/json"),u.end(JSON.stringify({error:"Session not found"}));return}}else g=await i();g.lastUsedAt=Date.now();let m=c.method==="POST"?await R$n(c):void 0;await g.transport.handleRequest(c,u,m)}catch(d){Ie(d),u.headersSent||(u.statusCode=500,u.setHeader("Content-Type","application/json"),u.end(JSON.stringify({error:d instanceof Error?d.message:String(d)})))}}),l=await O$n(a,e,10);console.error(`${Ht} Hands MCP server running on http://localhost:${l}/mcp`),console.error("WARNING: HTTP transport has no authentication. Only use behind a reverse proxy or in a secured setup."),wjt(async()=>{clearInterval(s),await Promise.all(Array.from(t.keys()).map(c=>n(c))),await new Promise(c=>{a.close(()=>c())})})}function O$n(e,t,r){return new Promise((n,i)=>{let o=(s,a)=>{let l=u=>{if(e.removeListener("listening",c),u.code==="EADDRINUSE"&&a>0){c9.getAvailablePort().then(d=>{if(d==null){i(new Error("No available port in range 3000-3999 after retries"));return}setImmediate(()=>o(d,a-1))}).catch(i);return}i(u)},c=()=>{e.removeListener("error",l),n(s)};e.once("error",l),e.once("listening",c),e.listen(s,"0.0.0.0")};o(t,r)})}async function yCo(e){await Ul(e);let t=(process.env.MCP_TRANSPORT||"http").toLowerCase();if(t==="stdio"){await N$n();return}if(t==="http"){let r;if(process.env.PORT)r=parseInt(process.env.PORT,10);else{let n=await c9.getAvailablePort();n==null&&(console.error("No available port in range 3000-3999. Set PORT environment variable to specify one."),process.exit(1)),r=n}await B$n(r);return}console.error(`Unknown transport: ${t}. Use MCP_TRANSPORT=stdio or MCP_TRANSPORT=http`),process.exit(1)}export{yCo as startMCPServer};
3235
3235
  /*! Bundled license information:
3236
3236
 
3237
3237
  react/cjs/react.production.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dahawa/hawa-code",
3
- "version": "2.9.4",
3
+ "version": "2.9.5",
4
4
  "bin": {
5
5
  "hcode": "hawa.js"
6
6
  },
package/server.js CHANGED
@@ -596,7 +596,7 @@ data: ${JSON.stringify(L)}
596
596
  `);a=P.pop()||"";for(let L of P){let j=L.trim();if(!(!j||j==="data: [DONE]"))if(j.startsWith("data: ")){let z=j.slice(6);try{let W=JSON.parse(z);D(W)}catch(W){this.logger&&this.logger.error({err:W,line:j},"Failed to parse Gemini SSE chunk")}}else try{let z=JSON.parse(j);D(z)}catch{}}};(async()=>{try{for(;;){let{value:P,done:L}=await s.read();if(L)break;a+=n.decode(P,{stream:!0}),M()}T()}catch(P){o.error(P)}})()}})}convertGeminiResponseToAnthropic(t){this.logger&&this.logger.debug({response:t},"Original Gemini response");try{if(!t.candidates||!t.candidates[0])throw new Error("No candidates found in Gemini response");let r=t.candidates[0],n=[];r.content&&r.content.parts&&r.content.parts.forEach(o=>{if(o.text&&n.push({type:"text",text:o.text}),o.functionCall){let s=`toolu_${mN()}`,a=o.functionCall.thoughtSignature||o.functionCall.thought_signature||null;n.push({type:"tool_use",id:s,name:o.functionCall.name,input:o.functionCall.args||{},thought_signature:a})}}),r.groundingMetadata&&(this.logger&&this.logger.debug({groundingMetadata:r.groundingMetadata},"Processing grounding metadata"),r.groundingMetadata.webSearchQueries&&n.push({type:"text",text:`
597
597
 
598
598
  [Search queries used: ${r.groundingMetadata.webSearchQueries.join(", ")}]`}));let i={id:`msg_${Math.random().toString(36).slice(2)}`,type:"message",role:"assistant",model:t.modelVersion||"gemini",content:n,stop_reason:r.finishReason?r.finishReason==="STOP"&&n.some(o=>o.type==="tool_use")?"tool_use":this.mapGeminiFinishReason(r.finishReason):"end_turn",stop_sequence:null,usage:{input_tokens:t.usageMetadata?.promptTokenCount||0,output_tokens:t.usageMetadata?.candidatesTokenCount||0}};return this.logger&&this.logger.debug({result:i},"Conversion complete, final Anthropic response"),i}catch{throw rLr(`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"}}},age=new sge;var Uat=De(Pat(),1);jt();Fo();function Wm(e){return e?typeof e.entries=="function"?Object.fromEntries(e.entries()):{...e}:{}}function Lat(e){let t=String(e?.["x-thinking-level"]??"medium").toLowerCase();return["off","low","medium","high"].includes(t)?t:"medium"}function AYr(e,t){if(t==="off"){delete e.reasoning;return}e.reasoning={effort:t}}function hYr(e,t){if(t==="off"){delete e.reasoning;return}e.reasoning={effort:t,summary:"auto"}}function EYr(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 gF(e,t,r){U8(t,e),$8(t,EYr(e,r),r)}function rB(e){let t=[],r=e.getReader(),n,i=new Promise(l=>n=l),o=!1,s=()=>{o||(o=!0,n(Buffer.concat(t).toString("utf8")))};return{stream:new ReadableStream({async pull(l){try{let{done:c,value:u}=await r.read();if(c){l.close(),s();return}t.push(u),l.enqueue(u)}catch(c){l.error(c),s()}},cancel(l){r.cancel(l).catch(()=>{}),s()}}),done:i}}function AF(e){let t=new Headers(e);return t.delete("content-encoding"),t.delete("content-length"),t.delete("transfer-encoding"),t}function M0e(e,t,r,n,i){let o;try{o={type:"error",error:{type:"api_error",message:JSON.parse(i).error?.message??`${e}: ${n}`,code:`${t}_${r}_ERROR`}}}catch{o={type:"error",error:{type:"api_error",message:`${e}: ${n}`,code:`${t}_${r}_ERROR`}}}return new Response(JSON.stringify(o),{status:r,statusText:n,headers:{"Content-Type":"application/json"}})}var Fat=["/v1/messages"];function Q0e(e){let t;try{typeof e=="string"?t=new mT(e):e instanceof mT?t=e:t=new mT(e.url)}catch{return""}let r=t.pathname;for(let n of Fat){let i=r.indexOf(n);if(i!==-1)return t.origin+r.slice(0,i)}return t.origin}function oW(e,t){let r=typeof e=="string"?e:e instanceof mT?e.toString():e.url,n;try{n=new mT(r).pathname}catch{return!1}return Fat.some(i=>n.includes(i))&&(t.method==="POST"||t.method==="post")}function _Yr(e){return async(t,r)=>{if(!oW(t,r))return e(t,r);let n=JSON.parse(r.body),i=await sY.transformRequestOut(n),o=Q0e(t)+"/chat/completions",s=Wm(r.headers),a=s.authorization??s.Authorization??"";AYr(i,Lat(s));let l=await e(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:a},body:JSON.stringify(i),signal:r.signal});if(!l.ok){let y=await l.text();return V(`OpenAI Chat Completions API error: ${l.status}`,{url:o,errorResponse:y}),M0e("OpenAI Chat Completions API error","OPENROUTER",l.status,l.statusText,y)}let c=n.stream===!0,u=s["x-agent-id"],f={request:{url:o,method:r.method,headers:s,body:n},response:{status:l.status,statusText:l.statusText,headers:Wm(l.headers)},openai:{request:{body:i},response:{}}};if(!c){let y=await l.text(),C=new Response(y,{status:l.status,statusText:l.statusText,headers:AF(l.headers)}),I=await sY.transformResponseIn(C,n),T=await I.text();try{gF({...f,openai:{...f.openai,response:{body:JSON.parse(y)}},response:{...f.response,body:JSON.parse(T)}},u)}catch(D){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Chat \u975E\u6D41\u5F0F):",D)}return new Response(T,{status:I.status,statusText:I.statusText,headers:I.headers})}let g=rB(l.body),m=new Response(g.stream,{status:l.status,statusText:l.statusText,headers:AF(l.headers)}),A=await sY.transformResponseIn(m,n),E=rB(A.body);return Promise.all([g.done,E.done]).then(async([y,C])=>{try{gF({...f,openai:{...f.openai,response:{body:await dZe(y)}},response:{...f.response,body:await aL(C)}},u)}catch(I){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Chat \u6D41\u5F0F):"+I?.stack)}}).catch(y=>V("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Chat):"+y)),new Response(E.stream,{status:A.status,statusText:A.statusText,headers:A.headers})}}function yYr(e){return async(t,r)=>{if(!oW(t,r))return e(t,r);let n=JSON.parse(r.body),i=await aY.transformRequestOut(n),o=Wm(r.headers);hYr(i,Lat(o));let s=JSON.stringify(i),l=Q0e(t)+"/responses",c=o.authorization??o.Authorization??"";if(!c)return new Response(JSON.stringify({type:"error",error:{type:"api_error",message:"Missing Authorization header",code:"RESPONSES_AUTH_MISSING"}}),{status:401,headers:{"Content-Type":"application/json"}});let u=await e(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:c,"x-api-key":c.replace(/^Bearer\s+/i,"").trim()},body:s,signal:r.signal});if(!u.ok){let I=await u.text();return V(`OpenAI Responses API error: ${u.status} ${u.statusText}`,{url:l,status:u.status,errorResponse:I}),M0e("OpenAI Responses API error","RESPONSES",u.status,u.statusText,I)}let f=n.stream===!0,g=o["x-agent-id"],m={request:{url:l,method:r.method,headers:o,body:n},response:{status:u.status,statusText:u.statusText,headers:Wm(u.headers)},openai:{request:{body:i},response:{}}};if(!f){let I=await u.text(),T=new Response(I,{status:u.status,statusText:u.statusText,headers:AF(u.headers)}),D=await aY.transformResponseIn(T,n),M=await D.text();try{gF({...m,openai:{...m.openai,response:{body:JSON.parse(I)}},response:{...m.response,body:JSON.parse(M)}},g,"responses")}catch(P){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Responses \u975E\u6D41\u5F0F):",P)}return new Response(M,{status:D.status,statusText:D.statusText,headers:D.headers})}let A=rB(u.body),E=new Response(A.stream,{status:u.status,statusText:u.statusText,headers:AF(u.headers)}),y=await aY.transformResponseIn(E,n),C=rB(y.body);return Promise.all([A.done,C.done]).then(async([I,T])=>{try{gF({...m,openai:{...m.openai,response:{body:await uZe(I)}},response:{...m.response,body:await aL(T)}},g,"responses")}catch(D){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Responses \u6D41\u5F0F):"+D?.stack)}}).catch(I=>V("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Responses):"+I)),new Response(C.stream,{status:y.status,statusText:y.statusText,headers:y.headers})}}function bYr(e){return async(t,r)=>{if(!oW(t,r))return e(t,r);let n=JSON.parse(r.body),i=Wm(r.headers),o=await age.transformRequestOut(n),s=JSON.stringify(o),a=Q0e(t)+`/models/${n.model}:streamGenerateContent?alt=sse`,l=i.authorization??i.Authorization??"",c;try{c=await e(a,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":String(l).replace(/^Bearer\s+/i,"").trim()},body:s,signal:r.signal})}catch(C){throw V("gemini request error:",C),C}if(!c.ok){let C=await c.text();return V(`Gemini API error response: ${c.status} ${c.statusText}`,{url:a,status:c.status,errorResponse:C}),M0e("Gemini API error","Gemini",c.status,c.statusText,C)}let u=n.stream===!0,f=i["x-agent-id"],g={request:{url:a,method:r.method,headers:Wm(r.headers),body:n},response:{status:c.status,statusText:c.statusText,headers:Wm(c.headers)},openai:{request:{body:o},response:{}}},m=rB(c.body),A=new Response(m.stream,{status:c.status,statusText:c.statusText,headers:AF(c.headers)}),E=await age.transformResponseIn(A),y=rB(E.body);return Promise.all([m.done,y.done]).then(async([C,I])=>{try{let T=u?fZe(C):JSON.parse(C),D=u?await aL(I):JSON.parse(I);gF({...g,openai:{...g.openai,response:{body:T}},response:{...g.response,body:D}},f)}catch(T){V("\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF(Gemini):"+T?.stack)}}).catch(C=>V("\u65E5\u5FD7\u805A\u5408\u9519\u8BEF(Gemini):"+C)),new Response(y.stream,{status:E.status,statusText:E.statusText,headers:E.headers})}}function CYr(e){return async(t,r)=>{if(!oW(t,r))return e(t,r);let n=r.body;if(r.body)try{let f=JSON.parse(r.body);n=JSON.stringify(f)}catch{}let i=Wm(r.headers);["1","true"].includes(String(process.env.HAWA_CODE_X_API_KEY_DISABLED??"").toLowerCase())&&(delete i["x-api-key"],delete i["X-API-Key"]),["1","true"].includes(String(process.env.HAWA_CODE_AUTH_DISABLED??"").toLowerCase())&&(delete i.authorization,delete i.Authorization),delete i["content-length"];let a=await e(t,{method:r.method,headers:i,body:n,signal:r.signal});if(!a.ok){let f=await a.text();V(`API error response: ${a.status} ${a.statusText}`,{url:typeof t=="string"?t:t instanceof mT?t.toString():t.url,status:a.status,errorResponse:f});let g;try{let m=JSON.parse(f);g={type:"error",error:{type:"api_error",message:m.error?.message||m.message||`API error: ${a.statusText}`,code:m.error?.code||m.code||`API_${a.status}_ERROR`}},m.error?.details&&(g.error.details=m.error.details)}catch{g={type:"error",error:{type:"api_error",message:`API error: ${a.statusText}`,code:`API_${a.status}_ERROR`}}}return new Response(JSON.stringify(g),{status:a.status,statusText:a.statusText,headers:{"Content-Type":"application/json"}})}let l=a.clone(),c=!(Object.hasOwn(JSON.parse(n),"stream")&&!JSON.parse(n).stream),u={request:{url:typeof t=="string"?t:t instanceof mT?t.toString():t.url,method:r.method,headers:Wm(r.headers),body:JSON.parse(n)},response:{status:a.status,statusText:a.statusText,headers:Wm(a.headers)}};return(async()=>{if(c){let m=await a.text();u.response.body=await aL(m)}else u.response.body=await a.json();let g=Wm(r.headers)["x-agent-id"];U8(g,u),$8(g,{request:u.request.body.messages,response:u.response.body.content,usage:u.response.body?.usage})})().catch(f=>V(`\u65E5\u5FD7\u89E3\u6790\u9519\u8BEF:
599
- Stack trace: `+f.stack)),new Response(l.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}var iW=null,k0e=!1;function SYr(){iW=null,k0e=!1}It.on("proxy:changed",SYr);function IYr(){if(k0e)return iW;if(k0e=!0,Ge().proxy!==!0)return null;let e=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;return e&&(iW=new Uat.ProxyAgent({uri:e}),rt(`[proxy] using proxy: ${e}`)),iW}function TYr(){let e=IYr();return e?((t,r={})=>global.fetch(t,{...r,dispatcher:e})):global.fetch}function sW(e){let t=e||process.env.API_TYPE,r=TYr();switch(t){case"openai":return _Yr(r);case"openai-responses":return yYr(r);case"gemini":return bYr(r);default:return CYr(r)}}HA();var NYr=De(Xe(),1);function qat(e,t){let r=[],n=Math.max(1,Math.floor(t)),i="",o=0;for(let s of e){let a=wYr(s);i&&o+a>n?(r.push(i),i=s,o=a):(i+=s,o+=a)}return i&&r.push(i),r}function wYr(e){if(e===" ")return 4;let t=e.codePointAt(0);return t===void 0||t===0||t<32||t>=127&&t<160||DYr(t)?0:RYr(t)?2:1}function DYr(e){return e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071}function RYr(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=127744&&e<=128591||e>=129280&&e<=129535||e>=131072&&e<=262141)}function hF(e){if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),n=(e%6e4/1e3).toFixed(1);return t>0?`${t}h ${r}m ${n}s`:r>0?`${r}m ${n}s`:`${n}s`}function aW(e){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(e).toLowerCase()}xe();Fo();var jl={totalCost:0,totalAPIDuration:0,startTime:Date.now(),inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,currentContextTokens:0};function lW(e,t){jl.totalCost+=e,jl.totalAPIDuration+=t}function cW(e,t){jl.inputTokens+=e,jl.outputTokens+=t,It.emit("token:change",{inputTokens:jl.inputTokens,outputTokens:jl.outputTokens})}function uW(e,t){jl.cacheCreationTokens+=e,jl.cacheReadTokens+=t}function EF(){return{inputTokens:jl.inputTokens,outputTokens:jl.outputTokens,cacheCreationTokens:jl.cacheCreationTokens,cacheReadTokens:jl.cacheReadTokens}}function Gat(){return jl.totalCost}function zat(){return Date.now()-jl.startTime}function jat(){return jl.totalAPIDuration}function Yat(e){jl.currentContextTokens=e}function Vat(){return jl.currentContextTokens}xe();He();He();var F0e="2.9.4";globalThis.MACRO={VERSION:F0e,PACKAGE_URL:`@dahawa/${ji}`,README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var dW=process.env.HAWA_CODE_USER_AGENT||`${ji}/${F0e} (${process.env.USER_TYPE})`;xe();xe();ir();function fd(e,t){let r=[],n=new Set,i=new Set;return e.filter(o=>o.type!=="progress"&&o.type!=="reminder").forEach(o=>{switch(o.type){case"user":{let s=tA(r);if(s?.type==="user"){r[r.length-1]=U0e(s,o);return}r.push(o);return}case"assistant":r.push(o);return;case"insert":{let s=tA(r);s?.type==="user"&&(r[r.length-1]=BYr(s,o));return}case"path_rules":{let s=t?.pathRules;if(!s)return;let a=o.content.paths.filter(f=>!n.has(f));if(a.length===0)return;let l=a.map(f=>s.get(f)).filter(f=>f!==void 0);if(a.forEach(f=>n.add(f)),l.length===0)return;let c=Ct([{type:"text",text:`<system-rules>
599
+ Stack trace: `+f.stack)),new Response(l.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}var iW=null,k0e=!1;function SYr(){iW=null,k0e=!1}It.on("proxy:changed",SYr);function IYr(){if(k0e)return iW;if(k0e=!0,Ge().proxy!==!0)return null;let e=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;return e&&(iW=new Uat.ProxyAgent({uri:e}),rt(`[proxy] using proxy: ${e}`)),iW}function TYr(){let e=IYr();return e?((t,r={})=>global.fetch(t,{...r,dispatcher:e})):global.fetch}function sW(e){let t=e||process.env.API_TYPE,r=TYr();switch(t){case"openai":return _Yr(r);case"openai-responses":return yYr(r);case"gemini":return bYr(r);default:return CYr(r)}}HA();var NYr=De(Xe(),1);function qat(e,t){let r=[],n=Math.max(1,Math.floor(t)),i="",o=0;for(let s of e){let a=wYr(s);i&&o+a>n?(r.push(i),i=s,o=a):(i+=s,o+=a)}return i&&r.push(i),r}function wYr(e){if(e===" ")return 4;let t=e.codePointAt(0);return t===void 0||t===0||t<32||t>=127&&t<160||DYr(t)?0:RYr(t)?2:1}function DYr(e){return e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071}function RYr(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=127744&&e<=128591||e>=129280&&e<=129535||e>=131072&&e<=262141)}function hF(e){if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),n=(e%6e4/1e3).toFixed(1);return t>0?`${t}h ${r}m ${n}s`:r>0?`${r}m ${n}s`:`${n}s`}function aW(e){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(e).toLowerCase()}xe();Fo();var jl={totalCost:0,totalAPIDuration:0,startTime:Date.now(),inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,currentContextTokens:0};function lW(e,t){jl.totalCost+=e,jl.totalAPIDuration+=t}function cW(e,t){jl.inputTokens+=e,jl.outputTokens+=t,It.emit("token:change",{inputTokens:jl.inputTokens,outputTokens:jl.outputTokens})}function uW(e,t){jl.cacheCreationTokens+=e,jl.cacheReadTokens+=t}function EF(){return{inputTokens:jl.inputTokens,outputTokens:jl.outputTokens,cacheCreationTokens:jl.cacheCreationTokens,cacheReadTokens:jl.cacheReadTokens}}function Gat(){return jl.totalCost}function zat(){return Date.now()-jl.startTime}function jat(){return jl.totalAPIDuration}function Yat(e){jl.currentContextTokens=e}function Vat(){return jl.currentContextTokens}xe();He();He();var F0e="2.9.5";globalThis.MACRO={VERSION:F0e,PACKAGE_URL:`@dahawa/${ji}`,README_URL:"https://github.com/italking/hawa-code",ISSUES_EXPLAINER:"report the issue at https://github.com/italking/hawa-code/issues"};var dW=process.env.HAWA_CODE_USER_AGENT||`${ji}/${F0e} (${process.env.USER_TYPE})`;xe();xe();ir();function fd(e,t){let r=[],n=new Set,i=new Set;return e.filter(o=>o.type!=="progress"&&o.type!=="reminder").forEach(o=>{switch(o.type){case"user":{let s=tA(r);if(s?.type==="user"){r[r.length-1]=U0e(s,o);return}r.push(o);return}case"assistant":r.push(o);return;case"insert":{let s=tA(r);s?.type==="user"&&(r[r.length-1]=BYr(s,o));return}case"path_rules":{let s=t?.pathRules;if(!s)return;let a=o.content.paths.filter(f=>!n.has(f));if(a.length===0)return;let l=a.map(f=>s.get(f)).filter(f=>f!==void 0);if(a.forEach(f=>n.add(f)),l.length===0)return;let c=Ct([{type:"text",text:`<system-rules>
600
600
  ${U7e(l)}
601
601
  </system-rules>`}]),u=tA(r);u?.type==="user"?r[r.length-1]=U0e(u,c,{skipTrailingSystemReminders:!0}):r.push(c);return}case"systemAutoMemory":{let s=t?.autoMemories;if(!s)return;let a=o.content.paths.filter(f=>!i.has(f));a.forEach(f=>i.add(f));let l=a.map(f=>{let g=s.get(f);return g===void 0||g.length===0?null:`## ${f.split(/[\\/]/).pop()||f}
602
602
  ${g}`}).filter(f=>f!==null);if(l.length===0)return;let c=Ct([{type:"text",text:`<system-auto-memory>
@@ -2969,7 +2969,7 @@ CREATE TABLE IF NOT EXISTS index_state (
2969
2969
  file_size INTEGER NOT NULL DEFAULT 0,
2970
2970
  file_mtime_ms INTEGER NOT NULL DEFAULT 0
2971
2971
  );
2972
- `;function x3(){if(!Gie())return null;if(R_)return R_;if(QQe)return null;let e=h7t();if(!e)return QQe=!0,A7t||(A7t=!0,Ce("hmemory: better-sqlite3 \u4E0D\u53EF\u7528\uFF0C\u6D88\u606F\u641C\u7D22\u529F\u80FD\u5DF2\u7981\u7528\uFF08JSONL \u6301\u4E45\u5316\u4E0D\u53D7\u5F71\u54CD\uFF09")),null;try{let t=zn.searchDb();return f6n(p6n(t),{recursive:!0}),R_=new e(t),R_.pragma("journal_mode = WAL"),R_.pragma("synchronous = NORMAL"),R_.pragma("busy_timeout = 3000"),R_.exec(m6n),R_}catch(t){return R_=null,QQe=!0,Ce("hmemory: \u6253\u5F00 search.db \u5931\u8D25\uFF0C\u6D88\u606F\u641C\u7D22\u529F\u80FD\u5DF2\u7981\u7528",t),null}}xe();Ay();var nAo=256*1024,A6n=10,h6n=50;function E6n(e){let t=e.split(/[^\p{L}\p{N}]+/u).map(r=>r.trim()).filter(r=>r.length>0);return t.length===0?null:t.map(r=>`"${r.replace(/"/g,'""')}"`).join(" AND ")}function _6n(e){return e.replace(/[\\%_]/g,t=>`\\${t}`)}var w3="id AS messageId, session_id AS sessionId, agent_id AS agentId, uuid, parent_uuid AS parentUuid, type, role, timestamp, content_text AS contentText, source_file AS sourceFile, source_line AS sourceLine";function y6n(e){let t=[],r=[];return e.sessionId&&(t.push("m.session_id = ?"),r.push(e.sessionId)),e.type&&(t.push("m.type = ?"),r.push(e.type)),e.role&&(t.push("m.role = ?"),r.push(e.role)),e.since!==void 0&&(t.push("m.timestamp >= ?"),r.push(e.since)),e.until!==void 0&&(t.push("m.timestamp <= ?"),r.push(e.until)),{where:t.length?" AND "+t.join(" AND "):"",params:r}}function PQe(e){return e===""||e===null?null:e}function LQe(e,t={}){let r=x3();if(!r)return[];let n=e.trim();if(!n)return[];let i=Math.min(t.limit??A6n,h6n),o=t.offset??0,{where:s,params:a}=y6n(t);try{if(n.length<3)return r.prepare(`SELECT m.id AS messageId, m.session_id AS sessionId, m.agent_id AS agentId, m.uuid,
2972
+ `;function x3(){if(!Gie())return null;if(R_)return R_;if(QQe)return null;let e=h7t();if(!e)return QQe=!0,A7t||(A7t=!0,Ce("hmemory: better-sqlite3 \u4E0D\u53EF\u7528\uFF0C\u6D88\u606F\u641C\u7D22\u529F\u80FD\u5DF2\u7981\u7528\uFF08JSONL \u6301\u4E45\u5316\u4E0D\u53D7\u5F71\u54CD\uFF09")),null;try{let t=zn.searchDb();return f6n(p6n(t),{recursive:!0}),R_=new e(t),R_.pragma("journal_mode = WAL"),R_.pragma("synchronous = NORMAL"),R_.pragma("busy_timeout = 3000"),R_.exec(m6n),R_}catch(t){return R_=null,QQe=!0,Ce("hmemory: \u6253\u5F00 search.db \u5931\u8D25\uFF0C\u6D88\u606F\u641C\u7D22\u529F\u80FD\u5DF2\u7981\u7528",t),null}}xe();Ay();var iAo=256*1024,A6n=10,h6n=50;function E6n(e){let t=e.split(/[^\p{L}\p{N}]+/u).map(r=>r.trim()).filter(r=>r.length>0);return t.length===0?null:t.map(r=>`"${r.replace(/"/g,'""')}"`).join(" AND ")}function _6n(e){return e.replace(/[\\%_]/g,t=>`\\${t}`)}var w3="id AS messageId, session_id AS sessionId, agent_id AS agentId, uuid, parent_uuid AS parentUuid, type, role, timestamp, content_text AS contentText, source_file AS sourceFile, source_line AS sourceLine";function y6n(e){let t=[],r=[];return e.sessionId&&(t.push("m.session_id = ?"),r.push(e.sessionId)),e.type&&(t.push("m.type = ?"),r.push(e.type)),e.role&&(t.push("m.role = ?"),r.push(e.role)),e.since!==void 0&&(t.push("m.timestamp >= ?"),r.push(e.since)),e.until!==void 0&&(t.push("m.timestamp <= ?"),r.push(e.until)),{where:t.length?" AND "+t.join(" AND "):"",params:r}}function PQe(e){return e===""||e===null?null:e}function LQe(e,t={}){let r=x3();if(!r)return[];let n=e.trim();if(!n)return[];let i=Math.min(t.limit??A6n,h6n),o=t.offset??0,{where:s,params:a}=y6n(t);try{if(n.length<3)return r.prepare(`SELECT m.id AS messageId, m.session_id AS sessionId, m.agent_id AS agentId, m.uuid,
2973
2973
  m.type, m.role, m.timestamp,
2974
2974
  substr(m.content_text, 1, 500) AS snippet,
2975
2975
  0 AS rank, m.source_file AS sourceFile, m.source_line AS sourceLine