@ebowwa/coder 0.1.11 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,312 @@
1
+ // @bun
2
+ var z6=Object.create;var{getPrototypeOf:J6,defineProperty:IQ,getOwnPropertyNames:Y6}=Object;var K6=Object.prototype.hasOwnProperty;var q6=(Q,Z,$)=>{$=Q!=null?z6(J6(Q)):{};let V=Z||!Q||!Q.__esModule?IQ($,"default",{value:Q,enumerable:!0}):$;for(let X of Y6(Q))if(!K6.call(V,X))IQ(V,X,{get:()=>Q[X],enumerable:!0});return V};var f0=import.meta.require;var W0={enabled:!0,ttl:"1h",cacheSystemPrompt:!0,cacheTools:!0,minTokensForCache:1024},W6={low:1024,medium:4096,high:16384,max:1e5},U7={enabled:!1,effort:"medium",interleaved:!0};function xQ(Q,Z){if(Q.budgetTokens)return Q.budgetTokens;let $=Q.effort||"medium",V=W6[$],X=Q.modelMultiplier??(Z.includes("opus")?2:1);return Math.min(V*X,1e5)}function EQ(Q){return Q.includes("claude-opus-4")||Q.includes("claude-sonnet-4")||Q.includes("claude-haiku-4")||Q.includes("claude-4")}var w7={"claude-opus-4-6":{input:15,output:75,cache_write:18.75,cache_read:1.5},"claude-sonnet-4-6":{input:3,output:15,cache_write:3.75,cache_read:0.3},"claude-haiku-4-5":{input:0.8,output:4,cache_write:1,cache_read:0.08}};var H6={maxRetries:3,baseDelayMs:1000,maxDelayMs:30000,jitterFactor:0.2,retryableStatusCodes:[429,500,502,503,504,529],onRetry:void 0};function G6(Q,Z,$,V){let X=Z*Math.pow(2,Q),z=X*V*(Math.random()*2-1);return Math.min(X+z,$)}function _6(Q,Z){if(Q.message.includes("429")||Q.message.includes("rate limit"))return!0;if(Q.message.includes("500")||Q.message.includes("502")||Q.message.includes("503")||Q.message.includes("504"))return!0;if(Q.message.includes("ECONNREFUSED")||Q.message.includes("ENOTFOUND")||Q.message.includes("ETIMEDOUT")||Q.message.includes("network")||Q.message.includes("fetch failed"))return!0;for(let $ of Z)if(Q.message.includes(String($)))return!0;return!1}function j6(Q){return new Promise((Z)=>setTimeout(Z,Q))}async function TQ(Q,Z={}){let $={...H6,...Z},V=null;for(let X=0;X<=$.maxRetries;X++)try{return await Q()}catch(z){if(V=z instanceof Error?z:Error(String(z)),X<$.maxRetries&&_6(V,$.retryableStatusCodes)){let J=G6(X,$.baseDelayMs,$.maxDelayMs,$.jitterFactor);if($.onRetry)$.onRetry(X+1,V,J);else console.warn(`\x1B[33mRetry ${X+1}/${$.maxRetries} after ${J}ms: ${V.message}\x1B[0m`);await j6(J)}else throw V}throw V||Error("Max retries exceeded")}var yQ={"claude-opus-4-6":{input:15,output:75,cache_write:18.75,cache_read:1.5},"claude-sonnet-4-6":{input:3,output:15,cache_write:3.75,cache_read:0.3},"claude-haiku-4-5":{input:0.8,output:4,cache_write:1,cache_read:0.08},"claude-3-5-sonnet":{input:3,output:15,cache_write:3.75,cache_read:0.3},"claude-3-5-haiku":{input:0.8,output:4,cache_write:1,cache_read:0.08},"claude-3-opus":{input:15,output:75,cache_write:18.75,cache_read:1.5}};function U6(Q,Z){let $=yQ[Q]??yQ["claude-sonnet-4-6"],V=Z.input_tokens-(Z.cache_read_input_tokens??0),X=Z.cache_read_input_tokens??0,z=Z.cache_creation_input_tokens??0,J=Z.output_tokens,Y=V/1e6*$.input,K=X/1e6*$.cache_read,q=z/1e6*$.cache_write,W=J/1e6*$.output,H=Y+K+q+W,_=(X+z)/1e6*($.input-$.cache_read);return{costUSD:H,estimatedSavingsUSD:_}}function w6(Q,Z){if(!Q||!Z.enabled||!Z.cacheSystemPrompt)return typeof Q==="string"?Q:void 0;if(Array.isArray(Q)){let $=[...Q];if($.length>0){let V=$[$.length-1];if(V&&V.type==="text")$[$.length-1]={type:"text",text:V.text,cache_control:{type:"ephemeral",ttl:Z.ttl}}}return $}return[{type:"text",text:Q,cache_control:{type:"ephemeral",ttl:Z.ttl}}]}function A6(Q,Z){if(!Z.enabled)return Q;let $=[];for(let V=0;V<Q.length;V++){let X=Q[V],z=[];for(let J=0;J<X.content.length;J++){let Y=X.content[J],K=J===X.content.length-1,q=V===Q.length-1;if(Y.type==="text"&&Y.text.length>=Z.minTokensForCache*4&&!Y.cache_control&&(K||q))z.push({...Y,cache_control:{type:"ephemeral",ttl:Z.ttl}});else z.push(Y)}$.push({...X,content:z})}if($.length>0&&Z.enabled){let V=$[$.length-1],X=V.content[V.content.length-1];if(X&&!("cache_control"in X))V.content[V.content.length-1]={...X,cache_control:{type:"ephemeral",ttl:Z.ttl}}}return $}function B6(Q){let Z=Q.cache_read_input_tokens??0,$=Q.cache_creation_input_tokens??0,V=Z+$,X=Z>0?1:0,z=$>0?1:0,J=X+z;return{cacheHits:X,cacheMisses:z,totalCacheReadTokens:Z,totalCacheWriteTokens:$,cacheHitRate:J>0?X/J:0,estimatedSavingsUSD:0}}async function kQ(Q,Z){let{apiKey:$,model:V="claude-sonnet-4-6",maxTokens:X=4096,tools:z,systemPrompt:J,cacheConfig:Y=W0,thinking:K,extendedThinking:q,stopSequences:W,onToken:H,onThinking:G,onRedactedThinking:_,onToolUse:U,signal:j}=Z,A=Date.now(),w=0,B=!0,O=0,v=A6(Q,Y),L=w6(J,Y),I={model:V,max_tokens:X,messages:v.map((R)=>({role:R.role,content:R.content})),stream:!0};if(L)I.system=L;if(z&&z.length>0)I.tools=z;if(W&&W.length>0)I.stop_sequences=W;let e=`${process.env.ANTHROPIC_BASE_URL||"https://api.anthropic.com"}/v1/messages`,P={"Content-Type":"application/json","x-api-key":$,"anthropic-version":"2023-06-01"};if(((q?.enabled??!1)||K&&K.type!=="disabled")&&EQ(V)){let R;if(q?.budgetTokens)R=q.budgetTokens;else if(K?.type==="enabled")R=K.budget_tokens;else{let v9=q?.effort||"medium";R=xQ({enabled:!0,effort:v9,modelMultiplier:V.includes("opus")?2:1},V)}R=Math.max(1024,Math.min(R,1e5)),I.thinking={type:"enabled",budget_tokens:R};let o=["extended-thinking-2025-01-24"];if(q?.interleaved!==!1)o.push("interleaved-thinking-2025-01-24");P["anthropic-beta"]=o.join(",")}else P["anthropic-beta"]="max-tokens-3-5-sonnet-2024-07-15";let b9={maxRetries:3,baseDelayMs:1000,maxDelayMs:30000,retryableStatusCodes:[429,500,502,503,504,529],onRetry:(R,o,v9)=>{console.log(`\x1B[33mAPI retry ${R}/3 after ${v9}ms: ${o.message}\x1B[0m`)}},Q9=await TQ(async()=>{let R=await fetch(e,{method:"POST",headers:P,body:JSON.stringify(I),signal:j});if(!R.ok&&b9.retryableStatusCodes?.includes(R.status)){let o=await R.text();throw Error(`API error: ${R.status} - ${o}`)}return R},b9);if(!Q9.ok){let R=await Q9.text();throw Error(`API error: ${Q9.status} - ${R}`)}if(!Q9.body)throw Error("No response body");let f9=Q9.body.getReader(),u9=new TextDecoder,q9=null,W9=[],H9={input_tokens:0,output_tokens:0},k=null,A9=null,Z9=null,c=null,O9="",h9=new Map,SQ="";try{let R="";while(!0){let{done:o,value:v9}=await f9.read();if(o)break;R+=u9.decode(v9,{stream:!0});let g9=R.split(`
3
+ `);R=g9.pop()||"";for(let d9 of g9){if(!d9.startsWith("data: "))continue;let N9=d9.slice(6);if(!N9)continue;try{let V9=JSON.parse(N9);switch(V9.type){case"message_start":{let F=V9.message;q9=F,H9=F.usage;break}case"content_block_start":{let{index:F,content_block:M}=V9;if(h9.set(F,M.type),M.type==="text")k={type:"text",text:""};else if(M.type==="thinking")A9={type:"thinking",thinking:""};else if(M.type==="redacted_thinking")Z9={type:"redacted_thinking",data:""};else if(M.type==="tool_use")c={type:"tool_use",id:M.id,name:M.name,input:{}},O9="";break}case"content_block_delta":{let F=V9.delta;if(F.type==="text_delta"&&k){let M=F.text;if(k.text+=M,H?.(M),B)w=Date.now()-A,B=!1}else if(F.type==="thinking_delta"&&A9){let M=F.thinking;A9.thinking+=M,G?.(M),O+=Math.ceil(M.length/4)}else if(F.type==="redacted_thinking_delta"&&Z9){let M=F.data;Z9.data+=M,_?.(M),O+=Math.ceil(M.length/4)}else if(F.type==="input_json_delta"&&c)O9+=F.partial_json;break}case"content_block_stop":{let F=V9.index,M=h9.get(F);if(M==="text"&&k)W9.push(k),k=null;else if(M==="thinking"&&A9)W9.push(A9),A9=null;else if(M==="redacted_thinking"){let C={type:"redacted_thinking",data:Z9?.data||""};W9.push(C),_?.(C.data),Z9=null}else if(M==="tool_use"&&c){try{c.input=JSON.parse(O9)}catch{c.input={}}W9.push(c),U?.({id:c.id,name:c.name,input:c.input}),c=null}h9.delete(F);break}case"message_delta":{let F=V9;if(F.usage)H9.output_tokens=F.usage.output_tokens;if(q9&&F.delta?.stop_reason)q9.stop_reason=F.delta.stop_reason;break}case"message_stop":break}}catch{}}}}finally{f9.releaseLock()}if(!q9)throw Error("No message received from API");q9.content=W9;let{costUSD:k0,estimatedSavingsUSD:G9}=U6(V,H9),P9=B6(H9);P9.estimatedSavingsUSD=G9;let $9=Date.now()-A;return{message:q9,usage:H9,cacheMetrics:P9,costUSD:k0,durationMs:$9,ttftMs:w||$9,thinkingTokens:O}}import*as bQ from"readline";var L6={Read:"low",Glob:"low",Grep:"low",Task:"low",Write:"medium",Edit:"medium",NotebookEdit:"medium",Bash:"high"},F6=[/\brm\s+-rf\b/,/\brm\s+-r\b/,/\brm\s+[^-]/,/\bgit\s+push\s+--force\b/,/\bgit\s+reset\s+--hard\b/,/\bgit\s+clean\s+-fd\b/,/\bdrop\b/i,/\bdelete\b/i,/\btruncate\b/i,/\bformat\b/i,/\bdd\s+if=/,/\bshred\b/,/\b:\(\)\{\s*:\|:\s*&\s*\};\s*:\b/];function O6(Q,Z){let $=L6[Q]??"medium";if(Q==="Bash"){let V=String(Z.command??"");for(let X of F6)if(X.test(V))return"critical";if(/\bsudo\b/.test(V)||/\bchmod\b/.test(V))$="high"}if(Q==="Write"||Q==="Edit"){let V=String(Z.file_path??Z.path??"");if(/\.(env|pem|key|secret|credentials)/.test(V))$="high";if(/\/\.ssh\//.test(V)||/\/\.gnupg\//.test(V))$="critical"}return $}function v6(Q,Z){switch(Q){case"Read":return`Read file: ${Z.file_path??"unknown"}`;case"Write":return`Write file: ${Z.file_path??"unknown"} (${String(Z.content??"").length} chars)`;case"Edit":return`Edit file: ${Z.file_path??"unknown"}`;case"Bash":return`Execute: ${String(Z.command??"").slice(0,100)}${String(Z.command??"").length>100?"...":""}`;case"Glob":return`Find files: ${Z.pattern??"*"}`;case"Grep":return`Search: "${Z.pattern??""}" in ${Z.path??"."}`;case"Task":return`Spawn agent: ${Z.subagent_type??"unknown"}`;default:return`Use tool: ${Q}`}}class u0{cache={};cacheTimeout=300000;promptCallback;mode;constructor(Q="default",Z){this.mode=Q,this.promptCallback=Z??this.defaultPrompt.bind(this)}async checkPermission(Q,Z){if(this.mode==="bypassPermissions")return{decision:"allow"};if(this.mode==="dontAsk")return{decision:"deny",reason:"Permission mode is dontAsk"};if(this.mode==="acceptEdits"){if(["Read","Write","Edit","Glob","Grep"].includes(Q))return{decision:"allow"}}if(this.mode==="plan"){if(["Read","Glob","Grep","Task"].includes(Q))return{decision:"allow"};return{decision:"deny",reason:"Plan mode - write operations disabled"}}let $=this.getCacheKey(Q,Z),V=this.cache[$];if(V&&Date.now()-V.timestamp<this.cacheTimeout){if(V.decision==="allowAlways")return{decision:"allow",reason:"Previously approved (always)"};if(V.decision==="denyAlways")return{decision:"deny",reason:"Previously denied (always)"}}let X=O6(Q,Z),z=v6(Q,Z),J={toolName:Q,toolInput:Z,riskLevel:X,description:z,file:Z.file_path??Z.path,command:Q==="Bash"?Z.command:void 0};if(this.mode==="interactive"||this.mode==="default"){let Y=await this.promptCallback(J);if(Y.decision==="allowAlways"||Y.decision==="denyAlways")this.cache[$]={decision:Y.decision,timestamp:Date.now()};return Y}return{decision:"allow"}}getCacheKey(Q,Z){if(["Read","Write","Edit"].includes(Q))return`${Q}:${Z.file_path??Z.path??"unknown"}`;if(Q==="Bash"){let $=String(Z.command??"").slice(0,100);return`${Q}:${$}`}return Q}async defaultPrompt(Q){return new Promise((Z)=>{let $=bQ.createInterface({input:process.stdin,output:process.stdout}),X={low:"\x1B[32m",medium:"\x1B[33m",high:"\x1B[31m",critical:"\x1B[35m"}[Q.riskLevel]??"\x1B[0m",z="\x1B[0m";if(console.log(""),console.log("\x1B[36m\u2501\u2501\u2501 Permission Required \u2501\u2501\u2501\x1B[0m"),console.log(`Tool: \x1B[1m${Q.toolName}\x1B[0m`),console.log(`Risk: ${X}${Q.riskLevel.toUpperCase()}\x1B[0m`),console.log(`Action: ${Q.description}`),Q.file)console.log(`File: ${Q.file}`);if(Q.command)console.log(`Command: ${Q.command.slice(0,200)}${Q.command.length>200?"...":""}`);console.log("");let J="[y]es / [n]o / [a]lways / [d]eny always";$.question(`Allow? ${J}: `,(Y)=>{switch($.close(),Y.trim().toLowerCase()){case"y":case"yes":Z({decision:"allow"});break;case"a":case"always":Z({decision:"allowAlways"});break;case"d":case"deny":case"deny always":Z({decision:"denyAlways"});break;case"n":case"no":default:Z({decision:"deny"});break}})})}clearCache(){this.cache={}}setMode(Q){this.mode=Q,this.clearCache()}}var h0={readOnly:["Read","Glob","Grep","Task"],fileEdit:["Write","Edit","NotebookEdit"],system:["Bash"],network:[]};function C7(Q){return h0.readOnly.includes(Q)}function R7(Q){return h0.fileEdit.includes(Q)}function D7(Q){return h0.system.includes(Q)}import{join as X9,dirname as M6}from"path";import{fileURLToPath as C6}from"url";import{existsSync as R6}from"fs";var c9=null,fQ=!1;function D(){if(c9)return c9;if(fQ)return gQ();fQ=!0;let{platform:Q,arch:Z}=process,$=`${Q}-${Z}`,V;try{V=M6(C6(import.meta.url))}catch{V=process.cwd()}let X=[X9(V,"..","..","native",`claude-code-native.${$}.node`),X9(V,"..","native",`claude-code-native.${$}.node`),X9(V,"native",`claude-code-native.${$}.node`),X9(V,"..","..","native",`claude_code_native.${$}.node`),X9(V,"..","..","native","index.node"),X9(V,"..","native","index.node"),X9(V,"..","..","native","claude-code-native.node"),X9(V,"..","..","node_modules","@ebowwa","coder-native","index.node"),X9(process.cwd(),"native",`claude-code-native.${$}.node`),X9(process.cwd(),"native","index.node")];for(let z of X)if(R6(z))try{let J=f0(z);return console.debug(`[native] Loaded module from: ${z}`),c9=J,c9}catch(J){console.debug(`[native] Failed to load ${z}:`,J);continue}return console.debug("[native] No native module found, using JS fallback"),gQ()}function G0(){try{return D(),c9!==null}catch{return!1}}var D6=4,l9=10,dQ=100;function d(Q){if(!Q||Q.length===0)return 0;return Math.ceil(Q.length/D6)}function c0(Q){switch(Q.type){case"text":return d(Q.text);case"image":return dQ;case"tool_use":{let Z=JSON.stringify(Q.input);return d(Q.name)+d(Z)+l9}case"tool_result":{if(typeof Q.content==="string")return d(Q.content)+l9;return Q.content.reduce((Z,$)=>Z+c0($),0)+l9}case"thinking":return d(Q.thinking);case"redacted_thinking":return d(Q.data);default:return 0}}function H0(Q){let Z=14695981039346656037n,$=1099511628211n,V=Z;for(let X=0;X<Q.length;X++)V^=BigInt(Q.charCodeAt(X)),V*=$,V&=0xFFFFFFFFFFFFFFFFn;return V.toString(16).padStart(16,"0")}function z9(Q){let Z=3735928559,$=1103553917;for(let V=0;V<Q.length;V++){let X=Q.charCodeAt(V);Z=Math.imul(Z^X,2654435761),$=Math.imul($^X,1597334677)}return Z=Math.imul(Z^Z>>>16,2246822507),Z=Math.imul(Z^Z>>>13,3266489909),Z=(Z^Z>>>16)>>>0,$=Math.imul($^$>>>16,2246822507),$=Math.imul($^$>>>13,3266489909),$=($^$>>>16)>>>0,(Z>>>0).toString(16).padStart(8,"0")+($>>>0).toString(16).padStart(8,"0")}function g0(Q){if(typeof Bun<"u"&&Bun.hash)try{return Bun.hash(Q).toString(16).padStart(16,"0")}catch{}if(typeof crypto<"u"&&crypto.subtle);let Z=z9(Q);for(let $=0;$<3;$++)Z=z9(Z+Q+$);return(Z+H0(Q)+z9(Q+Z)).slice(0,64)}function d0(Q){let Z;try{Z=JSON.parse(Q)}catch{return{pairs:[],totalToolUses:0,totalToolResults:0,matchedPairs:0,orphanUses:0,orphanResults:0}}let $=new Map,V=0,X=0,z=0;Z.forEach((W,H)=>{if(!Array.isArray(W.content))return;W.content.forEach((G)=>{if(G.type==="tool_use"&&G.id&&G.name)V++,$.set(G.id,{toolUse:{blockType:"tool_use",id:G.id,name:G.name,input:JSON.stringify(G.input||{})},toolResult:void 0,useMessageIndex:H,resultMessageIndex:void 0})})}),Z.forEach((W,H)=>{if(!Array.isArray(W.content))return;W.content.forEach((G)=>{if(G.type==="tool_result"&&G.tool_use_id){X++;let _=$.get(G.tool_use_id);if(_)z++,_.toolResult={blockType:"tool_result",toolUseId:G.tool_use_id,content:typeof G.content==="string"?G.content:JSON.stringify(G.content),isError:G.is_error||!1},_.resultMessageIndex=H}})});let J=Array.from($.values()),Y=J.filter((W)=>!W.toolResult).length,K=new Set(J.filter((W)=>W.toolResult).map((W)=>W.toolResult.toolUseId)),q=0;return Z.forEach((W)=>{if(!Array.isArray(W.content))return;W.content.forEach((H)=>{if(H.type==="tool_result"&&H.tool_use_id){if(!K.has(H.tool_use_id))q++}})}),{pairs:J,totalToolUses:V,totalToolResults:X,matchedPairs:z,orphanUses:Y,orphanResults:q}}function P6(Q){let Z;try{Z=JSON.parse(Q)}catch{return{toolCounts:"{}",totalInvocations:0,successRate:1,mostUsedTool:void 0,mostUsedCount:0}}let $=new Map,V=0,X=0,z=0;Z.forEach((W)=>{if(!Array.isArray(W.content))return;W.content.forEach((H)=>{if(H.type==="tool_use"&&H.name)$.set(H.name,($.get(H.name)||0)+1),V++;if(H.type==="tool_result")if(H.is_error)z++;else X++})});let J,Y=0;$.forEach((W,H)=>{if(W>Y)Y=W,J=H});let K=X+z,q=K>0?X/K:1;return{toolCounts:JSON.stringify(Object.fromEntries($)),totalInvocations:V,successRate:q,mostUsedTool:J,mostUsedCount:Y}}async function m9(Q,Z){let $=[],V=new Set,X=0,z=!1;try{let J=["--json"];if(Z.caseInsensitive)J.push("-i");if(Z.contextLines)J.push("-C",String(Z.contextLines));if(Z.glob)J.push("--glob",Z.glob);if(Z.hidden)J.push("--hidden");J.push(Z.pattern,Q);let K=Bun.spawnSync(["rg",...J],{maxBuffer:10485760}).stdout?.toString()||"";if(!K.trim())return{matches:[],totalCount:0,filesSearched:0,filesWithMatches:[],truncated:!1};let q=K.trim().split(`
4
+ `),W=Z.headLimit||100;for(let H of q){if($.length>=W){z=!0;break}try{let G=JSON.parse(H);if(G.type==="match"){let _=G.data?.path?.text||"",U=G.data?.line_number||0,j=G.data?.lines?.text||"";V.add(_),$.push({filePath:_,lineNumber:U,column:1,line:j.trim(),matchText:Z.pattern,beforeContext:[],afterContext:[]})}else if(G.type==="begin")X++}catch{}}}catch(J){}return{matches:$,totalCount:$.length,filesSearched:X,filesWithMatches:Array.from(V),truncated:z}}var uQ={ts:"TypeScript",tsx:"TypeScript",js:"JavaScript",jsx:"JavaScript",mjs:"JavaScript",py:"Python",rs:"Rust",go:"Go",json:"JSON",toml:"TOML",html:"HTML",htm:"HTML",css:"CSS",md:"Markdown",markdown:"Markdown",yaml:"YAML",yml:"YAML",sh:"Shell",bash:"Shell",zsh:"Shell",sql:"SQL",xml:"XML",java:"Java",kt:"Kotlin",swift:"Swift",c:"C",cpp:"C++",h:"C",hpp:"C++"},hQ={TypeScript:/\b(async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|if|implements|import|in|instanceof|interface|let|new|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|var|void|while|with|yield|as|is|keyof|type|namespace|declare|abstract|readonly|unique symbol|require|module)\b/g,JavaScript:/\b(async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|if|implements|import|in|instanceof|interface|let|new|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/g,Python:/\b(and|as|assert|async|await|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield|True|False|None)\b/g,Rust:/\b(as|async|await|break|const|continue|crate|dyn|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while)\b/g,Go:/\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go|goto|if|import|interface|map|package|range|return|select|struct|switch|type|var|true|false|nil|iota)\b/g};function mQ(Q,Z){let $=Z.rsplit(".",1)[1]?.toLowerCase()||"";if(uQ[$])return uQ[$];let V=Q.split(`
5
+ `)[0];if(V?.startsWith("#!")){if(V.includes("python"))return"Python";if(V.includes("node"))return"JavaScript";if(V.includes("bash")||V.includes("sh"))return"Shell"}return"Plain Text"}async function l0(Q,Z,$){let V=mQ(Q,Z),X=[],z=Q.split(`
6
+ `),J=0;for(let Y=0;Y<z.length;Y++){let K=z[Y],q=J,W=/(\s+|[a-zA-Z_][a-zA-Z0-9_]*|[0-9]+(?:\.[0-9]+)?|"[^"]*"|'[^']*'|`[^`]*`|[+\-*/%=<>!&|^~?:;,.\[\]{}()]+)/g,H;while((H=W.exec(K))!==null){let G=H[0],_=H.index+1,U=_+G.length,j="text";if(/^\s+$/.test(G))j="whitespace";else if(/^(\/\/|#|\/\*|\*\/)/.test(G)||G.startsWith("//")||G.startsWith("#"))j="comment";else if(/^"[^"]*"$/.test(G)||/^'[^']*'$/.test(G)||/^`[^`]*`$/.test(G))j="string";else if(/^[0-9]+(?:\.[0-9]+)?$/.test(G))j="number";else if(hQ[V]?.test(G))j="keyword",hQ[V].lastIndex=0;else if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(G))if(/^[A-Z][a-zA-Z0-9_]*$/.test(G))j="type";else j="variable";else if(/^[+\-*/%=<>!&|^~?:]+$/.test(G))j="operator";else if(/^[,.\[\]{}();]$/.test(G))j="punctuation";X.push({text:G,tokenType:j,start:q+H.index,end:q+H.index+G.length,line:Y+1,columnStart:_,columnEnd:U,bold:!1,italic:j==="comment",underline:!1})}J+=K.length+1}return{tokens:X,language:V,totalLines:z.length,totalTokens:X.length}}async function N6(Q,Z,$){let V=await l0(Q,Z);return Q.split(`
7
+ `).map((J,Y)=>{let K=V.tokens.filter((H)=>H.line===Y+1);if(K.length===0)return J;let q="",W=0;for(let H of K.sort((G,_)=>G.columnStart-_.columnStart)){if(H.columnStart-1>W)q+=J.slice(W,H.columnStart-1);let G={keyword:"35",string:"32",number:"33",comment:"90",type:"34",function:"36",operator:"37",punctuation:"90",variable:"0",text:"0",whitespace:"0",constant:"33",property:"36",label:"35"}[H.tokenType]||"0",_=[];if(H.bold)_.push("1");if(H.italic)_.push("3");if(H.underline)_.push("4");let U=[..._,`38;5;${G}`].join(";");q+=`\x1B[${U}m${H.text}\x1B[0m`,W=H.columnEnd-1}if(W<J.length)q+=J.slice(W);return q}).join(`
8
+ `)}async function S6(Q,Z,$){let V=await l0(Q,Z),X=[],z=0;for(let J of V.tokens.sort((Y,K)=>Y.start-K.start)){if(J.start>z)X.push(m0(Q.slice(z,J.start)));let Y=[`token-${J.tokenType}`],K=[];if(J.bold)K.push("font-weight:bold");if(J.italic)K.push("font-style:italic");if(J.underline)K.push("text-decoration:underline");let q=Y.join(" "),W=K.length>0?` style="${K.join(";")}"`:"";X.push(`<span class="${q}"${W}>${m0(J.text)}</span>`),z=J.end}if(z<Q.length)X.push(m0(Q.slice(z)));return`<pre class="highlight ${V.language.toLowerCase().replace(/\s+/g,"-")}">${X.join("")}</pre>`}function m0(Q){return Q.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function gQ(){return{searchFiles:(Q,Z,$)=>{return{matches:[],total_count:0,files_searched:0}},grepSearch:m9,grepQuick:async(Q,Z,$,V)=>{return m9(Z,{pattern:Q,case_insensitive:$,head_limit:V||100})},grepFiles:async(Q,Z,$,V)=>{return(await m9(Z,{pattern:Q,glob:$,case_insensitive:V,output_mode:"files_with_matches"})).files_with_matches},grepCount:async(Q,Z,$,V)=>{return(await m9(Z,{pattern:Q,glob:$,case_insensitive:V,output_mode:"count"})).total_count},grepFile:async(Q,Z,$,V)=>{return(await m9(Q,{pattern:Z,case_insensitive:$,head_limit:V||1000})).matches},extractToolPairs:(Q)=>{return d0(Q)},getSuccessfulToolPairIndices:(Q)=>{return d0(Q).pairs.map(($,V)=>({pair:$,index:V})).filter(({pair:$})=>$.toolResult&&!$.toolResult.isError).map(({index:$})=>$)},getRecentToolPairIndices:(Q,Z)=>{return d0(Q).pairs.map((X,z)=>({pair:X,index:z})).sort((X,z)=>z.pair.useMessageIndex-X.pair.useMessageIndex).slice(0,Z).map(({index:X})=>X)},calculateToolStats:(Q)=>{return P6(Q)},countTokens:(Q)=>{return Math.ceil(Q.length/4)},estimateTokens:d,estimateTextBlockTokens:(Q)=>d(Q),estimateImageBlockTokens:()=>dQ,estimateToolUseBlockTokens:(Q,Z)=>{return d(Q)+d(Z)+l9},estimateToolResultBlockTokens:(Q)=>{return d(Q)+l9},estimateThinkingBlockTokens:(Q)=>d(Q),estimateRedactedThinkingBlockTokens:(Q)=>d(Q),estimateBlocksFromJson:(Q)=>{try{return JSON.parse(Q).reduce(($,V)=>$+c0(V),0)}catch{return 0}},estimateMessageTokensJson:(Q,Z)=>{try{return 4+JSON.parse(Z).reduce((z,J)=>z+c0(J),0)}catch{return 4}},calculateDiff:(Q,Z)=>{let $=Q.split(`
9
+ `),V=Z.split(`
10
+ `),X=[];if(Q!==Z)X.push({old_start:1,old_lines:$.length,new_start:1,new_lines:V.length,content:`- ${$.join(`
11
+ - `)}
12
+ + ${V.join(`
13
+ + `)}`});return X},compactContent:(Q,Z,$="truncate")=>{let X=Z*4;if(Q.length<=X)return Q;switch($){case"truncate":return Q.slice(0,X/2)+`
14
+
15
+ ... [truncated] ...
16
+
17
+ `+Q.slice(-X/2);case"summarize":let z=Math.floor(X/4);return`=== BEGINNING ===
18
+ `+Q.slice(0,z)+`
19
+
20
+ === END ===
21
+ `+Q.slice(-z);case"extract":return Q.split(`
22
+ `).filter((K)=>K.trim().startsWith("#")||K.trim().startsWith("function")||K.trim().startsWith("const")||K.trim().startsWith("class")||K.trim().startsWith("export")||K.trim().startsWith("import")).slice(0,X/50).join(`
23
+ `);default:return Q.slice(0,X)}},hashContentXxhash3:z9,hashContentXxhash64:H0,hashContentSha256:g0,hashContent:(Q,Z="xxhash3")=>{let $=performance.now(),V;switch(Z){case"xxhash64":V=H0(Q);break;case"sha256":V=g0(Q);break;default:V=z9(Q)}return{hash:V,algorithm:Z,input_size:Q.length,elapsed_us:Math.round((performance.now()-$)*1000)}},hashCombined:(Q,Z="xxhash3")=>{let $=Q.join("\x00");switch(Z){case"xxhash64":return H0($);case"sha256":return g0($);default:return z9($)}},contentChanged:(Q,Z)=>z9(Q)!==Z,contentEquals:(Q,Z)=>Q.length===Z.length&&z9(Q)===z9(Z),generateCacheKey:(Q)=>z9(Q.join("\x00")),highlightPlain:async(Q,Z,$)=>{return l0(Q,Z,$)},highlightAnsi:async(Q,Z,$)=>{return N6(Q,Z,$)},highlightHtml:async(Q,Z,$)=>{return S6(Q,Z,$)},listHighlightThemes:()=>["base16-eighties.dark","base16-mocha.dark","base16-ocean.dark","InspiredGitHub","Solarized (dark)","Solarized (light)"],listHighlightLanguages:()=>["TypeScript","JavaScript","Python","Rust","Go","JSON","TOML","HTML","CSS","Markdown"],detectSyntaxLanguage:(Q,Z)=>mQ(Q,Z)}}function cQ(Q){return JSON.stringify(Q.map((Z)=>{switch(Z.type){case"text":return{type:"text",text:Z.text};case"image":return{type:"image"};case"tool_use":return{type:"tool_use",name:Z.name,input:Z.input};case"tool_result":return{type:"tool_result",content:Z.content};case"thinking":return{type:"thinking",thinking:Z.thinking};case"redacted_thinking":return{type:"redacted_thinking",data:Z.data};default:return{type:"text",text:""}}}))}function lQ(Q){return D().estimateBlocksFromJson(cQ(Q))}function pQ(Q,Z){return D().estimateMessageTokensJson(Q,cQ(Z))}function S9(Q){return D().hashContentXxhash3(Q)}function x7(Q){return D().hashContentSha256(Q)}function p0(Q,Z){return D().contentChanged(Q,Z)}function E7(Q,Z){return D().contentEquals(Q,Z)}function iQ(Q){return D().generateCacheKey(Q)}async function T7(Q,Z){return D().grepSearch(Q,Z)}async function y7(Q,Z,$=!1,V=100){return D().grepQuick(Q,Z,$,V)}async function k7(Q,Z,$,V=!1){return D().grepFiles(Q,Z,$,V)}async function b7(Q,Z,$,V=!1){return D().grepCount(Q,Z,$,V)}async function f7(Q,Z,$=!1,V=1000){return D().grepFile(Q,Z,$,V)}function nQ(Q){return D().extractToolPairs(Q)}function u7(Q){return D().getSuccessfulToolPairIndices(Q)}function h7(Q,Z){return D().getRecentToolPairIndices(Q,Z)}function g7(Q){return D().calculateToolStats(Q)}async function d7(Q,Z,$){return D().highlightPlain(Q,Z,$)}async function m7(Q,Z,$){return D().highlightAnsi(Q,Z,$)}async function c7(Q,Z,$){return D().highlightHtml(Q,Z,$)}function l7(){return D().listHighlightThemes()}function p7(){return D().listHighlightLanguages()}function i7(Q,Z){return D().detectSyntaxLanguage(Q,Z)}var M9=D();class _0{cache=new Map;hits=0;misses=0;name;constructor(Q="cache"){this.name=Q}get(Q){let Z=this.cache.get(Q);if(!Z)return this.misses++,null;if(Z.ttl&&Date.now()>Z.timestamp+Z.ttl)return this.cache.delete(Q),this.misses++,null;return this.hits++,Z.value}set(Q,Z,$){this.cache.set(Q,{value:Z,hash:Q,timestamp:Date.now(),ttl:$})}async getOrCompute(Q,Z,$){let V=S9(Q),X=this.get(V);if(X!==null)return X;let z=await Z();return this.set(V,z,$),z}hasChanged(Q,Z){return p0(Q,Z)}invalidateOlderThan(Q){let Z=Date.now()-Q,$=0;for(let[V,X]of this.cache.entries())if(X.timestamp<Z)this.cache.delete(V),$++;return $}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){let Q=this.hits+this.misses;return{entries:this.cache.size,hits:this.hits,misses:this.misses,hitRate:Q>0?this.hits/Q:0}}getName(){return this.name}}var rQ=new _0("compaction"),a7=new _0("tokens"),s7=new _0("file-hashes");function t7(Q){let Z=JSON.stringify(Q);return S9(Z)}function e7(Q){return S9(Q)}function Q$(Q,Z){return!p0(Q,Z)}function oQ(...Q){return iQ(Q)}function Z$(Q){let Z=new Map;for(let $ of Q)Z.set($,S9($));return Z}function aQ(Q,Z){let $=oQ(Q,String(Z));return rQ.get($)}function sQ(Q,Z,$){let V=oQ(Q,String(Z));rQ.set(V,JSON.stringify($),300000)}function tQ(Q){let Z=Q.map(($)=>({r:$.role,c:Array.isArray($.content)?$.content.map((V)=>{if(V.type==="text"&&V.text)return{t:V.type,txt:V.text.slice(0,200)};if(V.type==="tool_use")return{t:V.type,n:V.name};return{t:V.type||"unknown"}}):typeof $.content}));return S9(JSON.stringify(Z))}var n0={tokenWarningThreshold:0.8,costUpdateInterval:5,toolSummaryInterval:3,envInfoOnStart:!0},i0={WARNING:0.8,CRITICAL:0.9,EMERGENCY:0.95};function I6(Q){let{current:Z,max:$,threshold:V=i0.WARNING}=Q;if($<=0)return"";let X=Z/$;if(X<V)return"";let z=$-Z,J=Math.round(X*100),Y,K;if(X>=i0.EMERGENCY)Y="emergency",K="\uD83D\uDEA8";else if(X>=i0.CRITICAL)Y="critical",K="\u26A0\uFE0F";else Y="warning",K="\u26A1";let q=[`${K} Token Usage ${Y.toUpperCase()}`,"",`Current: ${Z.toLocaleString()} / ${$.toLocaleString()} tokens (${J}%)`,`Remaining: ${z.toLocaleString()} tokens`];if(Y==="emergency")q.push(""),q.push("Consider summarizing or compacting the conversation to continue.");else if(Y==="critical")q.push(""),q.push("Approaching token limit. Consider wrapping up soon.");return q.join(`
24
+ `)}function x6(Q){let{cost:Z,previousCost:$=0,currency:V="USD"}=Q,X=E6(V),z=eQ(Z,X),J=Z-$,Y=eQ(Math.abs(J),X),K=["\uD83D\uDCB0 Cost Update","",`Total: ${z} ${V}`];if(J!==0){let q=J>0?"+":"-";K.push(`This turn: ${q}${Y} ${V}`)}return K.join(`
25
+ `)}function eQ(Q,Z){if(Q<0.01)return`${Z}${Q.toFixed(4)}`;else if(Q<1)return`${Z}${Q.toFixed(3)}`;return`${Z}${Q.toFixed(2)}`}function E6(Q){return{USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5"}[Q]||Q}function T6(Q){let{tools:Z,maxDisplay:$=10}=Q;if(Z.length===0)return"No tools used this session.";let V=new Map;for(let Y of Z){let K=V.get(Y.name)||0;V.set(Y.name,K+1)}let X=[...V.entries()].sort((Y,K)=>K[1]-Y[1]),z=[`\uD83D\uDD27 Tool Usage Summary (${Z.length} total calls)`,""],J=X.slice(0,$);for(let[Y,K]of J)z.push(` \u2022 ${Y}: ${K} call${K===1?"":"s"}`);if(X.length>$){let Y=X.length-$;z.push(` ... and ${Y} more tool${Y===1?"":"s"}`)}return z.join(`
26
+ `)}function y6(Q){let{workingDirectory:Z,gitStatus:$,platform:V=process.platform,shell:X=process.env.SHELL||"unknown"}=Q,z=["\uD83D\uDCCD Environment Information","",`Working Directory: ${Z}`,`Platform: ${V}`,`Shell: ${X}`];if($){if(z.push(""),z.push("Git Status:"),z.push(` Branch: ${$.branch}`),$.ahead>0||$.behind>0)z.push(` Ahead: ${$.ahead}, Behind: ${$.behind}`);let J=$.staged.length+$.unstaged.length+$.untracked.length+$.conflicted.length;if(J>0){if(z.push(` Changes: ${J} file${J===1?"":"s"}`),$.staged.length>0)z.push(` Staged: ${$.staged.length}`);if($.unstaged.length>0)z.push(` Unstaged: ${$.unstaged.length}`);if($.untracked.length>0)z.push(` Untracked: ${$.untracked.length}`);if($.conflicted.length>0)z.push(` Conflicted: ${$.conflicted.length}`)}else z.push(" Working tree clean")}return z.join(`
27
+ `)}function Q8(Q){let{usage:Z,maxTokens:$,totalCost:V,previousCost:X,toolsUsed:z,workingDirectory:J,gitStatus:Y,turnNumber:K,config:q}=Q,W={...n0,...q},H=[],G=Z.input_tokens+Z.output_tokens,_=I6({current:G,max:$,threshold:W.tokenWarningThreshold});if(_)H.push(_);if(K%W.costUpdateInterval===0){let U=x6({cost:V,previousCost:X});H.push(U)}if(K%W.toolSummaryInterval===0&&z.length>0){let U=T6({tools:z});H.push(U)}if(K===1&&W.envInfoOnStart){let U=y6({workingDirectory:J,gitStatus:Y});H.push(U)}if(H.length===0)return"";return["---","System Reminders:","",...H,"---"].join(`
28
+ `)}var k6=4,b6=5,f6=1,u6=8,h6=0.9,Z8=8000,j0=10,g6=100;function I9(Q){if(!Q||Q.length===0)return 0;return Math.ceil(Q.length/k6)}function $8(Q){if(G0())try{switch(Q.type){case"text":return M9.estimateTextBlockTokens(Q.text);case"image":return M9.estimateImageBlockTokens();case"tool_use":return M9.estimateToolUseBlockTokens(Q.name,JSON.stringify(Q.input));case"tool_result":if(typeof Q.content==="string")return M9.estimateToolResultBlockTokens(Q.content);return lQ(Q.content)+j0;case"thinking":return M9.estimateThinkingBlockTokens(Q.thinking);case"redacted_thinking":return M9.estimateRedactedThinkingBlockTokens(Q.data);default:return 0}}catch{}switch(Q.type){case"text":return I9(Q.text);case"image":return g6;case"tool_use":let Z=JSON.stringify(Q.input);return I9(Q.name)+I9(Z)+j0;case"tool_result":if(typeof Q.content==="string")return I9(Q.content)+j0;return Q.content.reduce(($,V)=>$+$8(V),0)+j0;case"thinking":return I9(Q.thinking);case"redacted_thinking":return I9(Q.data);default:return 0}}function d6(Q){if(G0())try{return pQ(Q.role,Q.content)}catch{}let Z=4,$=Q.content.reduce((V,X)=>V+$8(X),0);return Z+$}function p9(Q){if(!Q||Q.length===0)return 0;return Q.reduce((Z,$)=>Z+d6($),0)}function m6(Q){let Z=[];for(let $ of Q.content)switch($.type){case"text":Z.push($.text);break;case"tool_use":Z.push(`[Tool: ${$.name}(${JSON.stringify($.input)})]`);break;case"tool_result":let V=typeof $.content==="string"?$.content:$.content.map((X)=>X.type==="text"?X.text:"[content]").join("");Z.push(`[Result: ${V.slice(0,500)}${V.length>500?"...":""}]`);break;case"thinking":Z.push(`[Thinking: ${$.thinking.slice(0,200)}...]`);break}return Z.join(`
29
+ `)}function c6(Q){let Z=new Map;if(G0())try{let $=JSON.stringify(Q),V=nQ($);for(let X of V.pairs){let z={};try{z=JSON.parse(X.toolUse.input)}catch{}let J={type:"tool_use",id:X.toolUse.id,name:X.toolUse.name,input:z},Y;if(X.toolResult){let K=X.toolResult.content;try{let q=JSON.parse(X.toolResult.content);if(Array.isArray(q))K=q}catch{}Y={type:"tool_result",tool_use_id:X.toolResult.toolUseId,content:K,is_error:X.toolResult.isError}}Z.set(X.toolUse.id,{use:J,result:Y})}return Z}catch{}for(let $ of Q)for(let V of $.content)if(V.type==="tool_use")Z.set(V.id,{use:V});for(let $ of Q)for(let V of $.content)if(V.type==="tool_result"){let X=Z.get(V.tool_use_id);if(X)X.result=V}return Z}async function l6(Q){if(!Q||Q.length===0)return"";let Z=[];Z.push(`[Context Summary: ${Q.length} messages compacted]
30
+ `);let $=[];for(let X=0;X<Q.length;X++){let z=Q[X];if(!z)continue;let J=z.role.toUpperCase(),Y=m6(z);for(let q of z.content)if(q.type==="tool_use")$.push(`${q.name}`);let K=Y.length>300?`${Y.slice(0,300)}...`:Y;Z.push(`${J}: ${K}
31
+ `)}if($.length>0){let X=$.reduce((J,Y)=>{return J[Y]=(J[Y]||0)+1,J},{}),z=Object.entries(X).map(([J,Y])=>`${J}(${Y})`).join(", ");Z.push(`
32
+ Tools used: ${z}
33
+ `)}let V=Z.join("");if(V.length>Z8)V=V.slice(0,Z8)+`
34
+ ...[truncated]`;return V}async function r0(Q,Z,$={}){let{keepFirst:V=f6,keepLast:X=b6,preserveToolPairs:z=!0}=$,J=p9(Q);if(J<=Z)return{messages:Q,messagesRemoved:0,tokensBefore:J,tokensAfter:J,didCompact:!1};if(Q.length<=V+X)return{messages:Q,messagesRemoved:0,tokensBefore:J,tokensAfter:J,didCompact:!1};let Y=tQ(Q),K=aQ(Y,Z);if(K){let O=Q.slice(0,V),v=Q.slice(-X),L={role:"user",content:[{type:"text",text:`[Previous context has been compacted for continuity]
35
+
36
+ ${K.summary}`}]},I=[...O,L,...v],y=p9(I);return{messages:I,messagesRemoved:Q.length-I.length,tokensBefore:J,tokensAfter:y,didCompact:!0}}let q=Q.slice(0,V),W=Q.slice(V,-X),H=Q.slice(-X),G=await l6(W),_=J-p9([...q,{role:"user",content:[{type:"text",text:G}]},...H]);sQ(Y,Z,{summary:G,tokensSaved:_});let U={role:"user",content:[{type:"text",text:`[Previous context has been compacted for continuity]
37
+
38
+ ${G}`}]},j=[];if(z&&W.length>0){let O=c6(W),v=Array.from(O.values()).slice(-3).filter((L)=>L.result&&!L.result.is_error);for(let L of v)if(j.push(L.use),L.result)j.push(L.result)}let A=[...q,U];if(j.length>0)A.push({role:"assistant",content:j.filter((O)=>O.type==="tool_use")}),A.push({role:"user",content:j.filter((O)=>O.type==="tool_result")});A.push(...H);let w=p9(A),B=Q.length-A.length;return console.log(`Context compaction: ${Q.length} -> ${A.length} messages, ${J} -> ${w} tokens`),{messages:A,messagesRemoved:B,tokensBefore:J,tokensAfter:w,didCompact:!0}}function V8(Q,Z,$=h6){if(Q.length<u6)return!1;let V=p9(Q),X=Math.floor(Z*$);return V>=X}function o0(Q){if(!Q.didCompact)return{reductionPercent:0,tokensSaved:0};let Z=Q.tokensBefore-Q.tokensAfter,$=Z/Q.tokensBefore*100;return{reductionPercent:Math.round($*100)/100,tokensSaved:Z}}async function A$(Q,Z){let{apiKey:$,model:V="claude-sonnet-4-6",maxTokens:X=4096,systemPrompt:z,tools:J,permissionMode:Y,workingDirectory:K,gitStatus:q=null,reminderConfig:W,cacheConfig:H=W0,thinking:G,extendedThinking:_,stopSequences:U,getStopSequences:j,onText:A,onThinking:w,onToolUse:B,onToolResult:O,onMetrics:v,onReminder:L,onPermissionRequest:I,signal:y}=Z,e=new u0(Y,I),P=[...Q],r=[],b9=[],Q9=0,f9=0,u9=0,q9=0,W9=0,H9=0,k={cacheHits:0,cacheMisses:0,totalCacheReadTokens:0,totalCacheWriteTokens:0,cacheHitRate:0,estimatedSavingsUSD:0},A9={...n0,...W},Z9=!0;while(Z9){if(y?.aborted)break;u9++;let c=r[r.length-1],O9=Q8({usage:c?.usage??{input_tokens:0,output_tokens:0},maxTokens:X,totalCost:Q9,previousCost:q9,toolsUsed:b9,workingDirectory:K,gitStatus:q,turnNumber:u9,config:A9});if(O9)L?.(O9);if(V8(P,X)){let F=await r0(P,X,{keepFirst:0,keepLast:3,preserveToolPairs:!0});if(F.didCompact&&F.tokensAfter<F.tokensBefore){P.length=0,P.push(...F.messages),W9++;let M=F.tokensBefore-F.tokensAfter;H9+=M;let C=o0(F);console.log(`Context compacted: ${C.reductionPercent}% reduction, ${C.tokensSaved} tokens saved`)}}let h9=p6(P,z,O9),SQ=j?j(u9,{lastStopReason:r[r.length-1]?.stopReason}):U,k0=await kQ(h9,{apiKey:$,model:V,maxTokens:X,systemPrompt:z,cacheConfig:H,thinking:G,extendedThinking:_,stopSequences:SQ,tools:J.map((F)=>({name:F.name,description:F.description,input_schema:F.input_schema})),onToken:A,onThinking:w,onToolUse:B,signal:y}),{message:G9,usage:P9,cacheMetrics:$9,costUSD:R,durationMs:o,ttftMs:v9}=k0,g9={model:V,messageCount:P.length,messageTokens:P9.input_tokens+P9.output_tokens,usage:P9,cacheMetrics:$9,durationMs:o,ttftMs:v9,costUSD:R,stopReason:G9.stop_reason,requestId:G9.id};if(r.push(g9),q9=Q9,Q9+=R,f9+=o,$9)k.cacheHits+=$9.cacheHits,k.cacheMisses+=$9.cacheMisses,k.totalCacheReadTokens+=$9.totalCacheReadTokens,k.totalCacheWriteTokens+=$9.totalCacheWriteTokens,k.estimatedSavingsUSD+=$9.estimatedSavingsUSD;let d9=k.cacheHits+k.cacheMisses;if(k.cacheHitRate=d9>0?k.cacheHits/d9:0,v?.(g9),P.push({role:"assistant",content:G9.content}),G9.stop_reason==="end_turn"||G9.stop_reason==="stop_sequence"){Z9=!1;break}if(G9.stop_reason==="max_tokens"){let F=await r0(P,X,{keepFirst:0,keepLast:3,preserveToolPairs:!0});if(F.didCompact&&F.tokensAfter<F.tokensBefore){P.length=0,P.push(...F.messages),W9++;let M=F.tokensBefore-F.tokensAfter;H9+=M;let C=o0(F);console.log(`Context compacted: ${C.reductionPercent}% reduction, ${C.tokensSaved} tokens saved`);continue}else{Z9=!1;break}}let N9=G9.content.filter((F)=>F.type==="tool_use");if(b9.push(...N9),N9.length===0){Z9=!1;break}let V9=[];if(y?.aborted);else{let F=N9.map(async(C)=>{let b0=J.find((_9)=>_9.name===C.name);if(!b0)return{toolUseId:C.id,result:{type:"tool_result",tool_use_id:C.id,content:`Error: Unknown tool "${C.name}"`,is_error:!0},toolResult:null};let q0=await e.checkPermission(b0.name,C.input);if(q0.decision==="deny"||q0.decision==="denyAlways")return{toolUseId:C.id,result:{type:"tool_result",tool_use_id:C.id,content:`Permission denied for tool "${C.name}"${q0.reason?`: ${q0.reason}`:""}`,is_error:!0},toolResult:null};try{let _9=await b0.handler(C.input,{workingDirectory:K,permissionMode:Y,abortSignal:y});return{toolUseId:C.id,result:{type:"tool_result",tool_use_id:C.id,content:_9.content,is_error:_9.is_error},toolResult:{id:C.id,result:_9}}}catch(_9){let X6=_9 instanceof Error?_9.message:String(_9);return{toolUseId:C.id,result:{type:"tool_result",tool_use_id:C.id,content:`Error: ${X6}`,is_error:!0},toolResult:null}}}),M=await Promise.all(F);for(let C of M)if(V9.push(C.result),C.toolResult)O?.(C.toolResult)}P.push({role:"user",content:V9})}return{messages:P,metrics:r,totalCost:Q9,totalDuration:f9,totalCacheMetrics:k,compactionCount:W9,totalTokensCompacted:H9}}function p6(Q,Z,$){if($&&Q.length>0){let V=[...Q];for(let X=V.length-1;X>=0;X--){let z=V[X];if(z&&z.role==="user"){let J={role:"user",content:Array.isArray(z.content)?i6(z.content,$):[{type:"text",text:`${String(z.content)}
39
+
40
+ ${$}`}]};V[X]=J;break}}return V}return Q}function i6(Q,Z){if(Q.length>0){let V=Q[Q.length-1];if(V&&V.type==="text"){let X={type:"text",text:`${V.text}
41
+
42
+ ${Z}`};return[...Q.slice(0,-1),X]}}let $={type:"text",text:`
43
+
44
+ ${Z}`};return[...Q,$]}function a0(Q){if(Q<0.01)return`$${Q.toFixed(4)}`;return`$${Q.toFixed(2)}`}function B$(Q){let Z=a0(Q.costUSD),$=`${Q.usage.input_tokens.toLocaleString()} input, ${Q.usage.output_tokens.toLocaleString()} output`;if(Q.usage.cache_read_input_tokens||Q.usage.cache_creation_input_tokens){let V=Q.usage.cache_read_input_tokens?.toLocaleString()??"0",X=Q.usage.cache_creation_input_tokens?.toLocaleString()??"0";return`Cost: ${Z} | Tokens: ${$} | Cache: ${V} read, ${X} write`}return`Cost: ${Z} | Tokens: ${$}`}function L$(Q){let Z=a0(Q.costUSD),$=Q.usage.input_tokens+Q.usage.output_tokens;return`Cost: ${Z} | Tokens: ${$.toLocaleString()}`}function F$(Q){let Z=a0(Q.estimatedSavingsUSD);return`Cache: ${(Q.cacheHitRate*100).toFixed(1)}% hit rate | ${Q.totalCacheReadTokens.toLocaleString()} read | ${Q.totalCacheWriteTokens.toLocaleString()} written | Saved: ${Z}`}import{homedir as n6}from"os";import{join as j9}from"path";class r6{sessionsDir;currentSessionId=null;currentSessionFile=null;writeQueue=Promise.resolve();constructor(Q){this.sessionsDir=Q??j9(n6(),".claude","sessions")}async init(){try{await Bun.write(j9(this.sessionsDir,".gitkeep"),"")}catch{}}generateSessionId(){let Q=Date.now().toString(36),Z=Math.random().toString(36).slice(2,8);return`${Q}-${Z}`}async createSession(Q){await this.init();let Z=this.generateSessionId();this.currentSessionId=Z,this.currentSessionFile=j9(this.sessionsDir,`${Z}.jsonl`);let $={id:Z,created:Date.now(),updated:Date.now(),model:Q.model,workingDirectory:Q.workingDirectory,agentName:Q.agentName,agentColor:Q.agentColor,teamName:Q.teamName};await this.appendEntry($);let V={type:"context",timestamp:Date.now(),workingDirectory:Q.workingDirectory};return await this.appendEntry(V),Z}async resumeSession(Q){let Z=j9(this.sessionsDir,`${Q}.jsonl`);try{let $=await Bun.file(Z).text();if(!$)return null;let V=$.trim().split(`
45
+ `),X=[];for(let z of V)try{X.push(JSON.parse(z))}catch{}return this.parseSessionEntries(X)}catch{return null}}parseSessionEntries(Q){let Z=null,$=[],V=[],X=[],z=null;for(let J of Q){if(!("type"in J)&&"id"in J&&"created"in J){Z=J;continue}if("type"in J){let Y=J;switch(Y.type){case"message":$.push(Y.data);break;case"tool_use":V.push(Y);break;case"metrics":X.push(Y.data);break;case"context":z=Y;break}}}if(!Z)Z={id:"unknown",created:Date.now(),updated:Date.now(),model:"claude-sonnet-4-6",workingDirectory:process.cwd()};return{metadata:Z,messages:$,tools:V,metrics:X,context:z}}async appendEntry(Q){if(!this.currentSessionFile)return;this.writeQueue=this.writeQueue.then(async()=>{let Z=JSON.stringify(Q)+`
46
+ `,$=Bun.file(this.currentSessionFile),V=await $.exists()?await $.text():"";await Bun.write(this.currentSessionFile,V+Z)}),await this.writeQueue}async saveMessage(Q){let Z={type:"message",timestamp:Date.now(),data:Q};await this.appendEntry(Z),await this.updateTimestamp()}async saveToolUse(Q,Z,$,V,X){let z={type:"tool_use",timestamp:Date.now(),toolId:Q,toolName:Z,input:$,result:V,isError:X};await this.appendEntry(z)}async saveMetrics(Q){let Z={type:"metrics",timestamp:Date.now(),data:Q};await this.appendEntry(Z)}async updateTimestamp(){if(!this.currentSessionFile||!this.currentSessionId)return}async listSessions(Q=20){await this.init();let Z=Bun.file(this.sessionsDir),$=[];try{let X=[...new Bun.Glob("*.jsonl").scanSync(this.sessionsDir)],z=await Promise.all(X.map(async(J)=>{let Y=j9(this.sessionsDir,J),K=await Bun.file(Y).stat();return{file:J,fullPath:Y,mtime:K?.mtime??new Date(0)}}));z.sort((J,Y)=>Y.mtime.getTime()-J.mtime.getTime());for(let{file:J,fullPath:Y}of z.slice(0,Q)){let K=J.replace(".jsonl",""),q=await this.getSessionSummary(K,Y);if(q)$.push(q)}}catch{}return $}async getSessionSummary(Q,Z){let $=Z??j9(this.sessionsDir,`${Q}.jsonl`);try{let V=await Bun.file($).text();if(!V)return null;let X=V.trim().split(`
47
+ `),z=null,J=0,Y=0,K=0,q=0,W;for(let H of X)try{let G=JSON.parse(H);if(G.id&&G.created)z=G;else if(G.type==="message"){J++;let _=G.data;if(!W&&_.role==="user"){let U=_.content.find((j)=>j.type==="text");if(U&&"text"in U){if(W=U.text.slice(0,100),U.text.length>100)W+="..."}}}else if(G.type==="metrics")Y+=G.data.costUSD,K+=G.data.usage.input_tokens,q+=G.data.usage.output_tokens}catch{}if(!z)return null;return{id:Q,created:z.created,updated:z.updated,model:z.model,messageCount:J,totalCost:Y,totalTokens:{input:K,output:q},firstMessage:W,workingDirectory:z.workingDirectory}}catch{return null}}getCurrentSessionId(){return this.currentSessionId}async exportSession(Q,Z,$){let V=await this.resumeSession(Q);if(!V)throw Error(`Session not found: ${Q}`);let X,z;switch(Z){case"jsonl":{let Y=j9(this.sessionsDir,`${Q}.jsonl`);X=await Bun.file(Y).text(),z="jsonl";break}case"json":{X=JSON.stringify(V,null,2),z="json";break}case"markdown":{X=this.sessionToMarkdown(V),z="md";break}default:throw Error(`Unsupported format: ${Z}`)}let J=$??j9(process.cwd(),`session-${Q}.${z}`);return await Bun.write(J,X),J}sessionToMarkdown(Q){let Z=[];Z.push(`# Session: ${Q.metadata.id}`),Z.push(""),Z.push(`**Created:** ${new Date(Q.metadata.created).toISOString()}`),Z.push(`**Model:** ${Q.metadata.model}`),Z.push(`**Working Directory:** ${Q.metadata.workingDirectory}`),Z.push(""),Z.push("## Conversation"),Z.push("");for(let $ of Q.messages){let V=$.role==="user"?"**User**":"**Claude**";Z.push(`### ${V}`),Z.push("");for(let X of $.content)if(X.type==="text")Z.push(X.text),Z.push("");else if(X.type==="tool_use"){let z=X;Z.push(`\`\`\`tool:${z.name}`),Z.push(JSON.stringify(z.input,null,2)),Z.push("```"),Z.push("")}else if(X.type==="tool_result"){let z=X;Z.push(`**Result**${z.is_error?" (error)":""}:`),Z.push("```"),Z.push(typeof z.content==="string"?z.content:JSON.stringify(z.content,null,2)),Z.push("```"),Z.push("")}}if(Q.metrics.length>0){Z.push("## Metrics"),Z.push("");let $=Q.metrics.reduce((z,J)=>z+J.costUSD,0),V=Q.metrics.reduce((z,J)=>z+J.usage.input_tokens,0),X=Q.metrics.reduce((z,J)=>z+J.usage.output_tokens,0);Z.push(`- **Total Cost:** $${$.toFixed(4)}`),Z.push(`- **Total Input Tokens:** ${V.toLocaleString()}`),Z.push(`- **Total Output Tokens:** ${X.toLocaleString()}`),Z.push(`- **API Calls:** ${Q.metrics.length}`)}return Z.join(`
48
+ `)}async deleteSession(Q){let Z=j9(this.sessionsDir,`${Q}.jsonl`);try{if(await Bun.file(Z).exists()){let{unlink:V}=await import("fs/promises");return await V(Z),!0}return!1}catch{return!1}}}function o6(Q){let Z=new Date(Q.created),$=new Date(Q.updated),V=a6($),X=[];X.push(`\x1B[1m${Q.id}\x1B[0m (${V})`),X.push(` Model: ${Q.model} | Messages: ${Q.messageCount}`);let z=Q.totalCost<0.01?`$${Q.totalCost.toFixed(4)}`:`$${Q.totalCost.toFixed(2)}`;if(X.push(` Cost: ${z} | Tokens: ${Q.totalTokens.input.toLocaleString()} in, ${Q.totalTokens.output.toLocaleString()} out`),Q.firstMessage)X.push(` Preview: ${Q.firstMessage}`);return X.push(` Directory: ${Q.workingDirectory}`),X.join(`
49
+ `)}function a6(Q){let $=new Date().getTime()-Q.getTime(),V=Math.floor($/60000),X=Math.floor($/3600000),z=Math.floor($/86400000);if(V<1)return"just now";if(V<60)return`${V}m ago`;if(X<24)return`${X}h ago`;if(z<7)return`${z}d ago`;return Q.toLocaleDateString()}function C$(Q){if(Q.length===0){console.log("No sessions found."),console.log(`
50
+ Start a new conversation to create a session.`);return}console.log(`\x1B[1mRecent Sessions (${Q.length})\x1B[0m
51
+ `);for(let Z of Q)console.log(o6(Z)),console.log("");console.log("To resume a session:"),console.log(" coder --resume <session-id>")}import{spawn as s0}from"child_process";import{mkdirSync as X8,rmSync as s6,existsSync as z8,readFileSync as t6}from"fs";import{join as i9}from"path";class J8{teams=new Map;teammates=new Map;messageQueue=new Map;storagePath;constructor(Q="~/.claude/teams"){if(this.storagePath=Q.replace("~",process.env.HOME||""),!z8(this.storagePath))X8(this.storagePath,{recursive:!0});this.loadTeams()}createTeam(Q){let Z={...Q,status:"active"};this.teams.set(Q.name,Z);for(let $ of Q.teammates)this.teammates.set($.teammateId,$);return this.persistTeam(Z).catch(($)=>{console.error(`Failed to persist team ${Q.name}:`,$)}),Z}getTeam(Q){return this.teams.get(Q)}listTeams(){return Array.from(this.teams.values())}deleteTeam(Q){let Z=this.teams.get(Q);if(Z){for(let V of Z.teammates)this.teammates.delete(V.teammateId),this.messageQueue.delete(V.teammateId);this.teams.delete(Q);let $=i9(this.storagePath,Q);try{s6($,{recursive:!0,force:!0})}catch(V){console.error(`Failed to delete team directory ${$}:`,V)}}}getTeammate(Q){return this.teammates.get(Q)}updateTeammateStatus(Q,Z){let $=this.teammates.get(Q);if($)$.status=Z}async spawnTeammate(Q,Z={}){let{session:$,workingDir:V=process.cwd()}=Z;if(!process.env.TMUX)await this.spawnInTerminal(Q,{session:$,workingDir:V});else await this.spawnInTmux(Q,{session:$,workingDir:V});this.updateTeammateStatus(Q.teammateId,"in_progress")}async spawnInTerminal(Q,Z){let $=["bun","run","src/cli.ts","--teammate-mode","--agent-id",Q.teammateId,"--agent-name",Q.name,"--team-name",Q.teamName,"--agent-color",Q.color];if(Q.planModeRequired)$.push("--permission-mode","plan");if(process.platform==="darwin"){let V=`
52
+ tell application "Terminal"
53
+ do script "cd ${Z.workingDir} && ${$.join(" ")}"
54
+ activate
55
+ end tell
56
+ `;s0("osascript",["-e",V])}else s0("xterm",["-e",$.join(" ")])}async spawnInTmux(Q,Z){let $=Z.session||process.env.TMUX?.split(",")[0]?.split(":")[0]||"claude";await this.tmuxCommand(["split-window","-t",$,"-c",Z.workingDir]);let V=await this.tmuxCommand(["display-message","-p","#{pane_id}"]);if(V)Q.paneId=V.trim();let X=["bun","run","src/cli.ts","--teammate-mode","--agent-id",Q.teammateId,"--agent-name",Q.name,"--team-name",Q.teamName];await this.tmuxCommand(["send-keys","-t",Q.paneId||"",X.join(" "),"Enter"])}async tmuxCommand(Q){return new Promise((Z)=>{let $=s0("tmux",Q),V="";$.stdout?.on("data",(X)=>{V+=X.toString()}),$.on("close",()=>{Z(V)})})}broadcast(Q,Z,$){let V=this.teams.get(Q);if(!V)return;let X={type:"broadcast",from:$||"system",content:Z,timestamp:Date.now()};for(let z of V.teammates){if($&&z.teammateId===$)continue;let J=this.messageQueue.get(z.teammateId)||[];J.push(X),this.messageQueue.set(z.teammateId,J)}}sendDirect(Q,Z,$){let V={type:"direct",from:Z,to:Q,content:$,timestamp:Date.now()},X=this.messageQueue.get(Q)||[];X.push(V),this.messageQueue.set(Q,X)}getMessages(Q){let Z=this.messageQueue.get(Q)||[];return this.messageQueue.delete(Q),Z}hasMessages(Q){let Z=this.messageQueue.get(Q);return Z!==void 0&&Z.length>0}peekMessages(Q){return this.messageQueue.get(Q)||[]}clearMessages(Q){this.messageQueue.delete(Q)}getMessageCount(Q){return this.messageQueue.get(Q)?.length||0}async persistTeam(Q){let Z=i9(this.storagePath,Q.name),$=i9(Z,"config.json");if(!z8(Z))X8(Z,{recursive:!0});await Bun.write(i9(Z,".gitkeep"),"");let V={name:Q.name,description:Q.description,teammates:Q.teammates,taskListId:Q.taskListId,status:Q.status,coordination:Q.coordination,updatedAt:Date.now()};await Bun.write($,JSON.stringify(V,null,2))}loadTeams(){let Q=new Bun.Glob("**/config.json");try{let Z=Array.from(Q.scanSync(this.storagePath));for(let $ of Z)try{let V=i9(this.storagePath,$);if(Bun.file(V).size===0)continue;let J=t6(V,"utf-8"),Y=JSON.parse(J);if(!Y.name||!Y.teammates||!Array.isArray(Y.teammates))continue;let K={name:Y.name,description:Y.description||"",teammates:Y.teammates,taskListId:Y.taskListId||"",status:Y.status||"active",coordination:Y.coordination||{dependencyOrder:[],communicationProtocol:"broadcast",taskAssignmentStrategy:"manual"}};this.teams.set(K.name,K);for(let q of K.teammates)this.teammates.set(q.teammateId,q)}catch(V){}}catch(Z){if(Z.code!=="ENOENT");}}async persistAllTeams(){let Q=Array.from(this.teams.values()).map((Z)=>this.persistTeam(Z));await Promise.all(Q)}}var S$={architect:(Q)=>({name:"architect",teamName:Q,role:"Code Architect",description:"Designs and plans technical architecture, API contracts, and system design",color:"blue",prompt:`You are an architect on the ${Q} team.
57
+ Your role is to design and plan the technical architecture.
58
+ Focus on:
59
+ - System design and component relationships
60
+ - API contracts and interfaces
61
+ - Data models and schemas
62
+ - Trade-offs and design decisions`,planModeRequired:!0,status:"pending"}),implementer:(Q)=>({name:"implementer",teamName:Q,role:"Software Engineer",description:"Implements features and writes clean, working code based on architecture",color:"green",prompt:`You are an implementer on the ${Q} team.
63
+ Your role is to write clean, working code based on the architecture.
64
+ Focus on:
65
+ - Implementing the designed architecture
66
+ - Writing tests
67
+ - Following coding standards
68
+ - Handling edge cases`,planModeRequired:!1,status:"pending"}),reviewer:(Q)=>({name:"reviewer",teamName:Q,role:"Code Reviewer",description:"Reviews code changes for quality, bugs, and best practices",color:"yellow",prompt:`You are a code reviewer on the ${Q} team.
69
+ Your role is to review code changes and provide feedback.
70
+ Focus on:
71
+ - Code quality and readability
72
+ - Potential bugs and issues
73
+ - Performance considerations
74
+ - Test coverage`,planModeRequired:!1,status:"pending"}),tester:(Q)=>({name:"tester",teamName:Q,role:"QA Engineer",description:"Writes tests, finds edge cases, and verifies requirements",color:"orange",prompt:`You are a tester on the ${Q} team.
75
+ Your role is to ensure features work correctly.
76
+ Focus on:
77
+ - Writing comprehensive tests
78
+ - Finding edge cases
79
+ - Verifying requirements
80
+ - Reporting bugs`,planModeRequired:!1,status:"pending"})};function Y8(){return`teammate_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function I$(Q){return{...Q,teammateId:Y8(),status:"pending"}}var U0=null;function B9(){if(!U0)U0=new J8;return U0}function x$(Q){U0=Q}var t0={name:"TeamCreate",description:`Create a new team with multiple teammates for parallel task execution.
81
+
82
+ Teams allow you to spawn multiple AI agents that work together on related tasks.
83
+ Each teammate runs in its own terminal/tmux pane and can communicate with others.
84
+
85
+ Usage:
86
+ - Create a team with a descriptive name and list of teammates
87
+ - Each teammate needs: name, role, description, and optional prompt
88
+ - Teammates can be spawned after creation using TeammateSpawn
89
+
90
+ Returns the team configuration with all teammate IDs for spawning.`,input_schema:{type:"object",properties:{name:{type:"string",description:"Unique team name (e.g., 'feature-auth-team')"},description:{type:"string",description:"Team description and goals"},teammates:{type:"array",description:"List of teammates to create",items:{type:"object",properties:{name:{type:"string",description:"Teammate name (e.g., 'architect', 'implementer')"},role:{type:"string",description:"Role in the team (e.g., 'Code Architect', 'Test Engineer')"},description:{type:"string",description:"Detailed description of responsibilities"},prompt:{type:"string",description:"Custom system prompt for this teammate"},color:{type:"string",description:"Color for UI display (blue, green, yellow, orange, red, purple)"},planModeRequired:{type:"boolean",description:"Whether this teammate requires plan mode"}},required:["name","role","description"]},minItems:1},coordination:{type:"object",description:"Team coordination settings",properties:{dependencyOrder:{type:"array",description:"Order of teammate execution (teammate names)",items:{type:"string"}},communicationProtocol:{type:"string",enum:["broadcast","direct","mixed"],description:"How teammates communicate"},taskAssignmentStrategy:{type:"string",enum:["manual","auto","priority"],description:"How tasks are assigned"}}}},required:["name","description","teammates"]},handler:async(Q,Z)=>{let{name:$,description:V,teammates:X,coordination:z}=Q;try{let J=B9();if(J.getTeam($))return{content:`Error: Team "${$}" already exists. Use a different name or delete the existing team first.`,is_error:!0};let Y=X.map((q,W)=>({teammateId:Y8(),name:q.name,teamName:$,role:q.role,description:q.description,prompt:q.prompt||`You are ${q.name}, a ${q.role} on the ${$} team.
91
+
92
+ ${q.description}`,color:q.color||["blue","green","yellow","orange","purple","red"][W%6],planModeRequired:q.planModeRequired??!1,status:"pending"})),K=J.createTeam({name:$,description:V,teammates:Y,taskListId:"",coordination:{dependencyOrder:z?.dependencyOrder||[],communicationProtocol:z?.communicationProtocol||"broadcast",taskAssignmentStrategy:z?.taskAssignmentStrategy||"manual"}});return{content:JSON.stringify({success:!0,team:{name:K.name,description:K.description,status:K.status,coordination:K.coordination},teammates:Y.map((q)=>({teammateId:q.teammateId,name:q.name,role:q.role,color:q.color,status:q.status})),message:`Team "${$}" created with ${Y.length} teammates. Use TeammateSpawn to start them.`},null,2)}}catch(J){return{content:`Error creating team: ${J instanceof Error?J.message:String(J)}`,is_error:!0}}}},e0={name:"TeammateSpawn",description:`Spawn a teammate agent to work on a task.
93
+
94
+ Spawns a new Claude Code instance in a separate terminal/tmux pane.
95
+ The teammate will run autonomously with its own context and can communicate
96
+ with other teammates through the messaging system.
97
+
98
+ Usage:
99
+ - First create a team using TeamCreate
100
+ - Spawn individual teammates using their teammateId
101
+ - Teammates run in their own context with their assigned role/prompt`,input_schema:{type:"object",properties:{teammateId:{type:"string",description:"The teammate ID to spawn (from TeamCreate response)"},teamName:{type:"string",description:"The team name (optional if teammateId is provided)"},task:{type:"string",description:"Initial task/prompt for the teammate"},workingDir:{type:"string",description:"Working directory for the teammate (default: current)"},model:{type:"string",enum:["sonnet","opus","haiku"],description:"Model for the teammate (default: sonnet)"}},required:["teammateId"]},handler:async(Q,Z)=>{let{teammateId:$,task:V}=Q,X=Q.workingDir||Z.workingDirectory,z=Q.model||"sonnet";try{let J=B9(),Y=J.getTeammate($);if(!Y)return{content:`Error: Teammate "${$}" not found. Use TeamList to see available teammates.`,is_error:!0};if(Y.status==="in_progress")return{content:`Teammate "${Y.name}" is already running.`,is_error:!0};if(await J.spawnTeammate(Y,{session:process.env.TMUX?.split(",")[0]?.split(":")[0],workingDir:X}),V)J.sendDirect($,"system",V);return{content:JSON.stringify({success:!0,teammate:{teammateId:Y.teammateId,name:Y.name,teamName:Y.teamName,role:Y.role,status:"in_progress",paneId:Y.paneId},message:`Teammate "${Y.name}" spawned successfully.`,note:"Teammate runs in separate terminal. Use TeammateMessage to communicate."},null,2)}}catch(J){return{content:`Error spawning teammate: ${J instanceof Error?J.message:String(J)}`,is_error:!0}}}},QQ={name:"TeammateMessage",description:`Send a message to one or more teammates.
102
+
103
+ Supports two modes:
104
+ - Direct: Send to a specific teammate
105
+ - Broadcast: Send to all teammates in a team
106
+
107
+ Messages are queued and retrieved when teammates check for messages.
108
+ This enables asynchronous coordination between teammates.`,input_schema:{type:"object",properties:{type:{type:"string",enum:["direct","broadcast"],description:"Message type (direct to one, broadcast to all)"},to:{type:"string",description:"Recipient teammateId (for direct messages)"},teamName:{type:"string",description:"Team name (for broadcast messages)"},from:{type:"string",description:"Sender identifier (default: 'system')"},content:{type:"string",description:"Message content"}},required:["type","content"]},handler:async(Q,Z)=>{let{type:$,content:V}=Q,X=Q.from||"system";try{let z=B9();if($==="direct"){let J=Q.to;if(!J)return{content:"Error: 'to' is required for direct messages",is_error:!0};let Y=z.getTeammate(J);if(!Y)return{content:`Error: Teammate "${J}" not found`,is_error:!0};return z.sendDirect(J,X,V),{content:JSON.stringify({success:!0,type:"direct",to:Y.name,from:X,messageCount:z.getMessageCount(J)})}}else{let J=Q.teamName;if(!J)return{content:"Error: 'teamName' is required for broadcast messages",is_error:!0};let Y=z.getTeam(J);if(!Y)return{content:`Error: Team "${J}" not found`,is_error:!0};return z.broadcast(J,V,X),{content:JSON.stringify({success:!0,type:"broadcast",teamName:J,from:X,recipients:Y.teammates.filter((K)=>K.teammateId!==X).map((K)=>({name:K.name,id:K.teammateId}))})}}}catch(z){return{content:`Error sending message: ${z instanceof Error?z.message:String(z)}`,is_error:!0}}}},ZQ={name:"TeammateStatus",description:`Check the status of teammates and teams.
109
+
110
+ Returns status information including:
111
+ - Team overview with all teammates
112
+ - Individual teammate status (pending, in_progress, idle, completed, failed)
113
+ - Pending message counts
114
+ - Coordination settings`,input_schema:{type:"object",properties:{teamName:{type:"string",description:"Team name to check (optional, shows all if not provided)"},teammateId:{type:"string",description:"Specific teammate ID to check (optional)"}},required:[]},handler:async(Q,Z)=>{let{teamName:$,teammateId:V}=Q;try{let X=B9();if(V){let J=X.getTeammate(V);if(!J)return{content:`Error: Teammate "${V}" not found`,is_error:!0};return{content:JSON.stringify({teammate:{...J,pendingMessages:X.getMessageCount(V)}},null,2)}}if($){let J=X.getTeam($);if(!J)return{content:`Error: Team "${$}" not found`,is_error:!0};return{content:JSON.stringify({team:{name:J.name,description:J.description,status:J.status,coordination:J.coordination},teammates:J.teammates.map((Y)=>({...Y,pendingMessages:X.getMessageCount(Y.teammateId)}))},null,2)}}let z=X.listTeams();return{content:JSON.stringify({teams:z.map((J)=>({name:J.name,description:J.description,status:J.status,teammateCount:J.teammates.length,teammates:J.teammates.map((Y)=>({name:Y.name,status:Y.status,pendingMessages:X.getMessageCount(Y.teammateId)}))})),totalTeams:z.length},null,2)}}catch(X){return{content:`Error getting status: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}},$Q={name:"TeamList",description:`List all teams and their teammates.
115
+
116
+ Shows a summary of all configured teams including:
117
+ - Team name, description, status
118
+ - All teammates with their roles and status
119
+ - Coordination settings`,input_schema:{type:"object",properties:{verbose:{type:"boolean",description:"Include detailed information (default: false)"}},required:[]},handler:async(Q,Z)=>{let $=Q.verbose||!1;try{let X=B9().listTeams();if(X.length===0)return{content:"No teams configured. Use TeamCreate to create a team."};let z=X.map((J)=>{let Y={name:J.name,description:J.description,status:J.status,teammateCount:J.teammates.length};if($)return{...Y,coordination:J.coordination,teammates:J.teammates.map((K)=>({id:K.teammateId,name:K.name,role:K.role,status:K.status,color:K.color}))};return{...Y,teammates:J.teammates.map((K)=>`${K.name} (${K.status})`).join(", ")}});return{content:JSON.stringify({teams:z,total:X.length},null,2)}}catch(V){return{content:`Error listing teams: ${V instanceof Error?V.message:String(V)}`,is_error:!0}}}},VQ={name:"TeammateUpdate",description:`Update a teammate's status or configuration.
120
+
121
+ Used by teammates to report their progress and by coordinators to manage teammates.`,input_schema:{type:"object",properties:{teammateId:{type:"string",description:"The teammate ID to update"},status:{type:"string",enum:["pending","in_progress","idle","completed","failed"],description:"New status for the teammate"}},required:["teammateId"]},handler:async(Q,Z)=>{let{teammateId:$,status:V}=Q;try{let X=B9(),z=X.getTeammate($);if(!z)return{content:`Error: Teammate "${$}" not found`,is_error:!0};if(V)X.updateTeammateStatus($,V);return{content:JSON.stringify({success:!0,teammate:{teammateId:z.teammateId,name:z.name,status:V||z.status}})}}catch(X){return{content:`Error updating teammate: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}},XQ={name:"TeammateMessages",description:`Retrieve pending messages for a teammate.
122
+
123
+ Called by teammates to check for new messages from other teammates or the system.
124
+ Messages are retrieved and cleared from the queue.`,input_schema:{type:"object",properties:{teammateId:{type:"string",description:"The teammate ID to get messages for"},peek:{type:"boolean",description:"Peek at messages without clearing them (default: false)"}},required:["teammateId"]},handler:async(Q,Z)=>{let $=Q.teammateId,V=Q.peek||!1;try{let X=B9(),z=X.getTeammate($);if(!z)return{content:`Error: Teammate "${$}" not found`,is_error:!0};let J=V?X.peekMessages($):X.getMessages($);return{content:JSON.stringify({teammateId:$,teammateName:z.name,messageCount:J.length,messages:J.map((Y)=>({type:Y.type,from:Y.from,to:Y.to,content:Y.content,timestamp:new Date(Y.timestamp).toISOString()}))},null,2)}}catch(X){return{content:`Error getting messages: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}},zQ={name:"TeamDelete",description:`Delete a team and all its teammates.
125
+
126
+ Warning: This permanently removes the team configuration.
127
+ Running teammates will continue but lose team association.`,input_schema:{type:"object",properties:{name:{type:"string",description:"The team name to delete"}},required:["name"]},handler:async(Q,Z)=>{let $=Q.name;try{let V=B9(),X=V.getTeam($);if(!X)return{content:`Error: Team "${$}" not found`,is_error:!0};let z=X.teammates.length;return V.deleteTeam($),{content:JSON.stringify({success:!0,deletedTeam:$,deletedTeammates:z})}}catch(V){return{content:`Error deleting team: ${V instanceof Error?V.message:String(V)}`,is_error:!0}}}},E$=[t0,$Q,zQ,e0,QQ,XQ,ZQ,VQ];var JQ=(Q,Z,$)=>{let V=Q instanceof RegExp?K8(Q,$):Q,X=Z instanceof RegExp?K8(Z,$):Z,z=V!==null&&X!=null&&e6(V,X,$);return z&&{start:z[0],end:z[1],pre:$.slice(0,z[0]),body:$.slice(z[0]+V.length,z[1]),post:$.slice(z[1]+X.length)}},K8=(Q,Z)=>{let $=Z.match(Q);return $?$[0]:null},e6=(Q,Z,$)=>{let V,X,z,J=void 0,Y,K=$.indexOf(Q),q=$.indexOf(Z,K+1),W=K;if(K>=0&&q>0){if(Q===Z)return[K,q];V=[],z=$.length;while(W>=0&&!Y){if(W===K)V.push(W),K=$.indexOf(Q,W+1);else if(V.length===1){let H=V.pop();if(H!==void 0)Y=[H,q]}else{if(X=V.pop(),X!==void 0&&X<z)z=X,J=q;q=$.indexOf(Z,W+1)}W=K<q&&K>=0?K:q}if(V.length&&J!==void 0)Y=[z,J]}return Y};var q8="\x00SLASH"+Math.random()+"\x00",W8="\x00OPEN"+Math.random()+"\x00",KQ="\x00CLOSE"+Math.random()+"\x00",H8="\x00COMMA"+Math.random()+"\x00",G8="\x00PERIOD"+Math.random()+"\x00",QZ=new RegExp(q8,"g"),ZZ=new RegExp(W8,"g"),$Z=new RegExp(KQ,"g"),VZ=new RegExp(H8,"g"),XZ=new RegExp(G8,"g"),zZ=/\\\\/g,JZ=/\\{/g,YZ=/\\}/g,KZ=/\\,/g,qZ=/\\./g,WZ=1e5;function YQ(Q){return!isNaN(Q)?parseInt(Q,10):Q.charCodeAt(0)}function HZ(Q){return Q.replace(zZ,q8).replace(JZ,W8).replace(YZ,KQ).replace(KZ,H8).replace(qZ,G8)}function GZ(Q){return Q.replace(QZ,"\\").replace(ZZ,"{").replace($Z,"}").replace(VZ,",").replace(XZ,".")}function _8(Q){if(!Q)return[""];let Z=[],$=JQ("{","}",Q);if(!$)return Q.split(",");let{pre:V,body:X,post:z}=$,J=V.split(",");J[J.length-1]+="{"+X+"}";let Y=_8(z);if(z.length)J[J.length-1]+=Y.shift(),J.push.apply(J,Y);return Z.push.apply(Z,J),Z}function j8(Q,Z={}){if(!Q)return[];let{max:$=WZ}=Z;if(Q.slice(0,2)==="{}")Q="\\{\\}"+Q.slice(2);return n9(HZ(Q),$,!0).map(GZ)}function _Z(Q){return"{"+Q+"}"}function jZ(Q){return/^-?0\d/.test(Q)}function UZ(Q,Z){return Q<=Z}function wZ(Q,Z){return Q>=Z}function n9(Q,Z,$){let V=[],X=JQ("{","}",Q);if(!X)return[Q];let z=X.pre,J=X.post.length?n9(X.post,Z,!1):[""];if(/\$$/.test(X.pre))for(let Y=0;Y<J.length&&Y<Z;Y++){let K=z+"{"+X.body+"}"+J[Y];V.push(K)}else{let Y=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(X.body),K=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(X.body),q=Y||K,W=X.body.indexOf(",")>=0;if(!q&&!W){if(X.post.match(/,(?!,).*\}/))return Q=X.pre+"{"+X.body+KQ+X.post,n9(Q,Z,!0);return[Q]}let H;if(q)H=X.body.split(/\.\./);else if(H=_8(X.body),H.length===1&&H[0]!==void 0){if(H=n9(H[0],Z,!1).map(_Z),H.length===1)return J.map((_)=>X.pre+H[0]+_)}let G;if(q&&H[0]!==void 0&&H[1]!==void 0){let _=YQ(H[0]),U=YQ(H[1]),j=Math.max(H[0].length,H[1].length),A=H.length===3&&H[2]!==void 0?Math.abs(YQ(H[2])):1,w=UZ;if(U<_)A*=-1,w=wZ;let O=H.some(jZ);G=[];for(let v=_;w(v,U);v+=A){let L;if(K){if(L=String.fromCharCode(v),L==="\\")L=""}else if(L=String(v),O){let I=j-L.length;if(I>0){let y=Array(I+1).join("0");if(v<0)L="-"+y+L.slice(1);else L=y+L}}G.push(L)}}else{G=[];for(let _=0;_<H.length;_++)G.push.apply(G,n9(H[_],Z,!1))}for(let _=0;_<G.length;_++)for(let U=0;U<J.length&&V.length<Z;U++){let j=z+G[_]+J[U];if(!$||q||j)V.push(j)}}return V}var r9=(Q)=>{if(typeof Q!=="string")throw TypeError("invalid pattern");if(Q.length>65536)throw TypeError("pattern is too long")};var AZ={"[: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]},o9=(Q)=>Q.replace(/[[\]\\-]/g,"\\$&"),BZ=(Q)=>Q.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),U8=(Q)=>Q.join(""),w8=(Q,Z)=>{let $=Z;if(Q.charAt($)!=="[")throw Error("not in a brace expression");let V=[],X=[],z=$+1,J=!1,Y=!1,K=!1,q=!1,W=$,H="";Q:while(z<Q.length){let j=Q.charAt(z);if((j==="!"||j==="^")&&z===$+1){q=!0,z++;continue}if(j==="]"&&J&&!K){W=z+1;break}if(J=!0,j==="\\"){if(!K){K=!0,z++;continue}}if(j==="["&&!K){for(let[A,[w,B,O]]of Object.entries(AZ))if(Q.startsWith(A,z)){if(H)return["$.",!1,Q.length-$,!0];if(z+=A.length,O)X.push(w);else V.push(w);Y=Y||B;continue Q}}if(K=!1,H){if(j>H)V.push(o9(H)+"-"+o9(j));else if(j===H)V.push(o9(j));H="",z++;continue}if(Q.startsWith("-]",z+1)){V.push(o9(j+"-")),z+=2;continue}if(Q.startsWith("-",z+1)){H=j,z+=2;continue}V.push(o9(j)),z++}if(W<z)return["",!1,0,!1];if(!V.length&&!X.length)return["$.",!1,Q.length-$,!0];if(X.length===0&&V.length===1&&/^\\?.$/.test(V[0])&&!q){let j=V[0].length===2?V[0].slice(-1):V[0];return[BZ(j),!1,W-$,!1]}let G="["+(q?"^":"")+U8(V)+"]",_="["+(q?"":"^")+U8(X)+"]";return[V.length&&X.length?"("+G+"|"+_+")":V.length?G:_,Y,W-$,!0]};var a=(Q,{windowsPathsNoEscape:Z=!1,magicalBraces:$=!0}={})=>{if($)return Z?Q.replace(/\[([^\/\\])\]/g,"$1"):Q.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");return Z?Q.replace(/\[([^\/\\{}])\]/g,"$1"):Q.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1")};var g,LZ=new Set(["!","?","+","*","@"]),qQ=(Q)=>LZ.has(Q),A8=(Q)=>qQ(Q.type),FZ=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),OZ=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),vZ=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),B8=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),MZ="(?!(?:^|/)\\.\\.?(?:$|/))",w0="(?!\\.)",CZ=new Set(["[","."]),RZ=new Set(["..","."]),DZ=new Set("().*{}+?[]^$\\!"),PZ=(Q)=>Q.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),WQ="[^/]",L8=WQ+"*?",F8=WQ+"+?",NZ=0;class x9{type;#Q;#V;#X=!1;#Z=[];#J;#M;#B;#H=!1;#Y;#G;#W=!1;id=++NZ;get depth(){return(this.#J?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#Q.id,parent:this.#J?.id,depth:this.depth,partsLength:this.#Z.length,parts:this.#Z}}constructor(Q,Z,$={}){if(this.type=Q,Q)this.#V=!0;if(this.#J=Z,this.#Q=this.#J?this.#J.#Q:this,this.#Y=this.#Q===this?$:this.#Q.#Y,this.#B=this.#Q===this?[]:this.#Q.#B,Q==="!"&&!this.#Q.#H)this.#B.push(this);this.#M=this.#J?this.#J.#Z.length:0}get hasMagic(){if(this.#V!==void 0)return this.#V;for(let Q of this.#Z){if(typeof Q==="string")continue;if(Q.type||Q.hasMagic)return this.#V=!0}return this.#V}toString(){if(this.#G!==void 0)return this.#G;if(!this.type)return this.#G=this.#Z.map((Q)=>String(Q)).join("");else return this.#G=this.type+"("+this.#Z.map((Q)=>String(Q)).join("|")+")"}#K(){if(this!==this.#Q)throw Error("should only call on root");if(this.#H)return this;this.toString(),this.#H=!0;let Q;while(Q=this.#B.pop()){if(Q.type!=="!")continue;let Z=Q,$=Z.#J;while($){for(let V=Z.#M+1;!$.type&&V<$.#Z.length;V++)for(let X of Q.#Z){if(typeof X==="string")throw Error("string part in extglob AST??");X.copyIn($.#Z[V])}Z=$,$=Z.#J}}return this}push(...Q){for(let Z of Q){if(Z==="")continue;if(typeof Z!=="string"&&!(Z instanceof g&&Z.#J===this))throw Error("invalid part: "+Z);this.#Z.push(Z)}}toJSON(){let Q=this.type===null?this.#Z.slice().map((Z)=>typeof Z==="string"?Z:Z.toJSON()):[this.type,...this.#Z.map((Z)=>Z.toJSON())];if(this.isStart()&&!this.type)Q.unshift([]);if(this.isEnd()&&(this===this.#Q||this.#Q.#H&&this.#J?.type==="!"))Q.push({});return Q}isStart(){if(this.#Q===this)return!0;if(!this.#J?.isStart())return!1;if(this.#M===0)return!0;let Q=this.#J;for(let Z=0;Z<this.#M;Z++){let $=Q.#Z[Z];if(!($ instanceof g&&$.type==="!"))return!1}return!0}isEnd(){if(this.#Q===this)return!0;if(this.#J?.type==="!")return!0;if(!this.#J?.isEnd())return!1;if(!this.type)return this.#J?.isEnd();let Q=this.#J?this.#J.#Z.length:0;return this.#M===Q-1}copyIn(Q){if(typeof Q==="string")this.push(Q);else this.push(Q.clone(this))}clone(Q){let Z=new g(this.type,Q);for(let $ of this.#Z)Z.copyIn($);return Z}static#z(Q,Z,$,V,X){let z=V.maxExtglobRecursion??2,J=!1,Y=!1,K=-1,q=!1;if(Z.type===null){let U=$,j="";while(U<Q.length){let A=Q.charAt(U++);if(J||A==="\\"){J=!J,j+=A;continue}if(Y){if(U===K+1){if(A==="^"||A==="!")q=!0}else if(A==="]"&&!(U===K+2&&q))Y=!1;j+=A;continue}else if(A==="["){Y=!0,K=U,q=!1,j+=A;continue}if(!V.noext&&qQ(A)&&Q.charAt(U)==="("&&X<=z){Z.push(j),j="";let B=new g(A,Z);U=g.#z(Q,B,U,V,X+1),Z.push(B);continue}j+=A}return Z.push(j),U}let W=$+1,H=new g(null,Z),G=[],_="";while(W<Q.length){let U=Q.charAt(W++);if(J||U==="\\"){J=!J,_+=U;continue}if(Y){if(W===K+1){if(U==="^"||U==="!")q=!0}else if(U==="]"&&!(W===K+2&&q))Y=!1;_+=U;continue}else if(U==="["){Y=!0,K=W,q=!1,_+=U;continue}if(!V.noext&&qQ(U)&&Q.charAt(W)==="("&&(X<=z||Z&&Z.#j(U))){let A=Z&&Z.#j(U)?0:1;H.push(_),_="";let w=new g(U,H);H.push(w),W=g.#z(Q,w,W,V,X+A);continue}if(U==="|"){H.push(_),_="",G.push(H),H=new g(null,Z);continue}if(U===")"){if(_===""&&Z.#Z.length===0)Z.#W=!0;return H.push(_),_="",Z.push(...G,H),W}_+=U}return Z.type=null,Z.#V=void 0,Z.#Z=[Q.substring($-1)],W}#L(Q){return this.#O(Q,OZ)}#O(Q,Z=FZ){if(!Q||typeof Q!=="object"||Q.type!==null||Q.#Z.length!==1||this.type===null)return!1;let $=Q.#Z[0];if(!$||typeof $!=="object"||$.type===null)return!1;return this.#j($.type,Z)}#j(Q,Z=vZ){return!!Z.get(this.type)?.includes(Q)}#U(Q,Z){let $=Q.#Z[0],V=new g(null,$,this.options);V.#Z.push(""),$.push(V),this.#D(Q,Z)}#D(Q,Z){let $=Q.#Z[0];this.#Z.splice(Z,1,...$.#Z);for(let V of $.#Z)if(typeof V==="object")V.#J=this;this.#G=void 0}#w(Q){return!!B8.get(this.type)?.has(Q)}#v(Q){if(!Q||typeof Q!=="object"||Q.type!==null||Q.#Z.length!==1||this.type===null||this.#Z.length!==1)return!1;let Z=Q.#Z[0];if(!Z||typeof Z!=="object"||Z.type===null)return!1;return this.#w(Z.type)}#C(Q){let Z=B8.get(this.type),$=Q.#Z[0],V=Z?.get($.type);if(!V)return!1;this.#Z=$.#Z;for(let X of this.#Z)if(typeof X==="object")X.#J=this;this.type=V,this.#G=void 0,this.#W=!1}static fromGlob(Q,Z={}){let $=new g(null,void 0,Z);return g.#z(Q,$,0,Z,0),$}toMMPattern(){if(this!==this.#Q)return this.#Q.toMMPattern();let Q=this.toString(),[Z,$,V,X]=this.toRegExpSource();if(!(V||this.#V||this.#Y.nocase&&!this.#Y.nocaseMagicOnly&&Q.toUpperCase()!==Q.toLowerCase()))return $;let J=(this.#Y.nocase?"i":"")+(X?"u":"");return Object.assign(new RegExp(`^${Z}$`,J),{_src:Z,_glob:Q})}get options(){return this.#Y}toRegExpSource(Q){let Z=Q??!!this.#Y.dot;if(this.#Q===this)this.#_(),this.#K();if(!A8(this)){let Y=this.isStart()&&this.isEnd()&&!this.#Z.some((G)=>typeof G!=="string"),K=this.#Z.map((G)=>{let[_,U,j,A]=typeof G==="string"?g.#F(G,this.#V,Y):G.toRegExpSource(Q);return this.#V=this.#V||j,this.#X=this.#X||A,_}).join(""),q="";if(this.isStart()){if(typeof this.#Z[0]==="string"){if(!(this.#Z.length===1&&RZ.has(this.#Z[0]))){let _=CZ,U=Z&&_.has(K.charAt(0))||K.startsWith("\\.")&&_.has(K.charAt(2))||K.startsWith("\\.\\.")&&_.has(K.charAt(4)),j=!Z&&!Q&&_.has(K.charAt(0));q=U?MZ:j?w0:""}}}let W="";if(this.isEnd()&&this.#Q.#H&&this.#J?.type==="!")W="(?:$|\\/)";return[q+K+W,a(K),this.#V=!!this.#V,this.#X]}let $=this.type==="*"||this.type==="+",V=this.type==="!"?"(?:(?!(?:":"(?:",X=this.#A(Z);if(this.isStart()&&this.isEnd()&&!X&&this.type!=="!"){let Y=this.toString(),K=this;return K.#Z=[Y],K.type=null,K.#V=void 0,[Y,a(this.toString()),!1,!1]}let z=!$||Q||Z||!w0?"":this.#A(!0);if(z===X)z="";if(z)X=`(?:${X})(?:${z})*?`;let J="";if(this.type==="!"&&this.#W)J=(this.isStart()&&!Z?w0:"")+F8;else{let Y=this.type==="!"?"))"+(this.isStart()&&!Z&&!Q?w0:"")+L8+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&z?")":this.type==="*"&&z?")?":`)${this.type}`;J=V+X+Y}return[J,a(X),this.#V=!!this.#V,this.#X]}#_(){if(!A8(this)){for(let Q of this.#Z)if(typeof Q==="object")Q.#_()}else{let Q=0,Z=!1;do{Z=!0;for(let $=0;$<this.#Z.length;$++){let V=this.#Z[$];if(typeof V==="object"){if(V.#_(),this.#O(V))Z=!1,this.#D(V,$);else if(this.#L(V))Z=!1,this.#U(V,$);else if(this.#v(V))Z=!1,this.#C(V)}}}while(!Z&&++Q<10)}this.#G=void 0}#A(Q){return this.#Z.map((Z)=>{if(typeof Z==="string")throw Error("string type in extglob ast??");let[$,V,X,z]=Z.toRegExpSource(Q);return this.#X=this.#X||z,$}).filter((Z)=>!(this.isStart()&&this.isEnd())||!!Z).join("|")}static#F(Q,Z,$=!1){let V=!1,X="",z=!1,J=!1;for(let Y=0;Y<Q.length;Y++){let K=Q.charAt(Y);if(V){V=!1,X+=(DZ.has(K)?"\\":"")+K;continue}if(K==="*"){if(J)continue;J=!0,X+=$&&/^[*]+$/.test(Q)?F8:L8,Z=!0;continue}else J=!1;if(K==="\\"){if(Y===Q.length-1)X+="\\\\";else V=!0;continue}if(K==="["){let[q,W,H,G]=w8(Q,Y);if(H){X+=q,z=z||W,Y+=H-1,Z=Z||G;continue}}if(K==="?"){X+=WQ,Z=!0;continue}X+=PZ(K)}return[X,a(Q),!!Z,z]}}g=x9;var E9=(Q,{windowsPathsNoEscape:Z=!1,magicalBraces:$=!1}={})=>{if($)return Z?Q.replace(/[?*()[\]{}]/g,"[$&]"):Q.replace(/[?*()[\]\\{}]/g,"\\$&");return Z?Q.replace(/[?*()[\]]/g,"[$&]"):Q.replace(/[?*()[\]\\]/g,"\\$&")};var f=(Q,Z,$={})=>{if(r9(Z),!$.nocomment&&Z.charAt(0)==="#")return!1;return new p(Z,$).match(Q)},SZ=/^\*+([^+@!?\*\[\(]*)$/,IZ=(Q)=>(Z)=>!Z.startsWith(".")&&Z.endsWith(Q),xZ=(Q)=>(Z)=>Z.endsWith(Q),EZ=(Q)=>{return Q=Q.toLowerCase(),(Z)=>!Z.startsWith(".")&&Z.toLowerCase().endsWith(Q)},TZ=(Q)=>{return Q=Q.toLowerCase(),(Z)=>Z.toLowerCase().endsWith(Q)},yZ=/^\*+\.\*+$/,kZ=(Q)=>!Q.startsWith(".")&&Q.includes("."),bZ=(Q)=>Q!=="."&&Q!==".."&&Q.includes("."),fZ=/^\.\*+$/,uZ=(Q)=>Q!=="."&&Q!==".."&&Q.startsWith("."),hZ=/^\*+$/,gZ=(Q)=>Q.length!==0&&!Q.startsWith("."),dZ=(Q)=>Q.length!==0&&Q!=="."&&Q!=="..",mZ=/^\?+([^+@!?\*\[\(]*)?$/,cZ=([Q,Z=""])=>{let $=M8([Q]);if(!Z)return $;return Z=Z.toLowerCase(),(V)=>$(V)&&V.toLowerCase().endsWith(Z)},lZ=([Q,Z=""])=>{let $=C8([Q]);if(!Z)return $;return Z=Z.toLowerCase(),(V)=>$(V)&&V.toLowerCase().endsWith(Z)},pZ=([Q,Z=""])=>{let $=C8([Q]);return!Z?$:(V)=>$(V)&&V.endsWith(Z)},iZ=([Q,Z=""])=>{let $=M8([Q]);return!Z?$:(V)=>$(V)&&V.endsWith(Z)},M8=([Q])=>{let Z=Q.length;return($)=>$.length===Z&&!$.startsWith(".")},C8=([Q])=>{let Z=Q.length;return($)=>$.length===Z&&$!=="."&&$!==".."},R8=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",O8={win32:{sep:"\\"},posix:{sep:"/"}},nZ=R8==="win32"?O8.win32.sep:O8.posix.sep;f.sep=nZ;var N=Symbol("globstar **");f.GLOBSTAR=N;var rZ="[^/]",oZ=rZ+"*?",aZ="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",sZ="(?:(?!(?:\\/|^)\\.).)*?",tZ=(Q,Z={})=>($)=>f($,Q,Z);f.filter=tZ;var l=(Q,Z={})=>Object.assign({},Q,Z),eZ=(Q)=>{if(!Q||typeof Q!=="object"||!Object.keys(Q).length)return f;let Z=f;return Object.assign((V,X,z={})=>Z(V,X,l(Q,z)),{Minimatch:class extends Z.Minimatch{constructor(X,z={}){super(X,l(Q,z))}static defaults(X){return Z.defaults(l(Q,X)).Minimatch}},AST:class extends Z.AST{constructor(X,z,J={}){super(X,z,l(Q,J))}static fromGlob(X,z={}){return Z.AST.fromGlob(X,l(Q,z))}},unescape:(V,X={})=>Z.unescape(V,l(Q,X)),escape:(V,X={})=>Z.escape(V,l(Q,X)),filter:(V,X={})=>Z.filter(V,l(Q,X)),defaults:(V)=>Z.defaults(l(Q,V)),makeRe:(V,X={})=>Z.makeRe(V,l(Q,X)),braceExpand:(V,X={})=>Z.braceExpand(V,l(Q,X)),match:(V,X,z={})=>Z.match(V,X,l(Q,z)),sep:Z.sep,GLOBSTAR:N})};f.defaults=eZ;var D8=(Q,Z={})=>{if(r9(Q),Z.nobrace||!/\{(?:(?!\{).)*\}/.test(Q))return[Q];return j8(Q,{max:Z.braceExpandMax})};f.braceExpand=D8;var Q5=(Q,Z={})=>new p(Q,Z).makeRe();f.makeRe=Q5;var Z5=(Q,Z,$={})=>{let V=new p(Z,$);if(Q=Q.filter((X)=>V.match(X)),V.options.nonull&&!Q.length)Q.push(Z);return Q};f.match=Z5;var v8=/[?*]|[+@!]\(.*?\)|\[|\]/,$5=(Q)=>Q.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class p{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(Q,Z={}){r9(Q),Z=Z||{},this.options=Z,this.maxGlobstarRecursion=Z.maxGlobstarRecursion??200,this.pattern=Q,this.platform=Z.platform||R8,this.isWindows=this.platform==="win32";let $="allowWindowsEscape";if(this.windowsPathsNoEscape=!!Z.windowsPathsNoEscape||Z[$]===!1,this.windowsPathsNoEscape)this.pattern=this.pattern.replace(/\\/g,"/");this.preserveMultipleSlashes=!!Z.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!Z.nonegate,this.comment=!1,this.empty=!1,this.partial=!!Z.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=Z.windowsNoMagicRoot!==void 0?Z.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 Q of this.set)for(let Z of Q)if(typeof Z!=="string")return!0;return!1}debug(...Q){}make(){let Q=this.pattern,Z=this.options;if(!Z.nocomment&&Q.charAt(0)==="#"){this.comment=!0;return}if(!Q){this.empty=!0;return}if(this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],Z.debug)this.debug=(...X)=>console.error(...X);this.debug(this.pattern,this.globSet);let $=this.globSet.map((X)=>this.slashSplit(X));this.globParts=this.preprocess($),this.debug(this.pattern,this.globParts);let V=this.globParts.map((X,z,J)=>{if(this.isWindows&&this.windowsNoMagicRoot){let Y=X[0]===""&&X[1]===""&&(X[2]==="?"||!v8.test(X[2]))&&!v8.test(X[3]),K=/^[a-z]:/i.test(X[0]);if(Y)return[...X.slice(0,4),...X.slice(4).map((q)=>this.parse(q))];else if(K)return[X[0],...X.slice(1).map((q)=>this.parse(q))]}return X.map((Y)=>this.parse(Y))});if(this.debug(this.pattern,V),this.set=V.filter((X)=>X.indexOf(!1)===-1),this.isWindows)for(let X=0;X<this.set.length;X++){let z=this.set[X];if(z[0]===""&&z[1]===""&&this.globParts[X][2]==="?"&&typeof z[3]==="string"&&/^[a-z]:$/i.test(z[3]))z[2]="?"}this.debug(this.pattern,this.set)}preprocess(Q){if(this.options.noglobstar){for(let $=0;$<Q.length;$++)for(let V=0;V<Q[$].length;V++)if(Q[$][V]==="**")Q[$][V]="*"}let{optimizationLevel:Z=1}=this.options;if(Z>=2)Q=this.firstPhasePreProcess(Q),Q=this.secondPhasePreProcess(Q);else if(Z>=1)Q=this.levelOneOptimize(Q);else Q=this.adjascentGlobstarOptimize(Q);return Q}adjascentGlobstarOptimize(Q){return Q.map((Z)=>{let $=-1;while(($=Z.indexOf("**",$+1))!==-1){let V=$;while(Z[V+1]==="**")V++;if(V!==$)Z.splice($,V-$)}return Z})}levelOneOptimize(Q){return Q.map((Z)=>{return Z=Z.reduce(($,V)=>{let X=$[$.length-1];if(V==="**"&&X==="**")return $;if(V===".."){if(X&&X!==".."&&X!=="."&&X!=="**")return $.pop(),$}return $.push(V),$},[]),Z.length===0?[""]:Z})}levelTwoFileOptimize(Q){if(!Array.isArray(Q))Q=this.slashSplit(Q);let Z=!1;do{if(Z=!1,!this.preserveMultipleSlashes){for(let V=1;V<Q.length-1;V++){let X=Q[V];if(V===1&&X===""&&Q[0]==="")continue;if(X==="."||X==="")Z=!0,Q.splice(V,1),V--}if(Q[0]==="."&&Q.length===2&&(Q[1]==="."||Q[1]===""))Z=!0,Q.pop()}let $=0;while(($=Q.indexOf("..",$+1))!==-1){let V=Q[$-1];if(V&&V!=="."&&V!==".."&&V!=="**")Z=!0,Q.splice($-1,2),$-=2}}while(Z);return Q.length===0?[""]:Q}firstPhasePreProcess(Q){let Z=!1;do{Z=!1;for(let $ of Q){let V=-1;while((V=$.indexOf("**",V+1))!==-1){let z=V;while($[z+1]==="**")z++;if(z>V)$.splice(V+1,z-V);let J=$[V+1],Y=$[V+2],K=$[V+3];if(J!=="..")continue;if(!Y||Y==="."||Y===".."||!K||K==="."||K==="..")continue;Z=!0,$.splice(V,1);let q=$.slice(0);q[V]="**",Q.push(q),V--}if(!this.preserveMultipleSlashes){for(let z=1;z<$.length-1;z++){let J=$[z];if(z===1&&J===""&&$[0]==="")continue;if(J==="."||J==="")Z=!0,$.splice(z,1),z--}if($[0]==="."&&$.length===2&&($[1]==="."||$[1]===""))Z=!0,$.pop()}let X=0;while((X=$.indexOf("..",X+1))!==-1){let z=$[X-1];if(z&&z!=="."&&z!==".."&&z!=="**"){Z=!0;let Y=X===1&&$[X+1]==="**"?["."]:[];if($.splice(X-1,2,...Y),$.length===0)$.push("");X-=2}}}}while(Z);return Q}secondPhasePreProcess(Q){for(let Z=0;Z<Q.length-1;Z++)for(let $=Z+1;$<Q.length;$++){let V=this.partsMatch(Q[Z],Q[$],!this.preserveMultipleSlashes);if(V){Q[Z]=[],Q[$]=V;break}}return Q.filter((Z)=>Z.length)}partsMatch(Q,Z,$=!1){let V=0,X=0,z=[],J="";while(V<Q.length&&X<Z.length)if(Q[V]===Z[X])z.push(J==="b"?Z[X]:Q[V]),V++,X++;else if($&&Q[V]==="**"&&Z[X]===Q[V+1])z.push(Q[V]),V++;else if($&&Z[X]==="**"&&Q[V]===Z[X+1])z.push(Z[X]),X++;else if(Q[V]==="*"&&Z[X]&&(this.options.dot||!Z[X].startsWith("."))&&Z[X]!=="**"){if(J==="b")return!1;J="a",z.push(Q[V]),V++,X++}else if(Z[X]==="*"&&Q[V]&&(this.options.dot||!Q[V].startsWith("."))&&Q[V]!=="**"){if(J==="a")return!1;J="b",z.push(Z[X]),V++,X++}else return!1;return Q.length===Z.length&&z}parseNegate(){if(this.nonegate)return;let Q=this.pattern,Z=!1,$=0;for(let V=0;V<Q.length&&Q.charAt(V)==="!";V++)Z=!Z,$++;if($)this.pattern=Q.slice($);this.negate=Z}matchOne(Q,Z,$=!1){let V=0,X=0;if(this.isWindows){let J=typeof Q[0]==="string"&&/^[a-z]:$/i.test(Q[0]),Y=!J&&Q[0]===""&&Q[1]===""&&Q[2]==="?"&&/^[a-z]:$/i.test(Q[3]),K=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),q=!K&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&typeof Z[3]==="string"&&/^[a-z]:$/i.test(Z[3]),W=Y?3:J?0:void 0,H=q?3:K?0:void 0;if(typeof W==="number"&&typeof H==="number"){let[G,_]=[Q[W],Z[H]];if(G.toLowerCase()===_.toLowerCase())Z[H]=G,X=H,V=W}}let{optimizationLevel:z=1}=this.options;if(z>=2)Q=this.levelTwoFileOptimize(Q);if(Z.includes(N))return this.#Q(Q,Z,$,V,X);return this.#X(Q,Z,$,V,X)}#Q(Q,Z,$,V,X){let z=Z.indexOf(N,X),J=Z.lastIndexOf(N),[Y,K,q]=$?[Z.slice(X,z),Z.slice(z+1),[]]:[Z.slice(X,z),Z.slice(z+1,J),Z.slice(J+1)];if(Y.length){let w=Q.slice(V,V+Y.length);if(!this.#X(w,Y,$,0,0))return!1;V+=Y.length,X+=Y.length}let W=0;if(q.length){if(q.length+V>Q.length)return!1;let w=Q.length-q.length;if(this.#X(Q,q,$,w,0))W=q.length;else{if(Q[Q.length-1]!==""||V+q.length===Q.length)return!1;if(w--,!this.#X(Q,q,$,w,0))return!1;W=q.length+1}}if(!K.length){let w=!!W;for(let B=V;B<Q.length-W;B++){let O=String(Q[B]);if(w=!0,O==="."||O===".."||!this.options.dot&&O.startsWith("."))return!1}return $||w}let H=[[[],0]],G=H[0],_=0,U=[0];for(let w of K)if(w===N)U.push(_),G=[[],0],H.push(G);else G[0].push(w),_++;let j=H.length-1,A=Q.length-W;for(let w of H)w[1]=A-(U[j--]+w[0].length);return!!this.#V(Q,H,V,0,$,0,!!W)}#V(Q,Z,$,V,X,z,J){let Y=Z[V];if(!Y){for(let W=$;W<Q.length;W++){J=!0;let H=Q[W];if(H==="."||H===".."||!this.options.dot&&H.startsWith("."))return!1}return J}let[K,q]=Y;while($<=q){if(this.#X(Q.slice(0,$+K.length),K,X,$,0)&&z<this.maxGlobstarRecursion){let G=this.#V(Q,Z,$+K.length,V+1,X,z+1,J);if(G!==!1)return G}let H=Q[$];if(H==="."||H===".."||!this.options.dot&&H.startsWith("."))return!1;$++}return X||null}#X(Q,Z,$,V,X){let z,J,Y,K;for(z=V,J=X,K=Q.length,Y=Z.length;z<K&&J<Y;z++,J++){this.debug("matchOne loop");let q=Z[J],W=Q[z];if(this.debug(Z,q,W),q===!1||q===N)return!1;let H;if(typeof q==="string")H=W===q,this.debug("string match",q,W,H);else H=q.test(W),this.debug("pattern match",q,W,H);if(!H)return!1}if(z===K&&J===Y)return!0;else if(z===K)return $;else if(J===Y)return z===K-1&&Q[z]==="";else throw Error("wtf?")}braceExpand(){return D8(this.pattern,this.options)}parse(Q){r9(Q);let Z=this.options;if(Q==="**")return N;if(Q==="")return"";let $,V=null;if($=Q.match(hZ))V=Z.dot?dZ:gZ;else if($=Q.match(SZ))V=(Z.nocase?Z.dot?TZ:EZ:Z.dot?xZ:IZ)($[1]);else if($=Q.match(mZ))V=(Z.nocase?Z.dot?lZ:cZ:Z.dot?pZ:iZ)($);else if($=Q.match(yZ))V=Z.dot?bZ:kZ;else if($=Q.match(fZ))V=uZ;let X=x9.fromGlob(Q,this.options).toMMPattern();if(V&&typeof X==="object")Reflect.defineProperty(X,"test",{value:V});return X}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Q=this.set;if(!Q.length)return this.regexp=!1,this.regexp;let Z=this.options,$=Z.noglobstar?oZ:Z.dot?aZ:sZ,V=new Set(Z.nocase?["i"]:[]),X=Q.map((Y)=>{let K=Y.map((W)=>{if(W instanceof RegExp)for(let H of W.flags.split(""))V.add(H);return typeof W==="string"?$5(W):W===N?N:W._src});K.forEach((W,H)=>{let G=K[H+1],_=K[H-1];if(W!==N||_===N)return;if(_===void 0)if(G!==void 0&&G!==N)K[H+1]="(?:\\/|"+$+"\\/)?"+G;else K[H]=$;else if(G===void 0)K[H-1]=_+"(?:\\/|\\/"+$+")?";else if(G!==N)K[H-1]=_+"(?:\\/|\\/"+$+"\\/)"+G,K[H+1]=N});let q=K.filter((W)=>W!==N);if(this.partial&&q.length>=1){let W=[];for(let H=1;H<=q.length;H++)W.push(q.slice(0,H).join("/"));return"(?:"+W.join("|")+")"}return q.join("/")}).join("|"),[z,J]=Q.length>1?["(?:",")"]:["",""];if(X="^"+z+X+J+"$",this.partial)X="^(?:\\/|"+z+X.slice(1,-1)+J+")$";if(this.negate)X="^(?!"+X+").+$";try{this.regexp=new RegExp(X,[...V].join(""))}catch(Y){this.regexp=!1}return this.regexp}slashSplit(Q){if(this.preserveMultipleSlashes)return Q.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Q))return["",...Q.split(/\/+/)];else return Q.split(/\/+/)}match(Q,Z=this.partial){if(this.debug("match",Q,this.pattern),this.comment)return!1;if(this.empty)return Q==="";if(Q==="/"&&Z)return!0;let $=this.options;if(this.isWindows)Q=Q.split("\\").join("/");let V=this.slashSplit(Q);this.debug(this.pattern,"split",V);let X=this.set;this.debug(this.pattern,"set",X);let z=V[V.length-1];if(!z)for(let J=V.length-2;!z&&J>=0;J--)z=V[J];for(let J=0;J<X.length;J++){let Y=X[J],K=V;if($.matchBase&&Y.length===1)K=[z];if(this.matchOne(K,Y,Z)){if($.flipNegate)return!0;return!this.negate}}if($.flipNegate)return!1;return this.negate}static defaults(Q){return f.defaults(Q).Minimatch}}f.AST=x9;f.Minimatch=p;f.escape=E9;f.unescape=a;import{fileURLToPath as b5}from"url";var V5=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,N8=new Set,HQ=typeof process=="object"&&process?process:{},S8=(Q,Z,$,V)=>{typeof HQ.emitWarning=="function"?HQ.emitWarning(Q,Z,$,V):console.error(`[${$}] ${Z}: ${Q}`)},B0=globalThis.AbortController,P8=globalThis.AbortSignal;if(typeof B0>"u"){P8=class{onabort;_onabort=[];reason;aborted=!1;addEventListener($,V){this._onabort.push(V)}},B0=class{constructor(){Z()}signal=new P8;abort($){if(!this.signal.aborted){this.signal.reason=$,this.signal.aborted=!0;for(let V of this.signal._onabort)V($);this.signal.onabort?.($)}}};let Q=HQ.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Z=()=>{Q&&(Q=!1,S8("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",Z))}}var X5=(Q)=>!N8.has(Q),e$=Symbol("type"),L9=(Q)=>Q&&Q===Math.floor(Q)&&Q>0&&isFinite(Q),I8=(Q)=>L9(Q)?Q<=Math.pow(2,8)?Uint8Array:Q<=Math.pow(2,16)?Uint16Array:Q<=Math.pow(2,32)?Uint32Array:Q<=Number.MAX_SAFE_INTEGER?A0:null:null,A0=class extends Array{constructor(Q){super(Q),this.fill(0)}},z5=class Q{heap;length;static#Q=!1;static create(Z){let $=I8(Z);if(!$)return[];Q.#Q=!0;let V=new Q(Z,$);return Q.#Q=!1,V}constructor(Z,$){if(!Q.#Q)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new $(Z),this.length=0}push(Z){this.heap[this.length++]=Z}pop(){return this.heap[--this.length]}},a9=class Q{#Q;#V;#X;#Z;#J;#M;#B;#H;get perf(){return this.#H}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#Y;#G;#W;#K;#z;#L;#O;#j;#U;#D;#w;#v;#C;#_;#A;#F;#P;#$;#y;static unsafeExposeInternals(Z){return{starts:Z.#C,ttls:Z.#_,autopurgeTimers:Z.#A,sizes:Z.#v,keyMap:Z.#W,keyList:Z.#K,valList:Z.#z,next:Z.#L,prev:Z.#O,get head(){return Z.#j},get tail(){return Z.#U},free:Z.#D,isBackgroundFetch:($)=>Z.#q($),backgroundFetch:($,V,X,z)=>Z.#m($,V,X,z),moveToTail:($)=>Z.#b($),indexes:($)=>Z.#I($),rindexes:($)=>Z.#x($),isStale:($)=>Z.#R($)}}get max(){return this.#Q}get maxSize(){return this.#V}get calculatedSize(){return this.#G}get size(){return this.#Y}get fetchMethod(){return this.#M}get memoMethod(){return this.#B}get dispose(){return this.#X}get onInsert(){return this.#Z}get disposeAfter(){return this.#J}constructor(Z){let{max:$=0,ttl:V,ttlResolution:X=1,ttlAutopurge:z,updateAgeOnGet:J,updateAgeOnHas:Y,allowStale:K,dispose:q,onInsert:W,disposeAfter:H,noDisposeOnSet:G,noUpdateTTL:_,maxSize:U=0,maxEntrySize:j=0,sizeCalculation:A,fetchMethod:w,memoMethod:B,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:L,allowStaleOnFetchAbort:I,ignoreFetchAbort:y,perf:e}=Z;if(e!==void 0&&typeof e?.now!="function")throw TypeError("perf option must have a now() method if specified");if(this.#H=e??V5,$!==0&&!L9($))throw TypeError("max option must be a nonnegative integer");let P=$?I8($):Array;if(!P)throw Error("invalid max value: "+$);if(this.#Q=$,this.#V=U,this.maxEntrySize=j||this.#V,this.sizeCalculation=A,this.sizeCalculation){if(!this.#V&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw TypeError("sizeCalculation set to non-function")}if(B!==void 0&&typeof B!="function")throw TypeError("memoMethod must be a function if defined");if(this.#B=B,w!==void 0&&typeof w!="function")throw TypeError("fetchMethod must be a function if specified");if(this.#M=w,this.#P=!!w,this.#W=new Map,this.#K=Array($).fill(void 0),this.#z=Array($).fill(void 0),this.#L=new P($),this.#O=new P($),this.#j=0,this.#U=0,this.#D=z5.create($),this.#Y=0,this.#G=0,typeof q=="function"&&(this.#X=q),typeof W=="function"&&(this.#Z=W),typeof H=="function"?(this.#J=H,this.#w=[]):(this.#J=void 0,this.#w=void 0),this.#F=!!this.#X,this.#y=!!this.#Z,this.#$=!!this.#J,this.noDisposeOnSet=!!G,this.noUpdateTTL=!!_,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!L,this.allowStaleOnFetchAbort=!!I,this.ignoreFetchAbort=!!y,this.maxEntrySize!==0){if(this.#V!==0&&!L9(this.#V))throw TypeError("maxSize must be a positive integer if specified");if(!L9(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#l()}if(this.allowStale=!!K,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!J,this.updateAgeOnHas=!!Y,this.ttlResolution=L9(X)||X===0?X:1,this.ttlAutopurge=!!z,this.ttl=V||0,this.ttl){if(!L9(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#E()}if(this.#Q===0&&this.ttl===0&&this.#V===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Q&&!this.#V){let r="LRU_CACHE_UNBOUNDED";X5(r)&&(N8.add(r),S8("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",r,Q))}}getRemainingTTL(Z){return this.#W.has(Z)?1/0:0}#E(){let Z=new A0(this.#Q),$=new A0(this.#Q);this.#_=Z,this.#C=$;let V=this.ttlAutopurge?Array(this.#Q):void 0;this.#A=V,this.#u=(J,Y,K=this.#H.now())=>{if($[J]=Y!==0?K:0,Z[J]=Y,V?.[J]&&(clearTimeout(V[J]),V[J]=void 0),Y!==0&&V){let q=setTimeout(()=>{this.#R(J)&&this.#S(this.#K[J],"expire")},Y+1);q.unref&&q.unref(),V[J]=q}},this.#N=(J)=>{$[J]=Z[J]!==0?this.#H.now():0},this.#T=(J,Y)=>{if(Z[Y]){let K=Z[Y],q=$[Y];if(!K||!q)return;J.ttl=K,J.start=q,J.now=X||z();let W=J.now-q;J.remainingTTL=K-W}};let X=0,z=()=>{let J=this.#H.now();if(this.ttlResolution>0){X=J;let Y=setTimeout(()=>X=0,this.ttlResolution);Y.unref&&Y.unref()}return J};this.getRemainingTTL=(J)=>{let Y=this.#W.get(J);if(Y===void 0)return 0;let K=Z[Y],q=$[Y];if(!K||!q)return 1/0;let W=(X||z())-q;return K-W},this.#R=(J)=>{let Y=$[J],K=Z[J];return!!K&&!!Y&&(X||z())-Y>K}}#N=()=>{};#T=()=>{};#u=()=>{};#R=()=>!1;#l(){let Z=new A0(this.#Q);this.#G=0,this.#v=Z,this.#f=($)=>{this.#G-=Z[$],Z[$]=0},this.#h=($,V,X,z)=>{if(this.#q(V))return 0;if(!L9(X))if(z){if(typeof z!="function")throw TypeError("sizeCalculation must be a function");if(X=z(V,$),!L9(X))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return X},this.#k=($,V,X)=>{if(Z[$]=V,this.#V){let z=this.#V-Z[$];for(;this.#G>z;)this.#d(!0)}this.#G+=Z[$],X&&(X.entrySize=V,X.totalCalculatedSize=this.#G)}}#f=(Z)=>{};#k=(Z,$,V)=>{};#h=(Z,$,V,X)=>{if(V||X)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#I({allowStale:Z=this.allowStale}={}){if(this.#Y)for(let $=this.#U;!(!this.#g($)||((Z||!this.#R($))&&(yield $),$===this.#j));)$=this.#O[$]}*#x({allowStale:Z=this.allowStale}={}){if(this.#Y)for(let $=this.#j;!(!this.#g($)||((Z||!this.#R($))&&(yield $),$===this.#U));)$=this.#L[$]}#g(Z){return Z!==void 0&&this.#W.get(this.#K[Z])===Z}*entries(){for(let Z of this.#I())this.#z[Z]!==void 0&&this.#K[Z]!==void 0&&!this.#q(this.#z[Z])&&(yield[this.#K[Z],this.#z[Z]])}*rentries(){for(let Z of this.#x())this.#z[Z]!==void 0&&this.#K[Z]!==void 0&&!this.#q(this.#z[Z])&&(yield[this.#K[Z],this.#z[Z]])}*keys(){for(let Z of this.#I()){let $=this.#K[Z];$!==void 0&&!this.#q(this.#z[Z])&&(yield $)}}*rkeys(){for(let Z of this.#x()){let $=this.#K[Z];$!==void 0&&!this.#q(this.#z[Z])&&(yield $)}}*values(){for(let Z of this.#I())this.#z[Z]!==void 0&&!this.#q(this.#z[Z])&&(yield this.#z[Z])}*rvalues(){for(let Z of this.#x())this.#z[Z]!==void 0&&!this.#q(this.#z[Z])&&(yield this.#z[Z])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(Z,$={}){for(let V of this.#I()){let X=this.#z[V],z=this.#q(X)?X.__staleWhileFetching:X;if(z!==void 0&&Z(z,this.#K[V],this))return this.get(this.#K[V],$)}}forEach(Z,$=this){for(let V of this.#I()){let X=this.#z[V],z=this.#q(X)?X.__staleWhileFetching:X;z!==void 0&&Z.call($,z,this.#K[V],this)}}rforEach(Z,$=this){for(let V of this.#x()){let X=this.#z[V],z=this.#q(X)?X.__staleWhileFetching:X;z!==void 0&&Z.call($,z,this.#K[V],this)}}purgeStale(){let Z=!1;for(let $ of this.#x({allowStale:!0}))this.#R($)&&(this.#S(this.#K[$],"expire"),Z=!0);return Z}info(Z){let $=this.#W.get(Z);if($===void 0)return;let V=this.#z[$],X=this.#q(V)?V.__staleWhileFetching:V;if(X===void 0)return;let z={value:X};if(this.#_&&this.#C){let J=this.#_[$],Y=this.#C[$];if(J&&Y){let K=J-(this.#H.now()-Y);z.ttl=K,z.start=Date.now()}}return this.#v&&(z.size=this.#v[$]),z}dump(){let Z=[];for(let $ of this.#I({allowStale:!0})){let V=this.#K[$],X=this.#z[$],z=this.#q(X)?X.__staleWhileFetching:X;if(z===void 0||V===void 0)continue;let J={value:z};if(this.#_&&this.#C){J.ttl=this.#_[$];let Y=this.#H.now()-this.#C[$];J.start=Math.floor(Date.now()-Y)}this.#v&&(J.size=this.#v[$]),Z.unshift([V,J])}return Z}load(Z){this.clear();for(let[$,V]of Z){if(V.start){let X=Date.now()-V.start;V.start=this.#H.now()-X}this.set($,V.value,V)}}set(Z,$,V={}){if($===void 0)return this.delete(Z),this;let{ttl:X=this.ttl,start:z,noDisposeOnSet:J=this.noDisposeOnSet,sizeCalculation:Y=this.sizeCalculation,status:K}=V,{noUpdateTTL:q=this.noUpdateTTL}=V,W=this.#h(Z,$,V.size||0,Y);if(this.maxEntrySize&&W>this.maxEntrySize)return K&&(K.set="miss",K.maxEntrySizeExceeded=!0),this.#S(Z,"set"),this;let H=this.#Y===0?void 0:this.#W.get(Z);if(H===void 0)H=this.#Y===0?this.#U:this.#D.length!==0?this.#D.pop():this.#Y===this.#Q?this.#d(!1):this.#Y,this.#K[H]=Z,this.#z[H]=$,this.#W.set(Z,H),this.#L[this.#U]=H,this.#O[H]=this.#U,this.#U=H,this.#Y++,this.#k(H,W,K),K&&(K.set="add"),q=!1,this.#y&&this.#Z?.($,Z,"add");else{this.#b(H);let G=this.#z[H];if($!==G){if(this.#P&&this.#q(G)){G.__abortController.abort(Error("replaced"));let{__staleWhileFetching:_}=G;_!==void 0&&!J&&(this.#F&&this.#X?.(_,Z,"set"),this.#$&&this.#w?.push([_,Z,"set"]))}else J||(this.#F&&this.#X?.(G,Z,"set"),this.#$&&this.#w?.push([G,Z,"set"]));if(this.#f(H),this.#k(H,W,K),this.#z[H]=$,K){K.set="replace";let _=G&&this.#q(G)?G.__staleWhileFetching:G;_!==void 0&&(K.oldValue=_)}}else K&&(K.set="update");this.#y&&this.onInsert?.($,Z,$===G?"update":"replace")}if(X!==0&&!this.#_&&this.#E(),this.#_&&(q||this.#u(H,X,z),K&&this.#T(K,H)),!J&&this.#$&&this.#w){let G=this.#w,_;for(;_=G?.shift();)this.#J?.(..._)}return this}pop(){try{for(;this.#Y;){let Z=this.#z[this.#j];if(this.#d(!0),this.#q(Z)){if(Z.__staleWhileFetching)return Z.__staleWhileFetching}else if(Z!==void 0)return Z}}finally{if(this.#$&&this.#w){let Z=this.#w,$;for(;$=Z?.shift();)this.#J?.(...$)}}}#d(Z){let $=this.#j,V=this.#K[$],X=this.#z[$];return this.#P&&this.#q(X)?X.__abortController.abort(Error("evicted")):(this.#F||this.#$)&&(this.#F&&this.#X?.(X,V,"evict"),this.#$&&this.#w?.push([X,V,"evict"])),this.#f($),this.#A?.[$]&&(clearTimeout(this.#A[$]),this.#A[$]=void 0),Z&&(this.#K[$]=void 0,this.#z[$]=void 0,this.#D.push($)),this.#Y===1?(this.#j=this.#U=0,this.#D.length=0):this.#j=this.#L[$],this.#W.delete(V),this.#Y--,$}has(Z,$={}){let{updateAgeOnHas:V=this.updateAgeOnHas,status:X}=$,z=this.#W.get(Z);if(z!==void 0){let J=this.#z[z];if(this.#q(J)&&J.__staleWhileFetching===void 0)return!1;if(this.#R(z))X&&(X.has="stale",this.#T(X,z));else return V&&this.#N(z),X&&(X.has="hit",this.#T(X,z)),!0}else X&&(X.has="miss");return!1}peek(Z,$={}){let{allowStale:V=this.allowStale}=$,X=this.#W.get(Z);if(X===void 0||!V&&this.#R(X))return;let z=this.#z[X];return this.#q(z)?z.__staleWhileFetching:z}#m(Z,$,V,X){let z=$===void 0?void 0:this.#z[$];if(this.#q(z))return z;let J=new B0,{signal:Y}=V;Y?.addEventListener("abort",()=>J.abort(Y.reason),{signal:J.signal});let K={signal:J.signal,options:V,context:X},q=(j,A=!1)=>{let{aborted:w}=J.signal,B=V.ignoreFetchAbort&&j!==void 0,O=V.ignoreFetchAbort||!!(V.allowStaleOnFetchAbort&&j!==void 0);if(V.status&&(w&&!A?(V.status.fetchAborted=!0,V.status.fetchError=J.signal.reason,B&&(V.status.fetchAbortIgnored=!0)):V.status.fetchResolved=!0),w&&!B&&!A)return H(J.signal.reason,O);let v=_,L=this.#z[$];return(L===_||B&&A&&L===void 0)&&(j===void 0?v.__staleWhileFetching!==void 0?this.#z[$]=v.__staleWhileFetching:this.#S(Z,"fetch"):(V.status&&(V.status.fetchUpdated=!0),this.set(Z,j,K.options))),j},W=(j)=>(V.status&&(V.status.fetchRejected=!0,V.status.fetchError=j),H(j,!1)),H=(j,A)=>{let{aborted:w}=J.signal,B=w&&V.allowStaleOnFetchAbort,O=B||V.allowStaleOnFetchRejection,v=O||V.noDeleteOnFetchRejection,L=_;if(this.#z[$]===_&&(!v||!A&&L.__staleWhileFetching===void 0?this.#S(Z,"fetch"):B||(this.#z[$]=L.__staleWhileFetching)),O)return V.status&&L.__staleWhileFetching!==void 0&&(V.status.returnedStale=!0),L.__staleWhileFetching;if(L.__returned===L)throw j},G=(j,A)=>{let w=this.#M?.(Z,z,K);w&&w instanceof Promise&&w.then((B)=>j(B===void 0?void 0:B),A),J.signal.addEventListener("abort",()=>{(!V.ignoreFetchAbort||V.allowStaleOnFetchAbort)&&(j(void 0),V.allowStaleOnFetchAbort&&(j=(B)=>q(B,!0)))})};V.status&&(V.status.fetchDispatched=!0);let _=new Promise(G).then(q,W),U=Object.assign(_,{__abortController:J,__staleWhileFetching:z,__returned:void 0});return $===void 0?(this.set(Z,U,{...K.options,status:void 0}),$=this.#W.get(Z)):this.#z[$]=U,U}#q(Z){if(!this.#P)return!1;let $=Z;return!!$&&$ instanceof Promise&&$.hasOwnProperty("__staleWhileFetching")&&$.__abortController instanceof B0}async fetch(Z,$={}){let{allowStale:V=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:z=this.noDeleteOnStaleGet,ttl:J=this.ttl,noDisposeOnSet:Y=this.noDisposeOnSet,size:K=0,sizeCalculation:q=this.sizeCalculation,noUpdateTTL:W=this.noUpdateTTL,noDeleteOnFetchRejection:H=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:G=this.allowStaleOnFetchRejection,ignoreFetchAbort:_=this.ignoreFetchAbort,allowStaleOnFetchAbort:U=this.allowStaleOnFetchAbort,context:j,forceRefresh:A=!1,status:w,signal:B}=$;if(!this.#P)return w&&(w.fetch="get"),this.get(Z,{allowStale:V,updateAgeOnGet:X,noDeleteOnStaleGet:z,status:w});let O={allowStale:V,updateAgeOnGet:X,noDeleteOnStaleGet:z,ttl:J,noDisposeOnSet:Y,size:K,sizeCalculation:q,noUpdateTTL:W,noDeleteOnFetchRejection:H,allowStaleOnFetchRejection:G,allowStaleOnFetchAbort:U,ignoreFetchAbort:_,status:w,signal:B},v=this.#W.get(Z);if(v===void 0){w&&(w.fetch="miss");let L=this.#m(Z,v,O,j);return L.__returned=L}else{let L=this.#z[v];if(this.#q(L)){let P=V&&L.__staleWhileFetching!==void 0;return w&&(w.fetch="inflight",P&&(w.returnedStale=!0)),P?L.__staleWhileFetching:L.__returned=L}let I=this.#R(v);if(!A&&!I)return w&&(w.fetch="hit"),this.#b(v),X&&this.#N(v),w&&this.#T(w,v),L;let y=this.#m(Z,v,O,j),e=y.__staleWhileFetching!==void 0&&V;return w&&(w.fetch=I?"stale":"refresh",e&&I&&(w.returnedStale=!0)),e?y.__staleWhileFetching:y.__returned=y}}async forceFetch(Z,$={}){let V=await this.fetch(Z,$);if(V===void 0)throw Error("fetch() returned undefined");return V}memo(Z,$={}){let V=this.#B;if(!V)throw Error("no memoMethod provided to constructor");let{context:X,forceRefresh:z,...J}=$,Y=this.get(Z,J);if(!z&&Y!==void 0)return Y;let K=V(Z,Y,{options:J,context:X});return this.set(Z,K,J),K}get(Z,$={}){let{allowStale:V=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:z=this.noDeleteOnStaleGet,status:J}=$,Y=this.#W.get(Z);if(Y!==void 0){let K=this.#z[Y],q=this.#q(K);return J&&this.#T(J,Y),this.#R(Y)?(J&&(J.get="stale"),q?(J&&V&&K.__staleWhileFetching!==void 0&&(J.returnedStale=!0),V?K.__staleWhileFetching:void 0):(z||this.#S(Z,"expire"),J&&V&&(J.returnedStale=!0),V?K:void 0)):(J&&(J.get="hit"),q?K.__staleWhileFetching:(this.#b(Y),X&&this.#N(Y),K))}else J&&(J.get="miss")}#c(Z,$){this.#O[$]=Z,this.#L[Z]=$}#b(Z){Z!==this.#U&&(Z===this.#j?this.#j=this.#L[Z]:this.#c(this.#O[Z],this.#L[Z]),this.#c(this.#U,Z),this.#U=Z)}delete(Z){return this.#S(Z,"delete")}#S(Z,$){let V=!1;if(this.#Y!==0){let X=this.#W.get(Z);if(X!==void 0)if(this.#A?.[X]&&(clearTimeout(this.#A?.[X]),this.#A[X]=void 0),V=!0,this.#Y===1)this.#p($);else{this.#f(X);let z=this.#z[X];if(this.#q(z)?z.__abortController.abort(Error("deleted")):(this.#F||this.#$)&&(this.#F&&this.#X?.(z,Z,$),this.#$&&this.#w?.push([z,Z,$])),this.#W.delete(Z),this.#K[X]=void 0,this.#z[X]=void 0,X===this.#U)this.#U=this.#O[X];else if(X===this.#j)this.#j=this.#L[X];else{let J=this.#O[X];this.#L[J]=this.#L[X];let Y=this.#L[X];this.#O[Y]=this.#O[X]}this.#Y--,this.#D.push(X)}}if(this.#$&&this.#w?.length){let X=this.#w,z;for(;z=X?.shift();)this.#J?.(...z)}return V}clear(){return this.#p("delete")}#p(Z){for(let $ of this.#x({allowStale:!0})){let V=this.#z[$];if(this.#q(V))V.__abortController.abort(Error("deleted"));else{let X=this.#K[$];this.#F&&this.#X?.(V,X,Z),this.#$&&this.#w?.push([V,X,Z])}}if(this.#W.clear(),this.#z.fill(void 0),this.#K.fill(void 0),this.#_&&this.#C){this.#_.fill(0),this.#C.fill(0);for(let $ of this.#A??[])$!==void 0&&clearTimeout($);this.#A?.fill(void 0)}if(this.#v&&this.#v.fill(0),this.#j=0,this.#U=0,this.#D.length=0,this.#G=0,this.#Y=0,this.#$&&this.#w){let $=this.#w,V;for(;V=$?.shift();)this.#J?.(...V)}}};import{posix as w5,win32 as OQ}from"path";import{fileURLToPath as A5}from"url";import{lstatSync as B5,readdir as L5,readdirSync as F5,readlinkSync as O5,realpathSync as v5}from"fs";import*as M5 from"fs";import{lstat as R5,readdir as D5,readlink as P5,realpath as N5}from"fs/promises";import{EventEmitter as AQ}from"events";import k8 from"stream";import{StringDecoder as J5}from"string_decoder";var x8=typeof process==="object"&&process?process:{stdout:null,stderr:null},Y5=(Q)=>!!Q&&typeof Q==="object"&&(Q instanceof R9||Q instanceof k8||K5(Q)||q5(Q)),K5=(Q)=>!!Q&&typeof Q==="object"&&Q instanceof AQ&&typeof Q.pipe==="function"&&Q.pipe!==k8.Writable.prototype.pipe,q5=(Q)=>!!Q&&typeof Q==="object"&&Q instanceof AQ&&typeof Q.write==="function"&&typeof Q.end==="function",U9=Symbol("EOF"),w9=Symbol("maybeEmitEnd"),F9=Symbol("emittedEnd"),L0=Symbol("emittingEnd"),s9=Symbol("emittedError"),F0=Symbol("closed"),E8=Symbol("read"),O0=Symbol("flush"),T8=Symbol("flushChunk"),s=Symbol("encoding"),T9=Symbol("decoder"),x=Symbol("flowing"),t9=Symbol("paused"),y9=Symbol("resume"),E=Symbol("buffer"),u=Symbol("pipes"),T=Symbol("bufferLength"),GQ=Symbol("bufferPush"),v0=Symbol("bufferShift"),b=Symbol("objectMode"),S=Symbol("destroyed"),_Q=Symbol("error"),jQ=Symbol("emitData"),y8=Symbol("emitEnd"),UQ=Symbol("emitEnd2"),J9=Symbol("async"),wQ=Symbol("abort"),M0=Symbol("aborted"),e9=Symbol("signal"),C9=Symbol("dataListeners"),m=Symbol("discarded"),Q0=(Q)=>Promise.resolve().then(Q),W5=(Q)=>Q(),H5=(Q)=>Q==="end"||Q==="finish"||Q==="prefinish",G5=(Q)=>Q instanceof ArrayBuffer||!!Q&&typeof Q==="object"&&Q.constructor&&Q.constructor.name==="ArrayBuffer"&&Q.byteLength>=0,_5=(Q)=>!Buffer.isBuffer(Q)&&ArrayBuffer.isView(Q);class BQ{src;dest;opts;ondrain;constructor(Q,Z,$){this.src=Q,this.dest=Z,this.opts=$,this.ondrain=()=>Q[y9](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(Q){}end(){if(this.unpipe(),this.opts.end)this.dest.end()}}class b8 extends BQ{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(Q,Z,$){super(Q,Z,$);this.proxyErrors=(V)=>this.dest.emit("error",V),Q.on("error",this.proxyErrors)}}var j5=(Q)=>!!Q.objectMode,U5=(Q)=>!Q.objectMode&&!!Q.encoding&&Q.encoding!=="buffer";class R9 extends AQ{[x]=!1;[t9]=!1;[u]=[];[E]=[];[b];[s];[J9];[T9];[U9]=!1;[F9]=!1;[L0]=!1;[F0]=!1;[s9]=null;[T]=0;[S]=!1;[e9];[M0]=!1;[C9]=0;[m]=!1;writable=!0;readable=!0;constructor(...Q){let Z=Q[0]||{};super();if(Z.objectMode&&typeof Z.encoding==="string")throw TypeError("Encoding and objectMode may not be used together");if(j5(Z))this[b]=!0,this[s]=null;else if(U5(Z))this[s]=Z.encoding,this[b]=!1;else this[b]=!1,this[s]=null;if(this[J9]=!!Z.async,this[T9]=this[s]?new J5(this[s]):null,Z&&Z.debugExposeBuffer===!0)Object.defineProperty(this,"buffer",{get:()=>this[E]});if(Z&&Z.debugExposePipes===!0)Object.defineProperty(this,"pipes",{get:()=>this[u]});let{signal:$}=Z;if($)if(this[e9]=$,$.aborted)this[wQ]();else $.addEventListener("abort",()=>this[wQ]())}get bufferLength(){return this[T]}get encoding(){return this[s]}set encoding(Q){throw Error("Encoding must be set at instantiation time")}setEncoding(Q){throw Error("Encoding must be set at instantiation time")}get objectMode(){return this[b]}set objectMode(Q){throw Error("objectMode must be set at instantiation time")}get["async"](){return this[J9]}set["async"](Q){this[J9]=this[J9]||!!Q}[wQ](){this[M0]=!0,this.emit("abort",this[e9]?.reason),this.destroy(this[e9]?.reason)}get aborted(){return this[M0]}set aborted(Q){}write(Q,Z,$){if(this[M0])return!1;if(this[U9])throw Error("write after end");if(this[S])return this.emit("error",Object.assign(Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof Z==="function")$=Z,Z="utf8";if(!Z)Z="utf8";let V=this[J9]?Q0:W5;if(!this[b]&&!Buffer.isBuffer(Q)){if(_5(Q))Q=Buffer.from(Q.buffer,Q.byteOffset,Q.byteLength);else if(G5(Q))Q=Buffer.from(Q);else if(typeof Q!=="string")throw Error("Non-contiguous data written to non-objectMode stream")}if(this[b]){if(this[x]&&this[T]!==0)this[O0](!0);if(this[x])this.emit("data",Q);else this[GQ](Q);if(this[T]!==0)this.emit("readable");if($)V($);return this[x]}if(!Q.length){if(this[T]!==0)this.emit("readable");if($)V($);return this[x]}if(typeof Q==="string"&&!(Z===this[s]&&!this[T9]?.lastNeed))Q=Buffer.from(Q,Z);if(Buffer.isBuffer(Q)&&this[s])Q=this[T9].write(Q);if(this[x]&&this[T]!==0)this[O0](!0);if(this[x])this.emit("data",Q);else this[GQ](Q);if(this[T]!==0)this.emit("readable");if($)V($);return this[x]}read(Q){if(this[S])return null;if(this[m]=!1,this[T]===0||Q===0||Q&&Q>this[T])return this[w9](),null;if(this[b])Q=null;if(this[E].length>1&&!this[b])this[E]=[this[s]?this[E].join(""):Buffer.concat(this[E],this[T])];let Z=this[E8](Q||null,this[E][0]);return this[w9](),Z}[E8](Q,Z){if(this[b])this[v0]();else{let $=Z;if(Q===$.length||Q===null)this[v0]();else if(typeof $==="string")this[E][0]=$.slice(Q),Z=$.slice(0,Q),this[T]-=Q;else this[E][0]=$.subarray(Q),Z=$.subarray(0,Q),this[T]-=Q}if(this.emit("data",Z),!this[E].length&&!this[U9])this.emit("drain");return Z}end(Q,Z,$){if(typeof Q==="function")$=Q,Q=void 0;if(typeof Z==="function")$=Z,Z="utf8";if(Q!==void 0)this.write(Q,Z);if($)this.once("end",$);if(this[U9]=!0,this.writable=!1,this[x]||!this[t9])this[w9]();return this}[y9](){if(this[S])return;if(!this[C9]&&!this[u].length)this[m]=!0;if(this[t9]=!1,this[x]=!0,this.emit("resume"),this[E].length)this[O0]();else if(this[U9])this[w9]();else this.emit("drain")}resume(){return this[y9]()}pause(){this[x]=!1,this[t9]=!0,this[m]=!1}get destroyed(){return this[S]}get flowing(){return this[x]}get paused(){return this[t9]}[GQ](Q){if(this[b])this[T]+=1;else this[T]+=Q.length;this[E].push(Q)}[v0](){if(this[b])this[T]-=1;else this[T]-=this[E][0].length;return this[E].shift()}[O0](Q=!1){do;while(this[T8](this[v0]())&&this[E].length);if(!Q&&!this[E].length&&!this[U9])this.emit("drain")}[T8](Q){return this.emit("data",Q),this[x]}pipe(Q,Z){if(this[S])return Q;this[m]=!1;let $=this[F9];if(Z=Z||{},Q===x8.stdout||Q===x8.stderr)Z.end=!1;else Z.end=Z.end!==!1;if(Z.proxyErrors=!!Z.proxyErrors,$){if(Z.end)Q.end()}else if(this[u].push(!Z.proxyErrors?new BQ(this,Q,Z):new b8(this,Q,Z)),this[J9])Q0(()=>this[y9]());else this[y9]();return Q}unpipe(Q){let Z=this[u].find(($)=>$.dest===Q);if(Z){if(this[u].length===1){if(this[x]&&this[C9]===0)this[x]=!1;this[u]=[]}else this[u].splice(this[u].indexOf(Z),1);Z.unpipe()}}addListener(Q,Z){return this.on(Q,Z)}on(Q,Z){let $=super.on(Q,Z);if(Q==="data"){if(this[m]=!1,this[C9]++,!this[u].length&&!this[x])this[y9]()}else if(Q==="readable"&&this[T]!==0)super.emit("readable");else if(H5(Q)&&this[F9])super.emit(Q),this.removeAllListeners(Q);else if(Q==="error"&&this[s9]){let V=Z;if(this[J9])Q0(()=>V.call(this,this[s9]));else V.call(this,this[s9])}return $}removeListener(Q,Z){return this.off(Q,Z)}off(Q,Z){let $=super.off(Q,Z);if(Q==="data"){if(this[C9]=this.listeners("data").length,this[C9]===0&&!this[m]&&!this[u].length)this[x]=!1}return $}removeAllListeners(Q){let Z=super.removeAllListeners(Q);if(Q==="data"||Q===void 0){if(this[C9]=0,!this[m]&&!this[u].length)this[x]=!1}return Z}get emittedEnd(){return this[F9]}[w9](){if(!this[L0]&&!this[F9]&&!this[S]&&this[E].length===0&&this[U9]){if(this[L0]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[F0])this.emit("close");this[L0]=!1}}emit(Q,...Z){let $=Z[0];if(Q!=="error"&&Q!=="close"&&Q!==S&&this[S])return!1;else if(Q==="data")return!this[b]&&!$?!1:this[J9]?(Q0(()=>this[jQ]($)),!0):this[jQ]($);else if(Q==="end")return this[y8]();else if(Q==="close"){if(this[F0]=!0,!this[F9]&&!this[S])return!1;let X=super.emit("close");return this.removeAllListeners("close"),X}else if(Q==="error"){this[s9]=$,super.emit(_Q,$);let X=!this[e9]||this.listeners("error").length?super.emit("error",$):!1;return this[w9](),X}else if(Q==="resume"){let X=super.emit("resume");return this[w9](),X}else if(Q==="finish"||Q==="prefinish"){let X=super.emit(Q);return this.removeAllListeners(Q),X}let V=super.emit(Q,...Z);return this[w9](),V}[jQ](Q){for(let $ of this[u])if($.dest.write(Q)===!1)this.pause();let Z=this[m]?!1:super.emit("data",Q);return this[w9](),Z}[y8](){if(this[F9])return!1;return this[F9]=!0,this.readable=!1,this[J9]?(Q0(()=>this[UQ]()),!0):this[UQ]()}[UQ](){if(this[T9]){let Z=this[T9].end();if(Z){for(let $ of this[u])$.dest.write(Z);if(!this[m])super.emit("data",Z)}}for(let Z of this[u])Z.end();let Q=super.emit("end");return this.removeAllListeners("end"),Q}async collect(){let Q=Object.assign([],{dataLength:0});if(!this[b])Q.dataLength=0;let Z=this.promise();return this.on("data",($)=>{if(Q.push($),!this[b])Q.dataLength+=$.length}),await Z,Q}async concat(){if(this[b])throw Error("cannot concat in objectMode");let Q=await this.collect();return this[s]?Q.join(""):Buffer.concat(Q,Q.dataLength)}async promise(){return new Promise((Q,Z)=>{this.on(S,()=>Z(Error("stream destroyed"))),this.on("error",($)=>Z($)),this.on("end",()=>Q())})}[Symbol.asyncIterator](){this[m]=!1;let Q=!1,Z=async()=>{return this.pause(),Q=!0,{value:void 0,done:!0}};return{next:()=>{if(Q)return Z();let V=this.read();if(V!==null)return Promise.resolve({done:!1,value:V});if(this[U9])return Z();let X,z,J=(W)=>{this.off("data",Y),this.off("end",K),this.off(S,q),Z(),z(W)},Y=(W)=>{this.off("error",J),this.off("end",K),this.off(S,q),this.pause(),X({value:W,done:!!this[U9]})},K=()=>{this.off("error",J),this.off("data",Y),this.off(S,q),Z(),X({done:!0,value:void 0})},q=()=>J(Error("stream destroyed"));return new Promise((W,H)=>{z=H,X=W,this.once(S,q),this.once("error",J),this.once("end",K),this.once("data",Y)})},throw:Z,return:Z,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[m]=!1;let Q=!1,Z=()=>{return this.pause(),this.off(_Q,Z),this.off(S,Z),this.off("end",Z),Q=!0,{done:!0,value:void 0}},$=()=>{if(Q)return Z();let V=this.read();return V===null?Z():{done:!1,value:V}};return this.once("end",Z),this.once(_Q,Z),this.once(S,Z),{next:$,throw:Z,return:Z,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(Q){if(this[S]){if(Q)this.emit("error",Q);else this.emit(S);return this}this[S]=!0,this[m]=!0,this[E].length=0,this[T]=0;let Z=this;if(typeof Z.close==="function"&&!this[F0])Z.close();if(Q)this.emit("error",Q);else this.emit(S);return this}static get isStream(){return Y5}}var C5=v5.native,$0={lstatSync:B5,readdir:L5,readdirSync:F5,readlinkSync:O5,realpathSync:C5,promises:{lstat:R5,readdir:D5,readlink:P5,realpath:N5}},d8=(Q)=>!Q||Q===$0||Q===M5?$0:{...$0,...Q,promises:{...$0.promises,...Q.promises||{}}},m8=/^\\\\\?\\([a-z]:)\\?$/i,S5=(Q)=>Q.replace(/\//g,"\\").replace(m8,"$1\\"),I5=/[\\\/]/,n=0,c8=1,l8=2,Y9=4,p8=6,i8=8,D9=10,n8=12,i=15,Z0=~i,LQ=16,f8=32,V0=64,t=128,C0=256,D0=512,u8=V0|t|D0,x5=1023,FQ=(Q)=>Q.isFile()?i8:Q.isDirectory()?Y9:Q.isSymbolicLink()?D9:Q.isCharacterDevice()?l8:Q.isBlockDevice()?p8:Q.isSocket()?n8:Q.isFIFO()?c8:n,h8=new a9({max:4096}),X0=(Q)=>{let Z=h8.get(Q);if(Z)return Z;let $=Q.normalize("NFKD");return h8.set(Q,$),$},g8=new a9({max:4096}),R0=(Q)=>{let Z=g8.get(Q);if(Z)return Z;let $=X0(Q.toLowerCase());return g8.set(Q,$),$};class vQ extends a9{constructor(){super({max:256})}}class r8 extends a9{constructor(Q=16384){super({maxSize:Q,sizeCalculation:(Z)=>Z.length+1})}}var o8=Symbol("PathScurry setAsCwd");class h{name;root;roots;parent;nocase;isCWD=!1;#Q;#V;get dev(){return this.#V}#X;get mode(){return this.#X}#Z;get nlink(){return this.#Z}#J;get uid(){return this.#J}#M;get gid(){return this.#M}#B;get rdev(){return this.#B}#H;get blksize(){return this.#H}#Y;get ino(){return this.#Y}#G;get size(){return this.#G}#W;get blocks(){return this.#W}#K;get atimeMs(){return this.#K}#z;get mtimeMs(){return this.#z}#L;get ctimeMs(){return this.#L}#O;get birthtimeMs(){return this.#O}#j;get atime(){return this.#j}#U;get mtime(){return this.#U}#D;get ctime(){return this.#D}#w;get birthtime(){return this.#w}#v;#C;#_;#A;#F;#P;#$;#y;#E;#N;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(Q,Z=n,$,V,X,z,J){if(this.name=Q,this.#v=X?R0(Q):X0(Q),this.#$=Z&x5,this.nocase=X,this.roots=V,this.root=$||this,this.#y=z,this.#_=J.fullpath,this.#F=J.relative,this.#P=J.relativePosix,this.parent=J.parent,this.parent)this.#Q=this.parent.#Q;else this.#Q=d8(J.fs)}depth(){if(this.#C!==void 0)return this.#C;if(!this.parent)return this.#C=0;return this.#C=this.parent.depth()+1}childrenCache(){return this.#y}resolve(Q){if(!Q)return this;let Z=this.getRootString(Q),V=Q.substring(Z.length).split(this.splitSep);return Z?this.getRoot(Z).#T(V):this.#T(V)}#T(Q){let Z=this;for(let $ of Q)Z=Z.child($);return Z}children(){let Q=this.#y.get(this);if(Q)return Q;let Z=Object.assign([],{provisional:0});return this.#y.set(this,Z),this.#$&=~LQ,Z}child(Q,Z){if(Q===""||Q===".")return this;if(Q==="..")return this.parent||this;let $=this.children(),V=this.nocase?R0(Q):X0(Q);for(let Y of $)if(Y.#v===V)return Y;let X=this.parent?this.sep:"",z=this.#_?this.#_+X+Q:void 0,J=this.newChild(Q,n,{...Z,parent:this,fullpath:z});if(!this.canReaddir())J.#$|=t;return $.push(J),J}relative(){if(this.isCWD)return"";if(this.#F!==void 0)return this.#F;let Q=this.name,Z=this.parent;if(!Z)return this.#F=this.name;let $=Z.relative();return $+(!$||!Z.parent?"":this.sep)+Q}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#P!==void 0)return this.#P;let Q=this.name,Z=this.parent;if(!Z)return this.#P=this.fullpathPosix();let $=Z.relativePosix();return $+(!$||!Z.parent?"":"/")+Q}fullpath(){if(this.#_!==void 0)return this.#_;let Q=this.name,Z=this.parent;if(!Z)return this.#_=this.name;let V=Z.fullpath()+(!Z.parent?"":this.sep)+Q;return this.#_=V}fullpathPosix(){if(this.#A!==void 0)return this.#A;if(this.sep==="/")return this.#A=this.fullpath();if(!this.parent){let V=this.fullpath().replace(/\\/g,"/");if(/^[a-z]:\//i.test(V))return this.#A=`//?/${V}`;else return this.#A=V}let Q=this.parent,Z=Q.fullpathPosix(),$=Z+(!Z||!Q.parent?"":"/")+this.name;return this.#A=$}isUnknown(){return(this.#$&i)===n}isType(Q){return this[`is${Q}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#$&i)===i8}isDirectory(){return(this.#$&i)===Y9}isCharacterDevice(){return(this.#$&i)===l8}isBlockDevice(){return(this.#$&i)===p8}isFIFO(){return(this.#$&i)===c8}isSocket(){return(this.#$&i)===n8}isSymbolicLink(){return(this.#$&D9)===D9}lstatCached(){return this.#$&f8?this:void 0}readlinkCached(){return this.#E}realpathCached(){return this.#N}readdirCached(){let Q=this.children();return Q.slice(0,Q.provisional)}canReadlink(){if(this.#E)return!0;if(!this.parent)return!1;let Q=this.#$&i;return!(Q!==n&&Q!==D9||this.#$&C0||this.#$&t)}calledReaddir(){return!!(this.#$&LQ)}isENOENT(){return!!(this.#$&t)}isNamed(Q){return!this.nocase?this.#v===X0(Q):this.#v===R0(Q)}async readlink(){let Q=this.#E;if(Q)return Q;if(!this.canReadlink())return;if(!this.parent)return;try{let Z=await this.#Q.promises.readlink(this.fullpath()),$=(await this.parent.realpath())?.resolve(Z);if($)return this.#E=$}catch(Z){this.#x(Z.code);return}}readlinkSync(){let Q=this.#E;if(Q)return Q;if(!this.canReadlink())return;if(!this.parent)return;try{let Z=this.#Q.readlinkSync(this.fullpath()),$=this.parent.realpathSync()?.resolve(Z);if($)return this.#E=$}catch(Z){this.#x(Z.code);return}}#u(Q){this.#$|=LQ;for(let Z=Q.provisional;Z<Q.length;Z++){let $=Q[Z];if($)$.#R()}}#R(){if(this.#$&t)return;this.#$=(this.#$|t)&Z0,this.#l()}#l(){let Q=this.children();Q.provisional=0;for(let Z of Q)Z.#R()}#f(){this.#$|=D0,this.#k()}#k(){if(this.#$&V0)return;let Q=this.#$;if((Q&i)===Y9)Q&=Z0;this.#$=Q|V0,this.#l()}#h(Q=""){if(Q==="ENOTDIR"||Q==="EPERM")this.#k();else if(Q==="ENOENT")this.#R();else this.children().provisional=0}#I(Q=""){if(Q==="ENOTDIR")this.parent.#k();else if(Q==="ENOENT")this.#R()}#x(Q=""){let Z=this.#$;if(Z|=C0,Q==="ENOENT")Z|=t;if(Q==="EINVAL"||Q==="UNKNOWN")Z&=Z0;if(this.#$=Z,Q==="ENOTDIR"&&this.parent)this.parent.#k()}#g(Q,Z){return this.#m(Q,Z)||this.#d(Q,Z)}#d(Q,Z){let $=FQ(Q),V=this.newChild(Q.name,$,{parent:this}),X=V.#$&i;if(X!==Y9&&X!==D9&&X!==n)V.#$|=V0;return Z.unshift(V),Z.provisional++,V}#m(Q,Z){for(let $=Z.provisional;$<Z.length;$++){let V=Z[$];if((this.nocase?R0(Q.name):X0(Q.name))!==V.#v)continue;return this.#q(Q,V,$,Z)}}#q(Q,Z,$,V){let X=Z.name;if(Z.#$=Z.#$&Z0|FQ(Q),X!==Q.name)Z.name=Q.name;if($!==V.provisional){if($===V.length-1)V.pop();else V.splice($,1);V.unshift(Z)}return V.provisional++,Z}async lstat(){if((this.#$&t)===0)try{return this.#c(await this.#Q.promises.lstat(this.fullpath())),this}catch(Q){this.#I(Q.code)}}lstatSync(){if((this.#$&t)===0)try{return this.#c(this.#Q.lstatSync(this.fullpath())),this}catch(Q){this.#I(Q.code)}}#c(Q){let{atime:Z,atimeMs:$,birthtime:V,birthtimeMs:X,blksize:z,blocks:J,ctime:Y,ctimeMs:K,dev:q,gid:W,ino:H,mode:G,mtime:_,mtimeMs:U,nlink:j,rdev:A,size:w,uid:B}=Q;this.#j=Z,this.#K=$,this.#w=V,this.#O=X,this.#H=z,this.#W=J,this.#D=Y,this.#L=K,this.#V=q,this.#M=W,this.#Y=H,this.#X=G,this.#U=_,this.#z=U,this.#Z=j,this.#B=A,this.#G=w,this.#J=B;let O=FQ(Q);if(this.#$=this.#$&Z0|O|f8,O!==n&&O!==Y9&&O!==D9)this.#$|=V0}#b=[];#S=!1;#p(Q){this.#S=!1;let Z=this.#b.slice();this.#b.length=0,Z.forEach(($)=>$(null,Q))}readdirCB(Q,Z=!1){if(!this.canReaddir()){if(Z)Q(null,[]);else queueMicrotask(()=>Q(null,[]));return}let $=this.children();if(this.calledReaddir()){let X=$.slice(0,$.provisional);if(Z)Q(null,X);else queueMicrotask(()=>Q(null,X));return}if(this.#b.push(Q),this.#S)return;this.#S=!0;let V=this.fullpath();this.#Q.readdir(V,{withFileTypes:!0},(X,z)=>{if(X)this.#h(X.code),$.provisional=0;else{for(let J of z)this.#g(J,$);this.#u($)}this.#p($.slice(0,$.provisional));return})}#i;async readdir(){if(!this.canReaddir())return[];let Q=this.children();if(this.calledReaddir())return Q.slice(0,Q.provisional);let Z=this.fullpath();if(this.#i)await this.#i;else{let $=()=>{};this.#i=new Promise((V)=>$=V);try{for(let V of await this.#Q.promises.readdir(Z,{withFileTypes:!0}))this.#g(V,Q);this.#u(Q)}catch(V){this.#h(V.code),Q.provisional=0}this.#i=void 0,$()}return Q.slice(0,Q.provisional)}readdirSync(){if(!this.canReaddir())return[];let Q=this.children();if(this.calledReaddir())return Q.slice(0,Q.provisional);let Z=this.fullpath();try{for(let $ of this.#Q.readdirSync(Z,{withFileTypes:!0}))this.#g($,Q);this.#u(Q)}catch($){this.#h($.code),Q.provisional=0}return Q.slice(0,Q.provisional)}canReaddir(){if(this.#$&u8)return!1;let Q=i&this.#$;if(!(Q===n||Q===Y9||Q===D9))return!1;return!0}shouldWalk(Q,Z){return(this.#$&Y9)===Y9&&!(this.#$&u8)&&!Q.has(this)&&(!Z||Z(this))}async realpath(){if(this.#N)return this.#N;if((D0|C0|t)&this.#$)return;try{let Q=await this.#Q.promises.realpath(this.fullpath());return this.#N=this.resolve(Q)}catch(Q){this.#f()}}realpathSync(){if(this.#N)return this.#N;if((D0|C0|t)&this.#$)return;try{let Q=this.#Q.realpathSync(this.fullpath());return this.#N=this.resolve(Q)}catch(Q){this.#f()}}[o8](Q){if(Q===this)return;Q.isCWD=!1,this.isCWD=!0;let Z=new Set([]),$=[],V=this;while(V&&V.parent)Z.add(V),V.#F=$.join(this.sep),V.#P=$.join("/"),V=V.parent,$.push("..");V=Q;while(V&&V.parent&&!Z.has(V))V.#F=void 0,V.#P=void 0,V=V.parent}}class P0 extends h{sep="\\";splitSep=I5;constructor(Q,Z=n,$,V,X,z,J){super(Q,Z,$,V,X,z,J)}newChild(Q,Z=n,$={}){return new P0(Q,Z,this.root,this.roots,this.nocase,this.childrenCache(),$)}getRootString(Q){return OQ.parse(Q).root}getRoot(Q){if(Q=S5(Q.toUpperCase()),Q===this.root.name)return this.root;for(let[Z,$]of Object.entries(this.roots))if(this.sameRoot(Q,Z))return this.roots[Q]=$;return this.roots[Q]=new z0(Q,this).root}sameRoot(Q,Z=this.root.name){return Q=Q.toUpperCase().replace(/\//g,"\\").replace(m8,"$1\\"),Q===Z}}class N0 extends h{splitSep="/";sep="/";constructor(Q,Z=n,$,V,X,z,J){super(Q,Z,$,V,X,z,J)}getRootString(Q){return Q.startsWith("/")?"/":""}getRoot(Q){return this.root}newChild(Q,Z=n,$={}){return new N0(Q,Z,this.root,this.roots,this.nocase,this.childrenCache(),$)}}class MQ{root;rootPath;roots;cwd;#Q;#V;#X;nocase;#Z;constructor(Q=process.cwd(),Z,$,{nocase:V,childrenCacheSize:X=16384,fs:z=$0}={}){if(this.#Z=d8(z),Q instanceof URL||Q.startsWith("file://"))Q=A5(Q);let J=Z.resolve(Q);this.roots=Object.create(null),this.rootPath=this.parseRootPath(J),this.#Q=new vQ,this.#V=new vQ,this.#X=new r8(X);let Y=J.substring(this.rootPath.length).split($);if(Y.length===1&&!Y[0])Y.pop();if(V===void 0)throw TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=V,this.root=this.newRoot(this.#Z),this.roots[this.rootPath]=this.root;let K=this.root,q=Y.length-1,W=Z.sep,H=this.rootPath,G=!1;for(let _ of Y){let U=q--;K=K.child(_,{relative:Array(U).fill("..").join(W),relativePosix:Array(U).fill("..").join("/"),fullpath:H+=(G?"":W)+_}),G=!0}this.cwd=K}depth(Q=this.cwd){if(typeof Q==="string")Q=this.cwd.resolve(Q);return Q.depth()}childrenCache(){return this.#X}resolve(...Q){let Z="";for(let X=Q.length-1;X>=0;X--){let z=Q[X];if(!z||z===".")continue;if(Z=Z?`${z}/${Z}`:z,this.isAbsolute(z))break}let $=this.#Q.get(Z);if($!==void 0)return $;let V=this.cwd.resolve(Z).fullpath();return this.#Q.set(Z,V),V}resolvePosix(...Q){let Z="";for(let X=Q.length-1;X>=0;X--){let z=Q[X];if(!z||z===".")continue;if(Z=Z?`${z}/${Z}`:z,this.isAbsolute(z))break}let $=this.#V.get(Z);if($!==void 0)return $;let V=this.cwd.resolve(Z).fullpathPosix();return this.#V.set(Z,V),V}relative(Q=this.cwd){if(typeof Q==="string")Q=this.cwd.resolve(Q);return Q.relative()}relativePosix(Q=this.cwd){if(typeof Q==="string")Q=this.cwd.resolve(Q);return Q.relativePosix()}basename(Q=this.cwd){if(typeof Q==="string")Q=this.cwd.resolve(Q);return Q.name}dirname(Q=this.cwd){if(typeof Q==="string")Q=this.cwd.resolve(Q);return(Q.parent||Q).fullpath()}async readdir(Q=this.cwd,Z={withFileTypes:!0}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q,Q=this.cwd;let{withFileTypes:$}=Z;if(!Q.canReaddir())return[];else{let V=await Q.readdir();return $?V:V.map((X)=>X.name)}}readdirSync(Q=this.cwd,Z={withFileTypes:!0}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q,Q=this.cwd;let{withFileTypes:$=!0}=Z;if(!Q.canReaddir())return[];else if($)return Q.readdirSync();else return Q.readdirSync().map((V)=>V.name)}async lstat(Q=this.cwd){if(typeof Q==="string")Q=this.cwd.resolve(Q);return Q.lstat()}lstatSync(Q=this.cwd){if(typeof Q==="string")Q=this.cwd.resolve(Q);return Q.lstatSync()}async readlink(Q=this.cwd,{withFileTypes:Z}={withFileTypes:!1}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q.withFileTypes,Q=this.cwd;let $=await Q.readlink();return Z?$:$?.fullpath()}readlinkSync(Q=this.cwd,{withFileTypes:Z}={withFileTypes:!1}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q.withFileTypes,Q=this.cwd;let $=Q.readlinkSync();return Z?$:$?.fullpath()}async realpath(Q=this.cwd,{withFileTypes:Z}={withFileTypes:!1}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q.withFileTypes,Q=this.cwd;let $=await Q.realpath();return Z?$:$?.fullpath()}realpathSync(Q=this.cwd,{withFileTypes:Z}={withFileTypes:!1}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q.withFileTypes,Q=this.cwd;let $=Q.realpathSync();return Z?$:$?.fullpath()}async walk(Q=this.cwd,Z={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q,Q=this.cwd;let{withFileTypes:$=!0,follow:V=!1,filter:X,walkFilter:z}=Z,J=[];if(!X||X(Q))J.push($?Q:Q.fullpath());let Y=new Set,K=(W,H)=>{Y.add(W),W.readdirCB((G,_)=>{if(G)return H(G);let U=_.length;if(!U)return H();let j=()=>{if(--U===0)H()};for(let A of _){if(!X||X(A))J.push($?A:A.fullpath());if(V&&A.isSymbolicLink())A.realpath().then((w)=>w?.isUnknown()?w.lstat():w).then((w)=>w?.shouldWalk(Y,z)?K(w,j):j());else if(A.shouldWalk(Y,z))K(A,j);else j()}},!0)},q=Q;return new Promise((W,H)=>{K(q,(G)=>{if(G)return H(G);W(J)})})}walkSync(Q=this.cwd,Z={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q,Q=this.cwd;let{withFileTypes:$=!0,follow:V=!1,filter:X,walkFilter:z}=Z,J=[];if(!X||X(Q))J.push($?Q:Q.fullpath());let Y=new Set([Q]);for(let K of Y){let q=K.readdirSync();for(let W of q){if(!X||X(W))J.push($?W:W.fullpath());let H=W;if(W.isSymbolicLink()){if(!(V&&(H=W.realpathSync())))continue;if(H.isUnknown())H.lstatSync()}if(H.shouldWalk(Y,z))Y.add(H)}}return J}[Symbol.asyncIterator](){return this.iterate()}iterate(Q=this.cwd,Z={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q,Q=this.cwd;return this.stream(Q,Z)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(Q=this.cwd,Z={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q,Q=this.cwd;let{withFileTypes:$=!0,follow:V=!1,filter:X,walkFilter:z}=Z;if(!X||X(Q))yield $?Q:Q.fullpath();let J=new Set([Q]);for(let Y of J){let K=Y.readdirSync();for(let q of K){if(!X||X(q))yield $?q:q.fullpath();let W=q;if(q.isSymbolicLink()){if(!(V&&(W=q.realpathSync())))continue;if(W.isUnknown())W.lstatSync()}if(W.shouldWalk(J,z))J.add(W)}}}stream(Q=this.cwd,Z={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q,Q=this.cwd;let{withFileTypes:$=!0,follow:V=!1,filter:X,walkFilter:z}=Z,J=new R9({objectMode:!0});if(!X||X(Q))J.write($?Q:Q.fullpath());let Y=new Set,K=[Q],q=0,W=()=>{let H=!1;while(!H){let G=K.shift();if(!G){if(q===0)J.end();return}q++,Y.add(G);let _=(j,A,w=!1)=>{if(j)return J.emit("error",j);if(V&&!w){let B=[];for(let O of A)if(O.isSymbolicLink())B.push(O.realpath().then((v)=>v?.isUnknown()?v.lstat():v));if(B.length){Promise.all(B).then(()=>_(null,A,!0));return}}for(let B of A)if(B&&(!X||X(B))){if(!J.write($?B:B.fullpath()))H=!0}q--;for(let B of A){let O=B.realpathCached()||B;if(O.shouldWalk(Y,z))K.push(O)}if(H&&!J.flowing)J.once("drain",W);else if(!U)W()},U=!0;G.readdirCB(_,!0),U=!1}};return W(),J}streamSync(Q=this.cwd,Z={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof h))Z=Q,Q=this.cwd;let{withFileTypes:$=!0,follow:V=!1,filter:X,walkFilter:z}=Z,J=new R9({objectMode:!0}),Y=new Set;if(!X||X(Q))J.write($?Q:Q.fullpath());let K=[Q],q=0,W=()=>{let H=!1;while(!H){let G=K.shift();if(!G){if(q===0)J.end();return}q++,Y.add(G);let _=G.readdirSync();for(let U of _)if(!X||X(U)){if(!J.write($?U:U.fullpath()))H=!0}q--;for(let U of _){let j=U;if(U.isSymbolicLink()){if(!(V&&(j=U.realpathSync())))continue;if(j.isUnknown())j.lstatSync()}if(j.shouldWalk(Y,z))K.push(j)}}if(H&&!J.flowing)J.once("drain",W)};return W(),J}chdir(Q=this.cwd){let Z=this.cwd;this.cwd=typeof Q==="string"?this.cwd.resolve(Q):Q,this.cwd[o8](Z)}}class z0 extends MQ{sep="\\";constructor(Q=process.cwd(),Z={}){let{nocase:$=!0}=Z;super(Q,OQ,"\\",{...Z,nocase:$});this.nocase=$;for(let V=this.cwd;V;V=V.parent)V.nocase=this.nocase}parseRootPath(Q){return OQ.parse(Q).root.toUpperCase()}newRoot(Q){return new P0(this.rootPath,Y9,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Q})}isAbsolute(Q){return Q.startsWith("/")||Q.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(Q)}}class J0 extends MQ{sep="/";constructor(Q=process.cwd(),Z={}){let{nocase:$=!1}=Z;super(Q,w5,"/",{...Z,nocase:$});this.nocase=$}parseRootPath(Q){return"/"}newRoot(Q){return new N0(this.rootPath,Y9,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Q})}isAbsolute(Q){return Q.startsWith("/")}}class S0 extends J0{constructor(Q=process.cwd(),Z={}){let{nocase:$=!0}=Z;super(Q,{...Z,nocase:$})}}var j1=process.platform==="win32"?P0:N0,a8=process.platform==="win32"?z0:process.platform==="darwin"?S0:J0;var E5=(Q)=>Q.length>=1,T5=(Q)=>Q.length>=1;class k9{#Q;#V;#X;length;#Z;#J;#M;#B;#H;#Y;#G=!0;constructor(Q,Z,$,V){if(!E5(Q))throw TypeError("empty pattern list");if(!T5(Z))throw TypeError("empty glob list");if(Z.length!==Q.length)throw TypeError("mismatched pattern list and glob list lengths");if(this.length=Q.length,$<0||$>=this.length)throw TypeError("index out of range");if(this.#Q=Q,this.#V=Z,this.#X=$,this.#Z=V,this.#X===0){if(this.isUNC()){let[X,z,J,Y,...K]=this.#Q,[q,W,H,G,..._]=this.#V;if(K[0]==="")K.shift(),_.shift();let U=[X,z,J,Y,""].join("/"),j=[q,W,H,G,""].join("/");this.#Q=[U,...K],this.#V=[j,..._],this.length=this.#Q.length}else if(this.isDrive()||this.isAbsolute()){let[X,...z]=this.#Q,[J,...Y]=this.#V;if(z[0]==="")z.shift(),Y.shift();let K=X+"/",q=J+"/";this.#Q=[K,...z],this.#V=[q,...Y],this.length=this.#Q.length}}}pattern(){return this.#Q[this.#X]}isString(){return typeof this.#Q[this.#X]==="string"}isGlobstar(){return this.#Q[this.#X]===N}isRegExp(){return this.#Q[this.#X]instanceof RegExp}globString(){return this.#M=this.#M||(this.#X===0?this.isAbsolute()?this.#V[0]+this.#V.slice(1).join("/"):this.#V.join("/"):this.#V.slice(this.#X).join("/"))}hasMore(){return this.length>this.#X+1}rest(){if(this.#J!==void 0)return this.#J;if(!this.hasMore())return this.#J=null;return this.#J=new k9(this.#Q,this.#V,this.#X+1,this.#Z),this.#J.#Y=this.#Y,this.#J.#H=this.#H,this.#J.#B=this.#B,this.#J}isUNC(){let Q=this.#Q;return this.#H!==void 0?this.#H:this.#H=this.#Z==="win32"&&this.#X===0&&Q[0]===""&&Q[1]===""&&typeof Q[2]==="string"&&!!Q[2]&&typeof Q[3]==="string"&&!!Q[3]}isDrive(){let Q=this.#Q;return this.#B!==void 0?this.#B:this.#B=this.#Z==="win32"&&this.#X===0&&this.length>1&&typeof Q[0]==="string"&&/^[a-z]:$/i.test(Q[0])}isAbsolute(){let Q=this.#Q;return this.#Y!==void 0?this.#Y:this.#Y=Q[0]===""&&Q.length>1||this.isDrive()||this.isUNC()}root(){let Q=this.#Q[0];return typeof Q==="string"&&this.isAbsolute()&&this.#X===0?Q:""}checkFollowGlobstar(){return!(this.#X===0||!this.isGlobstar()||!this.#G)}markFollowGlobstar(){if(this.#X===0||!this.isGlobstar()||!this.#G)return!1;return this.#G=!1,!0}}var y5=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class Y0{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(Q,{nobrace:Z,nocase:$,noext:V,noglobstar:X,platform:z=y5}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=z,this.mmopts={dot:!0,nobrace:Z,nocase:$,noext:V,noglobstar:X,optimizationLevel:2,platform:z,nocomment:!0,nonegate:!0};for(let J of Q)this.add(J)}add(Q){let Z=new p(Q,this.mmopts);for(let $=0;$<Z.set.length;$++){let V=Z.set[$],X=Z.globParts[$];if(!V||!X)throw Error("invalid pattern object");while(V[0]==="."&&X[0]===".")V.shift(),X.shift();let z=new k9(V,X,0,this.platform),J=new p(z.globString(),this.mmopts),Y=X[X.length-1]==="**",K=z.isAbsolute();if(K)this.absolute.push(J);else this.relative.push(J);if(Y)if(K)this.absoluteChildren.push(J);else this.relativeChildren.push(J)}}ignored(Q){let Z=Q.fullpath(),$=`${Z}/`,V=Q.relative()||".",X=`${V}/`;for(let z of this.relative)if(z.match(V)||z.match(X))return!0;for(let z of this.absolute)if(z.match(Z)||z.match($))return!0;return!1}childrenIgnored(Q){let Z=Q.fullpath()+"/",$=(Q.relative()||".")+"/";for(let V of this.relativeChildren)if(V.match($))return!0;for(let V of this.absoluteChildren)if(V.match(Z))return!0;return!1}}class CQ{store;constructor(Q=new Map){this.store=Q}copy(){return new CQ(new Map(this.store))}hasWalked(Q,Z){return this.store.get(Q.fullpath())?.has(Z.globString())}storeWalked(Q,Z){let $=Q.fullpath(),V=this.store.get($);if(V)V.add(Z.globString());else this.store.set($,new Set([Z.globString()]))}}class s8{store=new Map;add(Q,Z,$){let V=(Z?2:0)|($?1:0),X=this.store.get(Q);this.store.set(Q,X===void 0?V:V&X)}entries(){return[...this.store.entries()].map(([Q,Z])=>[Q,!!(Z&2),!!(Z&1)])}}class t8{store=new Map;add(Q,Z){if(!Q.canReaddir())return;let $=this.store.get(Q);if($){if(!$.find((V)=>V.globString()===Z.globString()))$.push(Z)}else this.store.set(Q,[Z])}get(Q){let Z=this.store.get(Q);if(!Z)throw Error("attempting to walk unknown path");return Z}entries(){return this.keys().map((Q)=>[Q,this.store.get(Q)])}keys(){return[...this.store.keys()].filter((Q)=>Q.canReaddir())}}class K0{hasWalkedCache;matches=new s8;subwalks=new t8;patterns;follow;dot;opts;constructor(Q,Z){this.opts=Q,this.follow=!!Q.follow,this.dot=!!Q.dot,this.hasWalkedCache=Z?Z.copy():new CQ}processPatterns(Q,Z){this.patterns=Z;let $=Z.map((V)=>[Q,V]);for(let[V,X]of $){this.hasWalkedCache.storeWalked(V,X);let z=X.root(),J=X.isAbsolute()&&this.opts.absolute!==!1;if(z){V=V.resolve(z==="/"&&this.opts.root!==void 0?this.opts.root:z);let W=X.rest();if(!W){this.matches.add(V,!0,!1);continue}else X=W}if(V.isENOENT())continue;let Y,K,q=!1;while(typeof(Y=X.pattern())==="string"&&(K=X.rest()))V=V.resolve(Y),X=K,q=!0;if(Y=X.pattern(),K=X.rest(),q){if(this.hasWalkedCache.hasWalked(V,X))continue;this.hasWalkedCache.storeWalked(V,X)}if(typeof Y==="string"){let W=Y===".."||Y===""||Y===".";this.matches.add(V.resolve(Y),J,W);continue}else if(Y===N){if(!V.isSymbolicLink()||this.follow||X.checkFollowGlobstar())this.subwalks.add(V,X);let W=K?.pattern(),H=K?.rest();if(!K||(W===""||W===".")&&!H)this.matches.add(V,J,W===""||W===".");else if(W===".."){let G=V.parent||V;if(!H)this.matches.add(G,J,!0);else if(!this.hasWalkedCache.hasWalked(G,H))this.subwalks.add(G,H)}}else if(Y instanceof RegExp)this.subwalks.add(V,X)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new K0(this.opts,this.hasWalkedCache)}filterEntries(Q,Z){let $=this.subwalks.get(Q),V=this.child();for(let X of Z)for(let z of $){let J=z.isAbsolute(),Y=z.pattern(),K=z.rest();if(Y===N)V.testGlobstar(X,z,K,J);else if(Y instanceof RegExp)V.testRegExp(X,Y,K,J);else V.testString(X,Y,K,J)}return V}testGlobstar(Q,Z,$,V){if(this.dot||!Q.name.startsWith(".")){if(!Z.hasMore())this.matches.add(Q,V,!1);if(Q.canReaddir()){if(this.follow||!Q.isSymbolicLink())this.subwalks.add(Q,Z);else if(Q.isSymbolicLink()){if($&&Z.checkFollowGlobstar())this.subwalks.add(Q,$);else if(Z.markFollowGlobstar())this.subwalks.add(Q,Z)}}}if($){let X=$.pattern();if(typeof X==="string"&&X!==".."&&X!==""&&X!==".")this.testString(Q,X,$.rest(),V);else if(X===".."){let z=Q.parent||Q;this.subwalks.add(z,$)}else if(X instanceof RegExp)this.testRegExp(Q,X,$.rest(),V)}}testRegExp(Q,Z,$,V){if(!Z.test(Q.name))return;if(!$)this.matches.add(Q,V,!1);else this.subwalks.add(Q,$)}testString(Q,Z,$,V){if(!Q.isNamed(Z))return;if(!$)this.matches.add(Q,V,!1);else this.subwalks.add(Q,$)}}var k5=(Q,Z)=>typeof Q==="string"?new Y0([Q],Z):Array.isArray(Q)?new Y0(Q,Z):Q;class RQ{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#Q=[];#V;#X;signal;maxDepth;includeChildMatches;constructor(Q,Z,$){if(this.patterns=Q,this.path=Z,this.opts=$,this.#X=!$.posix&&$.platform==="win32"?"\\":"/",this.includeChildMatches=$.includeChildMatches!==!1,$.ignore||!this.includeChildMatches){if(this.#V=k5($.ignore??[],$),!this.includeChildMatches&&typeof this.#V.add!=="function")throw Error("cannot ignore child matches, ignore lacks add() method.")}if(this.maxDepth=$.maxDepth||1/0,$.signal)this.signal=$.signal,this.signal.addEventListener("abort",()=>{this.#Q.length=0})}#Z(Q){return this.seen.has(Q)||!!this.#V?.ignored?.(Q)}#J(Q){return!!this.#V?.childrenIgnored?.(Q)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let Q=void 0;while(!this.paused&&(Q=this.#Q.shift()))Q()}onResume(Q){if(this.signal?.aborted)return;if(!this.paused)Q();else this.#Q.push(Q)}async matchCheck(Q,Z){if(Z&&this.opts.nodir)return;let $;if(this.opts.realpath){if($=Q.realpathCached()||await Q.realpath(),!$)return;Q=$}let X=Q.isUnknown()||this.opts.stat?await Q.lstat():Q;if(this.opts.follow&&this.opts.nodir&&X?.isSymbolicLink()){let z=await X.realpath();if(z&&(z.isUnknown()||this.opts.stat))await z.lstat()}return this.matchCheckTest(X,Z)}matchCheckTest(Q,Z){return Q&&(this.maxDepth===1/0||Q.depth()<=this.maxDepth)&&(!Z||Q.canReaddir())&&(!this.opts.nodir||!Q.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!Q.isSymbolicLink()||!Q.realpathCached()?.isDirectory())&&!this.#Z(Q)?Q:void 0}matchCheckSync(Q,Z){if(Z&&this.opts.nodir)return;let $;if(this.opts.realpath){if($=Q.realpathCached()||Q.realpathSync(),!$)return;Q=$}let X=Q.isUnknown()||this.opts.stat?Q.lstatSync():Q;if(this.opts.follow&&this.opts.nodir&&X?.isSymbolicLink()){let z=X.realpathSync();if(z&&(z?.isUnknown()||this.opts.stat))z.lstatSync()}return this.matchCheckTest(X,Z)}matchFinish(Q,Z){if(this.#Z(Q))return;if(!this.includeChildMatches&&this.#V?.add){let X=`${Q.relativePosix()}/**`;this.#V.add(X)}let $=this.opts.absolute===void 0?Z:this.opts.absolute;this.seen.add(Q);let V=this.opts.mark&&Q.isDirectory()?this.#X:"";if(this.opts.withFileTypes)this.matchEmit(Q);else if($){let X=this.opts.posix?Q.fullpathPosix():Q.fullpath();this.matchEmit(X+V)}else{let X=this.opts.posix?Q.relativePosix():Q.relative(),z=this.opts.dotRelative&&!X.startsWith(".."+this.#X)?"."+this.#X:"";this.matchEmit(!X?"."+V:z+X+V)}}async match(Q,Z,$){let V=await this.matchCheck(Q,$);if(V)this.matchFinish(V,Z)}matchSync(Q,Z,$){let V=this.matchCheckSync(Q,$);if(V)this.matchFinish(V,Z)}walkCB(Q,Z,$){if(this.signal?.aborted)$();this.walkCB2(Q,Z,new K0(this.opts),$)}walkCB2(Q,Z,$,V){if(this.#J(Q))return V();if(this.signal?.aborted)V();if(this.paused){this.onResume(()=>this.walkCB2(Q,Z,$,V));return}$.processPatterns(Q,Z);let X=1,z=()=>{if(--X===0)V()};for(let[J,Y,K]of $.matches.entries()){if(this.#Z(J))continue;X++,this.match(J,Y,K).then(()=>z())}for(let J of $.subwalkTargets()){if(this.maxDepth!==1/0&&J.depth()>=this.maxDepth)continue;X++;let Y=J.readdirCached();if(J.calledReaddir())this.walkCB3(J,Y,$,z);else J.readdirCB((K,q)=>this.walkCB3(J,q,$,z),!0)}z()}walkCB3(Q,Z,$,V){$=$.filterEntries(Q,Z);let X=1,z=()=>{if(--X===0)V()};for(let[J,Y,K]of $.matches.entries()){if(this.#Z(J))continue;X++,this.match(J,Y,K).then(()=>z())}for(let[J,Y]of $.subwalks.entries())X++,this.walkCB2(J,Y,$.child(),z);z()}walkCBSync(Q,Z,$){if(this.signal?.aborted)$();this.walkCB2Sync(Q,Z,new K0(this.opts),$)}walkCB2Sync(Q,Z,$,V){if(this.#J(Q))return V();if(this.signal?.aborted)V();if(this.paused){this.onResume(()=>this.walkCB2Sync(Q,Z,$,V));return}$.processPatterns(Q,Z);let X=1,z=()=>{if(--X===0)V()};for(let[J,Y,K]of $.matches.entries()){if(this.#Z(J))continue;this.matchSync(J,Y,K)}for(let J of $.subwalkTargets()){if(this.maxDepth!==1/0&&J.depth()>=this.maxDepth)continue;X++;let Y=J.readdirSync();this.walkCB3Sync(J,Y,$,z)}z()}walkCB3Sync(Q,Z,$,V){$=$.filterEntries(Q,Z);let X=1,z=()=>{if(--X===0)V()};for(let[J,Y,K]of $.matches.entries()){if(this.#Z(J))continue;this.matchSync(J,Y,K)}for(let[J,Y]of $.subwalks.entries())X++,this.walkCB2Sync(J,Y,$.child(),z);z()}}class I0 extends RQ{matches=new Set;constructor(Q,Z,$){super(Q,Z,$)}matchEmit(Q){this.matches.add(Q)}async walk(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())await this.path.lstat();return await new Promise((Q,Z)=>{this.walkCB(this.path,this.patterns,()=>{if(this.signal?.aborted)Z(this.signal.reason);else Q(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}}class x0 extends RQ{results;constructor(Q,Z,$){super(Q,Z,$);this.results=new R9({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(Q){if(this.results.write(Q),!this.results.flowing)this.pause()}stream(){let Q=this.path;if(Q.isUnknown())Q.lstat().then(()=>{this.walkCB(Q,this.patterns,()=>this.results.end())});else this.walkCB(Q,this.patterns,()=>this.results.end());return this.results}streamSync(){if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}}var f5=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class K9{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(Q,Z){if(!Z)throw TypeError("glob options required");if(this.withFileTypes=!!Z.withFileTypes,this.signal=Z.signal,this.follow=!!Z.follow,this.dot=!!Z.dot,this.dotRelative=!!Z.dotRelative,this.nodir=!!Z.nodir,this.mark=!!Z.mark,!Z.cwd)this.cwd="";else if(Z.cwd instanceof URL||Z.cwd.startsWith("file://"))Z.cwd=b5(Z.cwd);if(this.cwd=Z.cwd||"",this.root=Z.root,this.magicalBraces=!!Z.magicalBraces,this.nobrace=!!Z.nobrace,this.noext=!!Z.noext,this.realpath=!!Z.realpath,this.absolute=Z.absolute,this.includeChildMatches=Z.includeChildMatches!==!1,this.noglobstar=!!Z.noglobstar,this.matchBase=!!Z.matchBase,this.maxDepth=typeof Z.maxDepth==="number"?Z.maxDepth:1/0,this.stat=!!Z.stat,this.ignore=Z.ignore,this.withFileTypes&&this.absolute!==void 0)throw Error("cannot set absolute and withFileTypes:true");if(typeof Q==="string")Q=[Q];if(this.windowsPathsNoEscape=!!Z.windowsPathsNoEscape||Z.allowWindowsEscape===!1,this.windowsPathsNoEscape)Q=Q.map((Y)=>Y.replace(/\\/g,"/"));if(this.matchBase){if(Z.noglobstar)throw TypeError("base matching requires globstar");Q=Q.map((Y)=>Y.includes("/")?Y:`./**/${Y}`)}if(this.pattern=Q,this.platform=Z.platform||f5,this.opts={...Z,platform:this.platform},Z.scurry){if(this.scurry=Z.scurry,Z.nocase!==void 0&&Z.nocase!==Z.scurry.nocase)throw Error("nocase option contradicts provided scurry option")}else{let Y=Z.platform==="win32"?z0:Z.platform==="darwin"?S0:Z.platform?J0:a8;this.scurry=new Y(this.cwd,{nocase:Z.nocase,fs:Z.fs})}this.nocase=this.scurry.nocase;let $=this.platform==="darwin"||this.platform==="win32",V={...Z,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:$,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},X=this.pattern.map((Y)=>new p(Y,V)),[z,J]=X.reduce((Y,K)=>{return Y[0].push(...K.set),Y[1].push(...K.globParts),Y},[[],[]]);this.patterns=z.map((Y,K)=>{let q=J[K];if(!q)throw Error("invalid pattern object");return new k9(Y,q,0,this.platform)})}async walk(){return[...await new I0(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new I0(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new x0(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new x0(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}}var DQ=(Q,Z={})=>{if(!Array.isArray(Q))Q=[Q];for(let $ of Q)if(new p($,Z).hasMagic())return!0;return!1};function T0(Q,Z={}){return new K9(Q,Z).streamSync()}function Q6(Q,Z={}){return new K9(Q,Z).stream()}function Z6(Q,Z={}){return new K9(Q,Z).walkSync()}async function e8(Q,Z={}){return new K9(Q,Z).walk()}function y0(Q,Z={}){return new K9(Q,Z).iterateSync()}function $6(Q,Z={}){return new K9(Q,Z).iterate()}var u5=T0,h5=Object.assign(Q6,{sync:T0}),g5=y0,d5=Object.assign($6,{sync:y0}),m5=Object.assign(Z6,{stream:T0,iterate:y0}),E0=Object.assign(e8,{glob:e8,globSync:Z6,sync:m5,globStream:Q6,stream:h5,globStreamSync:T0,streamSync:u5,globIterate:$6,iterate:d5,globIterateSync:y0,iterateSync:g5,Glob:K9,hasMagic:DQ,escape:E9,unescape:a});E0.glob=E0;var c5={name:"Read",description:"Reads a file from the local filesystem. You can access any file directly by using this tool.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based)"},limit:{type:"number",description:"The number of lines to read"}},required:["file_path"]},handler:async(Q,Z)=>{let $=Q.file_path,V=Q.offset||1,X=Q.limit||2000;try{let Y=(await Bun.file($).text()).split(`
128
+ `),K=Math.max(0,V-1),q=Math.min(Y.length,K+X);return{content:Y.slice(K,q).map((G,_)=>`${K+_+1} ${G}`).join(`
129
+ `)}}catch(z){return{content:`Error reading file: ${z instanceof Error?z.message:String(z)}`,is_error:!0}}}},l5={name:"Write",description:"Writes a file to the local filesystem. This tool will overwrite the existing file if there is one at the provided path.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to write"},content:{type:"string",description:"The content to write to the file"}},required:["file_path","content"]},handler:async(Q,Z)=>{let{file_path:$,content:V}=Q;try{return await Bun.write($,V),{content:`Successfully wrote to ${$}`}}catch(X){return{content:`Error writing file: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}},p5={name:"Edit",description:"Performs exact string replacements in files. Use this tool to modify existing files.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with"},replace_all:{type:"boolean",description:"Replace all occurrences (default false)"}},required:["file_path","old_string","new_string"]},handler:async(Q,Z)=>{let{file_path:$,old_string:V,new_string:X}=Q,z=Q.replace_all||!1;try{let Y=await Bun.file($).text();if(z){let K=Y;Y=Y.split(V).join(X);let q=(K.match(new RegExp(i5(V),"g"))||[]).length;if(q===0)return{content:"Error: String not found in file",is_error:!0};return await Bun.write($,Y),{content:`Successfully replaced ${q} occurrences`}}else{let K=Y.indexOf(V);if(K===-1)return{content:"Error: String not found in file",is_error:!0};if(Y.indexOf(V,K+1)!==-1)return{content:"Error: String appears multiple times in file. Use replace_all or provide more context.",is_error:!0};return Y=Y.replace(V,X),await Bun.write($,Y),{content:`Successfully edited ${$}`}}}catch(J){return{content:`Error editing file: ${J instanceof Error?J.message:String(J)}`,is_error:!0}}}};function i5(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var n5={name:"Bash",description:"Executes a given bash command with optional timeout. Working directory persists between commands.",input_schema:{type:"object",properties:{command:{type:"string",description:"The command to execute"},timeout:{type:"number",description:"Optional timeout in milliseconds (max 600000)"},description:{type:"string",description:"Clear, concise description of what this command does"}},required:["command"]},handler:async(Q,Z)=>{let $=Q.command,V=Q.timeout||120000;try{let X=Bun.spawnSync(["sh","-c",$],{cwd:Z.workingDirectory,timeout:V,maxBuffer:31457280}),z=X.stdout?.toString()||"",J=X.stderr?.toString()||"";if(X.exitCode!==0)return{content:`Exit code: ${X.exitCode}
130
+ ${z}
131
+ ${J}`.trim(),is_error:!0};return{content:z||"(no output)"}}catch(X){return{content:`Error executing command: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}},r5={name:"Glob",description:"Fast file pattern matching tool that works with any codebase size. Supports glob patterns.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files"},path:{type:"string",description:"The directory to search (default: current directory)"}},required:["pattern"]},handler:async(Q,Z)=>{let $=Q.pattern,V=Q.path||Z.workingDirectory;try{let X=await E0($,{cwd:V,absolute:!0,nodir:!0});if(X.length===0)return{content:"No files found matching pattern"};return{content:X.sort().join(`
132
+ `)}}catch(X){return{content:`Error searching files: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}},o5={name:"Grep",description:"A powerful search tool built on ripgrep. Supports full regex syntax.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for"},path:{type:"string",description:"File or directory to search"},glob:{type:"string",description:"Glob pattern to filter files"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode (default: content)"},"-i:":{type:"boolean",description:"Case insensitive search"},"-C:":{type:"number",description:"Context lines around match"},head_limit:{type:"number",description:"Maximum number of results"}},required:["pattern"]},handler:async(Q,Z)=>{let $=Q.pattern,V=Q.path||Z.workingDirectory,X=Q.glob,z=Q.output_mode||"content",J=Q["-i:"],Y=Q["-C:"]||0,K=Q.head_limit||100;try{let W=await D().grepSearch(V,{pattern:$,caseInsensitive:J,glob:X,outputMode:z,contextLines:Y,headLimit:K});if(z==="files_with_matches"){if(W.filesWithMatches.length===0)return{content:"No files matched"};return{content:W.filesWithMatches.join(`
133
+ `)}}if(z==="count")return{content:`${W.totalCount} matches in ${W.filesWithMatches.length} files`};if(W.matches.length===0)return{content:"No matches found"};let G=W.matches.map((_)=>{let U=[`${_.filePath}:${_.lineNumber}:${_.line}`];if(_.beforeContext.length>0)U.unshift(..._.beforeContext.map((j)=>` ${j}`));if(_.afterContext.length>0)U.push(..._.afterContext.map((j)=>` ${j}`));return U.join(`
134
+ `)}).join(`
135
+ `);if(W.truncated)G+=`
136
+
137
+ ... (${W.totalCount} total matches, showing first ${W.matches.length})`;return{content:G}}catch(q){return{content:`Error searching: ${q instanceof Error?q.message:String(q)}`,is_error:!0}}}},a5={name:"Task",description:`Launch a new agent to handle complex, multi-step tasks autonomously.
138
+
139
+ The Task tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
140
+
141
+ Available agent types and their tools:
142
+ - Bash: Command execution specialist for running bash commands. Use for git operations, command execution, and other terminal tasks.
143
+ - general-purpose: General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks.
144
+ - Explore: Fast agent specialized for exploring codebases. Use to quickly find files by patterns, search code for keywords, or answer questions about the codebase.
145
+ - Plan: Software architect agent for designing implementation plans. Returns step-by-step plans, identifies critical files and considers architectural trade-offs.
146
+
147
+ When using the Task tool, you must specify a subagent_type parameter to select the agent type.
148
+
149
+ Usage notes:
150
+ - Always include a short description (3-5 words) summarizing what the agent will do
151
+ - Launch multiple agents concurrently whenever possible to maximize performance
152
+ - Agents can be resumed using the "resume" parameter by passing the agent ID from a previous invocation.`,input_schema:{type:"object",properties:{subagent_type:{type:"string",enum:["Bash","general-purpose","Explore","Plan"],description:"The agent type to launch"},description:{type:"string",description:"A short (3-5 word) description of what the agent will do"},prompt:{type:"string",description:"The task for the agent to perform"},resume:{type:"string",description:"Resume a previous agent by its ID"},model:{type:"string",enum:["sonnet","opus","haiku"],description:"Model for the subagent (default: haiku for quick tasks)"},run_in_background:{type:"boolean",description:"Run the agent in the background"}},required:["subagent_type","prompt"]},handler:async(Q,Z)=>{let{subagent_type:$,prompt:V,description:X}=Q,z=Q.model||"haiku",J=Q.resume,Y=Q.run_in_background,K=J||`${$.toLowerCase()}-${Date.now().toString(36)}`;try{let q=process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.Z_AI_API_KEY||"";if(!q)return{content:"Error: No API key available for subagent. Set ANTHROPIC_API_KEY, CLAUDE_API_KEY, ANTHROPIC_AUTH_TOKEN, or Z_AI_API_KEY environment variable.",is_error:!0};let W={haiku:"claude-haiku-4-5",sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-6"},H=W[z]||W.haiku,G=[import.meta.dir+"/../../dist/cli.js",import.meta.dir+"/../cli.ts",process.cwd()+"/dist/cli.js",process.cwd()+"/src/cli.ts"],_=null;for(let B of G)try{if(await Bun.file(B).exists()){_=B;break}}catch{}if(!_)return{content:`Error: Could not find CLI. Tried:
153
+ ${G.join(`
154
+ `)}`,is_error:!0};let U=["run",_,"-m",H,"-p",Z.permissionMode,"-q",V];if(Y)return Bun.spawn(["bun",...U],{cwd:Z.workingDirectory,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:q}}).unref(),{content:JSON.stringify({agentId:K,status:"running",message:`Agent started in background. Use TaskOutput tool with task_id: "${K}" to check results.`,description:X||"Background task"})};let j=Bun.spawnSync(["bun",...U],{cwd:Z.workingDirectory,timeout:300000,maxBuffer:10485760,env:{...process.env,ANTHROPIC_API_KEY:q}}),A=j.stdout?.toString()||"",w=j.stderr?.toString()||"";if(j.exitCode!==0)return{content:`Agent failed with exit code ${j.exitCode}
155
+ ${w}
156
+ ${A}`.trim(),is_error:!0};return{content:JSON.stringify({agentId:K,status:"completed",output:A,description:X||"Task completed"})}}catch(q){return{content:`Error running subagent: ${q instanceof Error?q.message:String(q)}`,is_error:!0}}}},s5={name:"TaskOutput",description:`Retrieves output from a running or completed task (background shell, agent, or remote session).
157
+
158
+ Takes a task_id parameter identifying the task.
159
+ Returns the task output along with status information.
160
+ Use block=true (default) to wait for task completion.
161
+ Use block=false for non-blocking check of current status.
162
+
163
+ Task IDs can be found using the /tasks command
164
+ Works with all task types: background shells, async agents, and remote sessions`,input_schema:{type:"object",properties:{task_id:{type:"string",description:"The task ID to get output from"},block:{type:"boolean",description:"Whether to wait for completion (default: true)",default:!0},timeout:{type:"number",description:"Max wait time in ms (default: 30000, max: 600000)",default:30000,minimum:0,maximum:600000}},required:["task_id"]},handler:async(Q,Z)=>{let $=Q.task_id,V=Q.block??!0,X=Q.timeout??30000;try{let z=`${Z.workingDirectory}/.claude/tasks/${$}.json`,J=Bun.file(z);if(!await J.exists())return{content:`Task not found: ${$}. Use /tasks to list available tasks.`,is_error:!0};let Y=await J.json();if(V&&Y.status==="running"){let K=Date.now();while(Date.now()-K<X){await new Promise((W)=>setTimeout(W,1000));let q=Bun.file(z);if(await q.exists()){let W=await q.json();if(W.status!=="running")return{content:JSON.stringify({task_id:$,status:W.status,output:W.output,error:W.error,duration:W.endTime?W.endTime-W.startTime:null},null,2)}}}return{content:JSON.stringify({task_id:$,status:"timeout",message:`Task still running after ${X}ms`},null,2)}}return{content:JSON.stringify({task_id:$,status:Y.status,output:Y.output,error:Y.error,duration:Y.endTime?Y.endTime-Y.startTime:null},null,2)}}catch(z){return{content:`Error getting task output: ${z instanceof Error?z.message:String(z)}`,is_error:!0}}}},t5={name:"AskUserQuestion",description:`Use this tool when you need to ask the user questions during execution.
165
+
166
+ This allows you to:
167
+ 1. Gather user preferences or requirements
168
+ 2. Clarify ambiguous instructions
169
+ 3. Get decisions on implementation choices
170
+ 4. Offer choices to the user about what direction to take
171
+
172
+ Plan mode note: In plan mode, use this tool to clarify requirements or choose between approaches BEFORE finalizing your plan. Do NOT use this tool if your plan is ready - that's what ExitPlanMode is for.
173
+
174
+ The options array should have 2-4 options. Each option should be a distinct, mutually exclusive choice.
175
+ The preview feature allows showing markdown content in a side-by-side layout.
176
+
177
+ User can always select "Other" to provide custom text input.`,input_schema:{type:"object",properties:{questions:{type:"array",description:"Questions to ask the user (1-4 questions)",items:{type:"object",properties:{question:{type:"string",description:"The complete question to ask the user"},header:{type:"string",description:"Very short label displayed as a chip/tag (max 12 chars)"},options:{type:"array",description:"The available choices (2-4 options)",items:{type:"object",properties:{label:{type:"string",description:"The display text for this option (5 words max)"},description:{type:"string",description:"Explanation of what this option means"},markdown:{type:"string",description:"Optional preview content shown in a monospace box"}},required:["label","description"]},minItems:2,maxItems:4},multiSelect:{type:"boolean",description:"Allow selecting multiple options (default: false)",default:!1}},required:["question","header","options"]},minItems:1,maxItems:4}},required:["questions"]},handler:async(Q,Z)=>{let $=Q.questions;try{let V=$.map((X,z)=>{let J=X.options.map((Y,K)=>{let q=` ${K+1}. ${Y.label}`;if(Y.description)q+=` - ${Y.description}`;return q}).join(`
178
+ `);return`## Question ${z+1}: [${X.header}]
179
+ ${X.question}
180
+
181
+ Options:
182
+ ${J}${X.multiSelect?`
183
+ (multi-select enabled)`:""}`}).join(`
184
+
185
+ ---
186
+
187
+ `);return{content:JSON.stringify({type:"user_question",questions:$,formatted:V,message:"Questions prepared for user response"},null,2)}}catch(V){return{content:`Error preparing questions: ${V instanceof Error?V.message:String(V)}`,is_error:!0}}}},e5={name:"EnterPlanMode",description:`Use this tool when you are in plan mode and have finished writing your plan to the plan file and are ready for user approval.
188
+
189
+ How This Tool Works:
190
+ - You should have already written your plan to the plan file specified in the plan mode system message
191
+ - This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote
192
+ - This tool simply signals that you're done planning and ready for the user to review and approve
193
+
194
+ When to Use This Tool:
195
+ IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.
196
+
197
+ Plan mode note: In plan mode, use this tool to clarify requirements or choose between approaches BEFORE finalizing your plan. Do NOT use this tool if your plan is ready - that's what ExitPlanMode is for.
198
+
199
+ Examples:
200
+ - "Search for and understand the implementation of vim mode" - Do NOT use this tool
201
+ - "Help me implement yank mode for vim" - Use EnterPlanMode
202
+
203
+ Important notes:
204
+ - NEVER run additional commands to read or explore code, besides git bash commands
205
+ - NEVER use the TodoWrite or Task tools
206
+ - DO NOT commit files that likely contain secrets (.env, credentials.json, etc.)
207
+ - If you discover unexpected state like unfamiliar files, branches, or configuration, investigate before deleting or overwriting`,input_schema:{type:"object",properties:{allowedPrompts:{type:"array",description:"Prompt-based permissions needed to implement the plan",items:{type:"object",properties:{tool:{type:"string",description:"The tool this prompt applies to (e.g., 'Bash')"},prompt:{type:"string",description:"Semantic description of the action (e.g., 'run tests', 'install dependencies')"}},required:["tool","prompt"]}}},required:[]},handler:async(Q,Z)=>{let $=Q.allowedPrompts;try{let V=`${Z.workingDirectory}/.claude/plan.md`,X=Bun.file(V);if(!await X.exists())return{content:"Error: No plan file found. Please write your plan to .claude/plan.md first.",is_error:!0};let z=await X.text();return{content:JSON.stringify({type:"plan_ready",planFile:V,planLength:z.length,allowedPrompts:$||[],message:"Plan is ready for user review. ExitPlanMode will request user approval."},null,2)}}catch(V){return{content:`Error entering plan mode: ${V instanceof Error?V.message:String(V)}`,is_error:!0}}}},Q7={name:"ExitPlanMode",description:`Use this tool when you are in plan mode and have finished writing your plan to the plan file and are ready for user approval.
208
+
209
+ This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote.
210
+ This tool simply signals that you're done planning and ready for the user to review and approve.
211
+
212
+ IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code.
213
+ ExitPlanMode inherently requests user approval of the plan.`,input_schema:{type:"object",properties:{allowedPrompts:{type:"array",description:"Prompt-based permissions needed to implement the plan",items:{type:"object",properties:{tool:{type:"string",description:"The tool this prompt applies to"},prompt:{type:"string",description:"Semantic description of the action"}},required:["tool","prompt"]}}},required:[]},handler:async(Q,Z)=>{let $=Q.allowedPrompts;try{let V=`${Z.workingDirectory}/.claude/plan.md`,X=Bun.file(V);if(!await X.exists())return{content:"Error: No plan file found at .claude/plan.md",is_error:!0};let z=await X.text();return{content:JSON.stringify({type:"exit_plan_mode",status:"awaiting_approval",planFile:V,planPreview:z.slice(0,500)+(z.length>500?"...":""),allowedPrompts:$||[],message:"Plan submitted for user approval."},null,2)}}catch(V){return{content:`Error exiting plan mode: ${V instanceof Error?V.message:String(V)}`,is_error:!0}}}},Z7={name:"Skill",description:`Execute a skill within the main conversation.
214
+
215
+ When users ask you to perform tasks, check if any of the available skills match. Skills provide specialized capabilities and domain knowledge.
216
+
217
+ When users reference a "slash command" or "/<something>" (e.g., "/commit", "/review-pr"), they are referring to a skill. Use this tool to invoke it.
218
+
219
+ How to invoke:
220
+ - Use this tool with the skill name and optional arguments
221
+ - Examples:
222
+ - skill: "commit" - invoke the commit skill
223
+ - skill: "review-pr", args: "123" - invoke with arguments
224
+ - Use fully qualified name for namespaced skills: skill: "ms-office-suite:pdf"
225
+
226
+ Available skills are listed in system-reminder messages in the conversation.
227
+ When a skill matches the user's request, this is a BLOCKING REQUIREMENT: invoke the relevant Skill tool BEFORE generating any other response about the task.
228
+
229
+ Important:
230
+ - NEVER mention a skill without actually calling this tool
231
+ - Do not invoke a skill that is already running
232
+ - Do not use this tool for built-in CLI commands (like /help, /clear)`,input_schema:{type:"object",properties:{skill:{type:"string",description:"The skill name (e.g., 'commit', 'review-pr', or fully qualified 'namespace:skill')"},args:{type:"string",description:"Optional arguments for the skill"}},required:["skill"]},handler:async(Q,Z)=>{let{skill:$,args:V}=Q;try{let X=`${Z.workingDirectory}/.claude/skills`,z=`${process.env.HOME||""}/.claude/skills`,J=[`${X}/${$}.md`,`${X}/${$}/skill.md`,`${z}/${$}.md`,`${z}/${$}/skill.md`],Y=null;for(let W of J)if(await Bun.file(W).exists()){Y=W;break}if(!Y)return{content:`Skill not found: ${$}. Available skills can be listed with /help.`,is_error:!0};let q=await Bun.file(Y).text();return{content:JSON.stringify({type:"skill_invocation",skill:$,args:V,skillFile:Y,content:q,message:`Skill "${$}" loaded. Follow the instructions in the skill content.`},null,2)}}catch(X){return{content:`Error invoking skill: ${X instanceof Error?X.message:String(X)}`,is_error:!0}}}},$7={name:"TaskStop",description:`Stops a running background task by its ID.
233
+ Takes a task_id parameter identifying the task to stop.
234
+ Returns a success or failure status.
235
+ Use this tool to terminate a long-running task.`,input_schema:{type:"object",properties:{task_id:{type:"string",description:"The ID of the background task to stop"},shell_id:{type:"string",description:"Deprecated: use task_id instead"}},required:["task_id"]},handler:async(Q,Z)=>{let $=Q.task_id;try{let V=`${Z.workingDirectory}/.claude/tasks/${$}.json`,X=Bun.file(V);if(!await X.exists())return{content:`Task not found: ${$}`,is_error:!0};let z=await X.json();if(z.status!=="running")return{content:JSON.stringify({task_id:$,status:z.status,message:`Task is already ${z.status}`},null,2)};return z.status="stopped",await Bun.write(V,JSON.stringify(z,null,2)),{content:JSON.stringify({task_id:$,status:"stopped",message:"Task stopped successfully"},null,2)}}catch(V){return{content:`Error stopping task: ${V instanceof Error?V.message:String(V)}`,is_error:!0}}}},V7={name:"NotebookEdit",description:`Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source.
236
+
237
+ Jupyter notebooks are interactive documents that combine code, text, and visualizations. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number.`,input_schema:{type:"object",properties:{notebook_path:{type:"string",description:"The absolute path to the Jupyter notebook file to edit"},cell_id:{type:"string",description:"The ID of the cell to edit (optional, alternative to cell_number)"},cell_number:{type:"number",description:"The index of the cell to edit (0-indexed)"},new_source:{type:"string",description:"The new source for the cell"},cell_type:{type:"string",enum:["code","markdown"],description:"The type of the cell (code or markdown). Defaults to code."},edit_mode:{type:"string",enum:["replace","insert","delete"],description:"The type of edit to perform (replace, insert, delete)"}},required:["notebook_path"]},handler:async(Q,Z)=>{let{notebook_path:$,cell_id:V,cell_number:X,new_source:z}=Q,J=Q.cell_type||"code",Y=Q.edit_mode||"replace";try{let K=Bun.file($);if(!await K.exists())return{content:`Error: Notebook not found: ${$}`,is_error:!0};let q=await K.json();if(!q.cells||!Array.isArray(q.cells))return{content:"Error: Invalid notebook format - no cells array",is_error:!0};let W;if(V){if(W=q.cells.findIndex((H)=>H.id===V),W===-1)return{content:`Error: Cell with ID "${V}" not found`,is_error:!0}}else if(X!==void 0){if(W=X,W<0||W>=q.cells.length)if(Y==="insert")W=q.cells.length;else return{content:`Error: Cell number ${W} out of range (0-${q.cells.length-1})`,is_error:!0}}else if(Y!=="insert")return{content:"Error: Must specify either cell_id or cell_number",is_error:!0};else W=q.cells.length;switch(Y){case"delete":{q.cells.splice(W,1);break}case"insert":{let H={id:`cell-${Date.now()}`,cell_type:J,source:z||"",metadata:{},...J==="code"?{outputs:[],execution_count:null}:{}};q.cells.splice(W,0,H);break}case"replace":default:{if(z===void 0)return{content:"Error: new_source is required for replace mode",is_error:!0};let H=q.cells[W];if(!H)return{content:`Error: Cell at index ${W} not found`,is_error:!0};q.cells[W]={...H,source:z,cell_type:J,...J==="code"?{execution_count:null}:{}};break}}return await Bun.write($,JSON.stringify(q,null,1)),{content:JSON.stringify({success:!0,message:`Successfully ${Y}d cell in ${$}`,cellCount:q.cells.length})}}catch(K){return{content:`Error editing notebook: ${K instanceof Error?K.message:String(K)}`,is_error:!0}}}},X7=[c5,l5,p5,n5,r5,o5,a5,s5,$7,t5,e5,Q7,Z7,V7,t0,$Q,zQ,e0,QQ,XQ,ZQ,VQ];function r1(Q){return X7.find((Z)=>Z.name===Q)}import{spawn as z7}from"child_process";import PQ from"ws";class NQ{static MCPClient=NQ;name;config;connected=!1;tools=[];process=null;websocket=null;requestId=0;pendingRequests=new Map;buffer="";onLog;constructor(Q){this.name=Q.name,this.config=Q.config,this.onLog=Q.onLog}async connect(){if(this.config.type==="stdio")await this.connectStdio();else if(this.config.type==="http"||this.config.type==="sse")await this.connectHttp();else if(this.config.type==="ws")await this.connectWebSocket()}async connectStdio(){if(!this.config.command)throw Error("No command specified for stdio transport");this.log(`Starting stdio transport: ${this.config.command}`),this.process=z7(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),this.process.stdout?.on("data",(Q)=>{this.handleData(Q.toString())}),this.process.stderr?.on("data",(Q)=>{this.log(`stderr: ${Q.toString()}`)}),this.process.on("error",(Q)=>{this.log(`Process error: ${Q.message}`)}),this.process.on("close",(Q)=>{this.log(`Process closed with code ${Q}`),this.connected=!1}),await new Promise((Q)=>setTimeout(Q,100)),await this.initialize()}async connectHttp(){if(!this.config.url)throw Error("No URL specified for HTTP transport");this.log(`Starting HTTP transport: ${this.config.url}`);try{let Q=await fetch(this.config.url,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"coder",version:"0.1.0"}}})});if(!Q.ok)throw Error(`HTTP error: ${Q.status}`);let Z=await Q.json();this.connected=!0,await this.loadTools()}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to connect to HTTP server: ${Z}`)}}async connectWebSocket(){if(!this.config.url)throw Error("No URL specified for WebSocket transport");let Q=this.config.url;return this.log(`Starting WebSocket transport: ${Q}`),new Promise((Z,$)=>{let V={...this.config.headers},X=new PQ(Q,{headers:V,handshakeTimeout:this.config.timeout||30000});X.on("open",()=>{this.log("WebSocket connection established"),this.websocket=X,this.connected=!0,this.initialize().then(()=>Z()).catch((z)=>{let J=z instanceof Error?z.message:String(z);this.log(`Initialization failed: ${J}`),$(z)})}),X.on("message",(z,J)=>{let Y=J?z.toString():z.toString();this.handleData(Y)}),X.on("error",(z)=>{if(this.log(`WebSocket error: ${z.message}`),!this.connected)$(Error(`WebSocket connection failed: ${z.message}`))}),X.on("close",(z,J)=>{this.log(`WebSocket closed: code=${z}, reason=${J.toString()}`),this.connected=!1,this.websocket=null;for(let[Y,K]of this.pendingRequests)this.pendingRequests.delete(Y),K.reject(Error(`WebSocket closed: ${J.toString()}`))}),X.on("ping",()=>{X.pong()})})}async initialize(){let Q=await this.request("initialize",{protocolVersion:"2024-11-05",capabilities:{tools:{},resources:{},prompts:{}},clientInfo:{name:"coder",version:"0.1.0"}});this.log(`Initialized with: ${JSON.stringify(Q)}`),this.connected=!0,this.notify("notifications/initialized",{}),await this.loadTools()}async loadTools(){try{let Q=await this.request("tools/list",{});this.tools=Q.tools.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema})),this.log(`Loaded ${this.tools.length} tools`)}catch(Q){this.log(`Failed to load tools: ${Q}`)}}async callTool(Q,Z){return{content:(await this.request("tools/call",{name:Q,arguments:Z})).content.filter((X)=>X.type==="text").map((X)=>X.text||"").join(`
238
+ `)}}async request(Q,Z){let $=++this.requestId,V={jsonrpc:"2.0",id:$,method:Q,params:Z};return new Promise((X,z)=>{this.pendingRequests.set($,{resolve:X,reject:z});let J=JSON.stringify(V);if(this.websocket&&this.websocket.readyState===PQ.OPEN)this.websocket.send(J);else if(this.process?.stdin?.writable)this.process.stdin.write(J+`
239
+ `);else{this.pendingRequests.delete($),z(Error("No active connection to send request"));return}setTimeout(()=>{if(this.pendingRequests.has($))this.pendingRequests.delete($),z(Error(`Request timeout for ${Q}`))},this.config.timeout||120000)})}notify(Q,Z){let V=JSON.stringify({jsonrpc:"2.0",method:Q,params:Z});if(this.websocket&&this.websocket.readyState===PQ.OPEN)this.websocket.send(V);else if(this.process?.stdin?.writable)this.process.stdin.write(V+`
240
+ `)}handleData(Q){this.buffer+=Q;let Z=this.buffer.split(`
241
+ `);this.buffer=Z.pop()||"";for(let $ of Z){if(!$.trim())continue;try{let V=JSON.parse($);if(V.id!==void 0){let X=this.pendingRequests.get(V.id);if(X)if(this.pendingRequests.delete(V.id),V.error)X.reject(Error(V.error.message));else X.resolve(V.result)}}catch(V){this.log(`Parse error: ${V}`)}}}async close(){if(this.websocket)this.websocket.close(),this.websocket=null;if(this.process)this.process.kill(),this.process=null;this.connected=!1}log(Q){this.onLog?.(`[MCP:${this.name}] ${Q}`)}}async function t1(Q,Z){let $=new Map;for(let[V,X]of Object.entries(Q)){if(X.disabled)continue;let z=new NQ({name:V,config:X,onLog:Z});try{await z.connect(),$.set(V,z)}catch(J){let Y=J instanceof Error?J.message:String(J);Z?.(`[MCP:${V}] Failed to connect: ${Y}`)}}return $}import{spawn as J7}from"child_process";class Y7{hooks=new Map;timeout;constructor(Q=60000){this.timeout=Q}register(Q,Z){if(!this.hooks.has(Q))this.hooks.set(Q,[]);this.hooks.get(Q)?.push(Z)}registerAll(Q){for(let[Z,$]of Object.entries(Q))for(let V of $)this.register(Z,V)}async execute(Q,Z){let $=this.hooks.get(Q);if(!$||$.length===0)return{decision:"allow"};let V={...Z,event:Q,timestamp:Date.now()};for(let X of $){if(X.enabled===!1)continue;let z=await this.executeHook(X,V);if(z.decision==="deny"||z.decision==="block")return z;if(z.modified_input)Object.assign(Z,z.modified_input)}return{decision:"allow"}}async executeHook(Q,Z){let $=Q.timeout||this.timeout;try{return await new Promise((X,z)=>{let J=J7(Q.command,[],{shell:!0,stdio:["pipe","pipe","pipe"]}),Y="",K="";J.stdout?.on("data",(q)=>{Y+=q.toString()}),J.stderr?.on("data",(q)=>{K+=q.toString()}),J.on("close",(q)=>{if(q===0)try{let W=JSON.parse(Y);X(W)}catch{X({decision:"allow"})}else if(q===1)X({decision:"deny",reason:K||"Hook denied execution"});else if(q===2)X({decision:"block",reason:K||"Hook blocked execution"});else X({decision:"allow"})}),J.on("error",(q)=>{X({decision:"allow",reason:`Hook error: ${q.message}`})}),J.stdin?.write(JSON.stringify(Z)),J.stdin?.end(),setTimeout(()=>{J.kill(),X({decision:"allow",reason:"Hook timeout"})},$)})}catch(V){return{decision:"allow",reason:`Hook execution failed: ${V instanceof Error?V.message:String(V)}`}}}getHooks(Q){return this.hooks.get(Q)||[]}clear(Q){if(Q)this.hooks.delete(Q);else this.hooks.clear()}}var Z2={validateWrite:{event:"PreToolUse",command:`node -e '
242
+ const input = JSON.parse(require("fs").readFileSync(0, "utf8"));
243
+ if (input.tool_name === "Write") {
244
+ const path = input.tool_input.file_path;
245
+ if (path.includes("..") || path.startsWith("/etc/")) {
246
+ console.log(JSON.stringify({ decision: "deny", reason: "Unsafe path" }));
247
+ process.exit(1);
248
+ }
249
+ }
250
+ console.log(JSON.stringify({ decision: "allow" }));
251
+ '`,timeout:5000,enabled:!1},logToolUse:{event:"PostToolUse",command:`node -e '
252
+ const input = JSON.parse(require("fs").readFileSync(0, "utf8"));
253
+ console.error(\`[LOG] Tool: \${input.tool_name}\`);
254
+ console.log(JSON.stringify({ decision: "allow" }));
255
+ '`,timeout:5000,enabled:!1}},$2={PreToolUse:"Before a tool is executed. Can modify input or deny execution.",PostToolUse:"After a tool successfully executes. Can process result.",PostToolUseFailure:"After a tool fails. Can handle error or retry.",Stop:"When the agent stops (end_turn, max_tokens, error).",UserPromptSubmit:"When user submits a prompt. Can modify or reject.",SessionStart:"When a new session starts.",SessionEnd:"When a session ends.",Notification:"When a notification is sent.",ConfigChange:"When configuration changes.",WorktreeCreate:"When a git worktree is created."},V2={ALLOW:0,DENY:1,BLOCK:2};import{readFileSync as K7,existsSync as V6,readdirSync as q7}from"fs";import{join as W7}from"path";function H7(Q,Z="project"){if(!V6(Q))return null;let $=K7(Q,"utf-8"),V=Q.split("/").pop()?.replace(/\.md$/i,"")||"unknown",X=$.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!X)return{path:Q,name:V,description:"",prompt:$.trim(),source:Z};let z=X[1]??"",J=X[2]??"",Y=G7(z);return{path:Q,name:Y.name||V,description:Y.description||"",prompt:J.trim(),tools:Y.tools,model:Y.model,color:Y.color,source:Z}}function G7(Q){let Z={},$=Q.split(`
256
+ `);for(let V of $){let X=V.match(/^(\w+):\s*(.*)$/);if(X){let z=X[1];if(!z)continue;let J=X[2]??"";if(J.startsWith("["))try{Z[z]=JSON.parse(J)}catch{Z[z]=J}else if(J==="true")Z[z]=!0;else if(J==="false")Z[z]=!1;else if(/^\d+$/.test(J))Z[z]=parseInt(J,10);else if(/^\d+\.\d+$/.test(J))Z[z]=parseFloat(J);else Z[z]=J}}return Z}class _7{skills=new Map;loadFromDirectory(Q,Z="project"){if(!V6(Q))return 0;let $=0,V=q7(Q);for(let X of V)if(X.endsWith(".md")){let z=H7(W7(Q,X),Z);if(z)this.skills.set(z.name,z),$++}return $}get(Q){return this.skills.get(Q)}getAll(){return Array.from(this.skills.values())}has(Q){return this.skills.has(Q)}getNames(){return Array.from(this.skills.keys())}}function K2(Q){return`
257
+ <skill-loading>
258
+ You are operating with the "${Q.name}" skill loaded.
259
+
260
+ ${Q.description?`Description: ${Q.description}
261
+ `:""}
262
+ ${Q.prompt}
263
+ </skill-loading>
264
+ `.trim()}var q2=[{path:"built-in://commit",name:"commit",description:"Create a git commit with the staged changes",prompt:`Analyze the staged changes and create a git commit.
265
+
266
+ Steps:
267
+ 1. Run \`git diff --staged\` to see staged changes
268
+ 2. Run \`git log --oneline -5\` to understand commit message style
269
+ 3. Create a commit message following conventional commits format
270
+ 4. Include "Co-Authored-By: Claude <noreply@anthropic.com>" if applicable
271
+ 5. Run \`git commit\` with the message`,tools:["Bash"],model:"sonnet",source:"built-in"},{path:"built-in://review-pr",name:"review-pr",description:"Review a pull request",prompt:`Review the current pull request and provide feedback.
272
+
273
+ Steps:
274
+ 1. Use \`gh pr view\` to get PR details
275
+ 2. Use \`gh pr diff\` to see the changes
276
+ 3. Analyze the code for:
277
+ - Bugs and potential issues
278
+ - Code quality and style
279
+ - Test coverage
280
+ - Documentation
281
+ 4. Provide constructive feedback
282
+ 5. Approve or request changes as appropriate`,tools:["Bash"],model:"sonnet",source:"built-in"},{path:"built-in://mcp-builder",name:"mcp-builder",description:"Guide for creating MCP servers",prompt:`Help the user build MCP (Model Context Protocol) servers.
283
+
284
+ MCP servers enable LLMs to interact with external services through well-designed tools.
285
+
286
+ Key concepts:
287
+ 1. Use FastMCP (Python) or MCP SDK (TypeScript)
288
+ 2. Define tools with clear input schemas
289
+ 3. Return structured content
290
+ 4. Handle errors gracefully
291
+
292
+ Transport types:
293
+ - stdio: Local process communication
294
+ - HTTP: REST API with JSON-RPC
295
+ - SSE: Server-Sent Events for streaming
296
+ - WebSocket: Bidirectional communication`,tools:["Read","Write","Edit","Bash"],model:"sonnet",source:"built-in"},{path:"built-in://claude-hooks",name:"claude-hooks",description:"Guide for Claude Code hooks",prompt:`Help the user configure Claude Code hooks.
297
+
298
+ Hooks are user-defined shell commands that execute at specific points during Claude Code's lifecycle.
299
+
300
+ Available events:
301
+ - PreToolUse: Before a tool executes
302
+ - PostToolUse: After a tool succeeds
303
+ - PostToolUseFailure: After a tool fails
304
+ - Stop: When agent stops
305
+ - UserPromptSubmit: When user submits prompt
306
+ - SessionStart/SessionEnd: Session lifecycle
307
+
308
+ Exit codes:
309
+ - 0: Allow execution
310
+ - 1: Deny and show stderr
311
+ - 2: Block silently`,tools:["Read","Write","Edit"],model:"sonnet",source:"built-in"}];function W2(Q){return Q.match(/^\/(\w+)(?:\s+(.*))?$/)?.[1]??null}function H2(Q){return Q.match(/^\/\w+\s+(.*)$/)?.[1]??""}
312
+ export{f0 as a,W0 as b,W6 as c,U7 as d,xQ as e,EQ as f,w7 as g,U6 as h,w6 as i,A6 as j,B6 as k,kQ as l,O6 as m,v6 as n,u0 as o,h0 as p,C7 as q,R7 as r,D7 as s,D as t,G0 as u,lQ as v,pQ as w,S9 as x,x7 as y,p0 as z,E7 as A,iQ as B,T7 as C,y7 as D,k7 as E,b7 as F,f7 as G,nQ as H,u7 as I,h7 as J,g7 as K,d7 as L,m7 as M,c7 as N,l7 as O,p7 as P,i7 as Q,M9 as R,_0 as S,rQ as T,a7 as U,s7 as V,t7 as W,e7 as X,Q$ as Y,oQ as Z,Z$ as _,tQ as $,A$ as aa,a0 as ba,B$ as ca,L$ as da,F$ as ea,r6 as fa,o6 as ga,C$ as ha,J8 as ia,S$ as ja,Y8 as ka,I$ as la,B9 as ma,x$ as na,t0 as oa,e0 as pa,QQ as qa,ZQ as ra,$Q as sa,VQ as ta,XQ as ua,zQ as va,E$ as wa,c5 as xa,l5 as ya,p5 as za,n5 as Aa,r5 as Ba,o5 as Ca,a5 as Da,s5 as Ea,t5 as Fa,e5 as Ga,Q7 as Ha,Z7 as Ia,$7 as Ja,V7 as Ka,X7 as La,r1 as Ma,NQ as Na,t1 as Oa,Y7 as Pa,Z2 as Qa,$2 as Ra,V2 as Sa,H7 as Ta,_7 as Ua,K2 as Va,q2 as Wa,W2 as Xa,H2 as Ya};