@ebowwa/coder 0.1.11 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{A as Gz,P as Az,S as bz,T as Nz,Y as Fz,Z as Tz,a as rz,ba as qz,t as n,u as p,w as i,y as Hz}from"./index-wn2m4wma.js";async function m(z,W){let X=Bun.spawn(["git",...z],{cwd:W,stdout:"pipe",stderr:"pipe"}),Y=await new Response(X.stdout).text(),$=await new Response(X.stderr).text(),Q=await X.exited;return{stdout:Y.trim(),stderr:$.trim(),exitCode:Q}}async function jz(z){let{exitCode:W}=await m(["rev-parse","--git-dir"],z);return W===0}async function Mz(z){let{stdout:W,exitCode:X}=await m(["rev-parse","--abbrev-ref","HEAD"],z);if(X!==0)return"HEAD";return W||"HEAD"}async function wz(z){let{stdout:W,exitCode:X}=await m(["rev-list","--left-right","--count","@{upstream}...HEAD"],z);if(X!==0||!W)return{ahead:0,behind:0};let Y=W.split(/\s+/);if(Y.length>=2&&Y[0]!==void 0&&Y[1]!==void 0)return{ahead:parseInt(Y[0],10)||0,behind:parseInt(Y[1],10)||0};return{ahead:0,behind:0}}async function Pz(z){let{stdout:W,exitCode:X}=await m(["status","--porcelain"],z);if(X!==0||!W)return{staged:[],unstaged:[],untracked:[],conflicted:[]};let Y=[],$=[],Q=[],L=[],J=W.split(`
3
+ import{A as Gz,P as Az,S as bz,T as Nz,Y as Fz,Z as Tz,a as rz,ba as qz,t as n,u as p,w as i,y as Hz}from"./index-z8cwtf8j.js";async function m(z,W){let X=Bun.spawn(["git",...z],{cwd:W,stdout:"pipe",stderr:"pipe"}),Y=await new Response(X.stdout).text(),$=await new Response(X.stderr).text(),Q=await X.exited;return{stdout:Y.trim(),stderr:$.trim(),exitCode:Q}}async function jz(z){let{exitCode:W}=await m(["rev-parse","--git-dir"],z);return W===0}async function Mz(z){let{stdout:W,exitCode:X}=await m(["rev-parse","--abbrev-ref","HEAD"],z);if(X!==0)return"HEAD";return W||"HEAD"}async function wz(z){let{stdout:W,exitCode:X}=await m(["rev-list","--left-right","--count","@{upstream}...HEAD"],z);if(X!==0||!W)return{ahead:0,behind:0};let Y=W.split(/\s+/);if(Y.length>=2&&Y[0]!==void 0&&Y[1]!==void 0)return{ahead:parseInt(Y[0],10)||0,behind:parseInt(Y[1],10)||0};return{ahead:0,behind:0}}async function Pz(z){let{stdout:W,exitCode:X}=await m(["status","--porcelain"],z);if(X!==0||!W)return{staged:[],unstaged:[],untracked:[],conflicted:[]};let Y=[],$=[],Q=[],L=[],J=W.split(`
4
4
  `);for(let K of J){if(!K)continue;let R=K[0],E=K[1],O=K.substring(3);if(O.includes(" -> ")){let _=O.split(" -> ");O=_[1]??_[0]??O}if(R==="U"||E==="U"||R==="A"&&E==="A"||R==="D"&&E==="D"||R==="A"&&E==="U"||R==="U"&&E==="A"||R==="D"&&E==="U"||R==="U"&&E==="D"){L.push(O);continue}if(R==="?"&&E==="?"){Q.push(O);continue}if(R!==" "&&R!=="?"&&R!=="!")Y.push(O);if(E!==" "&&E!=="?"&&E!=="!"){if(!Y.includes(O))$.push(O)}}return{staged:Y,unstaged:$,untracked:Q,conflicted:L}}async function k(z){try{if(!await jz(z))return null;let[X,Y,$]=await Promise.all([Mz(z),wz(z),Pz(z)]);return{branch:X,ahead:Y.ahead,behind:Y.behind,staged:$.staged,unstaged:$.unstaged,untracked:$.untracked,conflicted:$.conflicted}}catch(W){return console.error("Error getting git status:",W),null}}import{randomUUID as Dz}from"crypto";import{execSync as d}from"child_process";var h=process.env.CLAUDE_CHECKPOINTS_DIR||`${process.env.HOME}/.claude/checkpoints`;function vz(z){let W=0;for(let X=0;X<z.length;X++){let Y=z.charCodeAt(X);W=(W<<5)-W+Y,W=W&W}return Math.abs(W).toString(16)}function yz(z){try{d("git rev-parse --is-inside-work-tree",{cwd:z,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let W=d("git rev-parse --abbrev-ref HEAD",{cwd:z,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),X=0,Y=0;try{let K=d("git rev-list --left-right --count @{upstream}...HEAD 2>/dev/null || echo '0 0'",{cwd:z,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(/\s+/);Y=parseInt(K[0]||"0",10),X=parseInt(K[1]||"0",10)}catch{}let $=d("git status --porcelain",{cwd:z,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),Q=[],L=[],J=[];for(let K of $.split(`
5
5
  `)){if(!K.trim())continue;let R=K[0],E=K[1],O=K.slice(3);if(R==="?"&&E==="?")J.push(O);else if(R!==" "&&R!=="?")Q.push(O);else if(E!==" ")L.push(O)}return{branch:W,ahead:X,behind:Y,staged:Q,unstaged:L,untracked:J}}catch(W){return}}async function Sz(z,W){let X=[];for(let Y of W)try{let $=`${z}/${Y}`,Q=Bun.file($);if(await Q.exists()){let L=await Q.text();X.push({path:Y,content:L,hash:vz(L)})}}catch{}return X}async function Iz(z,W){let X=0,Y=0;for(let $ of W)try{let Q=`${z}/${$.path}`;await Bun.write(Q,$.content),X++}catch{Y++}return{restored:X,failed:Y}}async function r(){if(!await Bun.file(h).exists())await Bun.write(h+"/.gitkeep","")}function o(z){return`${h}/${z}.json`}async function S(z){let W=new Map;try{let X=o(z),Y=Bun.file(X);if(await Y.exists()){let $=await Y.text(),Q=JSON.parse($);for(let L of Q)W.set(L.id,L)}}catch(X){}return W}async function fz(z,W){await r();let X=o(z),Y=Array.from(W.values());await Bun.write(X,JSON.stringify(Y,null,2))}async function t(z,W,X={}){let Y=await S(z),$=X.workingDirectory||process.cwd(),Q=yz($),L=[];if(X.trackFiles!==!1&&Q){let K=[...Q.staged,...Q.unstaged,...Q.untracked];L=await Sz($,K)}let J={id:Dz().slice(0,8),sessionId:z,timestamp:Date.now(),label:X.label||`Checkpoint ${Y.size+1}`,description:X.description,messages:JSON.parse(JSON.stringify(W)),files:L,gitState:Q,metadata:{model:X.model,workingDirectory:$,totalCost:X.totalCost||0,messageCount:W.length,fileCount:L.length}};return Y.set(J.id,J),await fz(z,Y),J}async function g(z,W){return(await S(z)).get(W)||null}async function I(z,W={}){let X=W.workingDirectory||z.metadata.workingDirectory||process.cwd(),Y=0,$=0;if(W.restoreFiles!==!1&&z.files.length>0){let Q=await Iz(X,z.files);Y=Q.restored,$=Q.failed}return{messages:W.restoreMessages!==!1?z.messages:[],filesRestored:Y,filesFailed:$}}async function e(z){let W=await S(z);return Array.from(W.values()).sort((X,Y)=>Y.timestamp-X.timestamp)}function v(z,W=!1){let X=new Date(z.timestamp),Y=X.toLocaleTimeString(),$=X.toLocaleDateString(),Q=`\x1B[33m${z.id}\x1B[0m `;if(Q+=`\x1B[1m${z.label}\x1B[0m `,Q+=`\x1B[90m(${$} ${Y})\x1B[0m`,z.files.length>0)Q+=` \x1B[32m[${z.files.length} files]\x1B[0m`;if(z.gitState)Q+=` \x1B[34m(${z.gitState.branch})\x1B[0m`;if(W){if(Q+=`
6
6
  Messages: ${z.metadata.messageCount}`,Q+=`
@@ -22,7 +22,7 @@ ${Q}`);return{global:$,project:Q,merged:R.join(`
22
22
  ${X.length>0?`Loaded from: ${X.join(", ")}`:""}
23
23
 
24
24
  ${W}
25
- `}import{readFile as uz,access as lz}from"fs/promises";import{join as f}from"path";var Bz=process.env.HOME||"",Vz=f(Bz,".claude"),w={main:f(Bz,".claude.json"),settings:f(Vz,"settings.json"),keybindings:f(Vz,"keybindings.json"),projectSettings:(z)=>f(z,".claude","settings.json")};async function pz(z){try{return await lz(z),!0}catch{return!1}}async function l(z,W){try{if(await pz(z)){let X=await uz(z,"utf-8");return{config:JSON.parse(X),loaded:!0}}}catch(X){}return{config:W,loaded:!1}}async function gz(){return l(w.main,{})}async function cz(){return l(w.settings,{})}async function az(){return l(w.keybindings,{bindings:[]})}async function nz(z){return l(w.projectSettings(z),{})}function iz(z,W){return z.projects?.[W]}async function Uz(z=process.cwd()){let W=[],{config:X,loaded:Y}=await gz();if(Y)W.push(w.main);let{config:$,loaded:Q}=await cz();if(Q)W.push(w.settings);let{config:L,loaded:J}=await az();if(J)W.push(w.keybindings);let{config:K,loaded:R}=await nz(z);if(R)W.push(w.projectSettings(z));return{main:X,settings:$,keybindings:L,projectSettings:K,sources:W}}function Kz(z,W){return{hooks:{...z.hooks,...W.hooks},permissions:{...z.permissions,...W.permissions}}}function Lz(z,W){let X={};if(z.mcpServers)Object.assign(X,z.mcpServers);let Y=iz(z,W);if(Y?.mcpServers)Object.assign(X,Y.mcpServers);return X}function Rz(z){let W={};if(!z.hooks)return W;for(let[X,Y]of Object.entries(z.hooks)){let $=[],Q=X;for(let L of Y)for(let J of L.hooks)$.push({event:Q,command:J.type==="command"?J.command||"":"",timeout:J.timeout||60000,enabled:!0,_matcher:L.matcher,_prompt:J.type==="prompt"?J.prompt:void 0});if($.length>0)W[Q]=$}return W}function Ez(z){return z.permissions?.defaultMode||"default"}function Oz(z){return new Set(z.permissions?.allowedTools||[])}function _z(z){return new Set(z.permissions?.disallowedTools||[])}async function oz(z){try{let X=await Bun.file(z).text(),Y=JSON.parse(X);if("servers"in Y&&typeof Y.servers==="object"&&Y.servers!==null)return Y.servers;if("type"in Y){let $={};return $.default=Y,$}return Y}catch(W){let X=W instanceof Error?W.message:String(W);throw Error(`Failed to load MCP config from ${z}: ${X}`)}}function tz(z){let W=[];for(let[X,Y]of z)for(let $ of Y.tools)W.push({name:`mcp__${X}__${$.name}`,description:$.description,input_schema:$.inputSchema,handler:async(Q,L)=>{if(!Y.connected)return{content:`Error: MCP server "${X}" is not connected`,is_error:!0};return Y.callTool($.name,Q)}});return W}function ez(){let z=process.argv.slice(2),W={model:"claude-sonnet-4-6",permissionMode:"default",maxTokens:4096};for(let X=0;X<z.length;X++)switch(z[X]){case"--model":case"-m":W.model=z[++X]??"claude-sonnet-4-6";break;case"--permission-mode":case"-p":W.permissionMode=z[++X]??"default";break;case"--max-tokens":W.maxTokens=parseInt(z[++X]??"4096",10);break;case"--system-prompt":W.systemPrompt=z[++X];break;case"--append-system-prompt":W.appendSystemPrompt=z[++X];break;case"--config":W.configFile=z[++X];break;case"--mcp-config":W.mcpConfig=z[++X];break;case"--resume":W.resumeSession=z[++X];break;case"--sessions":W.listSessions=!0;break;case"--teammate-mode":W.teammateMode=!0;break;case"--agent-id":W.agentId=z[++X];break;case"--agent-name":W.agentName=z[++X];break;case"--team-name":W.teamName=z[++X];break;case"--agent-color":W.agentColor=z[++X];break;case"--interleaved":W.interleaved=!0;break;case"--no-interleaved":W.interleaved=!1;break;case"--extended-thinking":case"-e":W.extendedThinking=!0;break;case"--effort":W.effort=z[++X]??"medium";break;case"--query":case"-q":W.query=z[++X];break;case"--loop":case"-l":W.loop=!0;break;case"--max-iterations":W.maxIterations=parseInt(z[++X]??"100",10);break;case"--no-autonomous":W.noAutonomous=!0;break;case"--help":case"-h":sz(),process.exit(0)}return W}function sz(){console.log(`
25
+ `}import{readFile as uz,access as lz}from"fs/promises";import{join as f}from"path";var Bz=process.env.HOME||"",Vz=f(Bz,".claude"),w={main:f(Bz,".claude.json"),settings:f(Vz,"settings.json"),keybindings:f(Vz,"keybindings.json"),projectSettings:(z)=>f(z,".claude","settings.json")};async function pz(z){try{return await lz(z),!0}catch{return!1}}async function l(z,W){try{if(await pz(z)){let X=await uz(z,"utf-8");return{config:JSON.parse(X),loaded:!0}}}catch(X){}return{config:W,loaded:!1}}async function gz(){return l(w.main,{})}async function cz(){return l(w.settings,{})}async function az(){return l(w.keybindings,{bindings:[]})}async function nz(z){return l(w.projectSettings(z),{})}function iz(z,W){return z.projects?.[W]}async function Uz(z=process.cwd()){let W=[],{config:X,loaded:Y}=await gz();if(Y)W.push(w.main);let{config:$,loaded:Q}=await cz();if(Q)W.push(w.settings);let{config:L,loaded:J}=await az();if(J)W.push(w.keybindings);let{config:K,loaded:R}=await nz(z);if(R)W.push(w.projectSettings(z));return{main:X,settings:$,keybindings:L,projectSettings:K,sources:W}}function Kz(z,W){return{hooks:{...z.hooks,...W.hooks},permissions:{...z.permissions,...W.permissions}}}function Lz(z,W){let X={};if(z.mcpServers)Object.assign(X,z.mcpServers);let Y=iz(z,W);if(Y?.mcpServers)Object.assign(X,Y.mcpServers);return X}function Rz(z){let W={};if(!z.hooks)return W;for(let[X,Y]of Object.entries(z.hooks)){let $=[],Q=X;for(let L of Y)for(let J of L.hooks)$.push({event:Q,command:J.type==="command"?J.command||"":"",timeout:J.timeout||60000,enabled:!0,_matcher:L.matcher,_prompt:J.type==="prompt"?J.prompt:void 0});if($.length>0)W[Q]=$}return W}function Ez(z){return z.permissions?.defaultMode||"default"}function Oz(z){return new Set(z.permissions?.allowedTools||[])}function _z(z){return new Set(z.permissions?.disallowedTools||[])}async function oz(z){try{let X=await Bun.file(z).text(),Y=JSON.parse(X);if("servers"in Y&&typeof Y.servers==="object"&&Y.servers!==null)return Y.servers;if("type"in Y){let $={};return $.default=Y,$}return Y}catch(W){let X=W instanceof Error?W.message:String(W);throw Error(`Failed to load MCP config from ${z}: ${X}`)}}function tz(z){let W=[];for(let[X,Y]of z)for(let $ of Y.tools)W.push({name:`mcp__${X}__${$.name}`,description:$.description,input_schema:$.inputSchema,handler:async(Q,L)=>{if(!Y.connected)return{content:`Error: MCP server "${X}" is not connected`,is_error:!0};return Y.callTool($.name,Q)}});return W}function ez(){let z=process.argv.slice(2),W={model:"claude-sonnet-4-6",permissionMode:"default",maxTokens:4096};for(let X=0;X<z.length;X++)switch(z[X]){case"--model":case"-m":W.model=z[++X]??"claude-sonnet-4-6";break;case"--permission-mode":case"-p":W.permissionMode=z[++X]??"default";break;case"--max-tokens":W.maxTokens=parseInt(z[++X]??"4096",10);break;case"--system-prompt":W.systemPrompt=z[++X];break;case"--append-system-prompt":W.appendSystemPrompt=z[++X];break;case"--config":W.configFile=z[++X];break;case"--mcp-config":W.mcpConfig=z[++X];break;case"--resume":W.resumeSession=z[++X];break;case"--sessions":W.listSessions=!0;break;case"--teammate-mode":W.teammateMode=!0;break;case"--agent-id":W.agentId=z[++X];break;case"--agent-name":W.agentName=z[++X];break;case"--team-name":W.teamName=z[++X];break;case"--agent-color":W.agentColor=z[++X];break;case"--interleaved":W.interleaved=!0;break;case"--no-interleaved":W.interleaved=!1;break;case"--extended-thinking":case"-e":W.extendedThinking=!0;break;case"--effort":W.effort=z[++X]??"medium";break;case"--query":case"-q":W.query=z[++X];break;case"--loop":case"-l":W.loop=!0;break;case"--max-iterations":W.maxIterations=parseInt(z[++X]??"100",10);break;case"--no-autonomous":W.noAutonomous=!0;break;case"--stop-sequences":case"-s":W.stopSequences=(z[++X]??"").split(",").map(($)=>$.trim()).filter(Boolean);break;case"--help":case"-h":sz(),process.exit(0)}return W}function sz(){console.log(`
26
26
  Coder v0.1.0
27
27
  A reimplementation of Claude Code CLI
28
28
 
@@ -44,6 +44,7 @@ Autonomous Loop:
44
44
  -l, --loop Enable autonomous loop mode (runs until TASKS_COMPLETE)
45
45
  --max-iterations <n> Max iterations (default: 100, use 0 for unlimited)
46
46
  --no-autonomous Disable autonomous discovery (just continue original task)
47
+ -s, --stop-sequences <seq> Comma-separated stop sequences (e.g., "DONE,COMPLETE")
47
48
 
48
49
  Other:
49
50
  --system-prompt <prompt> Override system prompt
@@ -67,21 +68,22 @@ EXAMPLES:
67
68
  coder --loop "Fix all issues" # Autonomous: finds & fixes work
68
69
  coder --loop --max-iterations 0 "Go crazy" # Unlimited iterations
69
70
  coder --loop --no-autonomous "Just this" # No discovery, just continue
71
+ coder --stop-sequences "DONE,FINISHED" "Write docs" # Custom stop tokens
70
72
  coder --sessions
71
73
  coder --resume abc123-def456
72
- `)}async function zW(){let z=ez(),W=new Hz;if(await W.init(),z.listSessions){let B=await W.listSessions(20);Gz(B),process.exit(0)}let X=process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.Z_AI_API_KEY;if(!X)console.error("Error: ANTHROPIC_API_KEY, CLAUDE_API_KEY, ANTHROPIC_AUTH_TOKEN, or Z_AI_API_KEY environment variable required"),process.exit(1);console.log("\x1B[90mLoading configuration...\x1B[0m");let Y;try{Y=await Uz(process.cwd())}catch(B){let F=B instanceof Error?B.message:String(B);console.error(`\x1B[33mWarning: Failed to load config: ${F}\x1B[0m`),Y={main:{},settings:{},keybindings:{bindings:[]},projectSettings:{},sources:[]}}let $=Kz(Y.settings,Y.projectSettings);if(Y.sources.length>0)console.log(`\x1B[90m Config sources: ${Y.sources.length} files\x1B[0m`);if(z.permissionMode==="default"){let B=Ez($);if(B!=="default")z.permissionMode=B,console.log(`\x1B[90m Permission mode: ${B} (from config)\x1B[0m`)}let Q=Oz($),L=_z($),J=new Nz,K=new Fz,R=new qz,E=Rz($);for(let[B,F]of Object.entries(E))for(let G of F)J.register(B,G);if(Object.keys(E).length>0)console.log(`\x1B[90m Hooks registered: ${Object.keys(E).length} events\x1B[0m`);let O=process.cwd()+"/.claude/skills";K.loadFromDirectory(O,"project");let T=new Map,q=Lz(Y.main,process.cwd());if(z.mcpConfig)try{console.log(`\x1B[90mLoading MCP config from ${z.mcpConfig}...\x1B[0m`),q=await oz(z.mcpConfig)}catch(B){let F=B instanceof Error?B.message:String(B);console.error(`\x1B[33mWarning: Failed to load MCP config file: ${F}\x1B[0m`)}if(Object.keys(q).length>0){let F=Object.entries(q).filter(([G,M])=>!M.disabled).length;if(F>0){console.log(`\x1B[90m Connecting to ${F} MCP server(s)...\x1B[0m`);let G=await bz(q,(M)=>{console.log(`\x1B[90m ${M}\x1B[0m`)});for(let[M,y]of G)T.set(M,y);if(T.size>0)console.log(`\x1B[32m Connected to ${T.size} MCP server(s)\x1B[0m`);else console.log("\x1B[33m Warning: No MCP servers connected successfully\x1B[0m")}else if(Object.keys(q).length>0)console.log(`\x1B[90m MCP config loaded but all ${Object.keys(q).length} server(s) are disabled\x1B[0m`)}let x=[...Az,...tz(T)],A=await k(process.cwd()),b=z.systemPrompt||await YW(A);if(z.appendSystemPrompt)b+=`
73
-
74
- ${z.appendSystemPrompt}`;if(z.teammateMode&&z.teamName)b+=`
75
-
76
- You are running as a teammate agent in the "${z.teamName}" team.`,b+=`
77
- Agent ID: ${z.agentId}`,b+=`
78
- Agent Name: ${z.agentName}`;let U=[],N;if(z.resumeSession){let B=await W.resumeSession(z.resumeSession);if(!B)console.error(`Error: Session not found: ${z.resumeSession}`),process.exit(1);U=B.messages,N=z.resumeSession,z.model=B.metadata.model,z.agentName=B.metadata.agentName,z.agentColor=B.metadata.agentColor,z.teamName=B.metadata.teamName,console.log(`\x1B[90mResumed session: ${z.resumeSession}\x1B[0m`),console.log(`\x1B[90mModel: ${z.model} | Messages: ${U.length}\x1B[0m
79
- `)}else N=await W.createSession({model:z.model,workingDirectory:process.cwd(),agentName:z.agentName,agentColor:z.agentColor,teamName:z.teamName});let H=z.query,j=process.argv[2];if(!H&&process.argv.length>2&&j&&!j.startsWith("-"))H=process.argv.slice(2).join(" ");if(!H)console.log("Coder v0.1.0"),console.log(`Session: ${N}`),console.log(`Type your message or /help for commands.
80
- `),await WW(X,z,b,x,J,K,W,U,N,T);else await XW(X,z,b,x,H,W,N)}async function WW(z,W,X,Y,$,Q,L,J,K,R){let E=process.stdin.isTTY,O=process.env.CLAUDE_FORCE_INTERACTIVE==="true";if(!E&&!O){console.error("Error: Interactive mode requires a TTY. Use -q for single query mode."),console.error(" Or set CLAUDE_FORCE_INTERACTIVE=true for testing.");return}let T=!0,_=0,q=await k(process.cwd()),x=rz("readline").createInterface({input:process.stdin,output:process.stdout,terminal:!0,historySize:1000,removeHistoryDuplicates:!0});process.on("SIGINT",()=>{console.log(`
81
- \x1B[90mGoodbye!\x1B[0m`),x.close(),process.exit(0)});let A=(U)=>{return new Promise((N,H)=>{if(x.closed){H(Error("Readline closed"));return}x.question(U,(j)=>{N(j)})})},b=async(U)=>{if(console.log(`
82
- \x1B[36m\u2501\u2501\u2501 Permission Required \u2501\u2501\u2501\x1B[0m`),console.log(`Tool: \x1B[1m${U.toolName}\x1B[0m`),console.log(`Risk: \x1B[32m${U.riskLevel.toUpperCase()}\x1B[0m`),console.log(`Action: ${U.description}`),U.file)console.log(`File: ${U.file}`);else if(U.command)console.log(`Command: ${U.command}`);else if(U.toolInput.file_path)console.log(`File: ${U.toolInput.file_path}`);else if(U.toolInput.command)console.log(`Command: ${U.toolInput.command}`);while(!0)try{switch((await A(`
83
- Allow? [y]es / [n]o / [a]lways / [d]eny always: `)).trim().toLowerCase()){case"y":case"yes":case"":return{decision:"allow"};case"n":case"no":return{decision:"deny",reason:"User denied"};case"a":case"always":return{decision:"allowAlways"};case"d":case"deny":return{decision:"denyAlways",reason:"User denied always"};default:console.log("Please enter y, n, a, or d")}}catch{return{decision:"deny",reason:"Input error"}}};while(T)try{let U=await A(`
84
- \x1B[1;36mYou:\x1B[0m `);if(!U.trim())continue;if(U.startsWith("/")){let F=U.slice(1).split(" ")[0]??"",G=U.slice(F.length+2);switch(F){case"exit":case"quit":case"q":T=!1,console.log("\x1B[90mGoodbye!\x1B[0m");continue;case"help":case"?":console.log(`
74
+ `)}async function zW(){let z=ez(),W=new Hz;if(await W.init(),z.listSessions){let B=await W.listSessions(20);Gz(B),process.exit(0)}let X=process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.Z_AI_API_KEY;if(!X)console.error("Error: ANTHROPIC_API_KEY, CLAUDE_API_KEY, ANTHROPIC_AUTH_TOKEN, or Z_AI_API_KEY environment variable required"),process.exit(1);console.log("\x1B[90mLoading configuration...\x1B[0m");let Y;try{Y=await Uz(process.cwd())}catch(B){let F=B instanceof Error?B.message:String(B);console.error(`\x1B[33mWarning: Failed to load config: ${F}\x1B[0m`),Y={main:{},settings:{},keybindings:{bindings:[]},projectSettings:{},sources:[]}}let $=Kz(Y.settings,Y.projectSettings);if(Y.sources.length>0)console.log(`\x1B[90m Config sources: ${Y.sources.length} files\x1B[0m`);if(z.permissionMode==="default"){let B=Ez($);if(B!=="default")z.permissionMode=B,console.log(`\x1B[90m Permission mode: ${B} (from config)\x1B[0m`)}let Q=Oz($),L=_z($),J=new Nz,K=new Fz,R=new qz,E=Rz($);for(let[B,F]of Object.entries(E))for(let A of F)J.register(B,A);if(Object.keys(E).length>0)console.log(`\x1B[90m Hooks registered: ${Object.keys(E).length} events\x1B[0m`);let O=process.cwd()+"/.claude/skills";K.loadFromDirectory(O,"project");let T=new Map,q=Lz(Y.main,process.cwd());if(z.mcpConfig)try{console.log(`\x1B[90mLoading MCP config from ${z.mcpConfig}...\x1B[0m`),q=await oz(z.mcpConfig)}catch(B){let F=B instanceof Error?B.message:String(B);console.error(`\x1B[33mWarning: Failed to load MCP config file: ${F}\x1B[0m`)}if(Object.keys(q).length>0){let F=Object.entries(q).filter(([A,M])=>!M.disabled).length;if(F>0){console.log(`\x1B[90m Connecting to ${F} MCP server(s)...\x1B[0m`);let A=await bz(q,(M)=>{console.log(`\x1B[90m ${M}\x1B[0m`)});for(let[M,y]of A)T.set(M,y);if(T.size>0)console.log(`\x1B[32m Connected to ${T.size} MCP server(s)\x1B[0m`);else console.log("\x1B[33m Warning: No MCP servers connected successfully\x1B[0m")}else if(Object.keys(q).length>0)console.log(`\x1B[90m MCP config loaded but all ${Object.keys(q).length} server(s) are disabled\x1B[0m`)}let x=[...Az,...tz(T)],b=await k(process.cwd()),N=z.systemPrompt||await YW(b);if(z.appendSystemPrompt)N+=`
75
+
76
+ ${z.appendSystemPrompt}`;if(z.teammateMode&&z.teamName)N+=`
77
+
78
+ You are running as a teammate agent in the "${z.teamName}" team.`,N+=`
79
+ Agent ID: ${z.agentId}`,N+=`
80
+ Agent Name: ${z.agentName}`;let U=[],G;if(z.resumeSession){let B=await W.resumeSession(z.resumeSession);if(!B)console.error(`Error: Session not found: ${z.resumeSession}`),process.exit(1);U=B.messages,G=z.resumeSession,z.model=B.metadata.model,z.agentName=B.metadata.agentName,z.agentColor=B.metadata.agentColor,z.teamName=B.metadata.teamName,console.log(`\x1B[90mResumed session: ${z.resumeSession}\x1B[0m`),console.log(`\x1B[90mModel: ${z.model} | Messages: ${U.length}\x1B[0m
81
+ `)}else G=await W.createSession({model:z.model,workingDirectory:process.cwd(),agentName:z.agentName,agentColor:z.agentColor,teamName:z.teamName});let H=z.query,j=process.argv[2];if(!H&&process.argv.length>2&&j&&!j.startsWith("-"))H=process.argv.slice(2).join(" ");if(!H)console.log("Coder v0.1.0"),console.log(`Session: ${G}`),console.log(`Type your message or /help for commands.
82
+ `),await WW(X,z,N,x,J,K,W,U,G,T);else await XW(X,z,N,x,H,W,G)}async function WW(z,W,X,Y,$,Q,L,J,K,R){let E=process.stdin.isTTY,O=process.env.CLAUDE_FORCE_INTERACTIVE==="true";if(!E&&!O){console.error("Error: Interactive mode requires a TTY. Use -q for single query mode."),console.error(" Or set CLAUDE_FORCE_INTERACTIVE=true for testing.");return}let T=!0,_=0,q=await k(process.cwd()),x=rz("readline").createInterface({input:process.stdin,output:process.stdout,terminal:!0,historySize:1000,removeHistoryDuplicates:!0});process.on("SIGINT",()=>{console.log(`
83
+ \x1B[90mGoodbye!\x1B[0m`),x.close(),process.exit(0)});let b=(U)=>{return new Promise((G,H)=>{if(x.closed){H(Error("Readline closed"));return}x.question(U,(j)=>{G(j)})})},N=async(U)=>{if(console.log(`
84
+ \x1B[36m\u2501\u2501\u2501 Permission Required \u2501\u2501\u2501\x1B[0m`),console.log(`Tool: \x1B[1m${U.toolName}\x1B[0m`),console.log(`Risk: \x1B[32m${U.riskLevel.toUpperCase()}\x1B[0m`),console.log(`Action: ${U.description}`),U.file)console.log(`File: ${U.file}`);else if(U.command)console.log(`Command: ${U.command}`);else if(U.toolInput.file_path)console.log(`File: ${U.toolInput.file_path}`);else if(U.toolInput.command)console.log(`Command: ${U.toolInput.command}`);while(!0)try{switch((await b(`
85
+ Allow? [y]es / [n]o / [a]lways / [d]eny always: `)).trim().toLowerCase()){case"y":case"yes":case"":return{decision:"allow"};case"n":case"no":return{decision:"deny",reason:"User denied"};case"a":case"always":return{decision:"allowAlways"};case"d":case"deny":return{decision:"denyAlways",reason:"User denied always"};default:console.log("Please enter y, n, a, or d")}}catch{return{decision:"deny",reason:"Input error"}}};while(T)try{let U=await b(`
86
+ \x1B[1;36mYou:\x1B[0m `);if(!U.trim())continue;if(U.startsWith("/")){let F=U.slice(1).split(" ")[0]??"",A=U.slice(F.length+2);switch(F){case"exit":case"quit":case"q":T=!1,console.log("\x1B[90mGoodbye!\x1B[0m");continue;case"help":case"?":console.log(`
85
87
  \x1B[1mCommands:\x1B[0m
86
88
  /help, /? Show this help
87
89
  /exit, /quit, /q Exit the session
@@ -105,20 +107,20 @@ Allow? [y]es / [n]o / [a]lways / [d]eny always: `)).trim().toLowerCase()){case"y
105
107
 
106
108
  \x1B[1mExport:\x1B[0m
107
109
  /export [format] Export session (jsonl/json/md)
108
- `);continue;case"clear":J.length=0,console.log("\x1B[90mConversation cleared.\x1B[0m");continue;case"compact":console.log("\x1B[90mForcing context compaction...\x1B[0m");continue;case"model":if(G)W.model=G,console.log(`\x1B[90mSwitched to model: ${G}\x1B[0m`);else console.log(`Current model: \x1B[1m${W.model}\x1B[0m`);continue;case"tools":console.log("\x1B[1mAvailable tools:\x1B[0m");for(let Z of Y){let V=Z.description.split(".")[0]??Z.description;console.log(` \x1B[33m${Z.name}\x1B[0m: ${V}`)}continue;case"mcp":if(R.size===0)console.log("\x1B[90mNo MCP servers connected.\x1B[0m"),console.log("\x1B[90mUse --mcp-config to specify a config file.\x1B[0m");else{console.log("\x1B[1mConnected MCP Servers:\x1B[0m");for(let[Z,V]of R){let P=V.connected?"\x1B[32m\u25CF\x1B[0m":"\x1B[31m\u25CB\x1B[0m";console.log(` ${P} \x1B[1m${Z}\x1B[0m (${V.tools.length} tools)`);for(let D of V.tools)console.log(` \x1B[33m${D.name}\x1B[0m: ${D.description.slice(0,50)}...`)}}continue;case"skills":let M=Q.getAll();if(M.length===0)console.log("\x1B[90mNo skills loaded.\x1B[0m");else{console.log("\x1B[1mAvailable skills:\x1B[0m");for(let Z of M){let V=Z.description??Z.prompt.slice(0,50);console.log(` \x1B[33m/${Z.name}\x1B[0m: ${V}...`)}}continue;case"cost":console.log(`Total cost: \x1B[1m${p(_)}\x1B[0m`);continue;case"status":case"session":console.log("\x1B[1mSession Status:\x1B[0m"),console.log(` ID: ${K}`),console.log(` Model: ${W.model}`),console.log(` Messages: ${J.length}`),console.log(` Total cost: ${p(_)}`),console.log(` Permission mode: ${W.permissionMode}`);continue;case"export":try{let Z=G||"markdown",V=await L.exportSession(K,Z);console.log(`\x1B[90mSession exported to: ${V}\x1B[0m`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mExport failed: ${V}\x1B[0m`)}continue;case"checkpoint":case"cp":if(!G){console.log("\x1B[31mUsage: /checkpoint <label>\x1B[0m"),console.log("\x1B[90mExample: /checkpoint before-refactor\x1B[0m"),console.log("\x1B[90mCreates checkpoint with chat history + file snapshots\x1B[0m");continue}try{let Z=await t(K,J,{label:G,model:W.model,workingDirectory:process.cwd(),totalCost:_,trackFiles:!0});await Xz(K,Z.id);let V=zz(Z);if(console.log(`\x1B[32m\u2713 Checkpoint saved:\x1B[0m ${v(Z)}`),V)console.log(`\x1B[90m ${V}\x1B[0m`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to create checkpoint: ${V}\x1B[0m`)}continue;case"checkpoints":case"cps":try{let Z=await e(K);s(Z)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to list checkpoints: ${V}\x1B[0m`)}continue;case"restore":case"rollback":case"rewind":if(!G){console.log("\x1B[31mUsage: /${command} <checkpoint-id>\x1B[0m"),console.log("\x1B[90mUse /checkpoints to see available checkpoints\x1B[0m");continue}try{let Z=G.trim(),V=await g(K,Z);if(!V){console.log(`\x1B[31mCheckpoint not found: ${Z}\x1B[0m`),console.log("\x1B[90mUse /checkpoints to see available checkpoints\x1B[0m");continue}console.log(`
109
- \x1B[1mRestoring checkpoint:\x1B[0m ${v(V)}`);let P=V.files.length>0,D=!1;if(P){console.log(`\x1B[33m${V.files.length} file(s) saved in checkpoint:\x1B[0m`);for(let xz of V.files.slice(0,5))console.log(` - ${xz.path}`);if(V.files.length>5)console.log(` ... and ${V.files.length-5} more`);D=(await A(`
110
+ `);continue;case"clear":J.length=0,console.log("\x1B[90mConversation cleared.\x1B[0m");continue;case"compact":console.log("\x1B[90mForcing context compaction...\x1B[0m");continue;case"model":if(A)W.model=A,console.log(`\x1B[90mSwitched to model: ${A}\x1B[0m`);else console.log(`Current model: \x1B[1m${W.model}\x1B[0m`);continue;case"tools":console.log("\x1B[1mAvailable tools:\x1B[0m");for(let Z of Y){let V=Z.description.split(".")[0]??Z.description;console.log(` \x1B[33m${Z.name}\x1B[0m: ${V}`)}continue;case"mcp":if(R.size===0)console.log("\x1B[90mNo MCP servers connected.\x1B[0m"),console.log("\x1B[90mUse --mcp-config to specify a config file.\x1B[0m");else{console.log("\x1B[1mConnected MCP Servers:\x1B[0m");for(let[Z,V]of R){let P=V.connected?"\x1B[32m\u25CF\x1B[0m":"\x1B[31m\u25CB\x1B[0m";console.log(` ${P} \x1B[1m${Z}\x1B[0m (${V.tools.length} tools)`);for(let D of V.tools)console.log(` \x1B[33m${D.name}\x1B[0m: ${D.description.slice(0,50)}...`)}}continue;case"skills":let M=Q.getAll();if(M.length===0)console.log("\x1B[90mNo skills loaded.\x1B[0m");else{console.log("\x1B[1mAvailable skills:\x1B[0m");for(let Z of M){let V=Z.description??Z.prompt.slice(0,50);console.log(` \x1B[33m/${Z.name}\x1B[0m: ${V}...`)}}continue;case"cost":console.log(`Total cost: \x1B[1m${p(_)}\x1B[0m`);continue;case"status":case"session":console.log("\x1B[1mSession Status:\x1B[0m"),console.log(` ID: ${K}`),console.log(` Model: ${W.model}`),console.log(` Messages: ${J.length}`),console.log(` Total cost: ${p(_)}`),console.log(` Permission mode: ${W.permissionMode}`);continue;case"export":try{let Z=A||"markdown",V=await L.exportSession(K,Z);console.log(`\x1B[90mSession exported to: ${V}\x1B[0m`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mExport failed: ${V}\x1B[0m`)}continue;case"checkpoint":case"cp":if(!A){console.log("\x1B[31mUsage: /checkpoint <label>\x1B[0m"),console.log("\x1B[90mExample: /checkpoint before-refactor\x1B[0m"),console.log("\x1B[90mCreates checkpoint with chat history + file snapshots\x1B[0m");continue}try{let Z=await t(K,J,{label:A,model:W.model,workingDirectory:process.cwd(),totalCost:_,trackFiles:!0});await Xz(K,Z.id);let V=zz(Z);if(console.log(`\x1B[32m\u2713 Checkpoint saved:\x1B[0m ${v(Z)}`),V)console.log(`\x1B[90m ${V}\x1B[0m`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to create checkpoint: ${V}\x1B[0m`)}continue;case"checkpoints":case"cps":try{let Z=await e(K);s(Z)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to list checkpoints: ${V}\x1B[0m`)}continue;case"restore":case"rollback":case"rewind":if(!A){console.log("\x1B[31mUsage: /${command} <checkpoint-id>\x1B[0m"),console.log("\x1B[90mUse /checkpoints to see available checkpoints\x1B[0m");continue}try{let Z=A.trim(),V=await g(K,Z);if(!V){console.log(`\x1B[31mCheckpoint not found: ${Z}\x1B[0m`),console.log("\x1B[90mUse /checkpoints to see available checkpoints\x1B[0m");continue}console.log(`
111
+ \x1B[1mRestoring checkpoint:\x1B[0m ${v(V)}`);let P=V.files.length>0,D=!1;if(P){console.log(`\x1B[33m${V.files.length} file(s) saved in checkpoint:\x1B[0m`);for(let xz of V.files.slice(0,5))console.log(` - ${xz.path}`);if(V.files.length>5)console.log(` ... and ${V.files.length-5} more`);D=(await b(`
110
112
  \x1B[36mRestore files too? [Y/n]: \x1B[0m`)).trim().toLowerCase()!=="n"}let C=await I(V,{restoreFiles:D,restoreMessages:!0,workingDirectory:process.cwd()});if(J.length=0,J.push(...C.messages),_=V.metadata.totalCost,console.log(`
111
- \x1B[32m\u2713 Checkpoint restored:\x1B[0m`),console.log(` Messages: ${J.length}`),D&&P){if(console.log(` Files restored: ${C.filesRestored}`),C.filesFailed>0)console.log(` \x1B[33mFiles failed: ${C.filesFailed}\x1B[0m`)}console.log(` Cost reset to: $${_.toFixed(4)}`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to restore checkpoint: ${V}\x1B[0m`)}continue;case"restore-chat":if(!G){console.log("\x1B[31mUsage: /restore-chat <checkpoint-id>\x1B[0m"),console.log("\x1B[90mRestores chat only, no files\x1B[0m");continue}try{let Z=G.trim(),V=await g(K,Z);if(!V){console.log(`\x1B[31mCheckpoint not found: ${Z}\x1B[0m`);continue}let P=await I(V,{restoreFiles:!1,restoreMessages:!0});J.length=0,J.push(...P.messages),_=V.metadata.totalCost,console.log(`\x1B[32m\u2713 Chat restored:\x1B[0m ${J.length} messages (no files changed)`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to restore chat: ${V}\x1B[0m`)}continue;case"undo":try{let Z=await Yz(K);if(!Z.checkpoint){console.log("\x1B[33mNothing to undo\x1B[0m");continue}let V=await I(Z.checkpoint,{restoreFiles:!0,restoreMessages:!0,workingDirectory:process.cwd()});if(J.length=0,J.push(...V.messages),_=Z.checkpoint.metadata.totalCost,console.log(`\x1B[32m\u2713 Undone to:\x1B[0m ${v(Z.checkpoint)}`),console.log(`\x1B[90mMessages: ${J.length} | Files: ${V.filesRestored}\x1B[0m`),Z.canRedo)console.log("\x1B[90mUse /redo to go forward\x1B[0m")}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mUndo failed: ${V}\x1B[0m`)}continue;case"redo":try{let Z=await Zz(K);if(!Z.checkpoint){console.log("\x1B[33mNothing to redo\x1B[0m");continue}let V=await I(Z.checkpoint,{restoreFiles:!0,restoreMessages:!0,workingDirectory:process.cwd()});if(J.length=0,J.push(...V.messages),_=Z.checkpoint.metadata.totalCost,console.log(`\x1B[32m\u2713 Redone to:\x1B[0m ${v(Z.checkpoint)}`),console.log(`\x1B[90mMessages: ${J.length} | Files: ${V.filesRestored}\x1B[0m`),Z.canRedo)console.log("\x1B[90mUse /redo to go forward again\x1B[0m")}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mRedo failed: ${V}\x1B[0m`)}continue;case"checkpoint-status":case"cps-status":try{let Z=await $z(K);if(console.log("\x1B[1mCheckpoint Navigation:\x1B[0m"),console.log(` Position: ${Z.current}/${Z.total}`),console.log(` Can undo: ${Z.canUndo?"\x1B[32myes\x1B[0m":"\x1B[31mno\x1B[0m"}`),console.log(` Can redo: ${Z.canRedo?"\x1B[32myes\x1B[0m":"\x1B[31mno\x1B[0m"}`),Z.currentId)console.log(` Current: ${Z.currentId}`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to get status: ${V}\x1B[0m`)}continue;default:let y=Q.get(F);if(y){console.log(`\x1B[90mLoading skill: ${y.name}\x1B[0m`),X+=`
113
+ \x1B[32m\u2713 Checkpoint restored:\x1B[0m`),console.log(` Messages: ${J.length}`),D&&P){if(console.log(` Files restored: ${C.filesRestored}`),C.filesFailed>0)console.log(` \x1B[33mFiles failed: ${C.filesFailed}\x1B[0m`)}console.log(` Cost reset to: $${_.toFixed(4)}`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to restore checkpoint: ${V}\x1B[0m`)}continue;case"restore-chat":if(!A){console.log("\x1B[31mUsage: /restore-chat <checkpoint-id>\x1B[0m"),console.log("\x1B[90mRestores chat only, no files\x1B[0m");continue}try{let Z=A.trim(),V=await g(K,Z);if(!V){console.log(`\x1B[31mCheckpoint not found: ${Z}\x1B[0m`);continue}let P=await I(V,{restoreFiles:!1,restoreMessages:!0});J.length=0,J.push(...P.messages),_=V.metadata.totalCost,console.log(`\x1B[32m\u2713 Chat restored:\x1B[0m ${J.length} messages (no files changed)`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to restore chat: ${V}\x1B[0m`)}continue;case"undo":try{let Z=await Yz(K);if(!Z.checkpoint){console.log("\x1B[33mNothing to undo\x1B[0m");continue}let V=await I(Z.checkpoint,{restoreFiles:!0,restoreMessages:!0,workingDirectory:process.cwd()});if(J.length=0,J.push(...V.messages),_=Z.checkpoint.metadata.totalCost,console.log(`\x1B[32m\u2713 Undone to:\x1B[0m ${v(Z.checkpoint)}`),console.log(`\x1B[90mMessages: ${J.length} | Files: ${V.filesRestored}\x1B[0m`),Z.canRedo)console.log("\x1B[90mUse /redo to go forward\x1B[0m")}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mUndo failed: ${V}\x1B[0m`)}continue;case"redo":try{let Z=await Zz(K);if(!Z.checkpoint){console.log("\x1B[33mNothing to redo\x1B[0m");continue}let V=await I(Z.checkpoint,{restoreFiles:!0,restoreMessages:!0,workingDirectory:process.cwd()});if(J.length=0,J.push(...V.messages),_=Z.checkpoint.metadata.totalCost,console.log(`\x1B[32m\u2713 Redone to:\x1B[0m ${v(Z.checkpoint)}`),console.log(`\x1B[90mMessages: ${J.length} | Files: ${V.filesRestored}\x1B[0m`),Z.canRedo)console.log("\x1B[90mUse /redo to go forward again\x1B[0m")}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mRedo failed: ${V}\x1B[0m`)}continue;case"checkpoint-status":case"cps-status":try{let Z=await $z(K);if(console.log("\x1B[1mCheckpoint Navigation:\x1B[0m"),console.log(` Position: ${Z.current}/${Z.total}`),console.log(` Can undo: ${Z.canUndo?"\x1B[32myes\x1B[0m":"\x1B[31mno\x1B[0m"}`),console.log(` Can redo: ${Z.canRedo?"\x1B[32myes\x1B[0m":"\x1B[31mno\x1B[0m"}`),Z.currentId)console.log(` Current: ${Z.currentId}`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to get status: ${V}\x1B[0m`)}continue;default:let y=Q.get(F);if(y){console.log(`\x1B[90mLoading skill: ${y.name}\x1B[0m`),X+=`
112
114
 
113
115
  `+Tz(y);continue}console.log(`\x1B[31mUnknown command: /${F}\x1B[0m`),console.log("\x1B[90mType /help for available commands.\x1B[0m");continue}}J.push({role:"user",content:[{type:"text",text:U}]}),await L.saveMessage(J[J.length-1]),process.stdout.write(`
114
- \x1B[1;35mClaude:\x1B[0m `);let N=W.extendedThinking?{enabled:!0,effort:W.effort??"medium",interleaved:W.interleaved??!0}:void 0,H=await n(J,{apiKey:z,model:W.model,maxTokens:W.maxTokens,systemPrompt:X,tools:Y,permissionMode:W.permissionMode,workingDirectory:process.cwd(),gitStatus:q,extendedThinking:N,onText:(B)=>{process.stdout.write(B)},onThinking:(B)=>{process.stdout.write(`\x1B[90m${B}\x1B[0m`)},onToolUse:(B)=>{process.stdout.write(`
116
+ \x1B[1;35mClaude:\x1B[0m `);let G=W.extendedThinking?{enabled:!0,effort:W.effort??"medium",interleaved:W.interleaved??!0}:void 0,H=await n(J,{apiKey:z,model:W.model,maxTokens:W.maxTokens,systemPrompt:X,tools:Y,permissionMode:W.permissionMode,workingDirectory:process.cwd(),gitStatus:q,extendedThinking:G,stopSequences:W.stopSequences,onText:(B)=>{process.stdout.write(B)},onThinking:(B)=>{process.stdout.write(`\x1B[90m${B}\x1B[0m`)},onToolUse:(B)=>{process.stdout.write(`
115
117
  \x1B[90m[Trying: ${B.name}]\x1B[0m `)},onToolResult:(B)=>{if(B.result.is_error)process.stdout.write("\x1B[31m[Error]\x1B[0m ")},onMetrics:async(B)=>{console.log(`
116
- \x1B[90m${i(B)}\x1B[0m`),await L.saveMetrics(B)},onPermissionRequest:async(B)=>{return await b({toolName:B.toolName,toolInput:B.toolInput,riskLevel:B.riskLevel,description:B.description,file:B.file,command:B.command})}}),j=H.messages[H.messages.length-1];if(j&&j.role==="assistant")await L.saveMessage(j);J.length=0,J.push(...H.messages),_+=H.totalCost}catch(U){if(U instanceof Error&&U.message==="Readline closed")break;let N=U instanceof Error?U.message:String(U);console.error(`
117
- \x1B[31mError: ${N}\x1B[0m`)}x.close()}async function XW(z,W,X,Y,$,Q,L){let J=[{role:"user",content:[{type:"text",text:$}]}];await Q.saveMessage(J[0]);let K=await k(process.cwd()),R=W.extendedThinking?{enabled:!0,effort:W.effort??"medium",interleaved:W.interleaved??!0}:void 0,E=W.loop??!1,O=W.maxIterations??100,T=W.noAutonomous??!1,_=0,q=0,x=!1;try{while(!0){if(_++,O>0&&_>O){console.log(`
118
+ \x1B[90m${i(B)}\x1B[0m`),await L.saveMetrics(B)},onPermissionRequest:async(B)=>{return await N({toolName:B.toolName,toolInput:B.toolInput,riskLevel:B.riskLevel,description:B.description,file:B.file,command:B.command})}}),j=H.messages[H.messages.length-1];if(j&&j.role==="assistant")await L.saveMessage(j);J.length=0,J.push(...H.messages),_+=H.totalCost}catch(U){if(U instanceof Error&&U.message==="Readline closed")break;let G=U instanceof Error?U.message:String(U);console.error(`
119
+ \x1B[31mError: ${G}\x1B[0m`)}x.close()}async function XW(z,W,X,Y,$,Q,L){let J=[{role:"user",content:[{type:"text",text:$}]}];await Q.saveMessage(J[0]);let K=await k(process.cwd()),R=W.extendedThinking?{enabled:!0,effort:W.effort??"medium",interleaved:W.interleaved??!0}:void 0,E=W.loop??!1,O=W.maxIterations??100,T=W.noAutonomous??!1,_=0,q=0,x=!1;try{while(!0){if(_++,O>0&&_>O){console.log(`
118
120
  \x1B[33m\u26A0 Max iterations (${O}) reached\x1B[0m`);break}if(E){let U=O>0?`/${O}`:"";console.log(`
119
- \x1B[36m\u2501\u2501\u2501 Iteration ${_}${U} \u2501\u2501\u2501\x1B[0m`)}let A=await n(J,{apiKey:z,model:W.model,maxTokens:W.maxTokens,systemPrompt:X,tools:Y,permissionMode:W.permissionMode,workingDirectory:process.cwd(),gitStatus:K,extendedThinking:R,onText:(U)=>{process.stdout.write(U)},onThinking:(U)=>{process.stdout.write(`\x1B[90m${U}\x1B[0m`)},onMetrics:async(U)=>{console.log(`
120
- \x1B[90m${i(U)}\x1B[0m`),await Q.saveMetrics(U)}}),b=A.messages[A.messages.length-1];if(b&&b.role==="assistant")await Q.saveMessage(b);if(q+=A.totalCost,J.length=0,J.push(...A.messages),E&&!x){let U=[...J].reverse().find((H)=>H.role==="assistant");if(U){let H=U.content;if((Array.isArray(H)?H.filter((B)=>B.type==="text").map((B)=>B.text).join(" "):String(H)).includes("TASKS_COMPLETE")){console.log(`
121
- \x1B[32m\u2713 Model signaled TASKS_COMPLETE - all work done\x1B[0m`),x=!0;break}}let N=T?"Continue working on the original task. If fully complete, respond with 'TASKS_COMPLETE'.":`Autonomous check #${_}: Scan for additional productive work in this codebase.
121
+ \x1B[36m\u2501\u2501\u2501 Iteration ${_}${U} \u2501\u2501\u2501\x1B[0m`)}let b=await n(J,{apiKey:z,model:W.model,maxTokens:W.maxTokens,systemPrompt:X,tools:Y,permissionMode:W.permissionMode,workingDirectory:process.cwd(),gitStatus:K,extendedThinking:R,getStopSequences:E?(U,G)=>{return W.stopSequences??["TASKS_COMPLETE"]}:void 0,stopSequences:E?void 0:W.stopSequences,onText:(U)=>{process.stdout.write(U)},onThinking:(U)=>{process.stdout.write(`\x1B[90m${U}\x1B[0m`)},onMetrics:async(U)=>{console.log(`
122
+ \x1B[90m${i(U)}\x1B[0m`),await Q.saveMetrics(U)}}),N=b.messages[b.messages.length-1];if(N&&N.role==="assistant")await Q.saveMessage(N);if(q+=b.totalCost,J.length=0,J.push(...b.messages),E&&!x){let U=[...J].reverse().find((H)=>H.role==="assistant");if(U){let H=U.content;if((Array.isArray(H)?H.filter((B)=>B.type==="text").map((B)=>B.text).join(" "):String(H)).includes("TASKS_COMPLETE")){console.log(`
123
+ \x1B[32m\u2713 Model signaled TASKS_COMPLETE - all work done\x1B[0m`),x=!0;break}}let G=T?"Continue working on the original task. If fully complete, respond with 'TASKS_COMPLETE'.":`Autonomous check #${_}: Scan for additional productive work in this codebase.
122
124
 
123
125
  Look for:
124
126
  - TODOs, FIXMEs, or incomplete code
@@ -132,10 +134,10 @@ Look for:
132
134
 
133
135
  Use your tools (Glob, Grep, Read, Bash) to actively search. Do not guess or hallucinate - investigate.
134
136
 
135
- If you find productive work, do it. If nothing productive remains, respond with exactly: TASKS_COMPLETE`;J.push({role:"user",content:[{type:"text",text:N}]})}else break}if(E)if(x)console.log(`
137
+ If you find productive work, do it. If nothing productive remains, respond with exactly: TASKS_COMPLETE`;J.push({role:"user",content:[{type:"text",text:G}]})}else break}if(E)if(x)console.log(`
136
138
  \x1B[32m\u2713 Autonomous loop completed after ${_} iteration(s)\x1B[0m`);else console.log(`
137
139
  \x1B[33m\u2713 Loop ended after ${_} iteration(s)\x1B[0m`);console.log(`
138
- \x1B[90mSession: ${L}\x1B[0m`),console.log(`\x1B[90mTotal cost: ${p(q)}\x1B[0m`)}catch(A){let b=A instanceof Error?A.message:String(A);console.error(`Error: ${b}`),process.exit(1)}}async function YW(z){let W=`You are Claude Code, an AI coding assistant created by Anthropic.
140
+ \x1B[90mSession: ${L}\x1B[0m`),console.log(`\x1B[90mTotal cost: ${p(q)}\x1B[0m`)}catch(b){let N=b instanceof Error?b.message:String(b);console.error(`Error: ${N}`),process.exit(1)}}async function YW(z){let W=`You are Claude Code, an AI coding assistant created by Anthropic.
139
141
 
140
142
  You help users with software engineering tasks:
141
143
  - Reading, writing, and editing code
@@ -0,0 +1,240 @@
1
+ // @bun
2
+ var q8=Object.create;var{getPrototypeOf:W8,defineProperty:Q7,getOwnPropertyNames:j8}=Object;var _8=Object.prototype.hasOwnProperty;var G8=(Q,X,Z)=>{Z=Q!=null?q8(W8(Q)):{};let V=X||!Q||!Q.__esModule?Q7(Z,"default",{value:Q,enumerable:!0}):Z;for(let $ of j8(Q))if(!_8.call(V,$))Q7(V,$,{get:()=>Q[$],enumerable:!0});return V};var U8=import.meta.require;var e5={enabled:!0,ttl:"1h",cacheSystemPrompt:!0,cacheTools:!0,minTokensForCache:1024},A8={low:1024,medium:4096,high:16384,max:1e5},qQ={enabled:!1,effort:"medium",interleaved:!0};function X7(Q,X){if(Q.budgetTokens)return Q.budgetTokens;let Z=Q.effort||"medium",V=A8[Z],$=Q.modelMultiplier??(X.includes("opus")?2:1);return Math.min(V*$,1e5)}function Z7(Q){return Q.includes("claude-opus-4")||Q.includes("claude-sonnet-4")||Q.includes("claude-haiku-4")||Q.includes("claude-4")}var WQ={"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 w8={maxRetries:3,baseDelayMs:1000,maxDelayMs:30000,jitterFactor:0.2,retryableStatusCodes:[429,500,502,503,504,529],onRetry:void 0};function L8(Q,X,Z,V){let $=X*Math.pow(2,Q),J=$*V*(Math.random()*2-1);return Math.min($+J,Z)}function B8(Q,X){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 Z of X)if(Q.message.includes(String(Z)))return!0;return!1}function O8(Q){return new Promise((X)=>setTimeout(X,Q))}async function V7(Q,X={}){let Z={...w8,...X},V=null;for(let $=0;$<=Z.maxRetries;$++)try{return await Q()}catch(J){if(V=J instanceof Error?J:Error(String(J)),$<Z.maxRetries&&B8(V,Z.retryableStatusCodes)){let z=L8($,Z.baseDelayMs,Z.maxDelayMs,Z.jitterFactor);if(Z.onRetry)Z.onRetry($+1,V,z);else console.warn(`\x1B[33mRetry ${$+1}/${Z.maxRetries} after ${z}ms: ${V.message}\x1B[0m`);await O8(z)}else throw V}throw V||Error("Max retries exceeded")}var $7={"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 v8(Q,X){let Z=$7[Q]??$7["claude-sonnet-4-6"],V=X.input_tokens-(X.cache_read_input_tokens??0),$=X.cache_read_input_tokens??0,J=X.cache_creation_input_tokens??0,z=X.output_tokens,Y=V/1e6*Z.input,K=$/1e6*Z.cache_read,H=J/1e6*Z.cache_write,q=z/1e6*Z.output,W=Y+K+H+q,_=($+J)/1e6*(Z.input-Z.cache_read);return{costUSD:W,estimatedSavingsUSD:_}}function F8(Q,X){if(!Q||!X.enabled||!X.cacheSystemPrompt)return typeof Q==="string"?Q:void 0;if(Array.isArray(Q)){let Z=[...Q];if(Z.length>0){let V=Z[Z.length-1];if(V&&V.type==="text")Z[Z.length-1]={type:"text",text:V.text,cache_control:{type:"ephemeral",ttl:X.ttl}}}return Z}return[{type:"text",text:Q,cache_control:{type:"ephemeral",ttl:X.ttl}}]}function C8(Q,X){if(!X.enabled)return Q;let Z=[];for(let V=0;V<Q.length;V++){let $=Q[V],J=[];for(let z=0;z<$.content.length;z++){let Y=$.content[z],K=z===$.content.length-1,H=V===Q.length-1;if(Y.type==="text"&&Y.text.length>=X.minTokensForCache*4&&!Y.cache_control&&(K||H))J.push({...Y,cache_control:{type:"ephemeral",ttl:X.ttl}});else J.push(Y)}Z.push({...$,content:J})}if(Z.length>0&&X.enabled){let V=Z[Z.length-1],$=V.content[V.content.length-1];if($&&!("cache_control"in $))V.content[V.content.length-1]={...$,cache_control:{type:"ephemeral",ttl:X.ttl}}}return Z}function M8(Q){let X=Q.cache_read_input_tokens??0,Z=Q.cache_creation_input_tokens??0,V=X+Z,$=X>0?1:0,J=Z>0?1:0,z=$+J;return{cacheHits:$,cacheMisses:J,totalCacheReadTokens:X,totalCacheWriteTokens:Z,cacheHitRate:z>0?$/z:0,estimatedSavingsUSD:0}}async function J7(Q,X){let{apiKey:Z,model:V="claude-sonnet-4-6",maxTokens:$=4096,tools:J,systemPrompt:z,cacheConfig:Y=e5,thinking:K,extendedThinking:H,stopSequences:q,onToken:W,onThinking:j,onRedactedThinking:_,onToolUse:G,signal:U}=X,w=Date.now(),A=0,L=!0,v=0,F=C8(Q,Y),O=F8(z,Y),k={model:V,max_tokens:$,messages:F.map((R)=>({role:R.role,content:R.content})),stream:!0};if(O)k.system=O;if(J&&J.length>0)k.tools=J;if(q&&q.length>0)k.stop_sequences=q;let s=`${process.env.ANTHROPIC_BASE_URL||"https://api.anthropic.com"}/v1/messages`,P={"Content-Type":"application/json","x-api-key":Z,"anthropic-version":"2023-06-01"};if(((H?.enabled??!1)||K&&K.type!=="disabled")&&Z7(V)){let R;if(H?.budgetTokens)R=H.budgetTokens;else if(K?.type==="enabled")R=K.budget_tokens;else{let w5=H?.effort||"medium";R=X7({enabled:!0,effort:w5,modelMultiplier:V.includes("opus")?2:1},V)}R=Math.max(1024,Math.min(R,1e5)),k.thinking={type:"enabled",budget_tokens:R};let n=["extended-thinking-2025-01-24"];if(H?.interleaved!==!1)n.push("interleaved-thinking-2025-01-24");P["anthropic-beta"]=n.join(",")}else P["anthropic-beta"]="max-tokens-3-5-sonnet-2024-07-15";let D5={maxRetries:3,baseDelayMs:1000,maxDelayMs:30000,retryableStatusCodes:[429,500,502,503,504,529],onRetry:(R,n,w5)=>{console.log(`\x1B[33mAPI retry ${R}/3 after ${w5}ms: ${n.message}\x1B[0m`)}},t=await V7(async()=>{let R=await fetch(s,{method:"POST",headers:P,body:JSON.stringify(k),signal:U});if(!R.ok&&D5.retryableStatusCodes?.includes(R.status)){let n=await R.text();throw Error(`API error: ${R.status} - ${n}`)}return R},D5);if(!t.ok){let R=await t.text();throw Error(`API error: ${t.status} - ${R}`)}if(!t.body)throw Error("No response body");let x5=t.body.getReader(),I5=new TextDecoder,J5=null,z5=[],Y5={input_tokens:0,output_tokens:0},T=null,_5=null,e=null,m=null,A5="",S5=new Map,e6="";try{let R="";while(!0){let{done:n,value:w5}=await x5.read();if(n)break;R+=I5.decode(w5,{stream:!0});let T5=R.split(`
3
+ `);R=T5.pop()||"";for(let k5 of T5){if(!k5.startsWith("data: "))continue;let F5=k5.slice(6);if(!F5)continue;try{let X5=JSON.parse(F5);switch(X5.type){case"message_start":{let B=X5.message;J5=B,Y5=B.usage;break}case"content_block_start":{let{index:B,content_block:C}=X5;if(S5.set(B,C.type),C.type==="text")T={type:"text",text:""};else if(C.type==="thinking")_5={type:"thinking",thinking:""};else if(C.type==="redacted_thinking")e={type:"redacted_thinking",data:""};else if(C.type==="tool_use")m={type:"tool_use",id:C.id,name:C.name,input:{}},A5="";break}case"content_block_delta":{let B=X5.delta;if(B.type==="text_delta"&&T){let C=B.text;if(T.text+=C,W?.(C),L)A=Date.now()-w,L=!1}else if(B.type==="thinking_delta"&&_5){let C=B.thinking;_5.thinking+=C,j?.(C),v+=Math.ceil(C.length/4)}else if(B.type==="redacted_thinking_delta"&&e){let C=B.data;e.data+=C,_?.(C),v+=Math.ceil(C.length/4)}else if(B.type==="input_json_delta"&&m)A5+=B.partial_json;break}case"content_block_stop":{let B=X5.index,C=S5.get(B);if(C==="text"&&T)z5.push(T),T=null;else if(C==="thinking"&&_5)z5.push(_5),_5=null;else if(C==="redacted_thinking"){let M={type:"redacted_thinking",data:e?.data||""};z5.push(M),_?.(M.data),e=null}else if(C==="tool_use"&&m){try{m.input=JSON.parse(A5)}catch{m.input={}}z5.push(m),G?.({id:m.id,name:m.name,input:m.input}),m=null}S5.delete(B);break}case"message_delta":{let B=X5;if(B.usage)Y5.output_tokens=B.usage.output_tokens;if(J5&&B.delta?.stop_reason)J5.stop_reason=B.delta.stop_reason;break}case"message_stop":break}}catch{}}}}finally{x5.releaseLock()}if(!J5)throw Error("No message received from API");J5.content=z5;let{costUSD:B6,estimatedSavingsUSD:K5}=v8(V,Y5),v5=M8(Y5);v5.estimatedSavingsUSD=K5;let Q5=Date.now()-w;return{message:J5,usage:Y5,cacheMetrics:v5,costUSD:B6,durationMs:Q5,ttftMs:A||Q5,thinkingTokens:v}}import*as z7 from"readline";var R8={Read:"low",Glob:"low",Grep:"low",Task:"low",Write:"medium",Edit:"medium",NotebookEdit:"medium",Bash:"high"},P8=[/\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 N8(Q,X){let Z=R8[Q]??"medium";if(Q==="Bash"){let V=String(X.command??"");for(let $ of P8)if($.test(V))return"critical";if(/\bsudo\b/.test(V)||/\bchmod\b/.test(V))Z="high"}if(Q==="Write"||Q==="Edit"){let V=String(X.file_path??X.path??"");if(/\.(env|pem|key|secret|credentials)/.test(V))Z="high";if(/\/\.ssh\//.test(V)||/\/\.gnupg\//.test(V))Z="critical"}return Z}function D8(Q,X){switch(Q){case"Read":return`Read file: ${X.file_path??"unknown"}`;case"Write":return`Write file: ${X.file_path??"unknown"} (${String(X.content??"").length} chars)`;case"Edit":return`Edit file: ${X.file_path??"unknown"}`;case"Bash":return`Execute: ${String(X.command??"").slice(0,100)}${String(X.command??"").length>100?"...":""}`;case"Glob":return`Find files: ${X.pattern??"*"}`;case"Grep":return`Search: "${X.pattern??""}" in ${X.path??"."}`;case"Task":return`Spawn agent: ${X.subagent_type??"unknown"}`;default:return`Use tool: ${Q}`}}class v6{cache={};cacheTimeout=300000;promptCallback;mode;constructor(Q="default",X){this.mode=Q,this.promptCallback=X??this.defaultPrompt.bind(this)}async checkPermission(Q,X){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 Z=this.getCacheKey(Q,X),V=this.cache[Z];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 $=N8(Q,X),J=D8(Q,X),z={toolName:Q,toolInput:X,riskLevel:$,description:J,file:X.file_path??X.path,command:Q==="Bash"?X.command:void 0};if(this.mode==="interactive"||this.mode==="default"){let Y=await this.promptCallback(z);if(Y.decision==="allowAlways"||Y.decision==="denyAlways")this.cache[Z]={decision:Y.decision,timestamp:Date.now()};return Y}return{decision:"allow"}}getCacheKey(Q,X){if(["Read","Write","Edit"].includes(Q))return`${Q}:${X.file_path??X.path??"unknown"}`;if(Q==="Bash"){let Z=String(X.command??"").slice(0,100);return`${Q}:${Z}`}return Q}async defaultPrompt(Q){return new Promise((X)=>{let Z=z7.createInterface({input:process.stdin,output:process.stdout}),$={low:"\x1B[32m",medium:"\x1B[33m",high:"\x1B[31m",critical:"\x1B[35m"}[Q.riskLevel]??"\x1B[0m",J="\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: ${$}${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 z="[y]es / [n]o / [a]lways / [d]eny always";Z.question(`Allow? ${z}: `,(Y)=>{switch(Z.close(),Y.trim().toLowerCase()){case"y":case"yes":X({decision:"allow"});break;case"a":case"always":X({decision:"allowAlways"});break;case"d":case"deny":case"deny always":X({decision:"denyAlways"});break;case"n":case"no":default:X({decision:"deny"});break}})})}clearCache(){this.cache={}}setMode(Q){this.mode=Q,this.clearCache()}}var F6={readOnly:["Read","Glob","Grep","Task"],fileEdit:["Write","Edit","NotebookEdit"],system:["Bash"],network:[]};function BQ(Q){return F6.readOnly.includes(Q)}function OQ(Q){return F6.fileEdit.includes(Q)}function vQ(Q){return F6.system.includes(Q)}var M6={tokenWarningThreshold:0.8,costUpdateInterval:5,toolSummaryInterval:3,envInfoOnStart:!0},C6={WARNING:0.8,CRITICAL:0.9,EMERGENCY:0.95};function x8(Q){let{current:X,max:Z,threshold:V=C6.WARNING}=Q;if(Z<=0)return"";let $=X/Z;if($<V)return"";let J=Z-X,z=Math.round($*100),Y,K;if($>=C6.EMERGENCY)Y="emergency",K="\uD83D\uDEA8";else if($>=C6.CRITICAL)Y="critical",K="\u26A0\uFE0F";else Y="warning",K="\u26A1";let H=[`${K} Token Usage ${Y.toUpperCase()}`,"",`Current: ${X.toLocaleString()} / ${Z.toLocaleString()} tokens (${z}%)`,`Remaining: ${J.toLocaleString()} tokens`];if(Y==="emergency")H.push(""),H.push("Consider summarizing or compacting the conversation to continue.");else if(Y==="critical")H.push(""),H.push("Approaching token limit. Consider wrapping up soon.");return H.join(`
4
+ `)}function I8(Q){let{cost:X,previousCost:Z=0,currency:V="USD"}=Q,$=S8(V),J=Y7(X,$),z=X-Z,Y=Y7(Math.abs(z),$),K=["\uD83D\uDCB0 Cost Update","",`Total: ${J} ${V}`];if(z!==0){let H=z>0?"+":"-";K.push(`This turn: ${H}${Y} ${V}`)}return K.join(`
5
+ `)}function Y7(Q,X){if(Q<0.01)return`${X}${Q.toFixed(4)}`;else if(Q<1)return`${X}${Q.toFixed(3)}`;return`${X}${Q.toFixed(2)}`}function S8(Q){return{USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5"}[Q]||Q}function T8(Q){let{tools:X,maxDisplay:Z=10}=Q;if(X.length===0)return"No tools used this session.";let V=new Map;for(let Y of X){let K=V.get(Y.name)||0;V.set(Y.name,K+1)}let $=[...V.entries()].sort((Y,K)=>K[1]-Y[1]),J=[`\uD83D\uDD27 Tool Usage Summary (${X.length} total calls)`,""],z=$.slice(0,Z);for(let[Y,K]of z)J.push(` \u2022 ${Y}: ${K} call${K===1?"":"s"}`);if($.length>Z){let Y=$.length-Z;J.push(` ... and ${Y} more tool${Y===1?"":"s"}`)}return J.join(`
6
+ `)}function k8(Q){let{workingDirectory:X,gitStatus:Z,platform:V=process.platform,shell:$=process.env.SHELL||"unknown"}=Q,J=["\uD83D\uDCCD Environment Information","",`Working Directory: ${X}`,`Platform: ${V}`,`Shell: ${$}`];if(Z){if(J.push(""),J.push("Git Status:"),J.push(` Branch: ${Z.branch}`),Z.ahead>0||Z.behind>0)J.push(` Ahead: ${Z.ahead}, Behind: ${Z.behind}`);let z=Z.staged.length+Z.unstaged.length+Z.untracked.length+Z.conflicted.length;if(z>0){if(J.push(` Changes: ${z} file${z===1?"":"s"}`),Z.staged.length>0)J.push(` Staged: ${Z.staged.length}`);if(Z.unstaged.length>0)J.push(` Unstaged: ${Z.unstaged.length}`);if(Z.untracked.length>0)J.push(` Untracked: ${Z.untracked.length}`);if(Z.conflicted.length>0)J.push(` Conflicted: ${Z.conflicted.length}`)}else J.push(" Working tree clean")}return J.join(`
7
+ `)}function K7(Q){let{usage:X,maxTokens:Z,totalCost:V,previousCost:$,toolsUsed:J,workingDirectory:z,gitStatus:Y,turnNumber:K,config:H}=Q,q={...M6,...H},W=[],j=X.input_tokens+X.output_tokens,_=x8({current:j,max:Z,threshold:q.tokenWarningThreshold});if(_)W.push(_);if(K%q.costUpdateInterval===0){let G=I8({cost:V,previousCost:$});W.push(G)}if(K%q.toolSummaryInterval===0&&J.length>0){let G=T8({tools:J});W.push(G)}if(K===1&&q.envInfoOnStart){let G=k8({workingDirectory:z,gitStatus:Y});W.push(G)}if(W.length===0)return"";return["---","System Reminders:","",...W,"---"].join(`
8
+ `)}function E5(Q){if(!Q||Q.length===0)return 0;return Math.ceil(Q.length/4)}function H7(Q){switch(Q.type){case"text":return E5(Q.text);case"image":return 100;case"tool_use":let X=JSON.stringify(Q.input);return E5(Q.name)+E5(X)+10;case"tool_result":if(typeof Q.content==="string")return E5(Q.content)+10;return Q.content.reduce((Z,V)=>Z+H7(V),0)+10;case"thinking":return E5(Q.thinking);default:return 0}}function E8(Q){return 4+Q.content.reduce((V,$)=>V+H7($),0)}function R6(Q){if(!Q||Q.length===0)return 0;return Q.reduce((X,Z)=>X+E8(Z),0)}function b8(Q){let X=[];for(let Z of Q.content)switch(Z.type){case"text":X.push(Z.text);break;case"tool_use":X.push(`[Tool: ${Z.name}(${JSON.stringify(Z.input)})]`);break;case"tool_result":let V=typeof Z.content==="string"?Z.content:Z.content.map(($)=>$.type==="text"?$.text:"[content]").join("");X.push(`[Result: ${V.slice(0,500)}${V.length>500?"...":""}]`);break;case"thinking":X.push(`[Thinking: ${Z.thinking.slice(0,200)}...]`);break}return X.join(`
9
+ `)}function y8(Q){let X=new Map;for(let Z of Q)for(let V of Z.content)if(V.type==="tool_use")X.set(V.id,{use:V});for(let Z of Q)for(let V of Z.content)if(V.type==="tool_result"){let $=X.get(V.tool_use_id);if($)$.result=V}return X}async function f8(Q){if(!Q||Q.length===0)return"";let X=[];X.push(`[Context Summary: ${Q.length} messages compacted]
10
+ `);let Z=[];for(let $=0;$<Q.length;$++){let J=Q[$];if(!J)continue;let z=J.role.toUpperCase(),Y=b8(J);for(let H of J.content)if(H.type==="tool_use")Z.push(`${H.name}`);let K=Y.length>300?`${Y.slice(0,300)}...`:Y;X.push(`${z}: ${K}
11
+ `)}if(Z.length>0){let $=Z.reduce((z,Y)=>{return z[Y]=(z[Y]||0)+1,z},{}),J=Object.entries($).map(([z,Y])=>`${z}(${Y})`).join(", ");X.push(`
12
+ Tools used: ${J}
13
+ `)}let V=X.join("");if(V.length>8000)V=V.slice(0,8000)+`
14
+ ...[truncated]`;return V}async function P6(Q,X,Z={}){let{keepFirst:V=1,keepLast:$=5,preserveToolPairs:J=!0}=Z,z=R6(Q);if(z<=X)return{messages:Q,messagesRemoved:0,tokensBefore:z,tokensAfter:z,didCompact:!1};if(Q.length<=V+$)return{messages:Q,messagesRemoved:0,tokensBefore:z,tokensAfter:z,didCompact:!1};let Y=Q.slice(0,V),K=Q.slice(V,-$),H=Q.slice(-$),W={role:"user",content:[{type:"text",text:`[Previous context has been compacted for continuity]
15
+
16
+ ${await f8(K)}`}]},j=[];if(J&&K.length>0){let w=y8(K),A=Array.from(w.values()).slice(-3).filter((L)=>L.result&&!L.result.is_error);for(let L of A)if(j.push(L.use),L.result)j.push(L.result)}let _=[...Y,W];if(j.length>0)_.push({role:"assistant",content:j.filter((w)=>w.type==="tool_use")}),_.push({role:"user",content:j.filter((w)=>w.type==="tool_result")});_.push(...H);let G=R6(_),U=Q.length-_.length;return console.log(`Context compaction: ${Q.length} -> ${_.length} messages, ${z} -> ${G} tokens`),{messages:_,messagesRemoved:U,tokensBefore:z,tokensAfter:G,didCompact:!0}}function q7(Q,X,Z=0.9){if(Q.length<8)return!1;let V=R6(Q),$=Math.floor(X*Z);return V>=$}function N6(Q){if(!Q.didCompact)return{reductionPercent:0,tokensSaved:0};let X=Q.tokensBefore-Q.tokensAfter,Z=X/Q.tokensBefore*100;return{reductionPercent:Math.round(Z*100)/100,tokensSaved:X}}async function EQ(Q,X){let{apiKey:Z,model:V="claude-sonnet-4-6",maxTokens:$=4096,systemPrompt:J,tools:z,permissionMode:Y,workingDirectory:K,gitStatus:H=null,reminderConfig:q,cacheConfig:W=e5,thinking:j,extendedThinking:_,stopSequences:G,getStopSequences:U,onText:w,onThinking:A,onToolUse:L,onToolResult:v,onMetrics:F,onReminder:O,onPermissionRequest:k,signal:b}=X,s=new v6(Y,k),P=[...Q],i=[],D5=[],t=0,x5=0,I5=0,J5=0,z5=0,Y5=0,T={cacheHits:0,cacheMisses:0,totalCacheReadTokens:0,totalCacheWriteTokens:0,cacheHitRate:0,estimatedSavingsUSD:0},_5={...M6,...q},e=!0;while(e){if(b?.aborted)break;I5++;let m=i[i.length-1],A5=K7({usage:m?.usage??{input_tokens:0,output_tokens:0},maxTokens:$,totalCost:t,previousCost:J5,toolsUsed:D5,workingDirectory:K,gitStatus:H,turnNumber:I5,config:_5});if(A5)O?.(A5);if(q7(P,$)){let B=await P6(P,$,{keepFirst:0,keepLast:3,preserveToolPairs:!0});if(B.didCompact&&B.tokensAfter<B.tokensBefore){P.length=0,P.push(...B.messages),z5++;let C=B.tokensBefore-B.tokensAfter;Y5+=C;let M=N6(B);console.log(`Context compacted: ${M.reductionPercent}% reduction, ${M.tokensSaved} tokens saved`)}}let S5=u8(P,J,A5),e6=U?U(I5,{lastStopReason:i[i.length-1]?.stopReason}):G,B6=await J7(S5,{apiKey:Z,model:V,maxTokens:$,systemPrompt:J,cacheConfig:W,thinking:j,extendedThinking:_,stopSequences:e6,tools:z.map((B)=>({name:B.name,description:B.description,input_schema:B.input_schema})),onToken:w,onThinking:A,onToolUse:L,signal:b}),{message:K5,usage:v5,cacheMetrics:Q5,costUSD:R,durationMs:n,ttftMs:w5}=B6,T5={model:V,messageCount:P.length,messageTokens:v5.input_tokens+v5.output_tokens,usage:v5,cacheMetrics:Q5,durationMs:n,ttftMs:w5,costUSD:R,stopReason:K5.stop_reason,requestId:K5.id};if(i.push(T5),J5=t,t+=R,x5+=n,Q5)T.cacheHits+=Q5.cacheHits,T.cacheMisses+=Q5.cacheMisses,T.totalCacheReadTokens+=Q5.totalCacheReadTokens,T.totalCacheWriteTokens+=Q5.totalCacheWriteTokens,T.estimatedSavingsUSD+=Q5.estimatedSavingsUSD;let k5=T.cacheHits+T.cacheMisses;if(T.cacheHitRate=k5>0?T.cacheHits/k5:0,F?.(T5),P.push({role:"assistant",content:K5.content}),K5.stop_reason==="end_turn"||K5.stop_reason==="stop_sequence"){e=!1;break}if(K5.stop_reason==="max_tokens"){let B=await P6(P,$,{keepFirst:0,keepLast:3,preserveToolPairs:!0});if(B.didCompact&&B.tokensAfter<B.tokensBefore){P.length=0,P.push(...B.messages),z5++;let C=B.tokensBefore-B.tokensAfter;Y5+=C;let M=N6(B);console.log(`Context compacted: ${M.reductionPercent}% reduction, ${M.tokensSaved} tokens saved`);continue}else{e=!1;break}}let F5=K5.content.filter((B)=>B.type==="tool_use");if(D5.push(...F5),F5.length===0){e=!1;break}let X5=[];if(b?.aborted);else{let B=F5.map(async(M)=>{let O6=z.find((H5)=>H5.name===M.name);if(!O6)return{toolUseId:M.id,result:{type:"tool_result",tool_use_id:M.id,content:`Error: Unknown tool "${M.name}"`,is_error:!0},toolResult:null};let t5=await s.checkPermission(O6.name,M.input);if(t5.decision==="deny"||t5.decision==="denyAlways")return{toolUseId:M.id,result:{type:"tool_result",tool_use_id:M.id,content:`Permission denied for tool "${M.name}"${t5.reason?`: ${t5.reason}`:""}`,is_error:!0},toolResult:null};try{let H5=await O6.handler(M.input,{workingDirectory:K,permissionMode:Y,abortSignal:b});return{toolUseId:M.id,result:{type:"tool_result",tool_use_id:M.id,content:H5.content,is_error:H5.is_error},toolResult:{id:M.id,result:H5}}}catch(H5){let H8=H5 instanceof Error?H5.message:String(H5);return{toolUseId:M.id,result:{type:"tool_result",tool_use_id:M.id,content:`Error: ${H8}`,is_error:!0},toolResult:null}}}),C=await Promise.all(B);for(let M of C)if(X5.push(M.result),M.toolResult)v?.(M.toolResult)}P.push({role:"user",content:X5})}return{messages:P,metrics:i,totalCost:t,totalDuration:x5,totalCacheMetrics:T,compactionCount:z5,totalTokensCompacted:Y5}}function u8(Q,X,Z){if(Z&&Q.length>0){let V=[...Q];for(let $=V.length-1;$>=0;$--){let J=V[$];if(J&&J.role==="user"){let z={role:"user",content:Array.isArray(J.content)?h8(J.content,Z):[{type:"text",text:`${String(J.content)}
17
+
18
+ ${Z}`}]};V[$]=z;break}}return V}return Q}function h8(Q,X){if(Q.length>0){let V=Q[Q.length-1];if(V&&V.type==="text"){let $={type:"text",text:`${V.text}
19
+
20
+ ${X}`};return[...Q.slice(0,-1),$]}}let Z={type:"text",text:`
21
+
22
+ ${X}`};return[...Q,Z]}function D6(Q){if(Q<0.01)return`$${Q.toFixed(4)}`;return`$${Q.toFixed(2)}`}function bQ(Q){let X=D6(Q.costUSD),Z=`${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",$=Q.usage.cache_creation_input_tokens?.toLocaleString()??"0";return`Cost: ${X} | Tokens: ${Z} | Cache: ${V} read, ${$} write`}return`Cost: ${X} | Tokens: ${Z}`}function yQ(Q){let X=D6(Q.costUSD),Z=Q.usage.input_tokens+Q.usage.output_tokens;return`Cost: ${X} | Tokens: ${Z.toLocaleString()}`}function fQ(Q){let X=D6(Q.estimatedSavingsUSD);return`Cache: ${(Q.cacheHitRate*100).toFixed(1)}% hit rate | ${Q.totalCacheReadTokens.toLocaleString()} read | ${Q.totalCacheWriteTokens.toLocaleString()} written | Saved: ${X}`}import{homedir as g8}from"os";import{join as q5}from"path";class m8{sessionsDir;currentSessionId=null;currentSessionFile=null;writeQueue=Promise.resolve();constructor(Q){this.sessionsDir=Q??q5(g8(),".claude","sessions")}async init(){try{await Bun.write(q5(this.sessionsDir,".gitkeep"),"")}catch{}}generateSessionId(){let Q=Date.now().toString(36),X=Math.random().toString(36).slice(2,8);return`${Q}-${X}`}async createSession(Q){await this.init();let X=this.generateSessionId();this.currentSessionId=X,this.currentSessionFile=q5(this.sessionsDir,`${X}.jsonl`);let Z={id:X,created:Date.now(),updated:Date.now(),model:Q.model,workingDirectory:Q.workingDirectory,agentName:Q.agentName,agentColor:Q.agentColor,teamName:Q.teamName};await this.appendEntry(Z);let V={type:"context",timestamp:Date.now(),workingDirectory:Q.workingDirectory};return await this.appendEntry(V),X}async resumeSession(Q){let X=q5(this.sessionsDir,`${Q}.jsonl`);try{let Z=await Bun.file(X).text();if(!Z)return null;let V=Z.trim().split(`
23
+ `),$=[];for(let J of V)try{$.push(JSON.parse(J))}catch{}return this.parseSessionEntries($)}catch{return null}}parseSessionEntries(Q){let X=null,Z=[],V=[],$=[],J=null;for(let z of Q){if(!("type"in z)&&"id"in z&&"created"in z){X=z;continue}if("type"in z){let Y=z;switch(Y.type){case"message":Z.push(Y.data);break;case"tool_use":V.push(Y);break;case"metrics":$.push(Y.data);break;case"context":J=Y;break}}}if(!X)X={id:"unknown",created:Date.now(),updated:Date.now(),model:"claude-sonnet-4-6",workingDirectory:process.cwd()};return{metadata:X,messages:Z,tools:V,metrics:$,context:J}}async appendEntry(Q){if(!this.currentSessionFile)return;this.writeQueue=this.writeQueue.then(async()=>{let X=JSON.stringify(Q)+`
24
+ `,Z=Bun.file(this.currentSessionFile),V=await Z.exists()?await Z.text():"";await Bun.write(this.currentSessionFile,V+X)}),await this.writeQueue}async saveMessage(Q){let X={type:"message",timestamp:Date.now(),data:Q};await this.appendEntry(X),await this.updateTimestamp()}async saveToolUse(Q,X,Z,V,$){let J={type:"tool_use",timestamp:Date.now(),toolId:Q,toolName:X,input:Z,result:V,isError:$};await this.appendEntry(J)}async saveMetrics(Q){let X={type:"metrics",timestamp:Date.now(),data:Q};await this.appendEntry(X)}async updateTimestamp(){if(!this.currentSessionFile||!this.currentSessionId)return}async listSessions(Q=20){await this.init();let X=Bun.file(this.sessionsDir),Z=[];try{let $=[...new Bun.Glob("*.jsonl").scanSync(this.sessionsDir)],J=await Promise.all($.map(async(z)=>{let Y=q5(this.sessionsDir,z),K=await Bun.file(Y).stat();return{file:z,fullPath:Y,mtime:K?.mtime??new Date(0)}}));J.sort((z,Y)=>Y.mtime.getTime()-z.mtime.getTime());for(let{file:z,fullPath:Y}of J.slice(0,Q)){let K=z.replace(".jsonl",""),H=await this.getSessionSummary(K,Y);if(H)Z.push(H)}}catch{}return Z}async getSessionSummary(Q,X){let Z=X??q5(this.sessionsDir,`${Q}.jsonl`);try{let V=await Bun.file(Z).text();if(!V)return null;let $=V.trim().split(`
25
+ `),J=null,z=0,Y=0,K=0,H=0,q;for(let W of $)try{let j=JSON.parse(W);if(j.id&&j.created)J=j;else if(j.type==="message"){z++;let _=j.data;if(!q&&_.role==="user"){let G=_.content.find((U)=>U.type==="text");if(G&&"text"in G){if(q=G.text.slice(0,100),G.text.length>100)q+="..."}}}else if(j.type==="metrics")Y+=j.data.costUSD,K+=j.data.usage.input_tokens,H+=j.data.usage.output_tokens}catch{}if(!J)return null;return{id:Q,created:J.created,updated:J.updated,model:J.model,messageCount:z,totalCost:Y,totalTokens:{input:K,output:H},firstMessage:q,workingDirectory:J.workingDirectory}}catch{return null}}getCurrentSessionId(){return this.currentSessionId}async exportSession(Q,X,Z){let V=await this.resumeSession(Q);if(!V)throw Error(`Session not found: ${Q}`);let $,J;switch(X){case"jsonl":{let Y=q5(this.sessionsDir,`${Q}.jsonl`);$=await Bun.file(Y).text(),J="jsonl";break}case"json":{$=JSON.stringify(V,null,2),J="json";break}case"markdown":{$=this.sessionToMarkdown(V),J="md";break}default:throw Error(`Unsupported format: ${X}`)}let z=Z??q5(process.cwd(),`session-${Q}.${J}`);return await Bun.write(z,$),z}sessionToMarkdown(Q){let X=[];X.push(`# Session: ${Q.metadata.id}`),X.push(""),X.push(`**Created:** ${new Date(Q.metadata.created).toISOString()}`),X.push(`**Model:** ${Q.metadata.model}`),X.push(`**Working Directory:** ${Q.metadata.workingDirectory}`),X.push(""),X.push("## Conversation"),X.push("");for(let Z of Q.messages){let V=Z.role==="user"?"**User**":"**Claude**";X.push(`### ${V}`),X.push("");for(let $ of Z.content)if($.type==="text")X.push($.text),X.push("");else if($.type==="tool_use"){let J=$;X.push(`\`\`\`tool:${J.name}`),X.push(JSON.stringify(J.input,null,2)),X.push("```"),X.push("")}else if($.type==="tool_result"){let J=$;X.push(`**Result**${J.is_error?" (error)":""}:`),X.push("```"),X.push(typeof J.content==="string"?J.content:JSON.stringify(J.content,null,2)),X.push("```"),X.push("")}}if(Q.metrics.length>0){X.push("## Metrics"),X.push("");let Z=Q.metrics.reduce((J,z)=>J+z.costUSD,0),V=Q.metrics.reduce((J,z)=>J+z.usage.input_tokens,0),$=Q.metrics.reduce((J,z)=>J+z.usage.output_tokens,0);X.push(`- **Total Cost:** $${Z.toFixed(4)}`),X.push(`- **Total Input Tokens:** ${V.toLocaleString()}`),X.push(`- **Total Output Tokens:** ${$.toLocaleString()}`),X.push(`- **API Calls:** ${Q.metrics.length}`)}return X.join(`
26
+ `)}async deleteSession(Q){let X=q5(this.sessionsDir,`${Q}.jsonl`);try{if(await Bun.file(X).exists()){let{unlink:V}=await import("fs/promises");return await V(X),!0}return!1}catch{return!1}}}function d8(Q){let X=new Date(Q.created),Z=new Date(Q.updated),V=c8(Z),$=[];$.push(`\x1B[1m${Q.id}\x1B[0m (${V})`),$.push(` Model: ${Q.model} | Messages: ${Q.messageCount}`);let J=Q.totalCost<0.01?`$${Q.totalCost.toFixed(4)}`:`$${Q.totalCost.toFixed(2)}`;if($.push(` Cost: ${J} | Tokens: ${Q.totalTokens.input.toLocaleString()} in, ${Q.totalTokens.output.toLocaleString()} out`),Q.firstMessage)$.push(` Preview: ${Q.firstMessage}`);return $.push(` Directory: ${Q.workingDirectory}`),$.join(`
27
+ `)}function c8(Q){let Z=new Date().getTime()-Q.getTime(),V=Math.floor(Z/60000),$=Math.floor(Z/3600000),J=Math.floor(Z/86400000);if(V<1)return"just now";if(V<60)return`${V}m ago`;if($<24)return`${$}h ago`;if(J<7)return`${J}d ago`;return Q.toLocaleDateString()}function mQ(Q){if(Q.length===0){console.log("No sessions found."),console.log(`
28
+ Start a new conversation to create a session.`);return}console.log(`\x1B[1mRecent Sessions (${Q.length})\x1B[0m
29
+ `);for(let X of Q)console.log(d8(X)),console.log("");console.log("To resume a session:"),console.log(" coder --resume <session-id>")}var x6=(Q,X,Z)=>{let V=Q instanceof RegExp?W7(Q,Z):Q,$=X instanceof RegExp?W7(X,Z):X,J=V!==null&&$!=null&&l8(V,$,Z);return J&&{start:J[0],end:J[1],pre:Z.slice(0,J[0]),body:Z.slice(J[0]+V.length,J[1]),post:Z.slice(J[1]+$.length)}},W7=(Q,X)=>{let Z=X.match(Q);return Z?Z[0]:null},l8=(Q,X,Z)=>{let V,$,J,z=void 0,Y,K=Z.indexOf(Q),H=Z.indexOf(X,K+1),q=K;if(K>=0&&H>0){if(Q===X)return[K,H];V=[],J=Z.length;while(q>=0&&!Y){if(q===K)V.push(q),K=Z.indexOf(Q,q+1);else if(V.length===1){let W=V.pop();if(W!==void 0)Y=[W,H]}else{if($=V.pop(),$!==void 0&&$<J)J=$,z=H;H=Z.indexOf(X,q+1)}q=K<H&&K>=0?K:H}if(V.length&&z!==void 0)Y=[J,z]}return Y};var j7="\x00SLASH"+Math.random()+"\x00",_7="\x00OPEN"+Math.random()+"\x00",S6="\x00CLOSE"+Math.random()+"\x00",G7="\x00COMMA"+Math.random()+"\x00",U7="\x00PERIOD"+Math.random()+"\x00",p8=new RegExp(j7,"g"),i8=new RegExp(_7,"g"),n8=new RegExp(S6,"g"),o8=new RegExp(G7,"g"),a8=new RegExp(U7,"g"),r8=/\\\\/g,s8=/\\{/g,t8=/\\}/g,e8=/\\,/g,Q9=/\\./g,X9=1e5;function I6(Q){return!isNaN(Q)?parseInt(Q,10):Q.charCodeAt(0)}function Z9(Q){return Q.replace(r8,j7).replace(s8,_7).replace(t8,S6).replace(e8,G7).replace(Q9,U7)}function V9(Q){return Q.replace(p8,"\\").replace(i8,"{").replace(n8,"}").replace(o8,",").replace(a8,".")}function A7(Q){if(!Q)return[""];let X=[],Z=x6("{","}",Q);if(!Z)return Q.split(",");let{pre:V,body:$,post:J}=Z,z=V.split(",");z[z.length-1]+="{"+$+"}";let Y=A7(J);if(J.length)z[z.length-1]+=Y.shift(),z.push.apply(z,Y);return X.push.apply(X,z),X}function w7(Q,X={}){if(!Q)return[];let{max:Z=X9}=X;if(Q.slice(0,2)==="{}")Q="\\{\\}"+Q.slice(2);return b5(Z9(Q),Z,!0).map(V9)}function $9(Q){return"{"+Q+"}"}function J9(Q){return/^-?0\d/.test(Q)}function z9(Q,X){return Q<=X}function Y9(Q,X){return Q>=X}function b5(Q,X,Z){let V=[],$=x6("{","}",Q);if(!$)return[Q];let J=$.pre,z=$.post.length?b5($.post,X,!1):[""];if(/\$$/.test($.pre))for(let Y=0;Y<z.length&&Y<X;Y++){let K=J+"{"+$.body+"}"+z[Y];V.push(K)}else{let Y=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test($.body),K=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test($.body),H=Y||K,q=$.body.indexOf(",")>=0;if(!H&&!q){if($.post.match(/,(?!,).*\}/))return Q=$.pre+"{"+$.body+S6+$.post,b5(Q,X,!0);return[Q]}let W;if(H)W=$.body.split(/\.\./);else if(W=A7($.body),W.length===1&&W[0]!==void 0){if(W=b5(W[0],X,!1).map($9),W.length===1)return z.map((_)=>$.pre+W[0]+_)}let j;if(H&&W[0]!==void 0&&W[1]!==void 0){let _=I6(W[0]),G=I6(W[1]),U=Math.max(W[0].length,W[1].length),w=W.length===3&&W[2]!==void 0?Math.abs(I6(W[2])):1,A=z9;if(G<_)w*=-1,A=Y9;let v=W.some(J9);j=[];for(let F=_;A(F,G);F+=w){let O;if(K){if(O=String.fromCharCode(F),O==="\\")O=""}else if(O=String(F),v){let k=U-O.length;if(k>0){let b=Array(k+1).join("0");if(F<0)O="-"+b+O.slice(1);else O=b+O}}j.push(O)}}else{j=[];for(let _=0;_<W.length;_++)j.push.apply(j,b5(W[_],X,!1))}for(let _=0;_<j.length;_++)for(let G=0;G<z.length&&V.length<X;G++){let U=J+j[_]+z[G];if(!Z||H||U)V.push(U)}}return V}var y5=(Q)=>{if(typeof Q!=="string")throw TypeError("invalid pattern");if(Q.length>65536)throw TypeError("pattern is too long")};var K9={"[: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]},f5=(Q)=>Q.replace(/[[\]\\-]/g,"\\$&"),H9=(Q)=>Q.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),L7=(Q)=>Q.join(""),B7=(Q,X)=>{let Z=X;if(Q.charAt(Z)!=="[")throw Error("not in a brace expression");let V=[],$=[],J=Z+1,z=!1,Y=!1,K=!1,H=!1,q=Z,W="";Q:while(J<Q.length){let U=Q.charAt(J);if((U==="!"||U==="^")&&J===Z+1){H=!0,J++;continue}if(U==="]"&&z&&!K){q=J+1;break}if(z=!0,U==="\\"){if(!K){K=!0,J++;continue}}if(U==="["&&!K){for(let[w,[A,L,v]]of Object.entries(K9))if(Q.startsWith(w,J)){if(W)return["$.",!1,Q.length-Z,!0];if(J+=w.length,v)$.push(A);else V.push(A);Y=Y||L;continue Q}}if(K=!1,W){if(U>W)V.push(f5(W)+"-"+f5(U));else if(U===W)V.push(f5(U));W="",J++;continue}if(Q.startsWith("-]",J+1)){V.push(f5(U+"-")),J+=2;continue}if(Q.startsWith("-",J+1)){W=U,J+=2;continue}V.push(f5(U)),J++}if(q<J)return["",!1,0,!1];if(!V.length&&!$.length)return["$.",!1,Q.length-Z,!0];if($.length===0&&V.length===1&&/^\\?.$/.test(V[0])&&!H){let U=V[0].length===2?V[0].slice(-1):V[0];return[H9(U),!1,q-Z,!1]}let j="["+(H?"^":"")+L7(V)+"]",_="["+(H?"":"^")+L7($)+"]";return[V.length&&$.length?"("+j+"|"+_+")":V.length?j:_,Y,q-Z,!0]};var o=(Q,{windowsPathsNoEscape:X=!1,magicalBraces:Z=!0}={})=>{if(Z)return X?Q.replace(/\[([^\/\\])\]/g,"$1"):Q.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");return X?Q.replace(/\[([^\/\\{}])\]/g,"$1"):Q.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1")};var h,q9=new Set(["!","?","+","*","@"]),T6=(Q)=>q9.has(Q),O7=(Q)=>T6(Q.type),W9=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),j9=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),_9=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),v7=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),G9="(?!(?:^|/)\\.\\.?(?:$|/))",Q6="(?!\\.)",U9=new Set(["[","."]),A9=new Set(["..","."]),w9=new Set("().*{}+?[]^$\\!"),L9=(Q)=>Q.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),k6="[^/]",F7=k6+"*?",C7=k6+"+?",B9=0;class C5{type;#Q;#V;#$=!1;#X=[];#z;#C;#L;#W=!1;#Y;#j;#q=!1;id=++B9;get depth(){return(this.#z?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#Q.id,parent:this.#z?.id,depth:this.depth,partsLength:this.#X.length,parts:this.#X}}constructor(Q,X,Z={}){if(this.type=Q,Q)this.#V=!0;if(this.#z=X,this.#Q=this.#z?this.#z.#Q:this,this.#Y=this.#Q===this?Z:this.#Q.#Y,this.#L=this.#Q===this?[]:this.#Q.#L,Q==="!"&&!this.#Q.#W)this.#L.push(this);this.#C=this.#z?this.#z.#X.length:0}get hasMagic(){if(this.#V!==void 0)return this.#V;for(let Q of this.#X){if(typeof Q==="string")continue;if(Q.type||Q.hasMagic)return this.#V=!0}return this.#V}toString(){if(this.#j!==void 0)return this.#j;if(!this.type)return this.#j=this.#X.map((Q)=>String(Q)).join("");else return this.#j=this.type+"("+this.#X.map((Q)=>String(Q)).join("|")+")"}#K(){if(this!==this.#Q)throw Error("should only call on root");if(this.#W)return this;this.toString(),this.#W=!0;let Q;while(Q=this.#L.pop()){if(Q.type!=="!")continue;let X=Q,Z=X.#z;while(Z){for(let V=X.#C+1;!Z.type&&V<Z.#X.length;V++)for(let $ of Q.#X){if(typeof $==="string")throw Error("string part in extglob AST??");$.copyIn(Z.#X[V])}X=Z,Z=X.#z}}return this}push(...Q){for(let X of Q){if(X==="")continue;if(typeof X!=="string"&&!(X instanceof h&&X.#z===this))throw Error("invalid part: "+X);this.#X.push(X)}}toJSON(){let Q=this.type===null?this.#X.slice().map((X)=>typeof X==="string"?X:X.toJSON()):[this.type,...this.#X.map((X)=>X.toJSON())];if(this.isStart()&&!this.type)Q.unshift([]);if(this.isEnd()&&(this===this.#Q||this.#Q.#W&&this.#z?.type==="!"))Q.push({});return Q}isStart(){if(this.#Q===this)return!0;if(!this.#z?.isStart())return!1;if(this.#C===0)return!0;let Q=this.#z;for(let X=0;X<this.#C;X++){let Z=Q.#X[X];if(!(Z instanceof h&&Z.type==="!"))return!1}return!0}isEnd(){if(this.#Q===this)return!0;if(this.#z?.type==="!")return!0;if(!this.#z?.isEnd())return!1;if(!this.type)return this.#z?.isEnd();let Q=this.#z?this.#z.#X.length:0;return this.#C===Q-1}copyIn(Q){if(typeof Q==="string")this.push(Q);else this.push(Q.clone(this))}clone(Q){let X=new h(this.type,Q);for(let Z of this.#X)X.copyIn(Z);return X}static#J(Q,X,Z,V,$){let J=V.maxExtglobRecursion??2,z=!1,Y=!1,K=-1,H=!1;if(X.type===null){let G=Z,U="";while(G<Q.length){let w=Q.charAt(G++);if(z||w==="\\"){z=!z,U+=w;continue}if(Y){if(G===K+1){if(w==="^"||w==="!")H=!0}else if(w==="]"&&!(G===K+2&&H))Y=!1;U+=w;continue}else if(w==="["){Y=!0,K=G,H=!1,U+=w;continue}if(!V.noext&&T6(w)&&Q.charAt(G)==="("&&$<=J){X.push(U),U="";let L=new h(w,X);G=h.#J(Q,L,G,V,$+1),X.push(L);continue}U+=w}return X.push(U),G}let q=Z+1,W=new h(null,X),j=[],_="";while(q<Q.length){let G=Q.charAt(q++);if(z||G==="\\"){z=!z,_+=G;continue}if(Y){if(q===K+1){if(G==="^"||G==="!")H=!0}else if(G==="]"&&!(q===K+2&&H))Y=!1;_+=G;continue}else if(G==="["){Y=!0,K=q,H=!1,_+=G;continue}if(!V.noext&&T6(G)&&Q.charAt(q)==="("&&($<=J||X&&X.#G(G))){let w=X&&X.#G(G)?0:1;W.push(_),_="";let A=new h(G,W);W.push(A),q=h.#J(Q,A,q,V,$+w);continue}if(G==="|"){W.push(_),_="",j.push(W),W=new h(null,X);continue}if(G===")"){if(_===""&&X.#X.length===0)X.#q=!0;return W.push(_),_="",X.push(...j,W),q}_+=G}return X.type=null,X.#V=void 0,X.#X=[Q.substring(Z-1)],q}#B(Q){return this.#v(Q,j9)}#v(Q,X=W9){if(!Q||typeof Q!=="object"||Q.type!==null||Q.#X.length!==1||this.type===null)return!1;let Z=Q.#X[0];if(!Z||typeof Z!=="object"||Z.type===null)return!1;return this.#G(Z.type,X)}#G(Q,X=_9){return!!X.get(this.type)?.includes(Q)}#U(Q,X){let Z=Q.#X[0],V=new h(null,Z,this.options);V.#X.push(""),Z.push(V),this.#P(Q,X)}#P(Q,X){let Z=Q.#X[0];this.#X.splice(X,1,...Z.#X);for(let V of Z.#X)if(typeof V==="object")V.#z=this;this.#j=void 0}#A(Q){return!!v7.get(this.type)?.has(Q)}#F(Q){if(!Q||typeof Q!=="object"||Q.type!==null||Q.#X.length!==1||this.type===null||this.#X.length!==1)return!1;let X=Q.#X[0];if(!X||typeof X!=="object"||X.type===null)return!1;return this.#A(X.type)}#M(Q){let X=v7.get(this.type),Z=Q.#X[0],V=X?.get(Z.type);if(!V)return!1;this.#X=Z.#X;for(let $ of this.#X)if(typeof $==="object")$.#z=this;this.type=V,this.#j=void 0,this.#q=!1}static fromGlob(Q,X={}){let Z=new h(null,void 0,X);return h.#J(Q,Z,0,X,0),Z}toMMPattern(){if(this!==this.#Q)return this.#Q.toMMPattern();let Q=this.toString(),[X,Z,V,$]=this.toRegExpSource();if(!(V||this.#V||this.#Y.nocase&&!this.#Y.nocaseMagicOnly&&Q.toUpperCase()!==Q.toLowerCase()))return Z;let z=(this.#Y.nocase?"i":"")+($?"u":"");return Object.assign(new RegExp(`^${X}$`,z),{_src:X,_glob:Q})}get options(){return this.#Y}toRegExpSource(Q){let X=Q??!!this.#Y.dot;if(this.#Q===this)this.#_(),this.#K();if(!O7(this)){let Y=this.isStart()&&this.isEnd()&&!this.#X.some((j)=>typeof j!=="string"),K=this.#X.map((j)=>{let[_,G,U,w]=typeof j==="string"?h.#O(j,this.#V,Y):j.toRegExpSource(Q);return this.#V=this.#V||U,this.#$=this.#$||w,_}).join(""),H="";if(this.isStart()){if(typeof this.#X[0]==="string"){if(!(this.#X.length===1&&A9.has(this.#X[0]))){let _=U9,G=X&&_.has(K.charAt(0))||K.startsWith("\\.")&&_.has(K.charAt(2))||K.startsWith("\\.\\.")&&_.has(K.charAt(4)),U=!X&&!Q&&_.has(K.charAt(0));H=G?G9:U?Q6:""}}}let q="";if(this.isEnd()&&this.#Q.#W&&this.#z?.type==="!")q="(?:$|\\/)";return[H+K+q,o(K),this.#V=!!this.#V,this.#$]}let Z=this.type==="*"||this.type==="+",V=this.type==="!"?"(?:(?!(?:":"(?:",$=this.#w(X);if(this.isStart()&&this.isEnd()&&!$&&this.type!=="!"){let Y=this.toString(),K=this;return K.#X=[Y],K.type=null,K.#V=void 0,[Y,o(this.toString()),!1,!1]}let J=!Z||Q||X||!Q6?"":this.#w(!0);if(J===$)J="";if(J)$=`(?:${$})(?:${J})*?`;let z="";if(this.type==="!"&&this.#q)z=(this.isStart()&&!X?Q6:"")+C7;else{let Y=this.type==="!"?"))"+(this.isStart()&&!X&&!Q?Q6:"")+F7+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&J?")":this.type==="*"&&J?")?":`)${this.type}`;z=V+$+Y}return[z,o($),this.#V=!!this.#V,this.#$]}#_(){if(!O7(this)){for(let Q of this.#X)if(typeof Q==="object")Q.#_()}else{let Q=0,X=!1;do{X=!0;for(let Z=0;Z<this.#X.length;Z++){let V=this.#X[Z];if(typeof V==="object"){if(V.#_(),this.#v(V))X=!1,this.#P(V,Z);else if(this.#B(V))X=!1,this.#U(V,Z);else if(this.#F(V))X=!1,this.#M(V)}}}while(!X&&++Q<10)}this.#j=void 0}#w(Q){return this.#X.map((X)=>{if(typeof X==="string")throw Error("string type in extglob ast??");let[Z,V,$,J]=X.toRegExpSource(Q);return this.#$=this.#$||J,Z}).filter((X)=>!(this.isStart()&&this.isEnd())||!!X).join("|")}static#O(Q,X,Z=!1){let V=!1,$="",J=!1,z=!1;for(let Y=0;Y<Q.length;Y++){let K=Q.charAt(Y);if(V){V=!1,$+=(w9.has(K)?"\\":"")+K;continue}if(K==="*"){if(z)continue;z=!0,$+=Z&&/^[*]+$/.test(Q)?C7:F7,X=!0;continue}else z=!1;if(K==="\\"){if(Y===Q.length-1)$+="\\\\";else V=!0;continue}if(K==="["){let[H,q,W,j]=B7(Q,Y);if(W){$+=H,J=J||q,Y+=W-1,X=X||j;continue}}if(K==="?"){$+=k6,X=!0;continue}$+=L9(K)}return[$,o(Q),!!X,J]}}h=C5;var M5=(Q,{windowsPathsNoEscape:X=!1,magicalBraces:Z=!1}={})=>{if(Z)return X?Q.replace(/[?*()[\]{}]/g,"[$&]"):Q.replace(/[?*()[\]\\{}]/g,"\\$&");return X?Q.replace(/[?*()[\]]/g,"[$&]"):Q.replace(/[?*()[\]\\]/g,"\\$&")};var y=(Q,X,Z={})=>{if(y5(X),!Z.nocomment&&X.charAt(0)==="#")return!1;return new c(X,Z).match(Q)},O9=/^\*+([^+@!?\*\[\(]*)$/,v9=(Q)=>(X)=>!X.startsWith(".")&&X.endsWith(Q),F9=(Q)=>(X)=>X.endsWith(Q),C9=(Q)=>{return Q=Q.toLowerCase(),(X)=>!X.startsWith(".")&&X.toLowerCase().endsWith(Q)},M9=(Q)=>{return Q=Q.toLowerCase(),(X)=>X.toLowerCase().endsWith(Q)},R9=/^\*+\.\*+$/,P9=(Q)=>!Q.startsWith(".")&&Q.includes("."),N9=(Q)=>Q!=="."&&Q!==".."&&Q.includes("."),D9=/^\.\*+$/,x9=(Q)=>Q!=="."&&Q!==".."&&Q.startsWith("."),I9=/^\*+$/,S9=(Q)=>Q.length!==0&&!Q.startsWith("."),T9=(Q)=>Q.length!==0&&Q!=="."&&Q!=="..",k9=/^\?+([^+@!?\*\[\(]*)?$/,E9=([Q,X=""])=>{let Z=P7([Q]);if(!X)return Z;return X=X.toLowerCase(),(V)=>Z(V)&&V.toLowerCase().endsWith(X)},b9=([Q,X=""])=>{let Z=N7([Q]);if(!X)return Z;return X=X.toLowerCase(),(V)=>Z(V)&&V.toLowerCase().endsWith(X)},y9=([Q,X=""])=>{let Z=N7([Q]);return!X?Z:(V)=>Z(V)&&V.endsWith(X)},f9=([Q,X=""])=>{let Z=P7([Q]);return!X?Z:(V)=>Z(V)&&V.endsWith(X)},P7=([Q])=>{let X=Q.length;return(Z)=>Z.length===X&&!Z.startsWith(".")},N7=([Q])=>{let X=Q.length;return(Z)=>Z.length===X&&Z!=="."&&Z!==".."},D7=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",M7={win32:{sep:"\\"},posix:{sep:"/"}},u9=D7==="win32"?M7.win32.sep:M7.posix.sep;y.sep=u9;var N=Symbol("globstar **");y.GLOBSTAR=N;var h9="[^/]",g9=h9+"*?",m9="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",d9="(?:(?!(?:\\/|^)\\.).)*?",c9=(Q,X={})=>(Z)=>y(Z,Q,X);y.filter=c9;var d=(Q,X={})=>Object.assign({},Q,X),l9=(Q)=>{if(!Q||typeof Q!=="object"||!Object.keys(Q).length)return y;let X=y;return Object.assign((V,$,J={})=>X(V,$,d(Q,J)),{Minimatch:class extends X.Minimatch{constructor($,J={}){super($,d(Q,J))}static defaults($){return X.defaults(d(Q,$)).Minimatch}},AST:class extends X.AST{constructor($,J,z={}){super($,J,d(Q,z))}static fromGlob($,J={}){return X.AST.fromGlob($,d(Q,J))}},unescape:(V,$={})=>X.unescape(V,d(Q,$)),escape:(V,$={})=>X.escape(V,d(Q,$)),filter:(V,$={})=>X.filter(V,d(Q,$)),defaults:(V)=>X.defaults(d(Q,V)),makeRe:(V,$={})=>X.makeRe(V,d(Q,$)),braceExpand:(V,$={})=>X.braceExpand(V,d(Q,$)),match:(V,$,J={})=>X.match(V,$,d(Q,J)),sep:X.sep,GLOBSTAR:N})};y.defaults=l9;var x7=(Q,X={})=>{if(y5(Q),X.nobrace||!/\{(?:(?!\{).)*\}/.test(Q))return[Q];return w7(Q,{max:X.braceExpandMax})};y.braceExpand=x7;var p9=(Q,X={})=>new c(Q,X).makeRe();y.makeRe=p9;var i9=(Q,X,Z={})=>{let V=new c(X,Z);if(Q=Q.filter(($)=>V.match($)),V.options.nonull&&!Q.length)Q.push(X);return Q};y.match=i9;var R7=/[?*]|[+@!]\(.*?\)|\[|\]/,n9=(Q)=>Q.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class c{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(Q,X={}){y5(Q),X=X||{},this.options=X,this.maxGlobstarRecursion=X.maxGlobstarRecursion??200,this.pattern=Q,this.platform=X.platform||D7,this.isWindows=this.platform==="win32";let Z="allowWindowsEscape";if(this.windowsPathsNoEscape=!!X.windowsPathsNoEscape||X[Z]===!1,this.windowsPathsNoEscape)this.pattern=this.pattern.replace(/\\/g,"/");this.preserveMultipleSlashes=!!X.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!X.nonegate,this.comment=!1,this.empty=!1,this.partial=!!X.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=X.windowsNoMagicRoot!==void 0?X.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 X of Q)if(typeof X!=="string")return!0;return!1}debug(...Q){}make(){let Q=this.pattern,X=this.options;if(!X.nocomment&&Q.charAt(0)==="#"){this.comment=!0;return}if(!Q){this.empty=!0;return}if(this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],X.debug)this.debug=(...$)=>console.error(...$);this.debug(this.pattern,this.globSet);let Z=this.globSet.map(($)=>this.slashSplit($));this.globParts=this.preprocess(Z),this.debug(this.pattern,this.globParts);let V=this.globParts.map(($,J,z)=>{if(this.isWindows&&this.windowsNoMagicRoot){let Y=$[0]===""&&$[1]===""&&($[2]==="?"||!R7.test($[2]))&&!R7.test($[3]),K=/^[a-z]:/i.test($[0]);if(Y)return[...$.slice(0,4),...$.slice(4).map((H)=>this.parse(H))];else if(K)return[$[0],...$.slice(1).map((H)=>this.parse(H))]}return $.map((Y)=>this.parse(Y))});if(this.debug(this.pattern,V),this.set=V.filter(($)=>$.indexOf(!1)===-1),this.isWindows)for(let $=0;$<this.set.length;$++){let J=this.set[$];if(J[0]===""&&J[1]===""&&this.globParts[$][2]==="?"&&typeof J[3]==="string"&&/^[a-z]:$/i.test(J[3]))J[2]="?"}this.debug(this.pattern,this.set)}preprocess(Q){if(this.options.noglobstar){for(let Z=0;Z<Q.length;Z++)for(let V=0;V<Q[Z].length;V++)if(Q[Z][V]==="**")Q[Z][V]="*"}let{optimizationLevel:X=1}=this.options;if(X>=2)Q=this.firstPhasePreProcess(Q),Q=this.secondPhasePreProcess(Q);else if(X>=1)Q=this.levelOneOptimize(Q);else Q=this.adjascentGlobstarOptimize(Q);return Q}adjascentGlobstarOptimize(Q){return Q.map((X)=>{let Z=-1;while((Z=X.indexOf("**",Z+1))!==-1){let V=Z;while(X[V+1]==="**")V++;if(V!==Z)X.splice(Z,V-Z)}return X})}levelOneOptimize(Q){return Q.map((X)=>{return X=X.reduce((Z,V)=>{let $=Z[Z.length-1];if(V==="**"&&$==="**")return Z;if(V===".."){if($&&$!==".."&&$!=="."&&$!=="**")return Z.pop(),Z}return Z.push(V),Z},[]),X.length===0?[""]:X})}levelTwoFileOptimize(Q){if(!Array.isArray(Q))Q=this.slashSplit(Q);let X=!1;do{if(X=!1,!this.preserveMultipleSlashes){for(let V=1;V<Q.length-1;V++){let $=Q[V];if(V===1&&$===""&&Q[0]==="")continue;if($==="."||$==="")X=!0,Q.splice(V,1),V--}if(Q[0]==="."&&Q.length===2&&(Q[1]==="."||Q[1]===""))X=!0,Q.pop()}let Z=0;while((Z=Q.indexOf("..",Z+1))!==-1){let V=Q[Z-1];if(V&&V!=="."&&V!==".."&&V!=="**")X=!0,Q.splice(Z-1,2),Z-=2}}while(X);return Q.length===0?[""]:Q}firstPhasePreProcess(Q){let X=!1;do{X=!1;for(let Z of Q){let V=-1;while((V=Z.indexOf("**",V+1))!==-1){let J=V;while(Z[J+1]==="**")J++;if(J>V)Z.splice(V+1,J-V);let z=Z[V+1],Y=Z[V+2],K=Z[V+3];if(z!=="..")continue;if(!Y||Y==="."||Y===".."||!K||K==="."||K==="..")continue;X=!0,Z.splice(V,1);let H=Z.slice(0);H[V]="**",Q.push(H),V--}if(!this.preserveMultipleSlashes){for(let J=1;J<Z.length-1;J++){let z=Z[J];if(J===1&&z===""&&Z[0]==="")continue;if(z==="."||z==="")X=!0,Z.splice(J,1),J--}if(Z[0]==="."&&Z.length===2&&(Z[1]==="."||Z[1]===""))X=!0,Z.pop()}let $=0;while(($=Z.indexOf("..",$+1))!==-1){let J=Z[$-1];if(J&&J!=="."&&J!==".."&&J!=="**"){X=!0;let Y=$===1&&Z[$+1]==="**"?["."]:[];if(Z.splice($-1,2,...Y),Z.length===0)Z.push("");$-=2}}}}while(X);return Q}secondPhasePreProcess(Q){for(let X=0;X<Q.length-1;X++)for(let Z=X+1;Z<Q.length;Z++){let V=this.partsMatch(Q[X],Q[Z],!this.preserveMultipleSlashes);if(V){Q[X]=[],Q[Z]=V;break}}return Q.filter((X)=>X.length)}partsMatch(Q,X,Z=!1){let V=0,$=0,J=[],z="";while(V<Q.length&&$<X.length)if(Q[V]===X[$])J.push(z==="b"?X[$]:Q[V]),V++,$++;else if(Z&&Q[V]==="**"&&X[$]===Q[V+1])J.push(Q[V]),V++;else if(Z&&X[$]==="**"&&Q[V]===X[$+1])J.push(X[$]),$++;else if(Q[V]==="*"&&X[$]&&(this.options.dot||!X[$].startsWith("."))&&X[$]!=="**"){if(z==="b")return!1;z="a",J.push(Q[V]),V++,$++}else if(X[$]==="*"&&Q[V]&&(this.options.dot||!Q[V].startsWith("."))&&Q[V]!=="**"){if(z==="a")return!1;z="b",J.push(X[$]),V++,$++}else return!1;return Q.length===X.length&&J}parseNegate(){if(this.nonegate)return;let Q=this.pattern,X=!1,Z=0;for(let V=0;V<Q.length&&Q.charAt(V)==="!";V++)X=!X,Z++;if(Z)this.pattern=Q.slice(Z);this.negate=X}matchOne(Q,X,Z=!1){let V=0,$=0;if(this.isWindows){let z=typeof Q[0]==="string"&&/^[a-z]:$/i.test(Q[0]),Y=!z&&Q[0]===""&&Q[1]===""&&Q[2]==="?"&&/^[a-z]:$/i.test(Q[3]),K=typeof X[0]==="string"&&/^[a-z]:$/i.test(X[0]),H=!K&&X[0]===""&&X[1]===""&&X[2]==="?"&&typeof X[3]==="string"&&/^[a-z]:$/i.test(X[3]),q=Y?3:z?0:void 0,W=H?3:K?0:void 0;if(typeof q==="number"&&typeof W==="number"){let[j,_]=[Q[q],X[W]];if(j.toLowerCase()===_.toLowerCase())X[W]=j,$=W,V=q}}let{optimizationLevel:J=1}=this.options;if(J>=2)Q=this.levelTwoFileOptimize(Q);if(X.includes(N))return this.#Q(Q,X,Z,V,$);return this.#$(Q,X,Z,V,$)}#Q(Q,X,Z,V,$){let J=X.indexOf(N,$),z=X.lastIndexOf(N),[Y,K,H]=Z?[X.slice($,J),X.slice(J+1),[]]:[X.slice($,J),X.slice(J+1,z),X.slice(z+1)];if(Y.length){let A=Q.slice(V,V+Y.length);if(!this.#$(A,Y,Z,0,0))return!1;V+=Y.length,$+=Y.length}let q=0;if(H.length){if(H.length+V>Q.length)return!1;let A=Q.length-H.length;if(this.#$(Q,H,Z,A,0))q=H.length;else{if(Q[Q.length-1]!==""||V+H.length===Q.length)return!1;if(A--,!this.#$(Q,H,Z,A,0))return!1;q=H.length+1}}if(!K.length){let A=!!q;for(let L=V;L<Q.length-q;L++){let v=String(Q[L]);if(A=!0,v==="."||v===".."||!this.options.dot&&v.startsWith("."))return!1}return Z||A}let W=[[[],0]],j=W[0],_=0,G=[0];for(let A of K)if(A===N)G.push(_),j=[[],0],W.push(j);else j[0].push(A),_++;let U=W.length-1,w=Q.length-q;for(let A of W)A[1]=w-(G[U--]+A[0].length);return!!this.#V(Q,W,V,0,Z,0,!!q)}#V(Q,X,Z,V,$,J,z){let Y=X[V];if(!Y){for(let q=Z;q<Q.length;q++){z=!0;let W=Q[q];if(W==="."||W===".."||!this.options.dot&&W.startsWith("."))return!1}return z}let[K,H]=Y;while(Z<=H){if(this.#$(Q.slice(0,Z+K.length),K,$,Z,0)&&J<this.maxGlobstarRecursion){let j=this.#V(Q,X,Z+K.length,V+1,$,J+1,z);if(j!==!1)return j}let W=Q[Z];if(W==="."||W===".."||!this.options.dot&&W.startsWith("."))return!1;Z++}return $||null}#$(Q,X,Z,V,$){let J,z,Y,K;for(J=V,z=$,K=Q.length,Y=X.length;J<K&&z<Y;J++,z++){this.debug("matchOne loop");let H=X[z],q=Q[J];if(this.debug(X,H,q),H===!1||H===N)return!1;let W;if(typeof H==="string")W=q===H,this.debug("string match",H,q,W);else W=H.test(q),this.debug("pattern match",H,q,W);if(!W)return!1}if(J===K&&z===Y)return!0;else if(J===K)return Z;else if(z===Y)return J===K-1&&Q[J]==="";else throw Error("wtf?")}braceExpand(){return x7(this.pattern,this.options)}parse(Q){y5(Q);let X=this.options;if(Q==="**")return N;if(Q==="")return"";let Z,V=null;if(Z=Q.match(I9))V=X.dot?T9:S9;else if(Z=Q.match(O9))V=(X.nocase?X.dot?M9:C9:X.dot?F9:v9)(Z[1]);else if(Z=Q.match(k9))V=(X.nocase?X.dot?b9:E9:X.dot?y9:f9)(Z);else if(Z=Q.match(R9))V=X.dot?N9:P9;else if(Z=Q.match(D9))V=x9;let $=C5.fromGlob(Q,this.options).toMMPattern();if(V&&typeof $==="object")Reflect.defineProperty($,"test",{value:V});return $}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Q=this.set;if(!Q.length)return this.regexp=!1,this.regexp;let X=this.options,Z=X.noglobstar?g9:X.dot?m9:d9,V=new Set(X.nocase?["i"]:[]),$=Q.map((Y)=>{let K=Y.map((q)=>{if(q instanceof RegExp)for(let W of q.flags.split(""))V.add(W);return typeof q==="string"?n9(q):q===N?N:q._src});K.forEach((q,W)=>{let j=K[W+1],_=K[W-1];if(q!==N||_===N)return;if(_===void 0)if(j!==void 0&&j!==N)K[W+1]="(?:\\/|"+Z+"\\/)?"+j;else K[W]=Z;else if(j===void 0)K[W-1]=_+"(?:\\/|\\/"+Z+")?";else if(j!==N)K[W-1]=_+"(?:\\/|\\/"+Z+"\\/)"+j,K[W+1]=N});let H=K.filter((q)=>q!==N);if(this.partial&&H.length>=1){let q=[];for(let W=1;W<=H.length;W++)q.push(H.slice(0,W).join("/"));return"(?:"+q.join("|")+")"}return H.join("/")}).join("|"),[J,z]=Q.length>1?["(?:",")"]:["",""];if($="^"+J+$+z+"$",this.partial)$="^(?:\\/|"+J+$.slice(1,-1)+z+")$";if(this.negate)$="^(?!"+$+").+$";try{this.regexp=new RegExp($,[...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,X=this.partial){if(this.debug("match",Q,this.pattern),this.comment)return!1;if(this.empty)return Q==="";if(Q==="/"&&X)return!0;let Z=this.options;if(this.isWindows)Q=Q.split("\\").join("/");let V=this.slashSplit(Q);this.debug(this.pattern,"split",V);let $=this.set;this.debug(this.pattern,"set",$);let J=V[V.length-1];if(!J)for(let z=V.length-2;!J&&z>=0;z--)J=V[z];for(let z=0;z<$.length;z++){let Y=$[z],K=V;if(Z.matchBase&&Y.length===1)K=[J];if(this.matchOne(K,Y,X)){if(Z.flipNegate)return!0;return!this.negate}}if(Z.flipNegate)return!1;return this.negate}static defaults(Q){return y.defaults(Q).Minimatch}}y.AST=C5;y.Minimatch=c;y.escape=M5;y.unescape=o;import{fileURLToPath as N0}from"url";var o9=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,S7=new Set,E6=typeof process=="object"&&process?process:{},T7=(Q,X,Z,V)=>{typeof E6.emitWarning=="function"?E6.emitWarning(Q,X,Z,V):console.error(`[${Z}] ${X}: ${Q}`)},Z6=globalThis.AbortController,I7=globalThis.AbortSignal;if(typeof Z6>"u"){I7=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(Z,V){this._onabort.push(V)}},Z6=class{constructor(){X()}signal=new I7;abort(Z){if(!this.signal.aborted){this.signal.reason=Z,this.signal.aborted=!0;for(let V of this.signal._onabort)V(Z);this.signal.onabort?.(Z)}}};let Q=E6.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",X=()=>{Q&&(Q=!1,T7("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",X))}}var a9=(Q)=>!S7.has(Q),KX=Symbol("type"),G5=(Q)=>Q&&Q===Math.floor(Q)&&Q>0&&isFinite(Q),k7=(Q)=>G5(Q)?Q<=Math.pow(2,8)?Uint8Array:Q<=Math.pow(2,16)?Uint16Array:Q<=Math.pow(2,32)?Uint32Array:Q<=Number.MAX_SAFE_INTEGER?X6:null:null,X6=class extends Array{constructor(Q){super(Q),this.fill(0)}},r9=class Q{heap;length;static#Q=!1;static create(X){let Z=k7(X);if(!Z)return[];Q.#Q=!0;let V=new Q(X,Z);return Q.#Q=!1,V}constructor(X,Z){if(!Q.#Q)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new Z(X),this.length=0}push(X){this.heap[this.length++]=X}pop(){return this.heap[--this.length]}},u5=class Q{#Q;#V;#$;#X;#z;#C;#L;#W;get perf(){return this.#W}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#Y;#j;#q;#K;#J;#B;#v;#G;#U;#P;#A;#F;#M;#_;#w;#O;#N;#Z;#E;static unsafeExposeInternals(X){return{starts:X.#M,ttls:X.#_,autopurgeTimers:X.#w,sizes:X.#F,keyMap:X.#q,keyList:X.#K,valList:X.#J,next:X.#B,prev:X.#v,get head(){return X.#G},get tail(){return X.#U},free:X.#P,isBackgroundFetch:(Z)=>X.#H(Z),backgroundFetch:(Z,V,$,J)=>X.#d(Z,V,$,J),moveToTail:(Z)=>X.#y(Z),indexes:(Z)=>X.#I(Z),rindexes:(Z)=>X.#S(Z),isStale:(Z)=>X.#R(Z)}}get max(){return this.#Q}get maxSize(){return this.#V}get calculatedSize(){return this.#j}get size(){return this.#Y}get fetchMethod(){return this.#C}get memoMethod(){return this.#L}get dispose(){return this.#$}get onInsert(){return this.#X}get disposeAfter(){return this.#z}constructor(X){let{max:Z=0,ttl:V,ttlResolution:$=1,ttlAutopurge:J,updateAgeOnGet:z,updateAgeOnHas:Y,allowStale:K,dispose:H,onInsert:q,disposeAfter:W,noDisposeOnSet:j,noUpdateTTL:_,maxSize:G=0,maxEntrySize:U=0,sizeCalculation:w,fetchMethod:A,memoMethod:L,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:F,allowStaleOnFetchRejection:O,allowStaleOnFetchAbort:k,ignoreFetchAbort:b,perf:s}=X;if(s!==void 0&&typeof s?.now!="function")throw TypeError("perf option must have a now() method if specified");if(this.#W=s??o9,Z!==0&&!G5(Z))throw TypeError("max option must be a nonnegative integer");let P=Z?k7(Z):Array;if(!P)throw Error("invalid max value: "+Z);if(this.#Q=Z,this.#V=G,this.maxEntrySize=U||this.#V,this.sizeCalculation=w,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(L!==void 0&&typeof L!="function")throw TypeError("memoMethod must be a function if defined");if(this.#L=L,A!==void 0&&typeof A!="function")throw TypeError("fetchMethod must be a function if specified");if(this.#C=A,this.#N=!!A,this.#q=new Map,this.#K=Array(Z).fill(void 0),this.#J=Array(Z).fill(void 0),this.#B=new P(Z),this.#v=new P(Z),this.#G=0,this.#U=0,this.#P=r9.create(Z),this.#Y=0,this.#j=0,typeof H=="function"&&(this.#$=H),typeof q=="function"&&(this.#X=q),typeof W=="function"?(this.#z=W,this.#A=[]):(this.#z=void 0,this.#A=void 0),this.#O=!!this.#$,this.#E=!!this.#X,this.#Z=!!this.#z,this.noDisposeOnSet=!!j,this.noUpdateTTL=!!_,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!O,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!b,this.maxEntrySize!==0){if(this.#V!==0&&!G5(this.#V))throw TypeError("maxSize must be a positive integer if specified");if(!G5(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#l()}if(this.allowStale=!!K,this.noDeleteOnStaleGet=!!F,this.updateAgeOnGet=!!z,this.updateAgeOnHas=!!Y,this.ttlResolution=G5($)||$===0?$:1,this.ttlAutopurge=!!J,this.ttl=V||0,this.ttl){if(!G5(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#T()}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 i="LRU_CACHE_UNBOUNDED";a9(i)&&(S7.add(i),T7("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",i,Q))}}getRemainingTTL(X){return this.#q.has(X)?1/0:0}#T(){let X=new X6(this.#Q),Z=new X6(this.#Q);this.#_=X,this.#M=Z;let V=this.ttlAutopurge?Array(this.#Q):void 0;this.#w=V,this.#u=(z,Y,K=this.#W.now())=>{if(Z[z]=Y!==0?K:0,X[z]=Y,V?.[z]&&(clearTimeout(V[z]),V[z]=void 0),Y!==0&&V){let H=setTimeout(()=>{this.#R(z)&&this.#x(this.#K[z],"expire")},Y+1);H.unref&&H.unref(),V[z]=H}},this.#D=(z)=>{Z[z]=X[z]!==0?this.#W.now():0},this.#k=(z,Y)=>{if(X[Y]){let K=X[Y],H=Z[Y];if(!K||!H)return;z.ttl=K,z.start=H,z.now=$||J();let q=z.now-H;z.remainingTTL=K-q}};let $=0,J=()=>{let z=this.#W.now();if(this.ttlResolution>0){$=z;let Y=setTimeout(()=>$=0,this.ttlResolution);Y.unref&&Y.unref()}return z};this.getRemainingTTL=(z)=>{let Y=this.#q.get(z);if(Y===void 0)return 0;let K=X[Y],H=Z[Y];if(!K||!H)return 1/0;let q=($||J())-H;return K-q},this.#R=(z)=>{let Y=Z[z],K=X[z];return!!K&&!!Y&&($||J())-Y>K}}#D=()=>{};#k=()=>{};#u=()=>{};#R=()=>!1;#l(){let X=new X6(this.#Q);this.#j=0,this.#F=X,this.#f=(Z)=>{this.#j-=X[Z],X[Z]=0},this.#h=(Z,V,$,J)=>{if(this.#H(V))return 0;if(!G5($))if(J){if(typeof J!="function")throw TypeError("sizeCalculation must be a function");if($=J(V,Z),!G5($))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 $},this.#b=(Z,V,$)=>{if(X[Z]=V,this.#V){let J=this.#V-X[Z];for(;this.#j>J;)this.#m(!0)}this.#j+=X[Z],$&&($.entrySize=V,$.totalCalculatedSize=this.#j)}}#f=(X)=>{};#b=(X,Z,V)=>{};#h=(X,Z,V,$)=>{if(V||$)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#I({allowStale:X=this.allowStale}={}){if(this.#Y)for(let Z=this.#U;!(!this.#g(Z)||((X||!this.#R(Z))&&(yield Z),Z===this.#G));)Z=this.#v[Z]}*#S({allowStale:X=this.allowStale}={}){if(this.#Y)for(let Z=this.#G;!(!this.#g(Z)||((X||!this.#R(Z))&&(yield Z),Z===this.#U));)Z=this.#B[Z]}#g(X){return X!==void 0&&this.#q.get(this.#K[X])===X}*entries(){for(let X of this.#I())this.#J[X]!==void 0&&this.#K[X]!==void 0&&!this.#H(this.#J[X])&&(yield[this.#K[X],this.#J[X]])}*rentries(){for(let X of this.#S())this.#J[X]!==void 0&&this.#K[X]!==void 0&&!this.#H(this.#J[X])&&(yield[this.#K[X],this.#J[X]])}*keys(){for(let X of this.#I()){let Z=this.#K[X];Z!==void 0&&!this.#H(this.#J[X])&&(yield Z)}}*rkeys(){for(let X of this.#S()){let Z=this.#K[X];Z!==void 0&&!this.#H(this.#J[X])&&(yield Z)}}*values(){for(let X of this.#I())this.#J[X]!==void 0&&!this.#H(this.#J[X])&&(yield this.#J[X])}*rvalues(){for(let X of this.#S())this.#J[X]!==void 0&&!this.#H(this.#J[X])&&(yield this.#J[X])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(X,Z={}){for(let V of this.#I()){let $=this.#J[V],J=this.#H($)?$.__staleWhileFetching:$;if(J!==void 0&&X(J,this.#K[V],this))return this.get(this.#K[V],Z)}}forEach(X,Z=this){for(let V of this.#I()){let $=this.#J[V],J=this.#H($)?$.__staleWhileFetching:$;J!==void 0&&X.call(Z,J,this.#K[V],this)}}rforEach(X,Z=this){for(let V of this.#S()){let $=this.#J[V],J=this.#H($)?$.__staleWhileFetching:$;J!==void 0&&X.call(Z,J,this.#K[V],this)}}purgeStale(){let X=!1;for(let Z of this.#S({allowStale:!0}))this.#R(Z)&&(this.#x(this.#K[Z],"expire"),X=!0);return X}info(X){let Z=this.#q.get(X);if(Z===void 0)return;let V=this.#J[Z],$=this.#H(V)?V.__staleWhileFetching:V;if($===void 0)return;let J={value:$};if(this.#_&&this.#M){let z=this.#_[Z],Y=this.#M[Z];if(z&&Y){let K=z-(this.#W.now()-Y);J.ttl=K,J.start=Date.now()}}return this.#F&&(J.size=this.#F[Z]),J}dump(){let X=[];for(let Z of this.#I({allowStale:!0})){let V=this.#K[Z],$=this.#J[Z],J=this.#H($)?$.__staleWhileFetching:$;if(J===void 0||V===void 0)continue;let z={value:J};if(this.#_&&this.#M){z.ttl=this.#_[Z];let Y=this.#W.now()-this.#M[Z];z.start=Math.floor(Date.now()-Y)}this.#F&&(z.size=this.#F[Z]),X.unshift([V,z])}return X}load(X){this.clear();for(let[Z,V]of X){if(V.start){let $=Date.now()-V.start;V.start=this.#W.now()-$}this.set(Z,V.value,V)}}set(X,Z,V={}){if(Z===void 0)return this.delete(X),this;let{ttl:$=this.ttl,start:J,noDisposeOnSet:z=this.noDisposeOnSet,sizeCalculation:Y=this.sizeCalculation,status:K}=V,{noUpdateTTL:H=this.noUpdateTTL}=V,q=this.#h(X,Z,V.size||0,Y);if(this.maxEntrySize&&q>this.maxEntrySize)return K&&(K.set="miss",K.maxEntrySizeExceeded=!0),this.#x(X,"set"),this;let W=this.#Y===0?void 0:this.#q.get(X);if(W===void 0)W=this.#Y===0?this.#U:this.#P.length!==0?this.#P.pop():this.#Y===this.#Q?this.#m(!1):this.#Y,this.#K[W]=X,this.#J[W]=Z,this.#q.set(X,W),this.#B[this.#U]=W,this.#v[W]=this.#U,this.#U=W,this.#Y++,this.#b(W,q,K),K&&(K.set="add"),H=!1,this.#E&&this.#X?.(Z,X,"add");else{this.#y(W);let j=this.#J[W];if(Z!==j){if(this.#N&&this.#H(j)){j.__abortController.abort(Error("replaced"));let{__staleWhileFetching:_}=j;_!==void 0&&!z&&(this.#O&&this.#$?.(_,X,"set"),this.#Z&&this.#A?.push([_,X,"set"]))}else z||(this.#O&&this.#$?.(j,X,"set"),this.#Z&&this.#A?.push([j,X,"set"]));if(this.#f(W),this.#b(W,q,K),this.#J[W]=Z,K){K.set="replace";let _=j&&this.#H(j)?j.__staleWhileFetching:j;_!==void 0&&(K.oldValue=_)}}else K&&(K.set="update");this.#E&&this.onInsert?.(Z,X,Z===j?"update":"replace")}if($!==0&&!this.#_&&this.#T(),this.#_&&(H||this.#u(W,$,J),K&&this.#k(K,W)),!z&&this.#Z&&this.#A){let j=this.#A,_;for(;_=j?.shift();)this.#z?.(..._)}return this}pop(){try{for(;this.#Y;){let X=this.#J[this.#G];if(this.#m(!0),this.#H(X)){if(X.__staleWhileFetching)return X.__staleWhileFetching}else if(X!==void 0)return X}}finally{if(this.#Z&&this.#A){let X=this.#A,Z;for(;Z=X?.shift();)this.#z?.(...Z)}}}#m(X){let Z=this.#G,V=this.#K[Z],$=this.#J[Z];return this.#N&&this.#H($)?$.__abortController.abort(Error("evicted")):(this.#O||this.#Z)&&(this.#O&&this.#$?.($,V,"evict"),this.#Z&&this.#A?.push([$,V,"evict"])),this.#f(Z),this.#w?.[Z]&&(clearTimeout(this.#w[Z]),this.#w[Z]=void 0),X&&(this.#K[Z]=void 0,this.#J[Z]=void 0,this.#P.push(Z)),this.#Y===1?(this.#G=this.#U=0,this.#P.length=0):this.#G=this.#B[Z],this.#q.delete(V),this.#Y--,Z}has(X,Z={}){let{updateAgeOnHas:V=this.updateAgeOnHas,status:$}=Z,J=this.#q.get(X);if(J!==void 0){let z=this.#J[J];if(this.#H(z)&&z.__staleWhileFetching===void 0)return!1;if(this.#R(J))$&&($.has="stale",this.#k($,J));else return V&&this.#D(J),$&&($.has="hit",this.#k($,J)),!0}else $&&($.has="miss");return!1}peek(X,Z={}){let{allowStale:V=this.allowStale}=Z,$=this.#q.get(X);if($===void 0||!V&&this.#R($))return;let J=this.#J[$];return this.#H(J)?J.__staleWhileFetching:J}#d(X,Z,V,$){let J=Z===void 0?void 0:this.#J[Z];if(this.#H(J))return J;let z=new Z6,{signal:Y}=V;Y?.addEventListener("abort",()=>z.abort(Y.reason),{signal:z.signal});let K={signal:z.signal,options:V,context:$},H=(U,w=!1)=>{let{aborted:A}=z.signal,L=V.ignoreFetchAbort&&U!==void 0,v=V.ignoreFetchAbort||!!(V.allowStaleOnFetchAbort&&U!==void 0);if(V.status&&(A&&!w?(V.status.fetchAborted=!0,V.status.fetchError=z.signal.reason,L&&(V.status.fetchAbortIgnored=!0)):V.status.fetchResolved=!0),A&&!L&&!w)return W(z.signal.reason,v);let F=_,O=this.#J[Z];return(O===_||L&&w&&O===void 0)&&(U===void 0?F.__staleWhileFetching!==void 0?this.#J[Z]=F.__staleWhileFetching:this.#x(X,"fetch"):(V.status&&(V.status.fetchUpdated=!0),this.set(X,U,K.options))),U},q=(U)=>(V.status&&(V.status.fetchRejected=!0,V.status.fetchError=U),W(U,!1)),W=(U,w)=>{let{aborted:A}=z.signal,L=A&&V.allowStaleOnFetchAbort,v=L||V.allowStaleOnFetchRejection,F=v||V.noDeleteOnFetchRejection,O=_;if(this.#J[Z]===_&&(!F||!w&&O.__staleWhileFetching===void 0?this.#x(X,"fetch"):L||(this.#J[Z]=O.__staleWhileFetching)),v)return V.status&&O.__staleWhileFetching!==void 0&&(V.status.returnedStale=!0),O.__staleWhileFetching;if(O.__returned===O)throw U},j=(U,w)=>{let A=this.#C?.(X,J,K);A&&A instanceof Promise&&A.then((L)=>U(L===void 0?void 0:L),w),z.signal.addEventListener("abort",()=>{(!V.ignoreFetchAbort||V.allowStaleOnFetchAbort)&&(U(void 0),V.allowStaleOnFetchAbort&&(U=(L)=>H(L,!0)))})};V.status&&(V.status.fetchDispatched=!0);let _=new Promise(j).then(H,q),G=Object.assign(_,{__abortController:z,__staleWhileFetching:J,__returned:void 0});return Z===void 0?(this.set(X,G,{...K.options,status:void 0}),Z=this.#q.get(X)):this.#J[Z]=G,G}#H(X){if(!this.#N)return!1;let Z=X;return!!Z&&Z instanceof Promise&&Z.hasOwnProperty("__staleWhileFetching")&&Z.__abortController instanceof Z6}async fetch(X,Z={}){let{allowStale:V=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:J=this.noDeleteOnStaleGet,ttl:z=this.ttl,noDisposeOnSet:Y=this.noDisposeOnSet,size:K=0,sizeCalculation:H=this.sizeCalculation,noUpdateTTL:q=this.noUpdateTTL,noDeleteOnFetchRejection:W=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:j=this.allowStaleOnFetchRejection,ignoreFetchAbort:_=this.ignoreFetchAbort,allowStaleOnFetchAbort:G=this.allowStaleOnFetchAbort,context:U,forceRefresh:w=!1,status:A,signal:L}=Z;if(!this.#N)return A&&(A.fetch="get"),this.get(X,{allowStale:V,updateAgeOnGet:$,noDeleteOnStaleGet:J,status:A});let v={allowStale:V,updateAgeOnGet:$,noDeleteOnStaleGet:J,ttl:z,noDisposeOnSet:Y,size:K,sizeCalculation:H,noUpdateTTL:q,noDeleteOnFetchRejection:W,allowStaleOnFetchRejection:j,allowStaleOnFetchAbort:G,ignoreFetchAbort:_,status:A,signal:L},F=this.#q.get(X);if(F===void 0){A&&(A.fetch="miss");let O=this.#d(X,F,v,U);return O.__returned=O}else{let O=this.#J[F];if(this.#H(O)){let P=V&&O.__staleWhileFetching!==void 0;return A&&(A.fetch="inflight",P&&(A.returnedStale=!0)),P?O.__staleWhileFetching:O.__returned=O}let k=this.#R(F);if(!w&&!k)return A&&(A.fetch="hit"),this.#y(F),$&&this.#D(F),A&&this.#k(A,F),O;let b=this.#d(X,F,v,U),s=b.__staleWhileFetching!==void 0&&V;return A&&(A.fetch=k?"stale":"refresh",s&&k&&(A.returnedStale=!0)),s?b.__staleWhileFetching:b.__returned=b}}async forceFetch(X,Z={}){let V=await this.fetch(X,Z);if(V===void 0)throw Error("fetch() returned undefined");return V}memo(X,Z={}){let V=this.#L;if(!V)throw Error("no memoMethod provided to constructor");let{context:$,forceRefresh:J,...z}=Z,Y=this.get(X,z);if(!J&&Y!==void 0)return Y;let K=V(X,Y,{options:z,context:$});return this.set(X,K,z),K}get(X,Z={}){let{allowStale:V=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:J=this.noDeleteOnStaleGet,status:z}=Z,Y=this.#q.get(X);if(Y!==void 0){let K=this.#J[Y],H=this.#H(K);return z&&this.#k(z,Y),this.#R(Y)?(z&&(z.get="stale"),H?(z&&V&&K.__staleWhileFetching!==void 0&&(z.returnedStale=!0),V?K.__staleWhileFetching:void 0):(J||this.#x(X,"expire"),z&&V&&(z.returnedStale=!0),V?K:void 0)):(z&&(z.get="hit"),H?K.__staleWhileFetching:(this.#y(Y),$&&this.#D(Y),K))}else z&&(z.get="miss")}#c(X,Z){this.#v[Z]=X,this.#B[X]=Z}#y(X){X!==this.#U&&(X===this.#G?this.#G=this.#B[X]:this.#c(this.#v[X],this.#B[X]),this.#c(this.#U,X),this.#U=X)}delete(X){return this.#x(X,"delete")}#x(X,Z){let V=!1;if(this.#Y!==0){let $=this.#q.get(X);if($!==void 0)if(this.#w?.[$]&&(clearTimeout(this.#w?.[$]),this.#w[$]=void 0),V=!0,this.#Y===1)this.#p(Z);else{this.#f($);let J=this.#J[$];if(this.#H(J)?J.__abortController.abort(Error("deleted")):(this.#O||this.#Z)&&(this.#O&&this.#$?.(J,X,Z),this.#Z&&this.#A?.push([J,X,Z])),this.#q.delete(X),this.#K[$]=void 0,this.#J[$]=void 0,$===this.#U)this.#U=this.#v[$];else if($===this.#G)this.#G=this.#B[$];else{let z=this.#v[$];this.#B[z]=this.#B[$];let Y=this.#B[$];this.#v[Y]=this.#v[$]}this.#Y--,this.#P.push($)}}if(this.#Z&&this.#A?.length){let $=this.#A,J;for(;J=$?.shift();)this.#z?.(...J)}return V}clear(){return this.#p("delete")}#p(X){for(let Z of this.#S({allowStale:!0})){let V=this.#J[Z];if(this.#H(V))V.__abortController.abort(Error("deleted"));else{let $=this.#K[Z];this.#O&&this.#$?.(V,$,X),this.#Z&&this.#A?.push([V,$,X])}}if(this.#q.clear(),this.#J.fill(void 0),this.#K.fill(void 0),this.#_&&this.#M){this.#_.fill(0),this.#M.fill(0);for(let Z of this.#w??[])Z!==void 0&&clearTimeout(Z);this.#w?.fill(void 0)}if(this.#F&&this.#F.fill(0),this.#G=0,this.#U=0,this.#P.length=0,this.#j=0,this.#Y=0,this.#Z&&this.#A){let Z=this.#A,V;for(;V=Z?.shift();)this.#z?.(...V)}}};import{posix as Y0,win32 as l6}from"path";import{fileURLToPath as K0}from"url";import{lstatSync as H0,readdir as q0,readdirSync as W0,readlinkSync as j0,realpathSync as _0}from"fs";import*as G0 from"fs";import{lstat as A0,readdir as w0,readlink as L0,realpath as B0}from"fs/promises";import{EventEmitter as g6}from"events";import u7 from"stream";import{StringDecoder as s9}from"string_decoder";var E7=typeof process==="object"&&process?process:{stdout:null,stderr:null},t9=(Q)=>!!Q&&typeof Q==="object"&&(Q instanceof B5||Q instanceof u7||e9(Q)||Q0(Q)),e9=(Q)=>!!Q&&typeof Q==="object"&&Q instanceof g6&&typeof Q.pipe==="function"&&Q.pipe!==u7.Writable.prototype.pipe,Q0=(Q)=>!!Q&&typeof Q==="object"&&Q instanceof g6&&typeof Q.write==="function"&&typeof Q.end==="function",W5=Symbol("EOF"),j5=Symbol("maybeEmitEnd"),U5=Symbol("emittedEnd"),V6=Symbol("emittingEnd"),h5=Symbol("emittedError"),$6=Symbol("closed"),b7=Symbol("read"),J6=Symbol("flush"),y7=Symbol("flushChunk"),a=Symbol("encoding"),R5=Symbol("decoder"),x=Symbol("flowing"),g5=Symbol("paused"),P5=Symbol("resume"),I=Symbol("buffer"),f=Symbol("pipes"),S=Symbol("bufferLength"),b6=Symbol("bufferPush"),z6=Symbol("bufferShift"),E=Symbol("objectMode"),D=Symbol("destroyed"),y6=Symbol("error"),f6=Symbol("emitData"),f7=Symbol("emitEnd"),u6=Symbol("emitEnd2"),Z5=Symbol("async"),h6=Symbol("abort"),Y6=Symbol("aborted"),m5=Symbol("signal"),L5=Symbol("dataListeners"),g=Symbol("discarded"),d5=(Q)=>Promise.resolve().then(Q),X0=(Q)=>Q(),Z0=(Q)=>Q==="end"||Q==="finish"||Q==="prefinish",V0=(Q)=>Q instanceof ArrayBuffer||!!Q&&typeof Q==="object"&&Q.constructor&&Q.constructor.name==="ArrayBuffer"&&Q.byteLength>=0,$0=(Q)=>!Buffer.isBuffer(Q)&&ArrayBuffer.isView(Q);class m6{src;dest;opts;ondrain;constructor(Q,X,Z){this.src=Q,this.dest=X,this.opts=Z,this.ondrain=()=>Q[P5](),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 h7 extends m6{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(Q,X,Z){super(Q,X,Z);this.proxyErrors=(V)=>this.dest.emit("error",V),Q.on("error",this.proxyErrors)}}var J0=(Q)=>!!Q.objectMode,z0=(Q)=>!Q.objectMode&&!!Q.encoding&&Q.encoding!=="buffer";class B5 extends g6{[x]=!1;[g5]=!1;[f]=[];[I]=[];[E];[a];[Z5];[R5];[W5]=!1;[U5]=!1;[V6]=!1;[$6]=!1;[h5]=null;[S]=0;[D]=!1;[m5];[Y6]=!1;[L5]=0;[g]=!1;writable=!0;readable=!0;constructor(...Q){let X=Q[0]||{};super();if(X.objectMode&&typeof X.encoding==="string")throw TypeError("Encoding and objectMode may not be used together");if(J0(X))this[E]=!0,this[a]=null;else if(z0(X))this[a]=X.encoding,this[E]=!1;else this[E]=!1,this[a]=null;if(this[Z5]=!!X.async,this[R5]=this[a]?new s9(this[a]):null,X&&X.debugExposeBuffer===!0)Object.defineProperty(this,"buffer",{get:()=>this[I]});if(X&&X.debugExposePipes===!0)Object.defineProperty(this,"pipes",{get:()=>this[f]});let{signal:Z}=X;if(Z)if(this[m5]=Z,Z.aborted)this[h6]();else Z.addEventListener("abort",()=>this[h6]())}get bufferLength(){return this[S]}get encoding(){return this[a]}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[E]}set objectMode(Q){throw Error("objectMode must be set at instantiation time")}get["async"](){return this[Z5]}set["async"](Q){this[Z5]=this[Z5]||!!Q}[h6](){this[Y6]=!0,this.emit("abort",this[m5]?.reason),this.destroy(this[m5]?.reason)}get aborted(){return this[Y6]}set aborted(Q){}write(Q,X,Z){if(this[Y6])return!1;if(this[W5])throw Error("write after end");if(this[D])return this.emit("error",Object.assign(Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof X==="function")Z=X,X="utf8";if(!X)X="utf8";let V=this[Z5]?d5:X0;if(!this[E]&&!Buffer.isBuffer(Q)){if($0(Q))Q=Buffer.from(Q.buffer,Q.byteOffset,Q.byteLength);else if(V0(Q))Q=Buffer.from(Q);else if(typeof Q!=="string")throw Error("Non-contiguous data written to non-objectMode stream")}if(this[E]){if(this[x]&&this[S]!==0)this[J6](!0);if(this[x])this.emit("data",Q);else this[b6](Q);if(this[S]!==0)this.emit("readable");if(Z)V(Z);return this[x]}if(!Q.length){if(this[S]!==0)this.emit("readable");if(Z)V(Z);return this[x]}if(typeof Q==="string"&&!(X===this[a]&&!this[R5]?.lastNeed))Q=Buffer.from(Q,X);if(Buffer.isBuffer(Q)&&this[a])Q=this[R5].write(Q);if(this[x]&&this[S]!==0)this[J6](!0);if(this[x])this.emit("data",Q);else this[b6](Q);if(this[S]!==0)this.emit("readable");if(Z)V(Z);return this[x]}read(Q){if(this[D])return null;if(this[g]=!1,this[S]===0||Q===0||Q&&Q>this[S])return this[j5](),null;if(this[E])Q=null;if(this[I].length>1&&!this[E])this[I]=[this[a]?this[I].join(""):Buffer.concat(this[I],this[S])];let X=this[b7](Q||null,this[I][0]);return this[j5](),X}[b7](Q,X){if(this[E])this[z6]();else{let Z=X;if(Q===Z.length||Q===null)this[z6]();else if(typeof Z==="string")this[I][0]=Z.slice(Q),X=Z.slice(0,Q),this[S]-=Q;else this[I][0]=Z.subarray(Q),X=Z.subarray(0,Q),this[S]-=Q}if(this.emit("data",X),!this[I].length&&!this[W5])this.emit("drain");return X}end(Q,X,Z){if(typeof Q==="function")Z=Q,Q=void 0;if(typeof X==="function")Z=X,X="utf8";if(Q!==void 0)this.write(Q,X);if(Z)this.once("end",Z);if(this[W5]=!0,this.writable=!1,this[x]||!this[g5])this[j5]();return this}[P5](){if(this[D])return;if(!this[L5]&&!this[f].length)this[g]=!0;if(this[g5]=!1,this[x]=!0,this.emit("resume"),this[I].length)this[J6]();else if(this[W5])this[j5]();else this.emit("drain")}resume(){return this[P5]()}pause(){this[x]=!1,this[g5]=!0,this[g]=!1}get destroyed(){return this[D]}get flowing(){return this[x]}get paused(){return this[g5]}[b6](Q){if(this[E])this[S]+=1;else this[S]+=Q.length;this[I].push(Q)}[z6](){if(this[E])this[S]-=1;else this[S]-=this[I][0].length;return this[I].shift()}[J6](Q=!1){do;while(this[y7](this[z6]())&&this[I].length);if(!Q&&!this[I].length&&!this[W5])this.emit("drain")}[y7](Q){return this.emit("data",Q),this[x]}pipe(Q,X){if(this[D])return Q;this[g]=!1;let Z=this[U5];if(X=X||{},Q===E7.stdout||Q===E7.stderr)X.end=!1;else X.end=X.end!==!1;if(X.proxyErrors=!!X.proxyErrors,Z){if(X.end)Q.end()}else if(this[f].push(!X.proxyErrors?new m6(this,Q,X):new h7(this,Q,X)),this[Z5])d5(()=>this[P5]());else this[P5]();return Q}unpipe(Q){let X=this[f].find((Z)=>Z.dest===Q);if(X){if(this[f].length===1){if(this[x]&&this[L5]===0)this[x]=!1;this[f]=[]}else this[f].splice(this[f].indexOf(X),1);X.unpipe()}}addListener(Q,X){return this.on(Q,X)}on(Q,X){let Z=super.on(Q,X);if(Q==="data"){if(this[g]=!1,this[L5]++,!this[f].length&&!this[x])this[P5]()}else if(Q==="readable"&&this[S]!==0)super.emit("readable");else if(Z0(Q)&&this[U5])super.emit(Q),this.removeAllListeners(Q);else if(Q==="error"&&this[h5]){let V=X;if(this[Z5])d5(()=>V.call(this,this[h5]));else V.call(this,this[h5])}return Z}removeListener(Q,X){return this.off(Q,X)}off(Q,X){let Z=super.off(Q,X);if(Q==="data"){if(this[L5]=this.listeners("data").length,this[L5]===0&&!this[g]&&!this[f].length)this[x]=!1}return Z}removeAllListeners(Q){let X=super.removeAllListeners(Q);if(Q==="data"||Q===void 0){if(this[L5]=0,!this[g]&&!this[f].length)this[x]=!1}return X}get emittedEnd(){return this[U5]}[j5](){if(!this[V6]&&!this[U5]&&!this[D]&&this[I].length===0&&this[W5]){if(this[V6]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[$6])this.emit("close");this[V6]=!1}}emit(Q,...X){let Z=X[0];if(Q!=="error"&&Q!=="close"&&Q!==D&&this[D])return!1;else if(Q==="data")return!this[E]&&!Z?!1:this[Z5]?(d5(()=>this[f6](Z)),!0):this[f6](Z);else if(Q==="end")return this[f7]();else if(Q==="close"){if(this[$6]=!0,!this[U5]&&!this[D])return!1;let $=super.emit("close");return this.removeAllListeners("close"),$}else if(Q==="error"){this[h5]=Z,super.emit(y6,Z);let $=!this[m5]||this.listeners("error").length?super.emit("error",Z):!1;return this[j5](),$}else if(Q==="resume"){let $=super.emit("resume");return this[j5](),$}else if(Q==="finish"||Q==="prefinish"){let $=super.emit(Q);return this.removeAllListeners(Q),$}let V=super.emit(Q,...X);return this[j5](),V}[f6](Q){for(let Z of this[f])if(Z.dest.write(Q)===!1)this.pause();let X=this[g]?!1:super.emit("data",Q);return this[j5](),X}[f7](){if(this[U5])return!1;return this[U5]=!0,this.readable=!1,this[Z5]?(d5(()=>this[u6]()),!0):this[u6]()}[u6](){if(this[R5]){let X=this[R5].end();if(X){for(let Z of this[f])Z.dest.write(X);if(!this[g])super.emit("data",X)}}for(let X of this[f])X.end();let Q=super.emit("end");return this.removeAllListeners("end"),Q}async collect(){let Q=Object.assign([],{dataLength:0});if(!this[E])Q.dataLength=0;let X=this.promise();return this.on("data",(Z)=>{if(Q.push(Z),!this[E])Q.dataLength+=Z.length}),await X,Q}async concat(){if(this[E])throw Error("cannot concat in objectMode");let Q=await this.collect();return this[a]?Q.join(""):Buffer.concat(Q,Q.dataLength)}async promise(){return new Promise((Q,X)=>{this.on(D,()=>X(Error("stream destroyed"))),this.on("error",(Z)=>X(Z)),this.on("end",()=>Q())})}[Symbol.asyncIterator](){this[g]=!1;let Q=!1,X=async()=>{return this.pause(),Q=!0,{value:void 0,done:!0}};return{next:()=>{if(Q)return X();let V=this.read();if(V!==null)return Promise.resolve({done:!1,value:V});if(this[W5])return X();let $,J,z=(q)=>{this.off("data",Y),this.off("end",K),this.off(D,H),X(),J(q)},Y=(q)=>{this.off("error",z),this.off("end",K),this.off(D,H),this.pause(),$({value:q,done:!!this[W5]})},K=()=>{this.off("error",z),this.off("data",Y),this.off(D,H),X(),$({done:!0,value:void 0})},H=()=>z(Error("stream destroyed"));return new Promise((q,W)=>{J=W,$=q,this.once(D,H),this.once("error",z),this.once("end",K),this.once("data",Y)})},throw:X,return:X,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[g]=!1;let Q=!1,X=()=>{return this.pause(),this.off(y6,X),this.off(D,X),this.off("end",X),Q=!0,{done:!0,value:void 0}},Z=()=>{if(Q)return X();let V=this.read();return V===null?X():{done:!1,value:V}};return this.once("end",X),this.once(y6,X),this.once(D,X),{next:Z,throw:X,return:X,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(Q){if(this[D]){if(Q)this.emit("error",Q);else this.emit(D);return this}this[D]=!0,this[g]=!0,this[I].length=0,this[S]=0;let X=this;if(typeof X.close==="function"&&!this[$6])X.close();if(Q)this.emit("error",Q);else this.emit(D);return this}static get isStream(){return t9}}var U0=_0.native,l5={lstatSync:H0,readdir:q0,readdirSync:W0,readlinkSync:j0,realpathSync:U0,promises:{lstat:A0,readdir:w0,readlink:L0,realpath:B0}},l7=(Q)=>!Q||Q===l5||Q===G0?l5:{...l5,...Q,promises:{...l5.promises,...Q.promises||{}}},p7=/^\\\\\?\\([a-z]:)\\?$/i,O0=(Q)=>Q.replace(/\//g,"\\").replace(p7,"$1\\"),v0=/[\\\/]/,p=0,i7=1,n7=2,V5=4,o7=6,a7=8,O5=10,r7=12,l=15,c5=~l,d6=16,g7=32,p5=64,r=128,K6=256,q6=512,m7=p5|r|q6,F0=1023,c6=(Q)=>Q.isFile()?a7:Q.isDirectory()?V5:Q.isSymbolicLink()?O5:Q.isCharacterDevice()?n7:Q.isBlockDevice()?o7:Q.isSocket()?r7:Q.isFIFO()?i7:p,d7=new u5({max:4096}),i5=(Q)=>{let X=d7.get(Q);if(X)return X;let Z=Q.normalize("NFKD");return d7.set(Q,Z),Z},c7=new u5({max:4096}),H6=(Q)=>{let X=c7.get(Q);if(X)return X;let Z=i5(Q.toLowerCase());return c7.set(Q,Z),Z};class p6 extends u5{constructor(){super({max:256})}}class s7 extends u5{constructor(Q=16384){super({maxSize:Q,sizeCalculation:(X)=>X.length+1})}}var t7=Symbol("PathScurry setAsCwd");class u{name;root;roots;parent;nocase;isCWD=!1;#Q;#V;get dev(){return this.#V}#$;get mode(){return this.#$}#X;get nlink(){return this.#X}#z;get uid(){return this.#z}#C;get gid(){return this.#C}#L;get rdev(){return this.#L}#W;get blksize(){return this.#W}#Y;get ino(){return this.#Y}#j;get size(){return this.#j}#q;get blocks(){return this.#q}#K;get atimeMs(){return this.#K}#J;get mtimeMs(){return this.#J}#B;get ctimeMs(){return this.#B}#v;get birthtimeMs(){return this.#v}#G;get atime(){return this.#G}#U;get mtime(){return this.#U}#P;get ctime(){return this.#P}#A;get birthtime(){return this.#A}#F;#M;#_;#w;#O;#N;#Z;#E;#T;#D;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(Q,X=p,Z,V,$,J,z){if(this.name=Q,this.#F=$?H6(Q):i5(Q),this.#Z=X&F0,this.nocase=$,this.roots=V,this.root=Z||this,this.#E=J,this.#_=z.fullpath,this.#O=z.relative,this.#N=z.relativePosix,this.parent=z.parent,this.parent)this.#Q=this.parent.#Q;else this.#Q=l7(z.fs)}depth(){if(this.#M!==void 0)return this.#M;if(!this.parent)return this.#M=0;return this.#M=this.parent.depth()+1}childrenCache(){return this.#E}resolve(Q){if(!Q)return this;let X=this.getRootString(Q),V=Q.substring(X.length).split(this.splitSep);return X?this.getRoot(X).#k(V):this.#k(V)}#k(Q){let X=this;for(let Z of Q)X=X.child(Z);return X}children(){let Q=this.#E.get(this);if(Q)return Q;let X=Object.assign([],{provisional:0});return this.#E.set(this,X),this.#Z&=~d6,X}child(Q,X){if(Q===""||Q===".")return this;if(Q==="..")return this.parent||this;let Z=this.children(),V=this.nocase?H6(Q):i5(Q);for(let Y of Z)if(Y.#F===V)return Y;let $=this.parent?this.sep:"",J=this.#_?this.#_+$+Q:void 0,z=this.newChild(Q,p,{...X,parent:this,fullpath:J});if(!this.canReaddir())z.#Z|=r;return Z.push(z),z}relative(){if(this.isCWD)return"";if(this.#O!==void 0)return this.#O;let Q=this.name,X=this.parent;if(!X)return this.#O=this.name;let Z=X.relative();return Z+(!Z||!X.parent?"":this.sep)+Q}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#N!==void 0)return this.#N;let Q=this.name,X=this.parent;if(!X)return this.#N=this.fullpathPosix();let Z=X.relativePosix();return Z+(!Z||!X.parent?"":"/")+Q}fullpath(){if(this.#_!==void 0)return this.#_;let Q=this.name,X=this.parent;if(!X)return this.#_=this.name;let V=X.fullpath()+(!X.parent?"":this.sep)+Q;return this.#_=V}fullpathPosix(){if(this.#w!==void 0)return this.#w;if(this.sep==="/")return this.#w=this.fullpath();if(!this.parent){let V=this.fullpath().replace(/\\/g,"/");if(/^[a-z]:\//i.test(V))return this.#w=`//?/${V}`;else return this.#w=V}let Q=this.parent,X=Q.fullpathPosix(),Z=X+(!X||!Q.parent?"":"/")+this.name;return this.#w=Z}isUnknown(){return(this.#Z&l)===p}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.#Z&l)===a7}isDirectory(){return(this.#Z&l)===V5}isCharacterDevice(){return(this.#Z&l)===n7}isBlockDevice(){return(this.#Z&l)===o7}isFIFO(){return(this.#Z&l)===i7}isSocket(){return(this.#Z&l)===r7}isSymbolicLink(){return(this.#Z&O5)===O5}lstatCached(){return this.#Z&g7?this:void 0}readlinkCached(){return this.#T}realpathCached(){return this.#D}readdirCached(){let Q=this.children();return Q.slice(0,Q.provisional)}canReadlink(){if(this.#T)return!0;if(!this.parent)return!1;let Q=this.#Z&l;return!(Q!==p&&Q!==O5||this.#Z&K6||this.#Z&r)}calledReaddir(){return!!(this.#Z&d6)}isENOENT(){return!!(this.#Z&r)}isNamed(Q){return!this.nocase?this.#F===i5(Q):this.#F===H6(Q)}async readlink(){let Q=this.#T;if(Q)return Q;if(!this.canReadlink())return;if(!this.parent)return;try{let X=await this.#Q.promises.readlink(this.fullpath()),Z=(await this.parent.realpath())?.resolve(X);if(Z)return this.#T=Z}catch(X){this.#S(X.code);return}}readlinkSync(){let Q=this.#T;if(Q)return Q;if(!this.canReadlink())return;if(!this.parent)return;try{let X=this.#Q.readlinkSync(this.fullpath()),Z=this.parent.realpathSync()?.resolve(X);if(Z)return this.#T=Z}catch(X){this.#S(X.code);return}}#u(Q){this.#Z|=d6;for(let X=Q.provisional;X<Q.length;X++){let Z=Q[X];if(Z)Z.#R()}}#R(){if(this.#Z&r)return;this.#Z=(this.#Z|r)&c5,this.#l()}#l(){let Q=this.children();Q.provisional=0;for(let X of Q)X.#R()}#f(){this.#Z|=q6,this.#b()}#b(){if(this.#Z&p5)return;let Q=this.#Z;if((Q&l)===V5)Q&=c5;this.#Z=Q|p5,this.#l()}#h(Q=""){if(Q==="ENOTDIR"||Q==="EPERM")this.#b();else if(Q==="ENOENT")this.#R();else this.children().provisional=0}#I(Q=""){if(Q==="ENOTDIR")this.parent.#b();else if(Q==="ENOENT")this.#R()}#S(Q=""){let X=this.#Z;if(X|=K6,Q==="ENOENT")X|=r;if(Q==="EINVAL"||Q==="UNKNOWN")X&=c5;if(this.#Z=X,Q==="ENOTDIR"&&this.parent)this.parent.#b()}#g(Q,X){return this.#d(Q,X)||this.#m(Q,X)}#m(Q,X){let Z=c6(Q),V=this.newChild(Q.name,Z,{parent:this}),$=V.#Z&l;if($!==V5&&$!==O5&&$!==p)V.#Z|=p5;return X.unshift(V),X.provisional++,V}#d(Q,X){for(let Z=X.provisional;Z<X.length;Z++){let V=X[Z];if((this.nocase?H6(Q.name):i5(Q.name))!==V.#F)continue;return this.#H(Q,V,Z,X)}}#H(Q,X,Z,V){let $=X.name;if(X.#Z=X.#Z&c5|c6(Q),$!==Q.name)X.name=Q.name;if(Z!==V.provisional){if(Z===V.length-1)V.pop();else V.splice(Z,1);V.unshift(X)}return V.provisional++,X}async lstat(){if((this.#Z&r)===0)try{return this.#c(await this.#Q.promises.lstat(this.fullpath())),this}catch(Q){this.#I(Q.code)}}lstatSync(){if((this.#Z&r)===0)try{return this.#c(this.#Q.lstatSync(this.fullpath())),this}catch(Q){this.#I(Q.code)}}#c(Q){let{atime:X,atimeMs:Z,birthtime:V,birthtimeMs:$,blksize:J,blocks:z,ctime:Y,ctimeMs:K,dev:H,gid:q,ino:W,mode:j,mtime:_,mtimeMs:G,nlink:U,rdev:w,size:A,uid:L}=Q;this.#G=X,this.#K=Z,this.#A=V,this.#v=$,this.#W=J,this.#q=z,this.#P=Y,this.#B=K,this.#V=H,this.#C=q,this.#Y=W,this.#$=j,this.#U=_,this.#J=G,this.#X=U,this.#L=w,this.#j=A,this.#z=L;let v=c6(Q);if(this.#Z=this.#Z&c5|v|g7,v!==p&&v!==V5&&v!==O5)this.#Z|=p5}#y=[];#x=!1;#p(Q){this.#x=!1;let X=this.#y.slice();this.#y.length=0,X.forEach((Z)=>Z(null,Q))}readdirCB(Q,X=!1){if(!this.canReaddir()){if(X)Q(null,[]);else queueMicrotask(()=>Q(null,[]));return}let Z=this.children();if(this.calledReaddir()){let $=Z.slice(0,Z.provisional);if(X)Q(null,$);else queueMicrotask(()=>Q(null,$));return}if(this.#y.push(Q),this.#x)return;this.#x=!0;let V=this.fullpath();this.#Q.readdir(V,{withFileTypes:!0},($,J)=>{if($)this.#h($.code),Z.provisional=0;else{for(let z of J)this.#g(z,Z);this.#u(Z)}this.#p(Z.slice(0,Z.provisional));return})}#i;async readdir(){if(!this.canReaddir())return[];let Q=this.children();if(this.calledReaddir())return Q.slice(0,Q.provisional);let X=this.fullpath();if(this.#i)await this.#i;else{let Z=()=>{};this.#i=new Promise((V)=>Z=V);try{for(let V of await this.#Q.promises.readdir(X,{withFileTypes:!0}))this.#g(V,Q);this.#u(Q)}catch(V){this.#h(V.code),Q.provisional=0}this.#i=void 0,Z()}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 X=this.fullpath();try{for(let Z of this.#Q.readdirSync(X,{withFileTypes:!0}))this.#g(Z,Q);this.#u(Q)}catch(Z){this.#h(Z.code),Q.provisional=0}return Q.slice(0,Q.provisional)}canReaddir(){if(this.#Z&m7)return!1;let Q=l&this.#Z;if(!(Q===p||Q===V5||Q===O5))return!1;return!0}shouldWalk(Q,X){return(this.#Z&V5)===V5&&!(this.#Z&m7)&&!Q.has(this)&&(!X||X(this))}async realpath(){if(this.#D)return this.#D;if((q6|K6|r)&this.#Z)return;try{let Q=await this.#Q.promises.realpath(this.fullpath());return this.#D=this.resolve(Q)}catch(Q){this.#f()}}realpathSync(){if(this.#D)return this.#D;if((q6|K6|r)&this.#Z)return;try{let Q=this.#Q.realpathSync(this.fullpath());return this.#D=this.resolve(Q)}catch(Q){this.#f()}}[t7](Q){if(Q===this)return;Q.isCWD=!1,this.isCWD=!0;let X=new Set([]),Z=[],V=this;while(V&&V.parent)X.add(V),V.#O=Z.join(this.sep),V.#N=Z.join("/"),V=V.parent,Z.push("..");V=Q;while(V&&V.parent&&!X.has(V))V.#O=void 0,V.#N=void 0,V=V.parent}}class W6 extends u{sep="\\";splitSep=v0;constructor(Q,X=p,Z,V,$,J,z){super(Q,X,Z,V,$,J,z)}newChild(Q,X=p,Z={}){return new W6(Q,X,this.root,this.roots,this.nocase,this.childrenCache(),Z)}getRootString(Q){return l6.parse(Q).root}getRoot(Q){if(Q=O0(Q.toUpperCase()),Q===this.root.name)return this.root;for(let[X,Z]of Object.entries(this.roots))if(this.sameRoot(Q,X))return this.roots[Q]=Z;return this.roots[Q]=new n5(Q,this).root}sameRoot(Q,X=this.root.name){return Q=Q.toUpperCase().replace(/\//g,"\\").replace(p7,"$1\\"),Q===X}}class j6 extends u{splitSep="/";sep="/";constructor(Q,X=p,Z,V,$,J,z){super(Q,X,Z,V,$,J,z)}getRootString(Q){return Q.startsWith("/")?"/":""}getRoot(Q){return this.root}newChild(Q,X=p,Z={}){return new j6(Q,X,this.root,this.roots,this.nocase,this.childrenCache(),Z)}}class i6{root;rootPath;roots;cwd;#Q;#V;#$;nocase;#X;constructor(Q=process.cwd(),X,Z,{nocase:V,childrenCacheSize:$=16384,fs:J=l5}={}){if(this.#X=l7(J),Q instanceof URL||Q.startsWith("file://"))Q=K0(Q);let z=X.resolve(Q);this.roots=Object.create(null),this.rootPath=this.parseRootPath(z),this.#Q=new p6,this.#V=new p6,this.#$=new s7($);let Y=z.substring(this.rootPath.length).split(Z);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.#X),this.roots[this.rootPath]=this.root;let K=this.root,H=Y.length-1,q=X.sep,W=this.rootPath,j=!1;for(let _ of Y){let G=H--;K=K.child(_,{relative:Array(G).fill("..").join(q),relativePosix:Array(G).fill("..").join("/"),fullpath:W+=(j?"":q)+_}),j=!0}this.cwd=K}depth(Q=this.cwd){if(typeof Q==="string")Q=this.cwd.resolve(Q);return Q.depth()}childrenCache(){return this.#$}resolve(...Q){let X="";for(let $=Q.length-1;$>=0;$--){let J=Q[$];if(!J||J===".")continue;if(X=X?`${J}/${X}`:J,this.isAbsolute(J))break}let Z=this.#Q.get(X);if(Z!==void 0)return Z;let V=this.cwd.resolve(X).fullpath();return this.#Q.set(X,V),V}resolvePosix(...Q){let X="";for(let $=Q.length-1;$>=0;$--){let J=Q[$];if(!J||J===".")continue;if(X=X?`${J}/${X}`:J,this.isAbsolute(J))break}let Z=this.#V.get(X);if(Z!==void 0)return Z;let V=this.cwd.resolve(X).fullpathPosix();return this.#V.set(X,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,X={withFileTypes:!0}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q,Q=this.cwd;let{withFileTypes:Z}=X;if(!Q.canReaddir())return[];else{let V=await Q.readdir();return Z?V:V.map(($)=>$.name)}}readdirSync(Q=this.cwd,X={withFileTypes:!0}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q,Q=this.cwd;let{withFileTypes:Z=!0}=X;if(!Q.canReaddir())return[];else if(Z)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:X}={withFileTypes:!1}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q.withFileTypes,Q=this.cwd;let Z=await Q.readlink();return X?Z:Z?.fullpath()}readlinkSync(Q=this.cwd,{withFileTypes:X}={withFileTypes:!1}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q.withFileTypes,Q=this.cwd;let Z=Q.readlinkSync();return X?Z:Z?.fullpath()}async realpath(Q=this.cwd,{withFileTypes:X}={withFileTypes:!1}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q.withFileTypes,Q=this.cwd;let Z=await Q.realpath();return X?Z:Z?.fullpath()}realpathSync(Q=this.cwd,{withFileTypes:X}={withFileTypes:!1}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q.withFileTypes,Q=this.cwd;let Z=Q.realpathSync();return X?Z:Z?.fullpath()}async walk(Q=this.cwd,X={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q,Q=this.cwd;let{withFileTypes:Z=!0,follow:V=!1,filter:$,walkFilter:J}=X,z=[];if(!$||$(Q))z.push(Z?Q:Q.fullpath());let Y=new Set,K=(q,W)=>{Y.add(q),q.readdirCB((j,_)=>{if(j)return W(j);let G=_.length;if(!G)return W();let U=()=>{if(--G===0)W()};for(let w of _){if(!$||$(w))z.push(Z?w:w.fullpath());if(V&&w.isSymbolicLink())w.realpath().then((A)=>A?.isUnknown()?A.lstat():A).then((A)=>A?.shouldWalk(Y,J)?K(A,U):U());else if(w.shouldWalk(Y,J))K(w,U);else U()}},!0)},H=Q;return new Promise((q,W)=>{K(H,(j)=>{if(j)return W(j);q(z)})})}walkSync(Q=this.cwd,X={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q,Q=this.cwd;let{withFileTypes:Z=!0,follow:V=!1,filter:$,walkFilter:J}=X,z=[];if(!$||$(Q))z.push(Z?Q:Q.fullpath());let Y=new Set([Q]);for(let K of Y){let H=K.readdirSync();for(let q of H){if(!$||$(q))z.push(Z?q:q.fullpath());let W=q;if(q.isSymbolicLink()){if(!(V&&(W=q.realpathSync())))continue;if(W.isUnknown())W.lstatSync()}if(W.shouldWalk(Y,J))Y.add(W)}}return z}[Symbol.asyncIterator](){return this.iterate()}iterate(Q=this.cwd,X={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q,Q=this.cwd;return this.stream(Q,X)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(Q=this.cwd,X={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q,Q=this.cwd;let{withFileTypes:Z=!0,follow:V=!1,filter:$,walkFilter:J}=X;if(!$||$(Q))yield Z?Q:Q.fullpath();let z=new Set([Q]);for(let Y of z){let K=Y.readdirSync();for(let H of K){if(!$||$(H))yield Z?H:H.fullpath();let q=H;if(H.isSymbolicLink()){if(!(V&&(q=H.realpathSync())))continue;if(q.isUnknown())q.lstatSync()}if(q.shouldWalk(z,J))z.add(q)}}}stream(Q=this.cwd,X={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q,Q=this.cwd;let{withFileTypes:Z=!0,follow:V=!1,filter:$,walkFilter:J}=X,z=new B5({objectMode:!0});if(!$||$(Q))z.write(Z?Q:Q.fullpath());let Y=new Set,K=[Q],H=0,q=()=>{let W=!1;while(!W){let j=K.shift();if(!j){if(H===0)z.end();return}H++,Y.add(j);let _=(U,w,A=!1)=>{if(U)return z.emit("error",U);if(V&&!A){let L=[];for(let v of w)if(v.isSymbolicLink())L.push(v.realpath().then((F)=>F?.isUnknown()?F.lstat():F));if(L.length){Promise.all(L).then(()=>_(null,w,!0));return}}for(let L of w)if(L&&(!$||$(L))){if(!z.write(Z?L:L.fullpath()))W=!0}H--;for(let L of w){let v=L.realpathCached()||L;if(v.shouldWalk(Y,J))K.push(v)}if(W&&!z.flowing)z.once("drain",q);else if(!G)q()},G=!0;j.readdirCB(_,!0),G=!1}};return q(),z}streamSync(Q=this.cwd,X={}){if(typeof Q==="string")Q=this.cwd.resolve(Q);else if(!(Q instanceof u))X=Q,Q=this.cwd;let{withFileTypes:Z=!0,follow:V=!1,filter:$,walkFilter:J}=X,z=new B5({objectMode:!0}),Y=new Set;if(!$||$(Q))z.write(Z?Q:Q.fullpath());let K=[Q],H=0,q=()=>{let W=!1;while(!W){let j=K.shift();if(!j){if(H===0)z.end();return}H++,Y.add(j);let _=j.readdirSync();for(let G of _)if(!$||$(G)){if(!z.write(Z?G:G.fullpath()))W=!0}H--;for(let G of _){let U=G;if(G.isSymbolicLink()){if(!(V&&(U=G.realpathSync())))continue;if(U.isUnknown())U.lstatSync()}if(U.shouldWalk(Y,J))K.push(U)}}if(W&&!z.flowing)z.once("drain",q)};return q(),z}chdir(Q=this.cwd){let X=this.cwd;this.cwd=typeof Q==="string"?this.cwd.resolve(Q):Q,this.cwd[t7](X)}}class n5 extends i6{sep="\\";constructor(Q=process.cwd(),X={}){let{nocase:Z=!0}=X;super(Q,l6,"\\",{...X,nocase:Z});this.nocase=Z;for(let V=this.cwd;V;V=V.parent)V.nocase=this.nocase}parseRootPath(Q){return l6.parse(Q).root.toUpperCase()}newRoot(Q){return new W6(this.rootPath,V5,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Q})}isAbsolute(Q){return Q.startsWith("/")||Q.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(Q)}}class o5 extends i6{sep="/";constructor(Q=process.cwd(),X={}){let{nocase:Z=!1}=X;super(Q,Y0,"/",{...X,nocase:Z});this.nocase=Z}parseRootPath(Q){return"/"}newRoot(Q){return new j6(this.rootPath,V5,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Q})}isAbsolute(Q){return Q.startsWith("/")}}class _6 extends o5{constructor(Q=process.cwd(),X={}){let{nocase:Z=!0}=X;super(Q,{...X,nocase:Z})}}var CX=process.platform==="win32"?W6:j6,e7=process.platform==="win32"?n5:process.platform==="darwin"?_6:o5;var C0=(Q)=>Q.length>=1,M0=(Q)=>Q.length>=1;class N5{#Q;#V;#$;length;#X;#z;#C;#L;#W;#Y;#j=!0;constructor(Q,X,Z,V){if(!C0(Q))throw TypeError("empty pattern list");if(!M0(X))throw TypeError("empty glob list");if(X.length!==Q.length)throw TypeError("mismatched pattern list and glob list lengths");if(this.length=Q.length,Z<0||Z>=this.length)throw TypeError("index out of range");if(this.#Q=Q,this.#V=X,this.#$=Z,this.#X=V,this.#$===0){if(this.isUNC()){let[$,J,z,Y,...K]=this.#Q,[H,q,W,j,..._]=this.#V;if(K[0]==="")K.shift(),_.shift();let G=[$,J,z,Y,""].join("/"),U=[H,q,W,j,""].join("/");this.#Q=[G,...K],this.#V=[U,..._],this.length=this.#Q.length}else if(this.isDrive()||this.isAbsolute()){let[$,...J]=this.#Q,[z,...Y]=this.#V;if(J[0]==="")J.shift(),Y.shift();let K=$+"/",H=z+"/";this.#Q=[K,...J],this.#V=[H,...Y],this.length=this.#Q.length}}}pattern(){return this.#Q[this.#$]}isString(){return typeof this.#Q[this.#$]==="string"}isGlobstar(){return this.#Q[this.#$]===N}isRegExp(){return this.#Q[this.#$]instanceof RegExp}globString(){return this.#C=this.#C||(this.#$===0?this.isAbsolute()?this.#V[0]+this.#V.slice(1).join("/"):this.#V.join("/"):this.#V.slice(this.#$).join("/"))}hasMore(){return this.length>this.#$+1}rest(){if(this.#z!==void 0)return this.#z;if(!this.hasMore())return this.#z=null;return this.#z=new N5(this.#Q,this.#V,this.#$+1,this.#X),this.#z.#Y=this.#Y,this.#z.#W=this.#W,this.#z.#L=this.#L,this.#z}isUNC(){let Q=this.#Q;return this.#W!==void 0?this.#W:this.#W=this.#X==="win32"&&this.#$===0&&Q[0]===""&&Q[1]===""&&typeof Q[2]==="string"&&!!Q[2]&&typeof Q[3]==="string"&&!!Q[3]}isDrive(){let Q=this.#Q;return this.#L!==void 0?this.#L:this.#L=this.#X==="win32"&&this.#$===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.#$===0?Q:""}checkFollowGlobstar(){return!(this.#$===0||!this.isGlobstar()||!this.#j)}markFollowGlobstar(){if(this.#$===0||!this.isGlobstar()||!this.#j)return!1;return this.#j=!1,!0}}var R0=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class a5{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(Q,{nobrace:X,nocase:Z,noext:V,noglobstar:$,platform:J=R0}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=J,this.mmopts={dot:!0,nobrace:X,nocase:Z,noext:V,noglobstar:$,optimizationLevel:2,platform:J,nocomment:!0,nonegate:!0};for(let z of Q)this.add(z)}add(Q){let X=new c(Q,this.mmopts);for(let Z=0;Z<X.set.length;Z++){let V=X.set[Z],$=X.globParts[Z];if(!V||!$)throw Error("invalid pattern object");while(V[0]==="."&&$[0]===".")V.shift(),$.shift();let J=new N5(V,$,0,this.platform),z=new c(J.globString(),this.mmopts),Y=$[$.length-1]==="**",K=J.isAbsolute();if(K)this.absolute.push(z);else this.relative.push(z);if(Y)if(K)this.absoluteChildren.push(z);else this.relativeChildren.push(z)}}ignored(Q){let X=Q.fullpath(),Z=`${X}/`,V=Q.relative()||".",$=`${V}/`;for(let J of this.relative)if(J.match(V)||J.match($))return!0;for(let J of this.absolute)if(J.match(X)||J.match(Z))return!0;return!1}childrenIgnored(Q){let X=Q.fullpath()+"/",Z=(Q.relative()||".")+"/";for(let V of this.relativeChildren)if(V.match(Z))return!0;for(let V of this.absoluteChildren)if(V.match(X))return!0;return!1}}class n6{store;constructor(Q=new Map){this.store=Q}copy(){return new n6(new Map(this.store))}hasWalked(Q,X){return this.store.get(Q.fullpath())?.has(X.globString())}storeWalked(Q,X){let Z=Q.fullpath(),V=this.store.get(Z);if(V)V.add(X.globString());else this.store.set(Z,new Set([X.globString()]))}}class Q8{store=new Map;add(Q,X,Z){let V=(X?2:0)|(Z?1:0),$=this.store.get(Q);this.store.set(Q,$===void 0?V:V&$)}entries(){return[...this.store.entries()].map(([Q,X])=>[Q,!!(X&2),!!(X&1)])}}class X8{store=new Map;add(Q,X){if(!Q.canReaddir())return;let Z=this.store.get(Q);if(Z){if(!Z.find((V)=>V.globString()===X.globString()))Z.push(X)}else this.store.set(Q,[X])}get(Q){let X=this.store.get(Q);if(!X)throw Error("attempting to walk unknown path");return X}entries(){return this.keys().map((Q)=>[Q,this.store.get(Q)])}keys(){return[...this.store.keys()].filter((Q)=>Q.canReaddir())}}class r5{hasWalkedCache;matches=new Q8;subwalks=new X8;patterns;follow;dot;opts;constructor(Q,X){this.opts=Q,this.follow=!!Q.follow,this.dot=!!Q.dot,this.hasWalkedCache=X?X.copy():new n6}processPatterns(Q,X){this.patterns=X;let Z=X.map((V)=>[Q,V]);for(let[V,$]of Z){this.hasWalkedCache.storeWalked(V,$);let J=$.root(),z=$.isAbsolute()&&this.opts.absolute!==!1;if(J){V=V.resolve(J==="/"&&this.opts.root!==void 0?this.opts.root:J);let q=$.rest();if(!q){this.matches.add(V,!0,!1);continue}else $=q}if(V.isENOENT())continue;let Y,K,H=!1;while(typeof(Y=$.pattern())==="string"&&(K=$.rest()))V=V.resolve(Y),$=K,H=!0;if(Y=$.pattern(),K=$.rest(),H){if(this.hasWalkedCache.hasWalked(V,$))continue;this.hasWalkedCache.storeWalked(V,$)}if(typeof Y==="string"){let q=Y===".."||Y===""||Y===".";this.matches.add(V.resolve(Y),z,q);continue}else if(Y===N){if(!V.isSymbolicLink()||this.follow||$.checkFollowGlobstar())this.subwalks.add(V,$);let q=K?.pattern(),W=K?.rest();if(!K||(q===""||q===".")&&!W)this.matches.add(V,z,q===""||q===".");else if(q===".."){let j=V.parent||V;if(!W)this.matches.add(j,z,!0);else if(!this.hasWalkedCache.hasWalked(j,W))this.subwalks.add(j,W)}}else if(Y instanceof RegExp)this.subwalks.add(V,$)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r5(this.opts,this.hasWalkedCache)}filterEntries(Q,X){let Z=this.subwalks.get(Q),V=this.child();for(let $ of X)for(let J of Z){let z=J.isAbsolute(),Y=J.pattern(),K=J.rest();if(Y===N)V.testGlobstar($,J,K,z);else if(Y instanceof RegExp)V.testRegExp($,Y,K,z);else V.testString($,Y,K,z)}return V}testGlobstar(Q,X,Z,V){if(this.dot||!Q.name.startsWith(".")){if(!X.hasMore())this.matches.add(Q,V,!1);if(Q.canReaddir()){if(this.follow||!Q.isSymbolicLink())this.subwalks.add(Q,X);else if(Q.isSymbolicLink()){if(Z&&X.checkFollowGlobstar())this.subwalks.add(Q,Z);else if(X.markFollowGlobstar())this.subwalks.add(Q,X)}}}if(Z){let $=Z.pattern();if(typeof $==="string"&&$!==".."&&$!==""&&$!==".")this.testString(Q,$,Z.rest(),V);else if($===".."){let J=Q.parent||Q;this.subwalks.add(J,Z)}else if($ instanceof RegExp)this.testRegExp(Q,$,Z.rest(),V)}}testRegExp(Q,X,Z,V){if(!X.test(Q.name))return;if(!Z)this.matches.add(Q,V,!1);else this.subwalks.add(Q,Z)}testString(Q,X,Z,V){if(!Q.isNamed(X))return;if(!Z)this.matches.add(Q,V,!1);else this.subwalks.add(Q,Z)}}var P0=(Q,X)=>typeof Q==="string"?new a5([Q],X):Array.isArray(Q)?new a5(Q,X):Q;class o6{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#Q=[];#V;#$;signal;maxDepth;includeChildMatches;constructor(Q,X,Z){if(this.patterns=Q,this.path=X,this.opts=Z,this.#$=!Z.posix&&Z.platform==="win32"?"\\":"/",this.includeChildMatches=Z.includeChildMatches!==!1,Z.ignore||!this.includeChildMatches){if(this.#V=P0(Z.ignore??[],Z),!this.includeChildMatches&&typeof this.#V.add!=="function")throw Error("cannot ignore child matches, ignore lacks add() method.")}if(this.maxDepth=Z.maxDepth||1/0,Z.signal)this.signal=Z.signal,this.signal.addEventListener("abort",()=>{this.#Q.length=0})}#X(Q){return this.seen.has(Q)||!!this.#V?.ignored?.(Q)}#z(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,X){if(X&&this.opts.nodir)return;let Z;if(this.opts.realpath){if(Z=Q.realpathCached()||await Q.realpath(),!Z)return;Q=Z}let $=Q.isUnknown()||this.opts.stat?await Q.lstat():Q;if(this.opts.follow&&this.opts.nodir&&$?.isSymbolicLink()){let J=await $.realpath();if(J&&(J.isUnknown()||this.opts.stat))await J.lstat()}return this.matchCheckTest($,X)}matchCheckTest(Q,X){return Q&&(this.maxDepth===1/0||Q.depth()<=this.maxDepth)&&(!X||Q.canReaddir())&&(!this.opts.nodir||!Q.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!Q.isSymbolicLink()||!Q.realpathCached()?.isDirectory())&&!this.#X(Q)?Q:void 0}matchCheckSync(Q,X){if(X&&this.opts.nodir)return;let Z;if(this.opts.realpath){if(Z=Q.realpathCached()||Q.realpathSync(),!Z)return;Q=Z}let $=Q.isUnknown()||this.opts.stat?Q.lstatSync():Q;if(this.opts.follow&&this.opts.nodir&&$?.isSymbolicLink()){let J=$.realpathSync();if(J&&(J?.isUnknown()||this.opts.stat))J.lstatSync()}return this.matchCheckTest($,X)}matchFinish(Q,X){if(this.#X(Q))return;if(!this.includeChildMatches&&this.#V?.add){let $=`${Q.relativePosix()}/**`;this.#V.add($)}let Z=this.opts.absolute===void 0?X:this.opts.absolute;this.seen.add(Q);let V=this.opts.mark&&Q.isDirectory()?this.#$:"";if(this.opts.withFileTypes)this.matchEmit(Q);else if(Z){let $=this.opts.posix?Q.fullpathPosix():Q.fullpath();this.matchEmit($+V)}else{let $=this.opts.posix?Q.relativePosix():Q.relative(),J=this.opts.dotRelative&&!$.startsWith(".."+this.#$)?"."+this.#$:"";this.matchEmit(!$?"."+V:J+$+V)}}async match(Q,X,Z){let V=await this.matchCheck(Q,Z);if(V)this.matchFinish(V,X)}matchSync(Q,X,Z){let V=this.matchCheckSync(Q,Z);if(V)this.matchFinish(V,X)}walkCB(Q,X,Z){if(this.signal?.aborted)Z();this.walkCB2(Q,X,new r5(this.opts),Z)}walkCB2(Q,X,Z,V){if(this.#z(Q))return V();if(this.signal?.aborted)V();if(this.paused){this.onResume(()=>this.walkCB2(Q,X,Z,V));return}Z.processPatterns(Q,X);let $=1,J=()=>{if(--$===0)V()};for(let[z,Y,K]of Z.matches.entries()){if(this.#X(z))continue;$++,this.match(z,Y,K).then(()=>J())}for(let z of Z.subwalkTargets()){if(this.maxDepth!==1/0&&z.depth()>=this.maxDepth)continue;$++;let Y=z.readdirCached();if(z.calledReaddir())this.walkCB3(z,Y,Z,J);else z.readdirCB((K,H)=>this.walkCB3(z,H,Z,J),!0)}J()}walkCB3(Q,X,Z,V){Z=Z.filterEntries(Q,X);let $=1,J=()=>{if(--$===0)V()};for(let[z,Y,K]of Z.matches.entries()){if(this.#X(z))continue;$++,this.match(z,Y,K).then(()=>J())}for(let[z,Y]of Z.subwalks.entries())$++,this.walkCB2(z,Y,Z.child(),J);J()}walkCBSync(Q,X,Z){if(this.signal?.aborted)Z();this.walkCB2Sync(Q,X,new r5(this.opts),Z)}walkCB2Sync(Q,X,Z,V){if(this.#z(Q))return V();if(this.signal?.aborted)V();if(this.paused){this.onResume(()=>this.walkCB2Sync(Q,X,Z,V));return}Z.processPatterns(Q,X);let $=1,J=()=>{if(--$===0)V()};for(let[z,Y,K]of Z.matches.entries()){if(this.#X(z))continue;this.matchSync(z,Y,K)}for(let z of Z.subwalkTargets()){if(this.maxDepth!==1/0&&z.depth()>=this.maxDepth)continue;$++;let Y=z.readdirSync();this.walkCB3Sync(z,Y,Z,J)}J()}walkCB3Sync(Q,X,Z,V){Z=Z.filterEntries(Q,X);let $=1,J=()=>{if(--$===0)V()};for(let[z,Y,K]of Z.matches.entries()){if(this.#X(z))continue;this.matchSync(z,Y,K)}for(let[z,Y]of Z.subwalks.entries())$++,this.walkCB2Sync(z,Y,Z.child(),J);J()}}class G6 extends o6{matches=new Set;constructor(Q,X,Z){super(Q,X,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,X)=>{this.walkCB(this.path,this.patterns,()=>{if(this.signal?.aborted)X(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 U6 extends o6{results;constructor(Q,X,Z){super(Q,X,Z);this.results=new B5({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 D0=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class $5{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,X){if(!X)throw TypeError("glob options required");if(this.withFileTypes=!!X.withFileTypes,this.signal=X.signal,this.follow=!!X.follow,this.dot=!!X.dot,this.dotRelative=!!X.dotRelative,this.nodir=!!X.nodir,this.mark=!!X.mark,!X.cwd)this.cwd="";else if(X.cwd instanceof URL||X.cwd.startsWith("file://"))X.cwd=N0(X.cwd);if(this.cwd=X.cwd||"",this.root=X.root,this.magicalBraces=!!X.magicalBraces,this.nobrace=!!X.nobrace,this.noext=!!X.noext,this.realpath=!!X.realpath,this.absolute=X.absolute,this.includeChildMatches=X.includeChildMatches!==!1,this.noglobstar=!!X.noglobstar,this.matchBase=!!X.matchBase,this.maxDepth=typeof X.maxDepth==="number"?X.maxDepth:1/0,this.stat=!!X.stat,this.ignore=X.ignore,this.withFileTypes&&this.absolute!==void 0)throw Error("cannot set absolute and withFileTypes:true");if(typeof Q==="string")Q=[Q];if(this.windowsPathsNoEscape=!!X.windowsPathsNoEscape||X.allowWindowsEscape===!1,this.windowsPathsNoEscape)Q=Q.map((Y)=>Y.replace(/\\/g,"/"));if(this.matchBase){if(X.noglobstar)throw TypeError("base matching requires globstar");Q=Q.map((Y)=>Y.includes("/")?Y:`./**/${Y}`)}if(this.pattern=Q,this.platform=X.platform||D0,this.opts={...X,platform:this.platform},X.scurry){if(this.scurry=X.scurry,X.nocase!==void 0&&X.nocase!==X.scurry.nocase)throw Error("nocase option contradicts provided scurry option")}else{let Y=X.platform==="win32"?n5:X.platform==="darwin"?_6:X.platform?o5:e7;this.scurry=new Y(this.cwd,{nocase:X.nocase,fs:X.fs})}this.nocase=this.scurry.nocase;let Z=this.platform==="darwin"||this.platform==="win32",V={...X,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:Z,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},$=this.pattern.map((Y)=>new c(Y,V)),[J,z]=$.reduce((Y,K)=>{return Y[0].push(...K.set),Y[1].push(...K.globParts),Y},[[],[]]);this.patterns=J.map((Y,K)=>{let H=z[K];if(!H)throw Error("invalid pattern object");return new N5(Y,H,0,this.platform)})}async walk(){return[...await new G6(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 G6(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 U6(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 U6(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 a6=(Q,X={})=>{if(!Array.isArray(Q))Q=[Q];for(let Z of Q)if(new c(Z,X).hasMagic())return!0;return!1};function w6(Q,X={}){return new $5(Q,X).streamSync()}function V8(Q,X={}){return new $5(Q,X).stream()}function $8(Q,X={}){return new $5(Q,X).walkSync()}async function Z8(Q,X={}){return new $5(Q,X).walk()}function L6(Q,X={}){return new $5(Q,X).iterateSync()}function J8(Q,X={}){return new $5(Q,X).iterate()}var x0=w6,I0=Object.assign(V8,{sync:w6}),S0=L6,T0=Object.assign(J8,{sync:L6}),k0=Object.assign($8,{stream:w6,iterate:L6}),A6=Object.assign(Z8,{glob:Z8,globSync:$8,sync:k0,globStream:V8,stream:I0,globStreamSync:w6,streamSync:x0,globIterate:J8,iterate:T0,globIterateSync:L6,iterateSync:S0,Glob:$5,hasMagic:a6,escape:M5,unescape:o});A6.glob=A6;var E0={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,X)=>{let Z=Q.file_path,V=Q.offset||1,$=Q.limit||2000;try{let Y=(await Bun.file(Z).text()).split(`
30
+ `),K=Math.max(0,V-1),H=Math.min(Y.length,K+$);return{content:Y.slice(K,H).map((j,_)=>`${K+_+1} ${j}`).join(`
31
+ `)}}catch(J){return{content:`Error reading file: ${J instanceof Error?J.message:String(J)}`,is_error:!0}}}},b0={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,X)=>{let{file_path:Z,content:V}=Q;try{return await Bun.write(Z,V),{content:`Successfully wrote to ${Z}`}}catch($){return{content:`Error writing file: ${$ instanceof Error?$.message:String($)}`,is_error:!0}}}},y0={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,X)=>{let{file_path:Z,old_string:V,new_string:$}=Q,J=Q.replace_all||!1;try{let Y=await Bun.file(Z).text();if(J){let K=Y;Y=Y.split(V).join($);let H=(K.match(new RegExp(f0(V),"g"))||[]).length;if(H===0)return{content:"Error: String not found in file",is_error:!0};return await Bun.write(Z,Y),{content:`Successfully replaced ${H} 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,$),await Bun.write(Z,Y),{content:`Successfully edited ${Z}`}}}catch(z){return{content:`Error editing file: ${z instanceof Error?z.message:String(z)}`,is_error:!0}}}};function f0(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var u0={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,X)=>{let Z=Q.command,V=Q.timeout||120000;try{let $=Bun.spawnSync(["sh","-c",Z],{cwd:X.workingDirectory,timeout:V,maxBuffer:31457280}),J=$.stdout?.toString()||"",z=$.stderr?.toString()||"";if($.exitCode!==0)return{content:`Exit code: ${$.exitCode}
32
+ ${J}
33
+ ${z}`.trim(),is_error:!0};return{content:J||"(no output)"}}catch($){return{content:`Error executing command: ${$ instanceof Error?$.message:String($)}`,is_error:!0}}}},h0={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,X)=>{let Z=Q.pattern,V=Q.path||X.workingDirectory;try{let $=await A6(Z,{cwd:V,absolute:!0,nodir:!0});if($.length===0)return{content:"No files found matching pattern"};return{content:$.sort().join(`
34
+ `)}}catch($){return{content:`Error searching files: ${$ instanceof Error?$.message:String($)}`,is_error:!0}}}},g0={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,X)=>{let Z=Q.pattern,V=Q.path||X.workingDirectory,$=Q.glob,J=Q.output_mode||"content",z=Q["-i:"],Y=Q["-C:"],K=Q.head_limit;try{let H=["--json"];if(z)H.push("-i");if(Y)H.push("-C",String(Y));if($)H.push("--glob",$);if(J==="files_with_matches")H.push("--files-with-matches");if(J==="count")H.push("--count");H.push(Z,V);let W=Bun.spawnSync(["rg",...H],{cwd:X.workingDirectory,maxBuffer:10485760}).stdout?.toString()||"";if(!W.trim())return{content:"No matches found"};if(J==="content"){let j=W.trim().split(`
35
+ `),_=[];for(let G of j.slice(0,K||100))try{let U=JSON.parse(G);if(U.type==="match"){let w=U.data?.path?.text||"",A=U.data?.line_number||0,L=U.data?.lines?.text||"";_.push(`${w}:${A}:${L.trim()}`)}}catch{_.push(G)}return{content:_.join(`
36
+ `)||"No matches found"}}return{content:W.trim()}}catch(H){return{content:`Error searching: ${H instanceof Error?H.message:String(H)}`,is_error:!0}}}},m0={name:"Task",description:`Launch a new agent to handle complex, multi-step tasks autonomously.
37
+
38
+ The Task tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
39
+
40
+ Available agent types and their tools:
41
+ - Bash: Command execution specialist for running bash commands. Use for git operations, command execution, and other terminal tasks.
42
+ - general-purpose: General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks.
43
+ - Explore: Fast agent specialized for exploring codebases. Use to quickly find files by patterns, search code for keywords, or answer questions about the codebase.
44
+ - Plan: Software architect agent for designing implementation plans. Returns step-by-step plans, identifies critical files and considers architectural trade-offs.
45
+
46
+ When using the Task tool, you must specify a subagent_type parameter to select the agent type.
47
+
48
+ Usage notes:
49
+ - Always include a short description (3-5 words) summarizing what the agent will do
50
+ - Launch multiple agents concurrently whenever possible to maximize performance
51
+ - 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,X)=>{let{subagent_type:Z,prompt:V,description:$}=Q,J=Q.model||"haiku",z=Q.resume,Y=Q.run_in_background,K=z||`${Z.toLowerCase()}-${Date.now().toString(36)}`;try{let H=process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.Z_AI_API_KEY||"";if(!H)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 q={haiku:"claude-haiku-4-5",sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-6"},W=q[J]||q.haiku,j=[import.meta.dir+"/../../dist/cli.js",import.meta.dir+"/../cli.ts",process.cwd()+"/dist/cli.js",process.cwd()+"/src/cli.ts"],_=null;for(let L of j)try{if(await Bun.file(L).exists()){_=L;break}}catch{}if(!_)return{content:`Error: Could not find CLI. Tried:
52
+ ${j.join(`
53
+ `)}`,is_error:!0};let G=["run",_,"-m",W,"-p",X.permissionMode,"-q",V];if(Y)return Bun.spawn(["bun",...G],{cwd:X.workingDirectory,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:H}}).unref(),{content:JSON.stringify({agentId:K,status:"running",message:`Agent started in background. Use TaskOutput tool with task_id: "${K}" to check results.`,description:$||"Background task"})};let U=Bun.spawnSync(["bun",...G],{cwd:X.workingDirectory,timeout:300000,maxBuffer:10485760,env:{...process.env,ANTHROPIC_API_KEY:H}}),w=U.stdout?.toString()||"",A=U.stderr?.toString()||"";if(U.exitCode!==0)return{content:`Agent failed with exit code ${U.exitCode}
54
+ ${A}
55
+ ${w}`.trim(),is_error:!0};return{content:JSON.stringify({agentId:K,status:"completed",output:w,description:$||"Task completed"})}}catch(H){return{content:`Error running subagent: ${H instanceof Error?H.message:String(H)}`,is_error:!0}}}},d0={name:"TaskOutput",description:`Retrieves output from a running or completed task (background shell, agent, or remote session).
56
+
57
+ Takes a task_id parameter identifying the task.
58
+ Returns the task output along with status information.
59
+ Use block=true (default) to wait for task completion.
60
+ Use block=false for non-blocking check of current status.
61
+
62
+ Task IDs can be found using the /tasks command
63
+ 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,X)=>{let Z=Q.task_id,V=Q.block??!0,$=Q.timeout??30000;try{let J=`${X.workingDirectory}/.claude/tasks/${Z}.json`,z=Bun.file(J);if(!await z.exists())return{content:`Task not found: ${Z}. Use /tasks to list available tasks.`,is_error:!0};let Y=await z.json();if(V&&Y.status==="running"){let K=Date.now();while(Date.now()-K<$){await new Promise((q)=>setTimeout(q,1000));let H=Bun.file(J);if(await H.exists()){let q=await H.json();if(q.status!=="running")return{content:JSON.stringify({task_id:Z,status:q.status,output:q.output,error:q.error,duration:q.endTime?q.endTime-q.startTime:null},null,2)}}}return{content:JSON.stringify({task_id:Z,status:"timeout",message:`Task still running after ${$}ms`},null,2)}}return{content:JSON.stringify({task_id:Z,status:Y.status,output:Y.output,error:Y.error,duration:Y.endTime?Y.endTime-Y.startTime:null},null,2)}}catch(J){return{content:`Error getting task output: ${J instanceof Error?J.message:String(J)}`,is_error:!0}}}},c0={name:"AskUserQuestion",description:`Use this tool when you need to ask the user questions during execution.
64
+
65
+ This allows you to:
66
+ 1. Gather user preferences or requirements
67
+ 2. Clarify ambiguous instructions
68
+ 3. Get decisions on implementation choices
69
+ 4. Offer choices to the user about what direction to take
70
+
71
+ 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.
72
+
73
+ The options array should have 2-4 options. Each option should be a distinct, mutually exclusive choice.
74
+ The preview feature allows showing markdown content in a side-by-side layout.
75
+
76
+ 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,X)=>{let Z=Q.questions;try{let V=Z.map(($,J)=>{let z=$.options.map((Y,K)=>{let H=` ${K+1}. ${Y.label}`;if(Y.description)H+=` - ${Y.description}`;return H}).join(`
77
+ `);return`## Question ${J+1}: [${$.header}]
78
+ ${$.question}
79
+
80
+ Options:
81
+ ${z}${$.multiSelect?`
82
+ (multi-select enabled)`:""}`}).join(`
83
+
84
+ ---
85
+
86
+ `);return{content:JSON.stringify({type:"user_question",questions:Z,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}}}},l0={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.
87
+
88
+ How This Tool Works:
89
+ - You should have already written your plan to the plan file specified in the plan mode system message
90
+ - This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote
91
+ - This tool simply signals that you're done planning and ready for the user to review and approve
92
+
93
+ When to Use This Tool:
94
+ 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.
95
+
96
+ 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.
97
+
98
+ Examples:
99
+ - "Search for and understand the implementation of vim mode" - Do NOT use this tool
100
+ - "Help me implement yank mode for vim" - Use EnterPlanMode
101
+
102
+ Important notes:
103
+ - NEVER run additional commands to read or explore code, besides git bash commands
104
+ - NEVER use the TodoWrite or Task tools
105
+ - DO NOT commit files that likely contain secrets (.env, credentials.json, etc.)
106
+ - 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,X)=>{let Z=Q.allowedPrompts;try{let V=`${X.workingDirectory}/.claude/plan.md`,$=Bun.file(V);if(!await $.exists())return{content:"Error: No plan file found. Please write your plan to .claude/plan.md first.",is_error:!0};let J=await $.text();return{content:JSON.stringify({type:"plan_ready",planFile:V,planLength:J.length,allowedPrompts:Z||[],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}}}},p0={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.
107
+
108
+ This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote.
109
+ This tool simply signals that you're done planning and ready for the user to review and approve.
110
+
111
+ IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code.
112
+ 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,X)=>{let Z=Q.allowedPrompts;try{let V=`${X.workingDirectory}/.claude/plan.md`,$=Bun.file(V);if(!await $.exists())return{content:"Error: No plan file found at .claude/plan.md",is_error:!0};let J=await $.text();return{content:JSON.stringify({type:"exit_plan_mode",status:"awaiting_approval",planFile:V,planPreview:J.slice(0,500)+(J.length>500?"...":""),allowedPrompts:Z||[],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}}}},i0={name:"Skill",description:`Execute a skill within the main conversation.
113
+
114
+ When users ask you to perform tasks, check if any of the available skills match. Skills provide specialized capabilities and domain knowledge.
115
+
116
+ 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.
117
+
118
+ How to invoke:
119
+ - Use this tool with the skill name and optional arguments
120
+ - Examples:
121
+ - skill: "commit" - invoke the commit skill
122
+ - skill: "review-pr", args: "123" - invoke with arguments
123
+ - Use fully qualified name for namespaced skills: skill: "ms-office-suite:pdf"
124
+
125
+ Available skills are listed in system-reminder messages in the conversation.
126
+ 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.
127
+
128
+ Important:
129
+ - NEVER mention a skill without actually calling this tool
130
+ - Do not invoke a skill that is already running
131
+ - 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,X)=>{let{skill:Z,args:V}=Q;try{let $=`${X.workingDirectory}/.claude/skills`,J=`${process.env.HOME||""}/.claude/skills`,z=[`${$}/${Z}.md`,`${$}/${Z}/skill.md`,`${J}/${Z}.md`,`${J}/${Z}/skill.md`],Y=null;for(let q of z)if(await Bun.file(q).exists()){Y=q;break}if(!Y)return{content:`Skill not found: ${Z}. Available skills can be listed with /help.`,is_error:!0};let H=await Bun.file(Y).text();return{content:JSON.stringify({type:"skill_invocation",skill:Z,args:V,skillFile:Y,content:H,message:`Skill "${Z}" loaded. Follow the instructions in the skill content.`},null,2)}}catch($){return{content:`Error invoking skill: ${$ instanceof Error?$.message:String($)}`,is_error:!0}}}},n0={name:"TaskStop",description:`Stops a running background task by its ID.
132
+ Takes a task_id parameter identifying the task to stop.
133
+ Returns a success or failure status.
134
+ 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,X)=>{let Z=Q.task_id;try{let V=`${X.workingDirectory}/.claude/tasks/${Z}.json`,$=Bun.file(V);if(!await $.exists())return{content:`Task not found: ${Z}`,is_error:!0};let J=await $.json();if(J.status!=="running")return{content:JSON.stringify({task_id:Z,status:J.status,message:`Task is already ${J.status}`},null,2)};return J.status="stopped",await Bun.write(V,JSON.stringify(J,null,2)),{content:JSON.stringify({task_id:Z,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}}}},o0={name:"NotebookEdit",description:`Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source.
135
+
136
+ 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,X)=>{let{notebook_path:Z,cell_id:V,cell_number:$,new_source:J}=Q,z=Q.cell_type||"code",Y=Q.edit_mode||"replace";try{let K=Bun.file(Z);if(!await K.exists())return{content:`Error: Notebook not found: ${Z}`,is_error:!0};let H=await K.json();if(!H.cells||!Array.isArray(H.cells))return{content:"Error: Invalid notebook format - no cells array",is_error:!0};let q;if(V){if(q=H.cells.findIndex((W)=>W.id===V),q===-1)return{content:`Error: Cell with ID "${V}" not found`,is_error:!0}}else if($!==void 0){if(q=$,q<0||q>=H.cells.length)if(Y==="insert")q=H.cells.length;else return{content:`Error: Cell number ${q} out of range (0-${H.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 q=H.cells.length;switch(Y){case"delete":{H.cells.splice(q,1);break}case"insert":{let W={id:`cell-${Date.now()}`,cell_type:z,source:J||"",metadata:{},...z==="code"?{outputs:[],execution_count:null}:{}};H.cells.splice(q,0,W);break}case"replace":default:{if(J===void 0)return{content:"Error: new_source is required for replace mode",is_error:!0};let W=H.cells[q];if(!W)return{content:`Error: Cell at index ${q} not found`,is_error:!0};H.cells[q]={...W,source:J,cell_type:z,...z==="code"?{execution_count:null}:{}};break}}return await Bun.write(Z,JSON.stringify(H,null,1)),{content:JSON.stringify({success:!0,message:`Successfully ${Y}d cell in ${Z}`,cellCount:H.cells.length})}}catch(K){return{content:`Error editing notebook: ${K instanceof Error?K.message:String(K)}`,is_error:!0}}}},a0=[E0,b0,y0,u0,h0,g0,m0,d0,n0,c0,l0,p0,i0,o0];function eX(Q){return a0.find((X)=>X.name===Q)}import{spawn as r0}from"child_process";import r6 from"ws";class s6{static MCPClient=s6;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=r0(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 X=await Q.json();this.connected=!0,await this.loadTools()}catch(Q){let X=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to connect to HTTP server: ${X}`)}}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((X,Z)=>{let V={...this.config.headers},$=new r6(Q,{headers:V,handshakeTimeout:this.config.timeout||30000});$.on("open",()=>{this.log("WebSocket connection established"),this.websocket=$,this.connected=!0,this.initialize().then(()=>X()).catch((J)=>{let z=J instanceof Error?J.message:String(J);this.log(`Initialization failed: ${z}`),Z(J)})}),$.on("message",(J,z)=>{let Y=z?J.toString():J.toString();this.handleData(Y)}),$.on("error",(J)=>{if(this.log(`WebSocket error: ${J.message}`),!this.connected)Z(Error(`WebSocket connection failed: ${J.message}`))}),$.on("close",(J,z)=>{this.log(`WebSocket closed: code=${J}, reason=${z.toString()}`),this.connected=!1,this.websocket=null;for(let[Y,K]of this.pendingRequests)this.pendingRequests.delete(Y),K.reject(Error(`WebSocket closed: ${z.toString()}`))}),$.on("ping",()=>{$.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((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema})),this.log(`Loaded ${this.tools.length} tools`)}catch(Q){this.log(`Failed to load tools: ${Q}`)}}async callTool(Q,X){return{content:(await this.request("tools/call",{name:Q,arguments:X})).content.filter(($)=>$.type==="text").map(($)=>$.text||"").join(`
137
+ `)}}async request(Q,X){let Z=++this.requestId,V={jsonrpc:"2.0",id:Z,method:Q,params:X};return new Promise(($,J)=>{this.pendingRequests.set(Z,{resolve:$,reject:J});let z=JSON.stringify(V);if(this.websocket&&this.websocket.readyState===r6.OPEN)this.websocket.send(z);else if(this.process?.stdin?.writable)this.process.stdin.write(z+`
138
+ `);else{this.pendingRequests.delete(Z),J(Error("No active connection to send request"));return}setTimeout(()=>{if(this.pendingRequests.has(Z))this.pendingRequests.delete(Z),J(Error(`Request timeout for ${Q}`))},this.config.timeout||120000)})}notify(Q,X){let V=JSON.stringify({jsonrpc:"2.0",method:Q,params:X});if(this.websocket&&this.websocket.readyState===r6.OPEN)this.websocket.send(V);else if(this.process?.stdin?.writable)this.process.stdin.write(V+`
139
+ `)}handleData(Q){this.buffer+=Q;let X=this.buffer.split(`
140
+ `);this.buffer=X.pop()||"";for(let Z of X){if(!Z.trim())continue;try{let V=JSON.parse(Z);if(V.id!==void 0){let $=this.pendingRequests.get(V.id);if($)if(this.pendingRequests.delete(V.id),V.error)$.reject(Error(V.error.message));else $.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 VZ(Q,X){let Z=new Map;for(let[V,$]of Object.entries(Q)){if($.disabled)continue;let J=new s6({name:V,config:$,onLog:X});try{await J.connect(),Z.set(V,J)}catch(z){let Y=z instanceof Error?z.message:String(z);X?.(`[MCP:${V}] Failed to connect: ${Y}`)}}return Z}import{spawn as s0}from"child_process";class t0{hooks=new Map;timeout;constructor(Q=60000){this.timeout=Q}register(Q,X){if(!this.hooks.has(Q))this.hooks.set(Q,[]);this.hooks.get(Q)?.push(X)}registerAll(Q){for(let[X,Z]of Object.entries(Q))for(let V of Z)this.register(X,V)}async execute(Q,X){let Z=this.hooks.get(Q);if(!Z||Z.length===0)return{decision:"allow"};let V={...X,event:Q,timestamp:Date.now()};for(let $ of Z){if($.enabled===!1)continue;let J=await this.executeHook($,V);if(J.decision==="deny"||J.decision==="block")return J;if(J.modified_input)Object.assign(X,J.modified_input)}return{decision:"allow"}}async executeHook(Q,X){let Z=Q.timeout||this.timeout;try{return await new Promise(($,J)=>{let z=s0(Q.command,[],{shell:!0,stdio:["pipe","pipe","pipe"]}),Y="",K="";z.stdout?.on("data",(H)=>{Y+=H.toString()}),z.stderr?.on("data",(H)=>{K+=H.toString()}),z.on("close",(H)=>{if(H===0)try{let q=JSON.parse(Y);$(q)}catch{$({decision:"allow"})}else if(H===1)$({decision:"deny",reason:K||"Hook denied execution"});else if(H===2)$({decision:"block",reason:K||"Hook blocked execution"});else $({decision:"allow"})}),z.on("error",(H)=>{$({decision:"allow",reason:`Hook error: ${H.message}`})}),z.stdin?.write(JSON.stringify(X)),z.stdin?.end(),setTimeout(()=>{z.kill(),$({decision:"allow",reason:"Hook timeout"})},Z)})}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 zZ={validateWrite:{event:"PreToolUse",command:`node -e '
141
+ const input = JSON.parse(require("fs").readFileSync(0, "utf8"));
142
+ if (input.tool_name === "Write") {
143
+ const path = input.tool_input.file_path;
144
+ if (path.includes("..") || path.startsWith("/etc/")) {
145
+ console.log(JSON.stringify({ decision: "deny", reason: "Unsafe path" }));
146
+ process.exit(1);
147
+ }
148
+ }
149
+ console.log(JSON.stringify({ decision: "allow" }));
150
+ '`,timeout:5000,enabled:!1},logToolUse:{event:"PostToolUse",command:`node -e '
151
+ const input = JSON.parse(require("fs").readFileSync(0, "utf8"));
152
+ console.error(\`[LOG] Tool: \${input.tool_name}\`);
153
+ console.log(JSON.stringify({ decision: "allow" }));
154
+ '`,timeout:5000,enabled:!1}},YZ={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."},KZ={ALLOW:0,DENY:1,BLOCK:2};import{readFileSync as e0,existsSync as z8,readdirSync as QQ}from"fs";import{join as XQ}from"path";function ZQ(Q,X="project"){if(!z8(Q))return null;let Z=e0(Q,"utf-8"),V=Q.split("/").pop()?.replace(/\.md$/i,"")||"unknown",$=Z.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!$)return{path:Q,name:V,description:"",prompt:Z.trim(),source:X};let J=$[1]??"",z=$[2]??"",Y=VQ(J);return{path:Q,name:Y.name||V,description:Y.description||"",prompt:z.trim(),tools:Y.tools,model:Y.model,color:Y.color,source:X}}function VQ(Q){let X={},Z=Q.split(`
155
+ `);for(let V of Z){let $=V.match(/^(\w+):\s*(.*)$/);if($){let J=$[1];if(!J)continue;let z=$[2]??"";if(z.startsWith("["))try{X[J]=JSON.parse(z)}catch{X[J]=z}else if(z==="true")X[J]=!0;else if(z==="false")X[J]=!1;else if(/^\d+$/.test(z))X[J]=parseInt(z,10);else if(/^\d+\.\d+$/.test(z))X[J]=parseFloat(z);else X[J]=z}}return X}class $Q{skills=new Map;loadFromDirectory(Q,X="project"){if(!z8(Q))return 0;let Z=0,V=QQ(Q);for(let $ of V)if($.endsWith(".md")){let J=ZQ(XQ(Q,$),X);if(J)this.skills.set(J.name,J),Z++}return Z}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 _Z(Q){return`
156
+ <skill-loading>
157
+ You are operating with the "${Q.name}" skill loaded.
158
+
159
+ ${Q.description?`Description: ${Q.description}
160
+ `:""}
161
+ ${Q.prompt}
162
+ </skill-loading>
163
+ `.trim()}var GZ=[{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.
164
+
165
+ Steps:
166
+ 1. Run \`git diff --staged\` to see staged changes
167
+ 2. Run \`git log --oneline -5\` to understand commit message style
168
+ 3. Create a commit message following conventional commits format
169
+ 4. Include "Co-Authored-By: Claude <noreply@anthropic.com>" if applicable
170
+ 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.
171
+
172
+ Steps:
173
+ 1. Use \`gh pr view\` to get PR details
174
+ 2. Use \`gh pr diff\` to see the changes
175
+ 3. Analyze the code for:
176
+ - Bugs and potential issues
177
+ - Code quality and style
178
+ - Test coverage
179
+ - Documentation
180
+ 4. Provide constructive feedback
181
+ 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.
182
+
183
+ MCP servers enable LLMs to interact with external services through well-designed tools.
184
+
185
+ Key concepts:
186
+ 1. Use FastMCP (Python) or MCP SDK (TypeScript)
187
+ 2. Define tools with clear input schemas
188
+ 3. Return structured content
189
+ 4. Handle errors gracefully
190
+
191
+ Transport types:
192
+ - stdio: Local process communication
193
+ - HTTP: REST API with JSON-RPC
194
+ - SSE: Server-Sent Events for streaming
195
+ - 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.
196
+
197
+ Hooks are user-defined shell commands that execute at specific points during Claude Code's lifecycle.
198
+
199
+ Available events:
200
+ - PreToolUse: Before a tool executes
201
+ - PostToolUse: After a tool succeeds
202
+ - PostToolUseFailure: After a tool fails
203
+ - Stop: When agent stops
204
+ - UserPromptSubmit: When user submits prompt
205
+ - SessionStart/SessionEnd: Session lifecycle
206
+
207
+ Exit codes:
208
+ - 0: Allow execution
209
+ - 1: Deny and show stderr
210
+ - 2: Block silently`,tools:["Read","Write","Edit"],model:"sonnet",source:"built-in"}];function UZ(Q){return Q.match(/^\/(\w+)(?:\s+(.*))?$/)?.[1]??null}function AZ(Q){return Q.match(/^\/\w+\s+(.*)$/)?.[1]??""}import{spawn as t6}from"child_process";import{mkdirSync as Y8,rmSync as JQ,existsSync as K8,readFileSync as zQ}from"fs";import{join as s5}from"path";class YQ{teams=new Map;teammates=new Map;messageQueue=new Map;storagePath;constructor(Q="~/.claude/teams"){if(this.storagePath=Q.replace("~",process.env.HOME||""),!K8(this.storagePath))Y8(this.storagePath,{recursive:!0});this.loadTeams()}createTeam(Q){let X={...Q,status:"active"};this.teams.set(Q.name,X);for(let Z of Q.teammates)this.teammates.set(Z.teammateId,Z);return this.persistTeam(X).catch((Z)=>{console.error(`Failed to persist team ${Q.name}:`,Z)}),X}getTeam(Q){return this.teams.get(Q)}listTeams(){return Array.from(this.teams.values())}deleteTeam(Q){let X=this.teams.get(Q);if(X){for(let V of X.teammates)this.teammates.delete(V.teammateId),this.messageQueue.delete(V.teammateId);this.teams.delete(Q);let Z=s5(this.storagePath,Q);try{JQ(Z,{recursive:!0,force:!0})}catch(V){console.error(`Failed to delete team directory ${Z}:`,V)}}}getTeammate(Q){return this.teammates.get(Q)}updateTeammateStatus(Q,X){let Z=this.teammates.get(Q);if(Z)Z.status=X}async spawnTeammate(Q,X={}){let{session:Z,workingDir:V=process.cwd()}=X;if(!process.env.TMUX)await this.spawnInTerminal(Q,{session:Z,workingDir:V});else await this.spawnInTmux(Q,{session:Z,workingDir:V});this.updateTeammateStatus(Q.teammateId,"in_progress")}async spawnInTerminal(Q,X){let Z=["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)Z.push("--permission-mode","plan");if(process.platform==="darwin"){let V=`
211
+ tell application "Terminal"
212
+ do script "cd ${X.workingDir} && ${Z.join(" ")}"
213
+ activate
214
+ end tell
215
+ `;t6("osascript",["-e",V])}else t6("xterm",["-e",Z.join(" ")])}async spawnInTmux(Q,X){let Z=X.session||process.env.TMUX?.split(",")[0]?.split(":")[0]||"claude";await this.tmuxCommand(["split-window","-t",Z,"-c",X.workingDir]);let V=await this.tmuxCommand(["display-message","-p","#{pane_id}"]);if(V)Q.paneId=V.trim();let $=["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||"",$.join(" "),"Enter"])}async tmuxCommand(Q){return new Promise((X)=>{let Z=t6("tmux",Q),V="";Z.stdout?.on("data",($)=>{V+=$.toString()}),Z.on("close",()=>{X(V)})})}broadcast(Q,X,Z){let V=this.teams.get(Q);if(!V)return;let $={type:"broadcast",from:Z||"system",content:X,timestamp:Date.now()};for(let J of V.teammates){if(Z&&J.teammateId===Z)continue;let z=this.messageQueue.get(J.teammateId)||[];z.push($),this.messageQueue.set(J.teammateId,z)}}sendDirect(Q,X,Z){let V={type:"direct",from:X,to:Q,content:Z,timestamp:Date.now()},$=this.messageQueue.get(Q)||[];$.push(V),this.messageQueue.set(Q,$)}getMessages(Q){let X=this.messageQueue.get(Q)||[];return this.messageQueue.delete(Q),X}hasMessages(Q){let X=this.messageQueue.get(Q);return X!==void 0&&X.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 X=s5(this.storagePath,Q.name),Z=s5(X,"config.json");if(!K8(X))Y8(X,{recursive:!0});await Bun.write(s5(X,".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(Z,JSON.stringify(V,null,2))}loadTeams(){let Q=new Bun.Glob("**/config.json");try{let X=Array.from(Q.scanSync(this.storagePath));for(let Z of X)try{let V=s5(this.storagePath,Z);if(Bun.file(V).size===0)continue;let z=zQ(V,"utf-8"),Y=JSON.parse(z);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 H of K.teammates)this.teammates.set(H.teammateId,H)}catch(V){}}catch(X){if(X.code!=="ENOENT");}}async persistAllTeams(){let Q=Array.from(this.teams.values()).map((X)=>this.persistTeam(X));await Promise.all(Q)}}var vZ={architect:(Q)=>({name:"architect",teamName:Q,color:"blue",prompt:`You are an architect on the ${Q} team.
216
+ Your role is to design and plan the technical architecture.
217
+ Focus on:
218
+ - System design and component relationships
219
+ - API contracts and interfaces
220
+ - Data models and schemas
221
+ - Trade-offs and design decisions`,planModeRequired:!0,status:"pending"}),implementer:(Q)=>({name:"implementer",teamName:Q,color:"green",prompt:`You are an implementer on the ${Q} team.
222
+ Your role is to write clean, working code based on the architecture.
223
+ Focus on:
224
+ - Implementing the designed architecture
225
+ - Writing tests
226
+ - Following coding standards
227
+ - Handling edge cases`,planModeRequired:!1,status:"pending"}),reviewer:(Q)=>({name:"reviewer",teamName:Q,color:"yellow",prompt:`You are a code reviewer on the ${Q} team.
228
+ Your role is to review code changes and provide feedback.
229
+ Focus on:
230
+ - Code quality and readability
231
+ - Potential bugs and issues
232
+ - Performance considerations
233
+ - Test coverage`,planModeRequired:!1,status:"pending"}),tester:(Q)=>({name:"tester",teamName:Q,color:"orange",prompt:`You are a tester on the ${Q} team.
234
+ Your role is to ensure features work correctly.
235
+ Focus on:
236
+ - Writing comprehensive tests
237
+ - Finding edge cases
238
+ - Verifying requirements
239
+ - Reporting bugs`,planModeRequired:!1,status:"pending"})};function KQ(){return`teammate_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function FZ(Q){return{...Q,teammateId:KQ(),status:"pending"}}
240
+ export{U8 as a,e5 as b,A8 as c,qQ as d,X7 as e,Z7 as f,WQ as g,v8 as h,F8 as i,C8 as j,M8 as k,J7 as l,N8 as m,D8 as n,v6 as o,F6 as p,BQ as q,OQ as r,vQ as s,EQ as t,D6 as u,bQ as v,yQ as w,fQ as x,m8 as y,d8 as z,mQ as A,E0 as B,b0 as C,y0 as D,u0 as E,h0 as F,g0 as G,m0 as H,d0 as I,c0 as J,l0 as K,p0 as L,i0 as M,n0 as N,o0 as O,a0 as P,eX as Q,s6 as R,VZ as S,t0 as T,zZ as U,YZ as V,KZ as W,ZQ as X,$Q as Y,_Z as Z,GZ as _,UZ as $,AZ as aa,YQ as ba,vZ as ca,KQ as da,FZ as ea};
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$ as kz,A as p,B as Qz,C as Vz,D as Wz,E as Xz,F as Yz,G as Zz,H as $z,I as Ez,J as Fz,K as Hz,L as Sz,M as Uz,N as bz,O as qz,P as _z,Q as Nz,R as Q,T as Pz,U as Rz,V as gz,W as yz,X as Lz,Y as fz,Z as wz,_ as Mz,aa as Cz,b as Dz,ba as pz,c as Gz,ca as vz,d as Iz,da as Tz,e as Jz,ea as hz,f as Kz,g as Oz,h as E,i as F,j as H,k as S,l as U,m as b,n as q,o as _,p as N,q as P,r as R,s as g,t as y,u as L,v as f,w,x as M,y as k,z as C}from"./index-wn2m4wma.js";import{dlopen as V,suffix as W}from"bun:ffi";import{join as X,dirname as Y}from"path";import{fileURLToPath as Z}from"url";var I=null;function O(){if(I)return I;try{let z=Y(Z(import.meta.url)),B=X(z,"..","native",`claude_code_native.${W}`);return I=V(B,{search_files:{args:["cstring","cstring","pointer"],returns:"pointer"},count_tokens:{args:["cstring"],returns:"u32"},calculate_diff:{args:["cstring","cstring"],returns:"pointer"},compact_content:{args:["cstring","u32","cstring"],returns:"pointer"}}).symbols,I}catch(z){return console.warn("Native module not available, using JS fallback:",z),$()}}function m(){try{return O(),I!==null}catch{return!1}}function $(){return{search_files:(z,B,D)=>{return{matches:[],total_count:0,files_searched:0}},count_tokens:(z)=>{return Math.ceil(z.length/4)},calculate_diff:(z,B)=>{let D=z.split(`
2
+ import{$ as kz,A as p,B as Qz,C as Vz,D as Wz,E as Xz,F as Yz,G as Zz,H as $z,I as Ez,J as Fz,K as Hz,L as Sz,M as Uz,N as bz,O as qz,P as _z,Q as Nz,R as Q,T as Pz,U as Rz,V as gz,W as yz,X as Lz,Y as fz,Z as wz,_ as Mz,aa as Cz,b as Dz,ba as pz,c as Gz,ca as vz,d as Iz,da as Tz,e as Jz,ea as hz,f as Kz,g as Oz,h as E,i as F,j as H,k as S,l as U,m as b,n as q,o as _,p as N,q as P,r as R,s as g,t as y,u as L,v as f,w,x as M,y as k,z as C}from"./index-z8cwtf8j.js";import{dlopen as V,suffix as W}from"bun:ffi";import{join as X,dirname as Y}from"path";import{fileURLToPath as Z}from"url";var I=null;function O(){if(I)return I;try{let z=Y(Z(import.meta.url)),B=X(z,"..","native",`claude_code_native.${W}`);return I=V(B,{search_files:{args:["cstring","cstring","pointer"],returns:"pointer"},count_tokens:{args:["cstring"],returns:"u32"},calculate_diff:{args:["cstring","cstring"],returns:"pointer"},compact_content:{args:["cstring","u32","cstring"],returns:"pointer"}}).symbols,I}catch(z){return console.warn("Native module not available, using JS fallback:",z),$()}}function m(){try{return O(),I!==null}catch{return!1}}function $(){return{search_files:(z,B,D)=>{return{matches:[],total_count:0,files_searched:0}},count_tokens:(z)=>{return Math.ceil(z.length/4)},calculate_diff:(z,B)=>{let D=z.split(`
3
3
  `),J=B.split(`
4
4
  `),A=[];if(z!==B)A.push({old_start:1,old_lines:D.length,new_start:1,new_lines:J.length,content:`- ${D.join(`
5
5
  - `)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ebowwa/coder",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "AI coding assistant CLI with extended thinking and teammate mode",
5
5
  "author": "ebowwa",
6
6
  "license": "MIT",