context-mode 2.1.5 → 2.1.6

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/hook.mjs CHANGED
@@ -1,44 +1,44 @@
1
1
  import{createRequire as __cmRequire}from"node:module";if(typeof process.getBuiltinModule!=="function")process.getBuiltinModule=(id)=>__cmRequire(import.meta.url)(id);
2
- var Ce=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode"];var z="context-mode",lt=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function k(e,t){if(t==="")return e;let n=e;for(let o of lt)n=n.split(o).join(t+o);return n}var V=16384;var mr=2048;var hr=640,gn="</context_mode_state>",mn=1048576,Sr=65536,br=4096,Or=Object.freeze(["Read","view"]),Tr=Object.freeze(["offset","limit","view_range"]),Rr=96,Ar=256,yr=48;function Nr(e,t,n,o="",r=""){let s=r===""?[e]:[e,r];return o+"ctx_search({queries:["+s.map(i=>JSON.stringify(i)).join(",")+"], source:"+JSON.stringify(t)+"}) searches the whole output ("+n+" B)."}var Ir=3,re=4096;var hn=85,Sn=340,bn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var Cr=.7,kr=.7,Dr=.3,On=Object.freeze([1e3,881,780,696,625,565,515,473,438,408,383,361,344,329,316,306,297,289,283,278,273,270,267,264,262,260,258,257,256,255,254,253,253,252,252,252,251,251,251,251,251,251,251,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250]),Lr='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var Fl=6e5;var J=5e3,ut="-wal",dt="-shm",wr=".tmp",Pr=255,Mr=11,Ur=26;var F=5e3;var Tn=0;var Hr=16,ke=6;var ft="projects",Fr="context.db";var Rn=".git",An="worktree ",yn="gitdir: ",vr="commondir",jr="HEAD",xt="--workspace-folder",N_=Object.freeze(["shell","powershell","javascript","typescript","python"]),Gr=Object.freeze(["sh","bash","zsh","dash","ksh","fish"]);var Br=80;var I_=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var C_=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),De="24.15.0",Wr="~/.context-mode",Le="CONTEXT_MODE_DATA_DIR";var Xr="CONTEXT_MODE_REQUIRE_SECURITY",Kr=".claude",pt="agents",_t=".md",Nn="plugins",Yr="installed_plugins.json",xe=":",qr="@";var k_=Object.freeze(["local","project"]),D_=Object.freeze({local:0,project:1,user:2,managed:2}),In="---",zr="tools",Vr="disallowedTools",Cn="mcp__",kn="__",Jr="mcp_",$r="_-.:",gr=10;function vl(e){if(e===void 0||e.trim()==="")return gr;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:gr}var L_=vl(process.env.CTX_MCP_HINT_EVERY);var v=32;var Dn="context-mode: ",Qr=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),Zr=" sends its body into the conversation.",es="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",ts="Tool: ",ns="state what you need",os="ctx_execute",rs=Object.freeze(["ctx_index","ctx_search"]),we="Blocked by security policy: matches deny pattern ",Et="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",gt="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",Ln="hook-errors.log";var ss=Object.freeze(["tool_name","toolName","tool"]),is=Object.freeze(["hook_event_name","hookEventName","type"]),cs=Object.freeze(["tool_input","toolArgs","input","args"]),as=Object.freeze(["cwd","directory"]),ls=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),us="CM_HOOK_FAULT",w_=Object.freeze(["decode","project","policy","store","encode"]),Pe=Object.freeze({shell:Object.freeze(["Bash","bash","shell"]),read:Object.freeze(["Read","read_file"]),grep:Object.freeze(["Grep","grep_search"]),fetch:Object.freeze(["WebFetch","web_fetch","fetch"])});function ds(e,t){return`${Dn}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var wn=Object.freeze({read:"Read the file in parts with offset and limit, or process it with ctx_execute(language, code); only what you print comes back.",shell:"Run the command with ctx_execute(language, code) or ctx_batch instead; only the part that matches your intent comes back.",grep:"Search with ctx_execute(language, code), or index the files with ctx_index and query them with ctx_search.",fetch:"Index the URL with ctx_index and query it with ctx_search."});var P_=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),M_=Object.freeze(["status"]),U_=Object.freeze(["--version","-v"]),H_=Object.freeze(["cp","mv","rm"]),F_=Object.freeze(["-v","--verbose"]),D=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),fs="{prefix}",xs=", then ",ps="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",_s=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),Es=Object.freeze(["curl","wget"]),gs=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),ms=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),hs="-D",Ss=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),Me="fetch(",bs="'\"`",Os="http",Ts=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),Rs=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),As=Object.freeze(["head","tail"]),Pn=Object.freeze(["-n","-c","--lines","--bytes"]),mt="sed",ys=Object.freeze(["-n","--quiet","--silent"]),Ns="jq",ht=Object.freeze(["file_path","absolute_path","path","filePath"]),pe="filePaths",Mn=Object.freeze({png:{exts:[".png"],sig:[{at:0,bytes:[137,80,78,71,13,10,26,10]}]},jpeg:{exts:[".jpg",".jpeg"],sig:[{at:0,bytes:[255,216,255]}]},gif:{exts:[".gif"],sig:[{at:0,bytes:[71,73,70,56]}]},webp:{exts:[".webp"],sig:[{at:0,bytes:[82,73,70,70]},{at:8,bytes:[87,69,66,80]}]},pdf:{exts:[".pdf"],sig:[{at:0,bytes:[37,80,68,70,45]}]}}),Un=12,En=Object.freeze(["png","jpeg","gif","webp"]),at=Object.freeze([...En,"pdf"]),Is=Object.freeze({"claude-code":at,gemini:at,qwen:at,opencode:at,pi:En,vscode:En,"copilot-cli":[],codex:[],kiro:[],zcode:[]}),St="ctx_",Cs="Bash",ks=Object.freeze(["Write","Edit"]),Ds=Object.freeze(["file_path","path"]),Hn="Exit code ",Ue="resume-hint",Fn="compact-state",vn="pending-compact",bt="pending_compact:",jn="1",He=2048,Gn=5,Ls=340,Bn="compacted:",ws="recall_units_seen:",Ps=8,Ms=64,Us="recall_seen:",Wn="<context_mode_recall>",Xn="</context_mode_recall>",Hs="recall",Kn="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",Fs="subagent:",vs="run.mjs",js="node",Gs=`context-mode: This command sends its body into the conversation.
3
- Run the command on the line above with Bash instead. It runs the same command in the same folder, indexes the full output and prints only the part that matches your intent, with the same exit code.`,Ot="--agent",Bs=1e3;var v_=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var j_=Object.freeze(["Ready. Your savings show up here after the first tool call.","Large outputs from ctx_execute, ctx_batch and ctx_index stay in the","sandbox, and only the short answer goes to the chat."]),G_=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),B_=Object.freeze(["ctx_resume brings back your last task, files changed and open issues","after a compact or a restart; ctx_search finds indexed content by words."]);var W_=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),X_=Object.freeze(["ctx_index","ctx_search"]);var K_=Object.freeze(["session","source","project"]);var Tt="decision";var Yn="AskUserQuestion",Ws="answers",Rt="option",Xs=" | ",jl="https://github.com/mksglu/context-mode.git";var Y_=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),q_=Object.freeze({D1:"version",D2:"node",D3:"host config",D4:"old entries",D5:"hook round trip",D5b:"double-fire",D6:"MCP",D7:"project and worktree",D8:"context.db",D9:"index",D10:"enforcement mode",D11:"shell"});var qn=256;var Gl="ctx_doctor:report";var z_=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(Gl)}})`;var V_=Object.freeze(["--tags","--refs"]),Bl="v*";var J_=`git ls-remote --tags --refs ${jl} "${Bl}"`;var $_=`install Node ${De} or later`;var Q_=Object.freeze(["MCP entry","hook entries","hook timeout"]);var Ks=Object.freeze({"claude-code":[".claude"],codex:[".codex"],gemini:[".gemini"],qwen:[".qwen"],"copilot-cli":[".copilot"],vscode:[".vscode"],kiro:[".kiro"],zcode:[".zcode"],pi:[".pi"],opencode:[".config","opencode"]});var Z_=Object.freeze(["upgrade","uninstall"]);var eE=Object.freeze(["clone","--depth","1","--branch"]),tE=Object.freeze(["rev-parse","HEAD"]);var nE=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),oE=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var rE=Object.freeze(["shell","bash","sh"]),sE=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var Ys="tool-results",qs=16*1024*1024;var iE=Object.freeze(["doctor-env.ts","doctor-config.ts","doctor-hook.ts","doctor-db.ts","doctor-heal.ts","verify-sums.ts","plugin-swap.ts","host-write.ts","v1-remove.ts","uninstall.ts"]);var cE=Object.freeze({"claude-code":{root:"plugin",file:["hooks","claude-code.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},codex:{root:"home",file:[".codex","hooks.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},gemini:{root:"plugin",file:["hooks","hooks.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!1},qwen:{root:"plugin",file:["hooks","qwen.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},"copilot-cli":{root:"home",file:[".copilot","hooks","context-mode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeoutSec",matcher:!1},vscode:{root:"home",file:[".copilot","hooks","context-mode-vscode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeout",matcher:!1},kiro:{root:"home",file:[".kiro","hooks","context-mode.json"],key:["hooks"],shape:"kiro",timeoutKey:"timeout",matcher:!1},zcode:{root:"home",file:[".zcode","cli","config.json"],key:["hooks","events"],shape:"zcode",timeoutKey:"timeoutMs",matcher:!0},pi:null,opencode:null}),aE=Object.freeze(["PreToolUse","PostToolUse"]);var lE=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var uE=Object.freeze(["features","hooks"]);var dE=Object.freeze(["",ut,dt]);var fE=Object.freeze({"claude-code":"claude plugin marketplace update context-mode && claude plugin update context-mode@context-mode",codex:"codex plugin marketplace upgrade context-mode",gemini:"gemini extensions update context-mode",qwen:"qwen extensions update context-mode",pi:"pi update --extensions",opencode:"opencode plugin update","copilot-cli":"npm i -g context-mode && context-mode setup --agents copilot-cli",vscode:"npm i -g context-mode && context-mode setup --agents vscode",kiro:"npm i -g context-mode && context-mode setup --agents kiro",zcode:"npm i -g context-mode && context-mode setup --agents zcode"});var xE=Object.freeze(["afteragentresponse.mjs","aftermodel.mjs","aftertool.mjs","agentspawn.mjs","beforeagent.mjs","beforetool.mjs","posttooluse.mjs","precompact.mjs","precompress.mjs","pretooluse.mjs","sessionend.mjs","sessionstart.mjs","stop.mjs","userpromptsubmit.mjs"]);var pE=Object.freeze(["hooks","codex"]);var _E=Object.freeze([".mjs",".sh"]);var Wl="npm:context-mode";var At="CLAUDE_CONFIG_DIR";var Xl=Object.freeze(["Code","User"]);var Kl="mcp.json",EE=Object.freeze(["agents","default.json"]);var gE=Object.freeze(["steering","KIRO.md"]);var mE=Object.freeze(["opencode.jsonc","opencode.json"]);var Yl=`${z}@`,ql="@",hE=`${Yl}latest`,SE=`${Wl}${ql}latest`;var bE=Object.freeze(["content","platform.json"]);var zs="custom";var zl=Object.freeze(["/","\\"]),Vl="${/}",OE=Object.freeze([...zl,Vl]),L=Object.freeze({hook:"old context-mode hook entry: command contains context-mode and an old script name or context-mode hook",cacheHealHook:"old context-mode cache-heal SessionStart hook entry",cacheHealFile:"old context-mode cache-heal script file",statusLine:"old context-mode statusLine (context-mode statusline): report only, never removed",mcpEntry:"old context-mode MCP entry mcpServers.context-mode",codexHook:"old context-mode Codex hook entry: context-mode hook codex or hooks/codex/*.mjs",codexToml:"old context-mode config.toml [mcp_servers.context-mode*] section",hookFile:"old context-mode hook file context-mode.json (runs context-mode hook)",vscodeMcp:"old context-mode MCP entry servers.context-mode in .vscode/mcp.json: report only, never removed",kiroHook:"old Kiro hook entry: command contains context-mode and an old script name or context-mode hook",kiroAgentFile:"old context-mode Kiro agent file agents/*.json with name context-mode",kiroSteering:"old context-mode Kiro steering doc .kiro/steering/KIRO.md: manual review, report only, never removed",piNpm:"old context-mode Pi package npm:context-mode",opencodePlugin:"old context-mode OpenCode plugin spec context-mode",piGit:"old context-mode Pi entry git:github.com/mksglu/context-mode@release: ctx_upgrade replaces it with npm:context-mode@latest",opencodeGit:"old context-mode OpenCode entry git+https://github.com/mksglu/context-mode.git#release: ctx_upgrade replaces it with context-mode@latest",zcodeHook:"old context-mode ZCode hook entry: command contains context-mode hook",dataDir:"old context-mode data dir <agent home>/context-mode/",dataDirShared:"old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",dataRoot:"old context-mode content under ~/.context-mode/",tmpFile:"old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep",projectLink:"context-mode path in the project reached through a link: report only, upgrade keeps it as is and never follows a link"}),TE=Object.freeze([L.statusLine,L.vscodeMcp,L.dataDirShared,L.tmpFile,L.kiroSteering,L.piGit,L.opencodeGit,L.projectLink]),RE=Object.freeze([L.dataDir,L.dataRoot]);var AE=z+"_";var yE=Object.freeze(["opencode","plugin.js"]);var Jl=Object.freeze(["features","mcp"]),$l="omit_tools_from",Ql=Object.freeze(["deferred"]),Zl="default_tools_approval_mode",eu="approve",NE=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",z],fields:{[$l]:Ql,[Zl]:eu}},vscode:{file:[Kl],key:["servers",z]},kiro:{file:[".kiro","settings","mcp.json"],key:["mcpServers",z]},zcode:{file:[".zcode","cli","config.json"],key:["mcp","servers",z],fields:{type:"stdio",enabled:!0,timeoutMs:Fl},also:[[Jl,!0]]}});var IE=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),tu="Environment: ";var nu="Docs: ";var ou="Report file: ",ru="File it: ",su="Or open: ",iu="Rules: ",cu=" --",CE=Object.freeze([tu,nu,ou,ru,cu.trim(),su,iu]),Vs="mksglu/context-mode",au="agent-report.yml",kE=`https://github.com/${Vs}/blob/main/.github/AGENT_ISSUE.md`,DE=Object.freeze(['Search for the same problem first: `gh issue list -R mksglu/context-mode --state all --search "<check id or error>"`. When one matches, add your facts there as a comment.',"File one bug per issue.","Call the `ctx_doctor` tool and paste its full output unchanged in the `ctx-report` field.","Give the versions: context-mode, the agent, the OS and arch, and Node.","Write numbered repro steps that start from a fresh project (`mktemp -d`) and the agent's own install command.","Give the exact command and its exact output in a fenced code block.","Say what you expected and what happened instead.","Name the source file and line when you found the cause.","Replace every secret with `<masked>` and the home folder with `~` before you send."]);var LE=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var wE=Object.freeze(["CODEX_HOME","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_ROOT","COPILOT_HOME","KIRO_HOME","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","XDG_CONFIG_HOME","SHELL"]),PE=Object.freeze(["node","git","sh"]),ME=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var UE=Object.freeze({"claude-code":["claude plugin marketplace add mksglu/context-mode","claude plugin install context-mode@context-mode"],codex:["codex plugin marketplace add mksglu/context-mode","codex plugin add context-mode@context-mode"],gemini:["gemini extensions install https://github.com/mksglu/context-mode"],qwen:["qwen extensions install https://github.com/mksglu/context-mode:context-mode"],opencode:["opencode plugin add context-mode"],pi:["pi install npm:context-mode"],"copilot-cli":["npm i -g context-mode","context-mode setup --agents copilot-cli"],vscode:["npm i -g context-mode","context-mode setup --agents vscode"],kiro:["npm i -g context-mode","context-mode setup --agents kiro"],zcode:["zcode plugins marketplace add mksglu/context-mode","zcode plugins install context-mode@context-mode"]}),HE=`https://github.com/${Vs}/issues/new?template=${au}`;import{dirname as Yp,join as Il,relative as qp,resolve as zp,sep as yl}from"node:path";var zn="mcp__plugin_context-mode_context-mode__",Zs=Object.freeze(["Bash","PowerShell"]),lu="PowerShell",uu="Bash",du=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],Js="mcp__",$s="__",fu={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function xu(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(Js))return e;let n=e.slice(Js.length),o=n.indexOf($s);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+$s.length)}function pu(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return ei(e).text;if(typeof e=="object"&&e!==null){let t=e;if(typeof t.stdout=="string"||typeof t.stderr=="string"){let n=typeof t.stdout=="string"?t.stdout:"",o=typeof t.stderr=="string"?t.stderr:"";return o===""?n:n===""?o:n+`
4
- `+o}}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Vn(e);if(t!==null)return t.text}return JSON.stringify(e)}function Vn(e){let t=e.file;return e.type==="text"&&typeof t=="object"&&t!==null&&typeof t.content=="string"?{text:t.content,put:(n,o)=>({...n,file:_u(n.file,o)})}:gu(e)?{text:e.content,put:(n,o)=>({...n,content:o})}:Array.isArray(e.filenames)&&e.filenames.every(n=>typeof n=="string")?{text:e.filenames.join(`
2
+ var Me=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode"];var $="context-mode",gt=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function D(e,t){if(t==="")return e;let n=e;for(let o of gt)n=n.split(o).join(t+o);return n}var ie=16384;var kr=2048;var Dr=640,Rn="</context_mode_state>",An=1048576,Lr=65536,Ir=4096,gu="CTX_REPLACE_TRIGGER_BYTES";function mu(e){if(e===void 0||e.trim()==="")return Ir;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Ir}var wr=mu(process.env[gu]),yn=Object.freeze(["Read","view"]),Pr=Object.freeze(["offset","limit","view_range"]),Mr=96,Ur=256,Hr=48;function Fr(e,t,n,o="",r=""){let s=r===""?[e]:[e,r];return o+"ctx_search({queries:["+s.map(i=>JSON.stringify(i)).join(",")+"], source:"+JSON.stringify(t)+"}) searches the whole output ("+n+" B)."}var vr=3,ce=4096;var Nn=85,In=340,Cn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var jr=.7,Gr=.7,Br=.3,kn=Object.freeze([1e3,881,780,696,625,565,515,473,438,408,383,361,344,329,316,306,297,289,283,278,273,270,267,264,262,260,258,257,256,255,254,253,253,252,252,252,251,251,251,251,251,251,251,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250]),Wr='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var hu=6e5;var Q=5e3,mt="-wal",ht="-shm",Xr=".tmp",Kr=255,Yr=11,qr=26;var j=5e3;var Dn=0;var zr=16,Ue=6;var St="projects",Vr="context.db";var Ln=".git",wn="worktree ",Pn="gitdir: ",Jr="commondir",$r="HEAD",bt="--workspace-folder",uE=Object.freeze(["shell","powershell","javascript","typescript","python"]),Qr=Object.freeze(["sh","bash","zsh","dash","ksh","fish"]);var Zr=80;var dE=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var fE=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),He="24.15.0",es="~/.context-mode",Fe="CONTEXT_MODE_DATA_DIR";var ts="CONTEXT_MODE_REQUIRE_SECURITY",ns=".claude",Ot="agents",Ee=".md",Mn="plugins",os="installed_plugins.json",ge=":",rs="@";var xE=Object.freeze(["local","project"]),pE=Object.freeze({local:0,project:1,user:2,managed:2}),Un="---",ss="tools",is="disallowedTools",Hn="mcp__",Fn="__",cs="mcp_",as="_-.:",Cr=10;function Su(e){if(e===void 0||e.trim()==="")return Cr;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Cr}var _E=Su(process.env.CTX_MCP_HINT_EVERY);var G=32;var ls=Object.freeze([".agents","skills"]),vn="context-mode: ",us=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),ds=" sends its body into the conversation.",fs="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",xs="Tool: ",ps="state what you need",_s="ctx_execute",Es=Object.freeze(["ctx_index","ctx_search"]),ve="Blocked by security policy: matches deny pattern ",Tt="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",Rt="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",jn="hook-errors.log";var gs=Object.freeze(["tool_name","toolName","tool"]),ms=Object.freeze(["hook_event_name","hookEventName","type"]),hs=Object.freeze(["tool_input","toolArgs","input","args"]),Ss=Object.freeze(["cwd","directory"]),bs=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),Os="CM_HOOK_FAULT",EE=Object.freeze(["decode","project","policy","store","encode"]),je=Object.freeze({shell:Object.freeze(["Bash","bash","shell"]),read:Object.freeze(["Read","read_file"]),grep:Object.freeze(["Grep","grep_search"]),fetch:Object.freeze(["WebFetch","web_fetch","fetch"])});function Ts(e,t){return`${vn}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var Gn=Object.freeze({read:"Read the file in parts with offset and limit, or process it with ctx_execute(language, code); only what you print comes back.",shell:"Run the command with ctx_execute(language, code) or ctx_batch instead; only the part that matches your intent comes back.",grep:"Search with ctx_execute(language, code), or index the files with ctx_index and query them with ctx_search.",fetch:"Index the URL with ctx_index and query it with ctx_search."});var gE=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),mE=Object.freeze(["status"]),hE=Object.freeze(["--version","-v"]),SE=Object.freeze(["cp","mv","rm"]),bE=Object.freeze(["-v","--verbose"]),L=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),Rs="{prefix}",As=", then ",ys="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",Ns=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),Is=Object.freeze(["curl","wget"]),Cs=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),ks=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),Ds="-D",Ls=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),Ge="fetch(",ws="'\"`",Ps="http",Ms=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),Us=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),Hs=Object.freeze(["head","tail"]),Bn=Object.freeze(["-n","-c","--lines","--bytes"]),At="sed",Fs=Object.freeze(["-n","--quiet","--silent"]),vs="jq",me=Object.freeze(["file_path","absolute_path","path","filePath"]),he="filePaths",Wn=Object.freeze({png:{exts:[".png"],sig:[{at:0,bytes:[137,80,78,71,13,10,26,10]}]},jpeg:{exts:[".jpg",".jpeg"],sig:[{at:0,bytes:[255,216,255]}]},gif:{exts:[".gif"],sig:[{at:0,bytes:[71,73,70,56]}]},webp:{exts:[".webp"],sig:[{at:0,bytes:[82,73,70,70]},{at:8,bytes:[87,69,66,80]}]},pdf:{exts:[".pdf"],sig:[{at:0,bytes:[37,80,68,70,45]}]}}),Xn=12,Et=Object.freeze(["png","jpeg","gif","webp"]),_t=Object.freeze([...Et,"pdf"]),js=Object.freeze({"claude-code":_t,gemini:_t,qwen:_t,opencode:_t,pi:Et,vscode:Et,zcode:Et,"copilot-cli":[],codex:[],kiro:[]}),yt="ctx_",Gs="Bash",Bs=Object.freeze(["Write","Edit"]),Ws=Object.freeze(["file_path","path"]),Kn="Exit code ",Be="resume-hint",Yn="compact-state",qn="pending-compact",Nt="pending_compact:",zn="1",We=2048,Vn=5,Xs=340,Jn="compacted:",Ks="recall_units_seen:",Ys=8,It=64,qs=64,zs="recall_seen:",$n="<context_mode_recall>",Qn="</context_mode_recall>",Vs="recall",Zn="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",Js="subagent:",$s="run.mjs",Qs="node",Zs=`context-mode: This command sends its body into the conversation.
3
+ Run the command on the line above with Bash instead. It runs the same command in the same folder, indexes the full output and prints only the part that matches your intent, with the same exit code.`,Ct="--agent",ei=1e3;var OE=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var TE=Object.freeze(["Ready. Your savings show up here after the first tool call.","Large outputs from ctx_execute, ctx_batch and ctx_index stay in the","sandbox, and only the short answer goes to the chat."]),RE=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),AE=Object.freeze(["ctx_resume brings back your last task, files changed and open issues","after a compact or a restart; ctx_search finds indexed content by words."]);var yE=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),NE=Object.freeze(["ctx_index","ctx_search"]);var IE=Object.freeze(["session","source","project"]);var kt="decision";var eo="AskUserQuestion",ti="answers",Dt="option",ni=" | ",bu="https://github.com/mksglu/context-mode.git";var CE=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),kE=Object.freeze({D1:"version",D2:"node",D3:"host config",D4:"old entries",D5:"hook round trip",D5b:"double-fire",D6:"MCP",D7:"project and worktree",D8:"context.db",D9:"index",D10:"enforcement mode",D11:"shell"});var to=256;var Ou="ctx_doctor:report";var DE=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(Ou)}})`;var LE=Object.freeze(["--tags","--refs"]),Tu="v*";var wE=`git ls-remote --tags --refs ${bu} "${Tu}"`;var PE=`nvm install ${He.split(".")[0]}, or install it from https://nodejs.org`;var ME=Object.freeze(["MCP entry","hook entries","hook timeout"]);var I=Object.freeze({"claude-code":[".claude"],codex:[".codex"],gemini:[".gemini"],qwen:[".qwen"],"copilot-cli":[".copilot"],vscode:[".vscode"],kiro:[".kiro"],zcode:[".zcode"],pi:[".pi"],opencode:[".config","opencode"]});var UE=Object.freeze(["upgrade","uninstall"]);var HE=Object.freeze(["clone","--depth","1","--branch"]),FE=Object.freeze(["rev-parse","HEAD"]);var vE=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),jE=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var GE=Object.freeze(["shell","bash","sh"]),BE=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var oi="tool-results",ri=16*1024*1024;var WE=Object.freeze(["doctor-env.ts","doctor-config.ts","doctor-hook.ts","doctor-db.ts","doctor-heal.ts","verify-sums.ts","plugin-swap.ts","host-write.ts","v1-remove.ts","uninstall.ts"]);var XE=Object.freeze({"claude-code":{root:"plugin",file:["hooks","claude-code.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},codex:{root:"home",file:[".codex","hooks.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},gemini:{root:"plugin",file:["hooks","hooks.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!1},qwen:{root:"plugin",file:["hooks","qwen.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},"copilot-cli":{root:"home",file:[".copilot","hooks","context-mode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeoutSec",matcher:!1},vscode:{root:"home",file:[".copilot","hooks","context-mode-vscode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeout",matcher:!1},kiro:{root:"home",file:[".kiro","hooks","context-mode.json"],key:["hooks"],shape:"kiro",timeoutKey:"timeout",matcher:!1},zcode:{root:"home",file:[".zcode","cli","config.json"],key:["hooks","events"],shape:"zcode",timeoutKey:"timeoutMs",matcher:!0},pi:null,opencode:null}),KE=Object.freeze(["PreToolUse","PostToolUse"]);var YE=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var qE=Object.freeze(["features","hooks"]);var zE=Object.freeze(["",mt,ht]);var VE=Object.freeze({"claude-code":"claude plugin marketplace update context-mode && claude plugin update context-mode@context-mode",codex:"codex plugin marketplace upgrade context-mode",gemini:"gemini extensions update context-mode",qwen:"qwen extensions update context-mode",pi:"pi update --extensions",opencode:"opencode plugin update","copilot-cli":"npm i -g context-mode && context-mode setup --agents copilot-cli",vscode:"npm i -g context-mode && context-mode setup --agents vscode",kiro:"npm i -g context-mode && context-mode setup --agents kiro",zcode:"npm i -g context-mode && context-mode setup --agents zcode"});var JE=Object.freeze(["afteragentresponse.mjs","aftermodel.mjs","aftertool.mjs","agentspawn.mjs","beforeagent.mjs","beforetool.mjs","posttooluse.mjs","precompact.mjs","precompress.mjs","pretooluse.mjs","sessionend.mjs","sessionstart.mjs","stop.mjs","userpromptsubmit.mjs"]);var $E=Object.freeze(["hooks","codex"]);var QE=Object.freeze([".mjs",".sh"]);var Ru="npm:context-mode";var Lt="CLAUDE_CONFIG_DIR";var si="CODEX_HOME",ii="COPILOT_HOME",ci="GEMINI_CLI_HOME",ai="KIRO_HOME",li="OPENCODE_CONFIG_DIR",no="APPDATA",wt=Object.freeze(["Code","User"]),Pt="XDG_CONFIG_HOME";var Au="mcp.json",ZE=Object.freeze(["agents","default.json"]);var eg=Object.freeze(["steering","KIRO.md"]),ui="agent",tg=Object.freeze(["opencode.jsonc","opencode.json"]);var yu=`${$}@`,Nu="@",ng=`${yu}latest`,og=`${Ru}${Nu}latest`;var rg=Object.freeze(["content","platform.json"]);var di="custom",fi="PI_CODING_AGENT_DIR";var Iu=Object.freeze(["/","\\"]),Cu="${/}",sg=Object.freeze([...Iu,Cu]),w=Object.freeze({hook:"old context-mode hook entry: command contains context-mode and an old script name or context-mode hook",cacheHealHook:"old context-mode cache-heal SessionStart hook entry",cacheHealFile:"old context-mode cache-heal script file",statusLine:"old context-mode statusLine (context-mode statusline): report only, never removed",mcpEntry:"old context-mode MCP entry mcpServers.context-mode",codexHook:"old context-mode Codex hook entry: context-mode hook codex or hooks/codex/*.mjs",codexToml:"old context-mode config.toml [mcp_servers.context-mode*] section",hookFile:"old context-mode hook file context-mode.json (runs context-mode hook)",vscodeMcp:"old context-mode MCP entry servers.context-mode in .vscode/mcp.json: report only, never removed",kiroHook:"old Kiro hook entry: command contains context-mode and an old script name or context-mode hook",kiroAgentFile:"old context-mode Kiro agent file agents/*.json with name context-mode",kiroSteering:"old context-mode Kiro steering doc .kiro/steering/KIRO.md: manual review, report only, never removed",piNpm:"old context-mode Pi package npm:context-mode",opencodePlugin:"old context-mode OpenCode plugin spec context-mode",piGit:"old context-mode Pi entry git:github.com/mksglu/context-mode@release: ctx_upgrade replaces it with npm:context-mode@latest",opencodeGit:"old context-mode OpenCode entry git+https://github.com/mksglu/context-mode.git#release: ctx_upgrade replaces it with context-mode@latest",zcodeHook:"old context-mode ZCode hook entry: command contains context-mode hook",dataDir:"old context-mode data dir <agent home>/context-mode/",dataDirShared:"old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",dataRoot:"old context-mode content under ~/.context-mode/",tmpFile:"old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep",projectLink:"context-mode path in the project reached through a link: report only, upgrade keeps it as is and never follows a link"}),ig=Object.freeze([w.statusLine,w.vscodeMcp,w.dataDirShared,w.tmpFile,w.kiroSteering,w.piGit,w.opencodeGit,w.projectLink]),cg=Object.freeze([w.dataDir,w.dataRoot]);var ag=$+"_";var lg=Object.freeze(["opencode","plugin.js"]);var ku=Object.freeze(["features","mcp"]),Du="omit_tools_from",Lu=Object.freeze(["deferred"]),wu="default_tools_approval_mode",Pu="approve",ug=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",$],fields:{[Du]:Lu,[wu]:Pu}},vscode:{file:[Au],key:["servers",$]},kiro:{file:[".kiro","settings","mcp.json"],key:["mcpServers",$]},zcode:{file:[".zcode","cli","config.json"],key:["mcp","servers",$],fields:{type:"stdio",enabled:!0,timeoutMs:hu},also:[[ku,!0]]}});var dg=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),Mu="Environment: ";var Uu="Docs: ";var Hu="Report file: ",Fu="File it: ",vu="Or open: ",ju="Rules: ",Gu=" --",fg=Object.freeze([Mu,Uu,Hu,Fu,Gu.trim(),vu,ju]),xi="mksglu/context-mode",Bu="agent-report.yml",xg=`https://github.com/${xi}/blob/main/.github/AGENT_ISSUE.md`,pg=Object.freeze(['Search for the same problem first: `gh issue list -R mksglu/context-mode --state all --search "<check id or error>"`. When one matches, add your facts there as a comment.',"File one bug per issue.","Call the `ctx_doctor` tool and paste its full output unchanged in the `ctx-report` field.","Give the versions: context-mode, the agent, the OS and arch, and Node.","Write numbered repro steps that start from a fresh project (`mktemp -d`) and the agent's own install command.","Give the exact command and its exact output in a fenced code block.","Say what you expected and what happened instead.","Name the source file and line when you found the cause.","Replace every secret with `<masked>` and the home folder with `~` before you send."]);var _g=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var Eg=Object.freeze(["CODEX_HOME","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_ROOT","COPILOT_HOME","KIRO_HOME","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","XDG_CONFIG_HOME","SHELL"]),gg=Object.freeze(["node","git","sh"]),mg=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var hg=Object.freeze({"claude-code":["claude plugin marketplace add mksglu/context-mode","claude plugin install context-mode@context-mode"],codex:["codex plugin marketplace add mksglu/context-mode","codex plugin add context-mode@context-mode"],gemini:["gemini extensions install https://github.com/mksglu/context-mode"],qwen:["qwen extensions install https://github.com/mksglu/context-mode:context-mode"],opencode:["opencode plugin add context-mode"],pi:["pi install npm:context-mode"],"copilot-cli":["npm i -g context-mode","context-mode setup --agents copilot-cli"],vscode:["npm i -g context-mode","context-mode setup --agents vscode"],kiro:["npm i -g context-mode","context-mode setup --agents kiro"],zcode:["zcode plugins marketplace add mksglu/context-mode","zcode plugins install context-mode@context-mode"]}),Sg=`https://github.com/${xi}/issues/new?template=${Bu}`;import{dirname as C_,join as iu,relative as k_,resolve as cu,sep as ru}from"node:path";var oo="mcp__plugin_context-mode_context-mode__",gi=Object.freeze(["Bash","PowerShell"]),Wu="PowerShell",Xu="Bash",Ku=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],pi="mcp__",_i="__",Yu={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function qu(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(pi))return e;let n=e.slice(pi.length),o=n.indexOf(_i);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+_i.length)}function zu(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return mi(e).text;if(typeof e=="object"&&e!==null){let t=e;if(typeof t.stdout=="string"||typeof t.stderr=="string"){let n=typeof t.stdout=="string"?t.stdout:"",o=typeof t.stderr=="string"?t.stderr:"";return o===""?n:n===""?o:n+`
4
+ `+o}}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=ro(e);if(t!==null)return t.text}return JSON.stringify(e)}function ro(e){let t=e.file;return e.type==="text"&&typeof t=="object"&&t!==null&&typeof t.content=="string"?{text:t.content,put:(n,o)=>({...n,file:Vu(n.file,o)})}:$u(e)?{text:e.content,put:(n,o)=>({...n,content:o})}:Array.isArray(e.filenames)&&e.filenames.every(n=>typeof n=="string")?{text:e.filenames.join(`
5
5
  `),put:(n,o)=>({...n,filenames:o.split(`
6
- `)})}:typeof e.result=="string"?{text:e.result,put:(n,o)=>({...n,result:o})}:null}function _u(e,t){let n=typeof e.startLine=="number"?e.startLine:1,o=String(e.content).split(`
6
+ `)})}:typeof e.result=="string"?{text:e.result,put:(n,o)=>({...n,result:o})}:null}function Vu(e,t){let n=typeof e.startLine=="number"?e.startLine:1,o=String(e.content).split(`
7
7
  `),r=typeof e.numLines=="number"?e.numLines:o.length,s=t.split(`
8
- `),i=Eu(o,s);if(i===null)return{...e,content:t,startLine:n+r,numLines:s.length};let c=s.slice(0,i.length);return i.length<s.length&&c.push(s[s.length-1]),{...e,content:c.join(`
9
- `),startLine:n+i.at,numLines:c.length}}function Eu(e,t){let n=null;for(let o=0;o<e.length;o++){if(e[o]!==t[0])continue;let r=1;for(;r<t.length&&o+r<e.length&&e[o+r]===t[r];)r++;if((n===null||r>n.length)&&(n={at:o,length:r}),r===t.length)break}return n}function Qs(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function gu(e){let t=e;return(t.mode==="content"||t.mode==="count")&&typeof t.content=="string"}function ei(e){let t=[],n=!1;for(let o of e){let r=typeof o=="object"&&o!==null?o:{};r.type==="text"&&typeof r.text=="string"?t.push(r.text):n=!0}return{text:t.join(`
10
- `),keep:n}}function mu(e){let t=pu(e),o={isError:typeof e=="object"&&e!==null&&e.is_error===!0,bytes:Buffer.byteLength(t),text:t};if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Qs(e)&&(o.shape=e),typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Qs(e)&&(Vn(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,ei(e).keep&&(o.keep=!0)),typeof e=="object"&&e!==null){let r=e;typeof r.persistedOutputPath=="string"&&r.persistedOutputPath!==""&&typeof r.persistedOutputSize=="number"&&r.persistedOutputSize>o.bytes&&(o.persistedPath=r.persistedOutputPath)}return o}function se(e,t,n,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(t+": hook payload is not a JSON object");let r=e,s=du.find(c=>c===r.hook_event_name);if(s===void 0)throw new Error(t+": unknown hook event "+String(r.hook_event_name));let i={event:s,agent:t,sessionId:String(r.session_id??""),cwd:String(r.cwd??"")};if(typeof r.agent_id=="string"&&(i.agentId=r.agent_id,typeof r.agent_type=="string"&&(i.agentType=r.agent_type)),s==="SessionStart"&&typeof r.source=="string"&&o[r.source]!==void 0&&(i.source=o[r.source]),s==="UserPromptSubmit"&&typeof r.prompt=="string"&&(i.prompt=r.prompt),s==="PreToolUse"||s==="PostToolUse"){let c=String(r.tool_name??""),l=typeof r.tool_input=="object"&&r.tool_input!==null?r.tool_input:{},a={name:c,canonicalName:xu(c,n),input:l};typeof r.tool_use_id=="string"&&r.tool_use_id!==""&&(a.callId=r.tool_use_id),i.tool=a}return s==="PostToolUse"&&(i.result=mu(r.tool_response)),i}function hu(e,t){let n=e.result?.shape;if(e.tool?.canonicalName==="Bash"){let{persistedOutputPath:r,persistedOutputSize:s,...i}=n??{};return{interrupted:!1,...i,stdout:t,stderr:""}}let o=n===void 0?null:Vn(n);return n!==void 0&&o!==null?o.put(n,t):e.result?.blocks===!0?[{type:"text",text:t}]:t}function j(e,t,n){let o=r=>({stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e.event,...r}}),exitCode:0});switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return o({additionalContext:t.text});case"deny":return o({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
11
- `+t.reason});case"replace":return n&&e.event==="PostToolUse"?o({updatedToolOutput:hu(e,t.output)}):{stdout:"",exitCode:0}}}var Su={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function bu(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Ou(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(t.hook_event_name===void 0)throw new Error("claude-code: missing required field hook_event_name");for(let n of Su[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function ti(e){Ou(e);let t=se(e,"claude-code",zn,fu);if(t.tool!==void 0&&t.tool.name===lu&&(t.tool.canonicalName=uu),t.cwd===""&&(t.cwd=process.env.CLAUDE_PROJECT_DIR||process.cwd()),t.event==="PostToolUse"&&t.tool!==void 0&&t.tool.callId===void 0){let n=typeof t.tool.input.command=="string"?t.tool.input.command:JSON.stringify(t.tool.input);t.tool.callId="h"+bu(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function ni(e,t,n){return j(e,t,!0)}var $n="mcp__context_mode__",Ru={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"},Jn="Stop",Au={stdout:"",exitCode:0};function oi(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===Jn){let t=e;return{event:Jn,agent:"codex",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")}}return se(e,"codex",$n,Ru)}function ri(e,t,n){return e.event===Jn?Au:j(e,t,!1)}var Nt="mcp_context-mode_",si={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},ii={startup:"startup",resume:"resume",clear:"clear"},Nu=["SessionStart","UserPromptSubmit","PostToolUse"],Iu=["UserPromptSubmit","PreToolUse"],yt={stdout:"",exitCode:0},Cu=`the tool ran and succeeded; context-mode indexed its full output, and this is the part that answers the call:
12
- `;function R(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var ci={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function ku(e,t){if(e.startsWith(Nt))return e.slice(Nt.length);if(Object.hasOwn(ci,e))return ci[e];if(typeof t!="object"||t===null)return e;let n=t,o=R(n,"server_name"),r=R(n,"tool_name");return typeof o!="string"||typeof r!="string"?e:"mcp:"+o+":"+r}function Du(e){if(!Array.isArray(e)||e.length===0)return;let t=[];for(let n of e){if(typeof n=="string"){t.push(n);continue}if(typeof n!="object"||n===null)return;let o=R(n,"text");if(typeof o!="string")return;t.push(o)}return t.join("")}function Lu(e){let t=typeof e=="object"&&e!==null?e:void 0,n=t===void 0?void 0:R(t,"llmContent"),o=e===void 0?"":typeof e=="string"?e:typeof n=="string"?n:Du(n)??JSON.stringify(e),r=t===void 0?void 0:R(t,"error"),s={isError:r!=null,bytes:Buffer.byteLength(o),text:o};return wu(n)&&(s.keep=!0),s}function wu(e){return(Array.isArray(e)?e:[e]).some(n=>typeof n=="object"&&n!==null&&(Object.hasOwn(n,"inlineData")||Object.hasOwn(n,"fileData")))}var Pu=["https://","http://"],Mu=`.,;:!?)]}>'"`,Uu=`
13
- \r\f\v`;function Hu(e){let t=[],n="";for(let o of e)Uu.includes(o)?(n!==""&&t.push(n),n=""):n+=o;return n!==""&&t.push(n),t}function Fu(e){if(typeof e=="string")for(let t of Hu(e)){let n=t.toLowerCase(),o=Pu.map(s=>n.indexOf(s)).filter(s=>s>=0).sort((s,i)=>s-i)[0];if(o===void 0)continue;let r=t.slice(o);for(;r.length>0&&Mu.includes(r[r.length-1]);)r=r.slice(0,-1);return r}}function vu(e,t){if(e==="web_fetch"&&R(t,"url")===void 0){let n=Fu(R(t,"prompt"));return n===void 0?t:{...t,url:n}}if(e==="read_many_files"&&R(t,"file_path")===void 0){let n=R(t,"include"),o=Array.isArray(n)?n.filter(r=>typeof r=="string"):[];return o.length===0?t:{...t,file_path:o.join(" ")}}return t}function ai(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("gemini: hook payload is not a JSON object");let t=e,n=R(t,"hook_event_name"),o=typeof n=="string"&&Object.hasOwn(si,n)?si[n]:void 0;if(o===void 0)throw new Error("gemini: unknown hook event "+String(n));let r={event:o,agent:"gemini",sessionId:String(R(t,"session_id")??""),cwd:String(R(t,"cwd")??"")},s=R(t,"source");o==="SessionStart"&&typeof s=="string"&&Object.hasOwn(ii,s)&&(r.source=ii[s]);let i=R(t,"prompt");if(o==="UserPromptSubmit"&&typeof i=="string"&&(r.prompt=i),o==="PreToolUse"||o==="PostToolUse"){let c=String(R(t,"tool_name")??""),l=R(t,"tool_input");r.tool={name:c,canonicalName:ku(c,R(t,"mcp_context")),input:vu(c,typeof l=="object"&&l!==null&&!Array.isArray(l)?l:{})}}return o==="PostToolUse"&&(r.result=Lu(R(t,"tool_response"))),r}function li(e,t,n){switch(t.kind){case"allow":return yt;case"hint":return Nu.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:yt;case"deny":return Iu.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
14
- `+t.reason}),exitCode:0}:yt;case"replace":return e.event!=="PostToolUse"?yt:{stdout:JSON.stringify({decision:"deny",reason:Cu+t.output}),exitCode:0}}}var Qn="mcp__context-mode__",Gu={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},ui={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},Bu="PostToolUseFailure";function di(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===Bu,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=se(n,"qwen",Qn,Gu);if(o.tool!==void 0&&Object.hasOwn(ui,o.tool.name)&&(o.tool.canonicalName=ui[o.tool.name]),t){let r=e.error,s=typeof r=="string"?r:r===void 0?"":JSON.stringify(r);o.result={isError:!0,bytes:Buffer.byteLength(s),text:s}}return o}function fi(e,t,n){return j(e,t,!1)}var Ct="context-mode-",Xu={sessionStart:{event:"SessionStart",casing:"camel",failure:!1},userPromptSubmitted:{event:"UserPromptSubmit",casing:"camel",failure:!1},preToolUse:{event:"PreToolUse",casing:"camel",failure:!1},postToolUse:{event:"PostToolUse",casing:"camel",failure:!1},postToolUseFailure:{event:"PostToolUse",casing:"camel",failure:!0},SessionStart:{event:"SessionStart",casing:"snake",failure:!1},UserPromptSubmit:{event:"UserPromptSubmit",casing:"snake",failure:!1},PreToolUse:{event:"PreToolUse",casing:"snake",failure:!1},PostToolUse:{event:"PostToolUse",casing:"snake",failure:!1},PostToolUseFailure:{event:"PostToolUse",casing:"snake",failure:!0}},xi={startup:"startup",resume:"resume",new:"startup"},Ku={camel:{event:"hookEventName",session:"sessionId",tool:"toolName",args:"toolArgs",result:"toolResult"},snake:{event:"hook_event_name",session:"session_id",tool:"tool_name",args:"tool_input",result:"tool_result"}},Ei="success";function kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Zn=Object.freeze(["bash","powershell"]),pi=Object.fromEntries(Zn.map(e=>[e,"Bash"]));function Yu(e){return e.startsWith(Ct)?e.slice(Ct.length):Object.hasOwn(pi,e)?pi[e]:e}var _i=e=>typeof e=="number"&&Number.isFinite(e);function qu(e,t){let n=t.view_range;if(e!=="view"||!Array.isArray(n)||!_i(n[0]))return t;let o={...t,offset:n[0]};return _i(n[1])&&n[1]>=n[0]&&(o.limit=n[1]-n[0]+1),o}function zu(e){if(kt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return kt(t)?t:{}}catch{return{}}}var Vu={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function Ju(e,t,n){let o=Vu[t],r=kt(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==Ei,bytes:Buffer.byteLength(s),text:s}}var $u=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function Qu(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:$u.find(([t])=>Object.hasOwn(e,t))?.[1]}function gi(e){if(!kt(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=Qu(e),n=typeof t=="string"?Xu[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Ku[n.casing],r=n.event,s={event:r,agent:"copilot-cli",sessionId:String(e[o.session]??""),cwd:String(e.cwd??"")};if(r==="SessionStart"&&typeof e.source=="string"&&xi[e.source]!==void 0&&(s.source=xi[e.source]),r==="UserPromptSubmit"&&typeof e.prompt=="string"&&(s.prompt=e.prompt),r==="PreToolUse"||r==="PostToolUse"){let i=String(e[o.tool]??""),c={name:i,canonicalName:Yu(i),input:qu(i,zu(e[o.args]))};s.tool=c}return r==="PostToolUse"&&(s.result=Ju(e[o.result],n.casing,n.failure)),s}var It={stdout:"",exitCode:0};function mi(e,t,n){switch(t.kind){case"allow":return It;case"hint":return e.event==="PostToolUse"?It:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?It:{stdout:JSON.stringify({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
15
- `+t.reason}),exitCode:0};case"replace":return e.event!=="PostToolUse"?It:{stdout:JSON.stringify({modifiedResult:{resultType:Ei,textResultForLlm:t.output}}),exitCode:0}}}var Dt="mcp_context-mode_",Ri=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],hi="mcp_",Si="_",ed="new",eo=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),wt=Object.freeze(["read_file","view"]),to=Object.freeze(["fetch_webpage","web_fetch"]),bi=Object.fromEntries([...eo.map(e=>[e,"Bash"]),...wt.map(e=>[e,"Read"]),...to.map(e=>[e,"WebFetch"])]);function Ai(e){if(e.startsWith(Dt))return e.slice(Dt.length);if(Object.hasOwn(bi,e))return bi[e];if(!e.startsWith(hi))return e;let t=e.slice(hi.length),n=t.indexOf(Si);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+Si.length)}var Fe=e=>typeof e=="number"&&Number.isFinite(e);function yi(e,t,n){if(t==="Read"&&wt.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),Fe(n.startLine)&&(o.offset=n.startLine),Fe(n.startLine)&&Fe(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&Fe(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];Fe(r)&&r>=n.view_range[0]&&(o.limit=r-n.view_range[0]+1)}return o}return t==="WebFetch"&&e==="fetch_webpage"&&Array.isArray(n.urls)&&typeof n.urls[0]=="string"?{...n,url:n.urls[0]}:n}function td(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:typeof e=="object"&&e!==null&&e.is_error===!0,bytes:Buffer.byteLength(t),text:t}}var nd={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},od=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],Oi={new:"startup",startup:"startup",resume:"resume"},rd="success";function Lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sd(e){if(Lt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Lt(t)?t:{}}catch{return{}}}function id(e){let t=Lt(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==rd,bytes:Buffer.byteLength(n),text:n}}function Ti(e,t){let n=typeof t=="string"?nd[t]??Ri.find(r=>r===t):void 0;if(n===void 0)throw new Error("vscode: unknown hook event "+String(t));let o={event:n,agent:"vscode",sessionId:String(e.sessionId??""),cwd:String(e.cwd??"")};if(n==="SessionStart"&&typeof e.source=="string"&&Oi[e.source]!==void 0&&(o.source=Oi[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=Ai(r);o.tool={name:r,canonicalName:s,input:yi(r,s,sd(e.toolArgs))}}return n==="PostToolUse"&&(o.result=id(e.toolResult)),o}function Ni(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("vscode: hook payload is not a JSON object");let t=e;if(t.hookEventName!==void 0)return Ti(t,t.hookEventName);if(t.hook_event_name===void 0){let r=od.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return Ti(t,r)}let n=Ri.find(r=>r===t.hook_event_name);if(n===void 0)throw new Error("vscode: unknown hook event "+String(t.hook_event_name));let o={event:n,agent:"vscode",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")};if(n==="SessionStart"&&t.source===ed&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=Lt(t.tool_input)?t.tool_input:{},i=Ai(r);o.tool={name:r,canonicalName:i,input:yi(r,i,s)}}return n==="PostToolUse"&&(o.result=td(t.tool_response)),o}function Ii(e,t,n){return j(e,t,!1)}var Pt="mcp_context_mode_",Ci="mcp_context-mode_",ki={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},ad="prompt",ld="USER_PROMPT",Di="mcp_",no=Object.freeze(["execute_bash","execute_pwsh","shell"]),Li=Object.fromEntries(no.map(e=>[e,"Bash"])),wi="_",Pi={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function ud(e){if(e.startsWith(Pt))return e.slice(Pt.length);if(e.startsWith(Ci))return e.slice(Ci.length);if(Object.hasOwn(Li,e))return Li[e];if(!e.startsWith(Di))return e;let t=e.slice(Di.length),n=t.indexOf(wi);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+wi.length)}function dd(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function Mi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("kiro: hook payload is not a JSON object");let t=e,n=typeof t.hook_event_name=="string"?t.hook_event_name:"",o=Object.prototype.hasOwnProperty.call(ki,n)?ki[n]:void 0;if(o===void 0)throw new Error("kiro: unknown hook event "+String(t.hook_event_name));let r={event:o,agent:"kiro",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")};if(o==="SessionStart"&&typeof t.source=="string"&&Pi[t.source]!==void 0&&(r.source=Pi[t.source]),o==="UserPromptSubmit"){let s=t[ad],i=typeof s=="string"?s:process.env[ld];i!==void 0&&(r.prompt=i)}if(o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool_name??""),i=typeof t.tool_input=="object"&&t.tool_input!==null&&!Array.isArray(t.tool_input)?t.tool_input:{};r.tool={name:s,canonicalName:ud(s),input:i}}return o==="PostToolUse"&&(r.result=dd(t.tool_response)),r}function Ui(e,t,n){if(e.event==="UserPromptSubmit")return{stdout:t.kind==="hint"?t.text:"",exitCode:0};switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:t.text,exitCode:0};case"deny":return{stdout:"",stderr:t.rewritten===void 0?t.reason:t.rewritten+`
16
- `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var oo="mcp__context-mode__",Hi="mcp__plugin_context-mode_context-mode__",xd={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},pd={hook_event_name:"hookEventName",session_id:"sessionId"},_d="PostToolUseFailure";function Fi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("zcode: hook payload is not a JSON object");let t={...e};for(let[i,c]of Object.entries(pd))t[i]===void 0&&(t[i]=t[c]);let n=t.hook_event_name===_d;n&&(t.hook_event_name="PostToolUse");let r=(typeof t.tool_name=="string"?t.tool_name:"").startsWith(Hi)?Hi:oo,s=se(t,"zcode",r,xd);if(n){let i=typeof t.error=="string"?t.error:t.error===void 0?"":JSON.stringify(t.error);s.result={isError:!0,bytes:Buffer.byteLength(i),text:i}}return s}function vi(e,t,n){return j(e,t,!1)}var Bi="",ji={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},Gi={bash:"Bash",read:"Read",edit:"Edit",write:"Write"};function gd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function md(e){let t=e.content===void 0?"":typeof e.content=="string"?e.content:JSON.stringify(e.content),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function Wi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("pi: hook payload is not an object");let t=e,n=typeof t.type=="string"?t.type:"",o=Object.prototype.hasOwnProperty.call(ji,n)?ji[n]:void 0;if(o===void 0)throw new Error("pi: unknown hook event "+String(t.type));let r={event:o.event,agent:"pi",sessionId:String(t.sessionId??""),cwd:String(t.cwd??"")};if(o.source!==void 0&&(r.source=o.source),o.event==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o.event==="PreToolUse"||o.event==="PostToolUse"){let s=String(t.toolName??"");r.tool={name:s,canonicalName:Object.hasOwn(Gi,s)?Gi[s]:s,input:gd(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=md(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function hd(e,t){switch(t?.kind){case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
17
- `+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function Xi(e,t,n){let o=hd(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:zs,content:o.stdout,timestamp:Date.now()}}function Ki(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var Vi="",Yi=z+"_",qi={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},ro="bash",so="read",bd=Object.freeze([ro,"shell"]),zi={webfetch:"WebFetch",[so]:"Read",...Object.fromEntries(bd.map(e=>[e,"Bash"]))};function io(e){return e.startsWith(Yi)?e.slice(Yi.length):Object.prototype.hasOwnProperty.call(zi,e)?zi[e]:e}function Od(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Td(e){let t=e.output===void 0?"":typeof e.output=="string"?e.output:JSON.stringify(e.output),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function Ji(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("opencode: hook payload is not an object");let t=e,n=typeof t.type=="string"?t.type:"",o=Object.prototype.hasOwnProperty.call(qi,n)?qi[n]:void 0;if(o===void 0)throw new Error("opencode: unknown hook event "+String(t.type));let r={event:o,agent:"opencode",sessionId:String(t.sessionID??""),cwd:String(t.directory??"")};if(o==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool??"");r.tool={name:s,canonicalName:io(s),input:Od(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=Td(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function $i(e,t,n){switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
18
- `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var ve={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},Qi={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},Ad={...Qi,shell:[...Zs]},yd=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:zn,nativeTools:Ad,execReadOnlyHint:!1,eventMap:ve,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:F,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"skills"},decode:ti,encode:ni},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:$n,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:ve,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:F,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:oi,encode:ri},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Nt,nativeTools:{shell:["run_shell_command"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:{UserPromptSubmit:"BeforeAgent",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",PreCompact:"PreCompress"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:F,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:ai,encode:li},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Qn,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:ve,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:F,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:di,encode:fi},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:Ct,nativeTools:{shell:[...Zn]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:F,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:gi,encode:mi},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:Dt,nativeTools:{shell:[...eo],read:[...wt],webfetch:[...to]},execReadOnlyHint:!1,eventMap:{...ve,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:F,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:Ni,encode:Ii},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:Pt,nativeTools:{shell:[...no]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:F,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:Mi,encode:Ui},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:oo,nativeTools:Qi,execReadOnlyHint:!1,eventMap:ve,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:F,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:Fi,encode:vi},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:Bi,nativeTools:{shell:["bash","powershell"],read:["read"]},execReadOnlyHint:!1,eventMap:{SessionStart:"session_start",UserPromptSubmit:"input",PreToolUse:"tool_call",PostToolUse:"tool_result"},compactDelivery:"pi-flag",compactSummary:"none",hookTimeoutMs:Tn,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:Wi,encode:Xi,checkPermission:Ki},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:Vi,nativeTools:{shell:[ro],read:[so]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:Tn,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:Ji,encode:$i,toCanonicalTool:io}]),Nd=new Map(yd.map(e=>[e.id,e])),Id=new Set(["claude-code","gemini","copilot-cli","pi"]);function _e(e){return Id.has(e.id)}var Cd=new Set(["claude-code","copilot-cli","pi"]);function co(e){return Cd.has(e.id)&&_e(e)}var kd=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function Mt(e){return kd.has(e.id)}function ie(e){return Nd.get(e)}import{resolve as en}from"node:path";var Dd=["&&","||",";;","|&",";","|","&","(",")"],Ld=["&>>","&>"],wd=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],Pd="&",Md="<<",Zi="<<-",Ud=";",ec=`\r
19
- `,tc=`\\
20
- `,nc=`\\\r
21
- `,Hd="$(",sc="${",ic="$'",je="((",oc="))",Ee="[[",Ut="]]",ao="<(",cc=">(",w=2,ac=`
22
- \r;&|()<>`,Fd=`
23
- \r`,vd='$`"\\\n',jd="case",Gd="esac";function ge(e,t){e.end==="complete"&&(e.end=t)}function lo(e){return e!==""&&e>="0"&&e<="9"}function rc(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function lc(e){return e===""||ac.includes(e)}function uo(e){return e!==""&&Fd.includes(e)}function G(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function Ht(e,t){let n=e.s.indexOf("'",t+1);return n<0?(ge(e,"unterminated-quote"),e.n):n+1}function uc(e,t){let n=t+ic.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=w;continue}if(o==="'")return n+1;n++}return ge(e,"unterminated-quote"),e.n}function fo(e,t,n){let o=t+1;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(r==="\\"){o+=w;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=Ge(e,o,n);continue}if(r==="$"&&s==="{"){o=xo(e,o,n);continue}if(r==="`"){o=me(e,o);continue}o++}return ge(e,"unterminated-quote"),e.n}function me(e,t){let n=t+1;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=w;continue}if(o==="`")return n+1;n++}return e.n}function xo(e,t,n){let o=t+sc.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=w;continue}if(s==="'"){o=Ht(e,o);continue}if(s==='"'){o=fo(e,o,n);continue}if(s==="$"&&i==="("){o=Ge(e,o,n);continue}if(s==="`"){o=me(e,o);continue}if(s==="{"&&r++,s==="}"){if(r===0)return o+1;r--}o++}return e.n}function po(e,t){let n=0,o=t+je.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(oc,o)?o+oc.length:-1;n--}o++}return-1}function Ge(e,t,n){let o=t+Hd.length-1;if(e.s.startsWith(je,o)){let r=po(e.s,o);if(r>0)return r}return Ft(e,o+1,!0,n+1,null,null)}function Bd(e,t,n){let o=t+Ee.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=w;continue}if(s==="'"){o=Ht(e,o);continue}if(s==='"'){o=fo(e,o,n);continue}if(s==="$"&&i==="("){o=Ge(e,o,n);continue}if(s==="$"&&i==="{"){o=xo(e,o,n);continue}if(s==="`"){o=me(e,o);continue}let c=uo(e.s.charAt(o-1));if(c&&e.s.startsWith(Ut,o)&&lc(e.s.charAt(o+Ut.length))){if(r===0)return o+Ut.length;r--,o+=Ut.length;continue}if(c&&e.s.startsWith(Ee,o)&&uo(e.s.charAt(o+Ee.length))){r++,o+=Ee.length;continue}o++}return-1}function Wd(e,t){let n=t;for(;lo(e.charAt(n));)n++;if(n===t){for(let o of Ld)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of wd){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(Pd))if(e.charAt(r)==="-")r++;else for(;lo(e.charAt(r));)r++;return{end:r,op:o}}return null}function Xd(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(ac.includes(r))break;if(r==="\\"){o+=w;continue}if(r==="'"){o=Ht(e,o);continue}if(r==='"'){o=fo(e,o,n);continue}if(r==="$"&&s==="'"){o=uc(e,o);continue}if(r==="$"&&s==="("){o=Ge(e,o,n);continue}if(r==="$"&&s==="{"){o=xo(e,o,n);continue}if(r==="`"){o=me(e,o);continue}o++}return Math.min(o,e.n)}function Kd(e,t,n,o,r){let s=t;for(let i of n){let c=s,l=!1;for(;s<e.n;){let a=e.s.indexOf(`
24
- `,s),d=a<0?e.n:a,u=e.s.slice(s,d);if(u.endsWith("\r")&&(u=u.slice(0,-1)),s=a<0?e.n:a+1,(i.strip?u.trim():u)===i.tag){l=!0;break}}if(o!==null&&r!==null&&r.push(o.length),G(o,"unhandled",e.s.slice(c,s),c,s),!l)return ge(e,"unterminated-heredoc"),e.n}return n.length=0,s}function Ft(e,t,n,o,r,s){if(o>v)return ge(e,"too-deep"),e.n;let i=e.s,c=t,l=0,a=0,d=null,u=[];for(;c<e.n;){let f=i.charAt(c),x=i.charAt(c+1);if(f===" "||f===" "){c++;continue}if(i.startsWith(tc,c)){c+=tc.length;continue}if(i.startsWith(nc,c)){c+=nc.length;continue}if(f===`
25
- `||f==="\r"){let S=c;c+=i.startsWith(ec,c)?ec.length:1,G(r,"op",Ud,S,c),d=null,u.length>0&&(c=Kd(e,c,u,r,s));continue}if(f==="#"){for(;c<e.n&&i.charAt(c)!==`
26
- `&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(ao,c)||i.startsWith(cc,c)){let S=Ft(e,c+ao.length,!0,o+1,null,null);G(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}let p=Wd(i,c);if(p!==null){G(r,"io",i.slice(c,p.end),c,p.end),d=p.op===Md||p.op===Zi?p.op===Zi:null,c=p.end;continue}if(i.startsWith(Ee,c)&&uo(i.charAt(c+Ee.length))){let S=Bd(e,c,o);if(S>0){G(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}if(i.startsWith(je,c)){let S=po(i,c);if(S>0){G(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}let g=Dd.find(S=>i.startsWith(S,c));if(g!==void 0){if(n&&g==="("&&l++,n&&g===")"){if(l>0)l--;else if(a===0)return c+1}G(r,"op",g,c,c+g.length),c+=g.length,d=null;continue}if(f==="$"&&x==="("||f==="`"){let S=f==="`"?me(e,c):Ge(e,c,o);if(lc(i.charAt(S))){G(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}let E=c;c=Xd(e,c,o);let h=i.slice(E,c);G(r,"word",h,E,c),d!==null&&(u.push({tag:he(h),strip:d}),d=null),n&&h===jd&&a++,n&&h===Gd&&a>0&&a--}return u.length>0&&ge(e,"unterminated-heredoc"),e.n}function dc(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return Ft(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function he(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=w;continue}if(r==="'"){let s=e.indexOf("'",n+1),i=s<0?o:s;t+=e.slice(n+1,i),n=i+1;continue}if(r==="$"&&e.charAt(n+1)==="'"){let s=n+ic.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=w;continue}t+=e.charAt(s),s++}n=s+1;continue}if(r==='"'){let s=n+1;for(;s<o&&e.charAt(s)!=='"';){let i=e.charAt(s+1);if(e.charAt(s)==="\\"&&i!==""&&vd.includes(i)){t+=i,s+=w;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function vt(e){let t={s:e,n:e.length,end:"complete"},n=[],o=!1,r=0;for(;r<t.n;){let s=e.charAt(r),i=e.charAt(r+1);if(s==="\\"){r+=w;continue}if(!o&&s==="'"){r=Ht(t,r);continue}if(!o&&s==="$"&&i==="'"){r=uc(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=sc.length;continue}let c=e.startsWith(ao,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(cc,r))){let l=r+1;if(s==="$"&&e.startsWith(je,l)&&po(e,l)>0){r=l+je.length;continue}let a=Ft(t,l+1,!0,1,null,null),d=a>l+1&&e.charAt(a-1)===")"?a-1:a;n.push({wrapper:s==="$"?"$()":c?"<()":">()",body:e.slice(l+1,d)}),r=a;continue}if(s==="`"){let l=me(t,r),a=l>r+1&&e.charAt(l-1)==="`"?l-1:l;n.push({wrapper:"`",body:e.slice(r+1,a)}),r=l;continue}r++}return n}function jt(e){let t=e.charAt(0);if(!(rc(t)||t==="_"))return!1;for(let n=1;n<e.length;n++){let o=e.charAt(n);if(o==="="||o==="+"&&e.charAt(n+1)==="=")return!0;if(!(rc(o)||lo(o)||o==="_"))return!1}return!1}var _c=[";","&","&&","||"],Ec=["|","|&"],Be="(",We=")",gc=";;",go=["(",")"],Yd="!";function P(e,t){for(let n of t)e.push(n)}var b=Object.freeze({group:"{",groupEnd:"}",if:"if",then:"then",elif:"elif",else:"else",fi:"fi",while:"while",until:"until",for:"for",in:"in",do:"do",done:"done",case:"case",esac:"esac",function:"function",coproc:"coproc",select:"select"}),mc=[],qd="[[",zd="((",hc=[">",">>",">|","&>","&>>",">&"],Vd=[...hc,"<","<>","<<<","<<","<<-"],Jd=["","1"],Sc=["-","/dev/stdout","/dev/stderr"],Bt="-",Xe="--",Ke="=",$d="/",Qd=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),Gt=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),_o="-c",Eo="--bytes",Zd="c",ef="--count",ce=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],$=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,I=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,mo=e=>e!==""&&e>="0"&&e<="9",tf=e=>mo(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function ho(e){let t=e.lastIndexOf($d);return t>=0&&t<e.length-1?e.slice(t+1):e}function So(e,t){let n=Qd[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===Xe)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+Ke))s=r.slice(n.long.length+Ke.length);else if(r.startsWith(Bt)&&!r.startsWith(Xe)){let i=r.indexOf(n.short,Bt.length);if(i<0)continue;s=i+n.short.length<r.length?r.slice(i+n.short.length):t[o+1]}else continue;if(s!==void 0&&!Sc.includes(s))return!0}return!1}function nf(e){if(e==="")return!1;for(let t of e)if(!mo(t))return!1;return!0}function of(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===_o||n===Eo?o=e[t+1]:n.startsWith(Eo+Ke)?o=n.slice(Eo.length+Ke.length):n.startsWith(_o)&&!n.startsWith(Xe)&&(o=n.slice(_o.length)),o!==void 0)return nf(o)&&Number(o)<=V}return!1}function rf(e){for(let t of e){if(t===Xe)return!1;if(t===ef||t.startsWith(Bt)&&!t.startsWith(Xe)&&t.includes(Zd))return!0}return!1}function fc(e){if(!e.startsWith(D.fieldSep))return!1;for(let t of e.slice(D.fieldSep.length).split(D.fieldSep)){if(t==="")return!1;for(let n of t)if(!tf(n))return!1}return!0}function sf(e){let t=e.trim();if(t===D.identity||t===D.length)return!0;let n=t.indexOf(D.pipeLength.charAt(0));if(n<0)return fc(t);let o=t.slice(0,n).trim(),r=D.pipeLength.slice(1).trim();return(o===D.identity||fc(o))&&t.slice(n+1).trim()===r}function cf(e){let t=e.argv0.toLowerCase();if(t===Gt.wc)return!0;if(t===Gt.head)return of(e.args);if(t===Gt.grep)return rf(e.args);if(t===Gt.jq){let n=e.args.filter(o=>!o.startsWith(Bt));return n.length===1&&sf(n[0])}return!1}function bo(e){return vt(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function bc(e,t,n){return n<=t?[]:bo(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function Oc(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function af(e){let t=0;for(;mo(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Tc(e){let t=af(e.toks[e.i].text);if(e.i++,!Vd.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,hc.includes(t.op)&&Jd.includes(t.fd)&&!Sc.includes(he(n.text)))}function Rc(e){let t=!1;for(;O(e)?.kind==="io";)t=Tc(e)||t;return t}function Ac(e){for(;O(e)?.kind==="op"&&_c.includes(O(e)?.text??"");)e.i++}function Se(e,t){if(e.depth++,e.depth>v)return e.err="nesting-too-deep",ce();let n=t();if(e.depth--,Rc(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function yc(e){if(Ac(e),!I(O(e),b.do))return[];e.i++;let t=B(e,[b.done]);return I(O(e),b.done)&&e.i++,t}function lf(e){e.i++;let t=B(e,[b.then]);for(;e.err===null;){let n=O(e);if(I(n,b.then)||I(n,b.else)){e.i++,P(t,B(e,[b.elif,b.else,b.fi]));continue}if(I(n,b.elif)){e.i++,P(t,B(e,[b.then]));continue}I(n,b.fi)&&e.i++;break}return t}function uf(e){e.i++;let t=B(e,[b.do]);return P(t,yc(e)),t}function df(e){e.i++;let t=[],n=O(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,I(O(e),b.in)){e.i++;let o=e.i;for(;(O(e)?.kind==="word"||O(e)?.kind==="unhandled")&&!I(O(e),b.do);)e.i++;P(t,bc(e,o,e.i))}return P(t,yc(e)),t}function ff(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,P(t,bc(e,e.i-1,e.i))),I(O(e),b.in)&&e.i++;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)||o.kind==="op"&&(_c.includes(o.text)||o.text===gc)){e.i++;continue}if(I(o,b.esac)){e.i++;break}for($(o,Be)&&e.i++;e.i<e.toks.length&&!$(O(e),We);){let s=e.toks[e.i];if(s.kind==="op"&&!Ec.includes(s.text))break;e.i++}if(!$(O(e),We))break;e.i++;let r=B(e,[b.esac]);Oc(r,b.case),P(t,r)}return t}function xc(e,t){Ac(e);let n=Nc(e);return Oc(n.cmds,t),{cmds:n.cmds,simple:null}}function pc(e,t){return go.every((n,o)=>$(e.toks[t+o],n))}function xf(e){let t=e.i,n=[],o=!1;for(;e.i<e.toks.length;){let a=e.toks[e.i];if(a.kind==="op")break;if(a.kind==="io"){o=Tc(e)||o;continue}if(n.length===0&&a.kind==="word"&&jt(a.text)){e.i++;let d=O(e);if(a.text.endsWith(Ke)&&d!==void 0&&$(d,Be)&&d.start===a.end){let u=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,$(f,Be)&&u++,$(f,We)&&--u===0)break}}continue}n.push(a),e.i++}if(e.i===t)return ce();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:bo(r),simple:null};let s=a=>a.kind==="word"?he(a.text):a.text,i=ho(s(n[0])),c=n.slice(1).map(s),l={argv0:i,args:c,redirectsToFile:o||So(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[l],simple:l}}function Nc(e){let t=O(e);if(t===void 0)return ce();if(t.kind==="op")return t.text!==Be?ce():Se(e,()=>{e.i++;let n=B(e,mc);return $(O(e),We)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(qd)||t.text.startsWith(zd)))return e.i++,Rc(e),{cmds:bo(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return Se(e,()=>{e.i++;let n=B(e,[b.groupEnd]);return I(O(e),b.groupEnd)&&e.i++,n});case b.if:return Se(e,()=>lf(e));case b.while:case b.until:return Se(e,()=>uf(e));case b.for:return Se(e,()=>df(e));case b.case:return Se(e,()=>ff(e));case b.coproc:return e.err="coproc",ce();case b.select:return e.err="select",ce();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=he(n.text),e.i++),pc(e,e.i)&&(e.i+=go.length),xc(e,o)}default:if(pc(e,e.i+1))return e.i+=go.length+1,xc(e,he(t.text))}return xf(e)}function pf(e){I(O(e),Yd)&&e.i++;let t=[],n=ce();for(;e.err===null;){n=Nc(e),P(t,n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&Ec.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&cf(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function B(e,t){let n=[];for(;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)){e.i++;continue}if(o.kind==="op"){if(o.text===We||o.text===gc)return n;if(o.text!==Be){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;P(n,pf(e)),e.i===r&&e.err===null&&e.i++}return n}function be(e){let t=dc(e);if(t.end==="unterminated-quote")return{ok:!1,construct:"unterminated-quote"};if(t.end==="unterminated-heredoc")return{ok:!1,construct:"unterminated-heredoc"};if(t.end==="too-deep")return{ok:!1,construct:"nesting-too-deep"};let n={toks:t.tokens,src:e,bodies:new Set(t.heredocBodies),i:0,depth:0,err:null},o=[];for(;n.i<n.toks.length&&n.err===null;)P(o,B(n,mc)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as Ic}from"node:path";var Xt="'",Oe='"',Kt="`",_f=" \r",qe="([{",Ao=")]}",Oo=` \r
27
- |;>`,Dc="*",Cc="1",To="::",Wt=To.length,Ef=Wt;function Yt(e,t){let n=e.charAt(t);for(let o=t+1;o<e.length;o++){let r=e.charAt(o);if(n===Oe&&r===Kt){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function gf(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===Oe&&r===Kt&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function Ye(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Xt||r===Oe){let s=Yt(e,o);if(s<0)return-1;o=s;continue}if(r===Kt){o++;continue}if(qe.includes(r))n++;else if(Ao.includes(r)&&--n===0)return o}return-1}function mf(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Xt||r===Oe){let s=Yt(e,o);if(s<0)return e.length;o=s;continue}if(qe.includes(r))n++;else if(Ao.includes(r))n--;else if(n<=0&&Oo.includes(r))return o}return e.length}function hf(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===Xt||s===Oe){let i=Yt(e,r);if(i<0)break;r=i;continue}qe.includes(s)?n++:Ao.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var Sf=e=>e!==""&&(e===Dc||[...e].every(t=>t>="0"&&t<="9")),kc=()=>({words:[],toFile:!1,chained:!1});function Lc(e){let t=[],n=[],o=kc(),r="",s=!1,i=!0,c=null,l=e.length,a=()=>{s&&(c!==null?(c==="file"&&(o.toFile=!0),c=null):o.words.push(r),r="",s=!1,i=!0)},d=()=>{a(),(o.words.length>0||o.toFile)&&n.push(o),o=kc()},u=()=>{d(),n.length>0&&t.push(n),n=[]},f=(p,g)=>{r+=p,s=!0,g&&(i=!1)},x=0;for(;x<l;){let p=e.charAt(x),g=e.charAt(x+1);if(p===Xt||p===Oe){let E=Yt(e,x);f(gf(e.slice(x+1,E<0?l:E),p),!0),x=E<0?l:E+1}else if(p===Kt)g!==`
28
- `&&g!==""&&f(g,!1),x+=Wt;else if(p===`
29
- `)u(),x++;else if(_f.includes(p))a(),x++;else if(p===";")u(),x++;else if(p==="|")g==="|"?(u(),x+=Wt):(d(),x++);else if(p==="&")g==="&"?(u(),x+=Wt):((s||o.words.length>0)&&f(p,!1),x++);else if(p==="#"&&!s)for(;x<l&&e.charAt(x)!==`
30
- `;)x++;else if(p===">"){let E=Cc;s&&i&&Sf(r)?(E=r,r="",s=!1):s&&a();let h=x+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<l&&!Oo.includes(e.charAt(h));)h++;else c=E===Cc||E===Dc?"file":"skip";x=h}else if(p==="("&&s&&i&&r.includes(To)){let E=Ye(e,x),h=e.slice(x+1,E<0?l:E);a();for(let S of h.trim()===""?[]:hf(h)){let _=Lc(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}x=E<0?l:E+1,x<l&&!Oo.includes(e.charAt(x))&&(o.chained=!0,x=mf(e,x))}else if(p==="["&&!s&&e.startsWith(To,Ye(e,x)+1)&&Ye(e,x)>=0){let E=Ye(e,x);f(e.slice(x,E+1),!1),x=E+1}else if(qe.includes(p)&&(p!=="["||!s)||(p==="$"||p==="@")&&qe.includes(g)&&g!=="["){let E=p==="$"||p==="@"?x+1:x,h=Ye(e,E);f(e.slice(x,h<0?l:h+1),!0),x=h<0?l:h+1}else f(p,!1),x++}return u(),t}var bf=["get-content","gc","cat","type"],Of=["[io.file]::","[system.io.file]::"],Tf=["readalltext","readalllines","readallbytes","readlines"],yo=["path","literalpath"],wc=["totalcount","head","first","tail","last"],Pc=[...yo,...wc,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],Rf=["raw","wait","force","asbytestream"],Af=[...Pc,...Rf],yf=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],Nf=["cd","chdir","sl","set-location","pushd","push-location"],If=["powershell","powershell.exe","pwsh","pwsh.exe"],Cf=["cmd","cmd.exe"],kf=["/c","/k","/r"],Df="command",ae="-";function Ro(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function No(e,t){let n=e.slice(ae.length),o=n.indexOf(":"),r=(o<0?n:n.slice(0,o)).toLowerCase(),s=o<0?void 0:n.slice(o+1);if(r==="")return{full:void 0,inline:s};if(t.includes(r))return{full:r,inline:s};let i=t.filter(c=>c.startsWith(r));return{full:i.length===1?i[0]:void 0,inline:s}}function Lf(e){if(e.length===0)return null;let t=Ro(e[0]);if(!bf.includes(t)){let r=e[0].toLowerCase(),s=Of.find(i=>r.startsWith(i));return s===void 0||!Tf.includes(r.slice(s.length))||e.length<Ef?null:{file:e[1],bounded:!1}}let n=[],o=!1;for(let r=1;r<e.length;r++){let s=e[r];if(!s.startsWith(ae)||s.length===ae.length){n.push(s);continue}let i=No(s,Af);if(i.full===void 0||!Pc.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;yo.includes(i.full)&&n.push(c),wc.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function wf(e,t){if(If.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(ae)||o.length===ae.length)continue;let r=No(o,[Df]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(Cf.includes(e)){for(let n=1;n<t.length;n++)if(kf.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function Pf(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(ae)||n.length===ae.length)return n;let o=No(n,yo);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function Mc(e,t,n,o){let r=t;for(let s of Lc(e)){let i=s[0];if(i.words.length===0)continue;let c=Ro(i.words[0]);if(s.length===1&&Nf.includes(c)){let u=Pf(i.words);u!==null&&(r=Ic(r,u));continue}let l=n<v?wf(c,i.words):null;if(l!==null){Mc(l,r,n+1,o);continue}if(i.toFile||i.chained)continue;let a=Lf(i.words);if(a===null||a.bounded)continue;let d=!0;for(let u=1;u<s.length;u++)if(s[u].toFile||!yf.includes(Ro(s[u].words[0]??""))){d=!1;break}d&&o.push(Ic(r,a.file))}}function Uc(e,t){let n=[];return Mc(e,t,0,n),n}import{join as Vt}from"node:path";var Hc=`\r
31
- `,Mf=`
32
- `;function qt(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(Hc)<0?t:t.split(Hc).join(Mf)}import{basename as pg,dirname as _g,join as Fc,posix as Eg,resolve as jf,win32 as gg}from"node:path";var Uf=Object.freeze({NODE_TOO_OLD:"Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",NO_SQLITE:"node:sqlite failed to load. Fix: run ctx_doctor.",DB_GONE:"context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",NO_PROJECT:"Project source <kind> is missing. Fix: run ctx_doctor.",UNKNOWN_FIELD:'Unknown field "<f>". Fix: use "queries".',TIMEOUT:"Timed out after <ms> ms. Fix: pass background: true.",NO_GIT_BASH:"Git Bash not found. Fix: install Git for Windows.",NO_RUNTIME:"No <lang> runtime on PATH. Fix: install it or pick another language.",FETCH_FAILED:"Fetch failed: <code>. Fix: check the URL or proxy.",SSRF:"Blocked private address <host>. Fix: use a public URL.",OUTSIDE_ROOT:"Path <p> is outside the project. Fix: use a path inside <root>.",INVALID_ARGS:"Invalid argument <field>. Fix: <action>.",ONE_OF_INPUT:"Pass exactly one of <names>. Fix: drop the extra field.",SPAWN_FAILED:"Failed to start the process: <detail>. Fix: check the command and PATH.",DB_CORRUPT:"context.db failed integrity_check. Fix: run ctx_doctor.",SCHEMA_STALE:"context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.",NO_GIT_DIR:"No git repository at <path>. Fix: run context-mode inside a git repository.",NO_HOME:"Env var <name> is not set. Fix: set <name> to your home directory.",PLUGIN_ROOT_MISSING:"Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.",BUNDLE_HASH_MISMATCH:"Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.",CONFIG_PARSE_FAILED:"<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade."});function Hf(e,t){let n=Uf[e],o="",r=0;for(;r<n.length;){if(n[r]!=="<"){o+=n[r],r+=1;continue}let s=r+1;for(;s<n.length&&n[s]!=="<"&&n[s]!==">";)s+=1;if(s>=n.length){o+=n.slice(r);break}if(n[s]==="<"){o+="<",r+=1;continue}let i=n.slice(r+1,s),c=t[i];if(c===void 0)throw new Error("formatError: missing var "+i+" for "+e);o+=String(c),r=s+1}return o}var T=class extends Error{code;vars;constructor(t,n){super(Hf(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{mkdirSync:Ff,realpathSync:vf}=process.getBuiltinModule("node:fs");function Q(e,t=process.platform){let n=o=>o!==void 0&&o!=="";return t==="win32"?n(e.USERPROFILE)?e.USERPROFILE:n(e.HOMEDRIVE)&&n(e.HOMEPATH)?e.HOMEDRIVE+e.HOMEPATH:n(e.HOME)?e.HOME:null:n(e.HOME)?e.HOME:n(e.USERPROFILE)?e.USERPROFILE:null}function le(e,t){let n=e[At];return n!==void 0&&n!==""?n:Fc(t,...Ks["claude-code"])}function Gf(e,t=process.platform){let n=Q(e,t);if(n!==null)return n;throw new T("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function zt(e,t){let n=e[Le];return n!==void 0&&n!==""?jf(n):Fc(t,Wr.slice(1))}function vc(e){let t=e[Le],n=zt(e,t!==void 0&&t!==""?"":Gf(e));return Ff(n,{recursive:!0}),vf.native(n)}var{readFileSync:Wc}=process.getBuiltinModule("node:fs");function Te(e){return e.agentId!==void 0&&e.agentId!==""}function ko(e,t){if(t===null)return"C";let n=ie(e.agent),o=new Set(t);for(let r of lt)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function Do(e,t){if(!Te(e))return null;let n=ie(e.agent);if(t.manifestTools!==void 0)return Bc(t.manifestTools.map(c=>Io(n,c)));let o=e.agentType??"",r=Bf(o,t);if(r===null)return null;let s=(r.tools??qf(n)).map(c=>Io(n,c)),i=r.disallowed.map(c=>Io(n,c));return Bc(s.filter(c=>!i.some(l=>Vf(l,c))))}function Bf(e,t){if(!Wf(e))return null;let n=Xf(t.env);if(e.indexOf(xe)>=0){if(n!==null){let s=Kf(le(t.env,n),e);if(s!==null)return s}}else{let s=Co(Vt(t.projectDir,Kr,pt,e+_t));if(s!==null)return s;if(n!==null){let i=Co(Vt(le(t.env,n),pt,e+_t));if(i!==null)return i}}let r=t.cliAgents;if(r!==void 0&&Object.prototype.hasOwnProperty.call(r,e)){let s=r[e];return{tools:Array.isArray(s.tools)?s.tools:null,disallowed:Array.isArray(s.disallowedTools)?s.disallowedTools:[]}}return null}function Wf(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(xe))if(t===""||t==="."||t==="..")return!1;return!0}function Xf(e){return Q(e)}function Kf(e,t){let n=t.indexOf(xe),o=t.slice(0,n),r=t.slice(n+xe.length);if(r.indexOf(xe)>=0)return null;let s;try{s=JSON.parse(qt(Wc(Vt(e,Nn,Yr),"utf8")))}catch{return null}let i=s?.plugins;if(i===null||typeof i!="object")return null;for(let c of Object.keys(i)){let l=c.indexOf(qr);if((l<0?c:c.slice(0,l))!==o)continue;let a=i[c];if(Array.isArray(a))for(let d of a){let u=d?.installPath;if(typeof u!="string"||u==="")continue;let f=Co(Vt(u,pt,r+_t));if(f!==null)return f}}return null}function Co(e){let t;try{t=Wc(e,"utf8")}catch{return null}return Yf(t)}function Yf(e){let t=e.split(`
33
- `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==In)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===In){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=jc(o,zr),s=jc(o,Vr);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function jc(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(t+":"))continue;let r=o.slice(t.length+1).trim();if(r===""){let s=[];for(let i=n+1;i<e.length;i++){let c=e[i].trim();if(!c.startsWith("-"))break;s.push(Gc(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>Gc(s.trim())).filter(s=>s!=="")}return null}function Gc(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function qf(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...lt.map(n=>e.toolNamePrefix+n)]}function Io(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(Jr)?zf(o):o}function zf(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||$r.indexOf(n)>=0;t+=o?n:"_"}return t}function Vf(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(Cn)){let n=e.slice(Cn.length);if(n!==""&&n.indexOf(kn)<0)return t.startsWith(e+kn)}return!1}function Bc(e){return[...new Set(e.filter(t=>t!==""))]}var ue="",Xc=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:ue},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:ue},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:ue},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:ue},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:ue},command:{valueShorts:ue,valueLongs:[],assignments:!1,duration:!1,refuseShorts:"vV"},xargs:{valueShorts:"aEdILnPs",valueLongs:["--arg-file","--delimiter","--max-args","--max-procs","--max-chars"],assignments:!1,duration:!1,refuseShorts:ue}}),Jf=["bash","sh","zsh"],$f="c",Qf=" -c",Zf=["-o","+o","-O","+O"],Jt="-",e0="+",Lo="--",t0="smhd",n0=".",Kc=e=>e!==""&&e>="0"&&e<="9";function o0(e){if(e===""||!Kc(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(Kc(n)||n===n0))return t===e.length-1&&t0.includes(n)}return!0}function r0(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===Lo){n++;break}if(e.assignments&&jt(o)){n++;continue}if(o.startsWith(Lo)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(Jt)&&o.length>Jt.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=Jt.length;r<o.length;r++)if(e.valueShorts.includes(o.charAt(r))){r===o.length-1&&n++;break}continue}break}if(e.duration){if(n>=t.length||!o0(t[n]))return null;n++}return n<t.length?t.slice(n):null}function s0(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(Lo)){if(o.startsWith(Jt)||o.startsWith(e0)){o.includes($f)&&(t=!0),Zf.includes(o)&&n++;continue}return t?o:null}}return null}function Yc(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function wo(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let l=s.toLowerCase();if(Jf.includes(l)){let u=s0(i),f=u!==null&&n<v?be(u):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=Yc(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,wo(p,[...r,l+Qf],n+1,o)}return}let a=Object.hasOwn(Xc,l)?Xc[l]:void 0,d=a===void 0?null:r0(a,i);if(d===null)break;r.push(l),s=ho(d[0]),i=d.slice(1),c=c||So(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=v))for(let l of vt(e.raw)){let a=be(l.body);if(a.ok)for(let d of a.commands)wo(Yc(d,e),[...t,l.wrapper],n+1,o)}}function Po(e){let t=[];for(let n of e)wo(n,[],0,t);return t}import{isAbsolute as c0,join as Mo,relative as a0,sep as Uo}from"node:path";var{readFileSync:i0}=process.getBuiltinModule("node:fs"),qc=".claude",l0="settings.local.json",zc="settings.json",ta="Bash",u0="Read",Vc=":*",Jc="//",$c="~/",Qc="./",Zc="..",d0=`
34
- \r`,f0=Object.freeze({tool:ta});function x0(e,t){if(t!=="claude-code")return[];let n=Q(process.env),o=process.env[At],r=o!==void 0&&o!==""?o:n===null?null:le(process.env,n),s=[Mo(e,qc,l0),Mo(e,qc,zc)];return r===null?s:[...s,Mo(r,zc)]}function ea(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function p0(e){let t;try{t=qt(i0(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!ea(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!ea(o))return{kind:"bad"};let r=o.deny;return r===void 0?{kind:"ok",deny:[]}:!Array.isArray(r)||!r.every(s=>typeof s=="string")?{kind:"bad"}:{kind:"ok",deny:r}}function na(e,t){let n=[];for(let o of x0(e,t)){let r=p0(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function Ho(e,t){let n=[],o=0;for(;o<e.length;){let r=e[o];if(r==="*"&&t&&e[o+1]==="*"){let s=e[o+2]==="/";n.push({t:s?"globstarDir":"globstar"}),o+=s?3:2;continue}r==="*"?(n.length===0||n[n.length-1].t!=="star")&&n.push({t:"star"}):r==="?"?n.push({t:"any1"}):n.push({t:"lit",c:r}),o++}return n}function Fo(e,t,n,o){let r=t.length,s=o,i=new Uint8Array(r+1);for(let c=e.length-1;c>=0;c--){let l=e[c];s===o&&(s=Uint8Array.from(o));let a=0;for(let u=r;u>=0;u--){let f=u<r,x=f?t[u]:"";switch(l.t){case"lit":i[u]=f&&x===l.c?s[u+1]:0;break;case"any1":i[u]=f&&!(n&&x==="/")?s[u+1]:0;break;case"star":i[u]=s[u]||(f&&!(n&&x==="/")?i[u+1]:0);break;case"globstar":i[u]=s[u]||(f?i[u+1]:0);break;case"globstarDir":f&&x==="/"&&s[u+1]&&(a=1),i[u]=s[u]||a;break}}let d=i;i=s,s=d}return s}function ze(e,t,n){let o=Ho(e,n),r=o[0];if(r!==void 0&&r.t==="lit"&&t[0]!==r.c)return!1;let s=new Uint8Array(t.length+1);return s[t.length]=1,Fo(o,t,n,s)[0]===1}function oa(e){let t=e.indexOf("(");if(t<1||!e.endsWith(")"))return null;let n=e.slice(t+1,e.length-1);return n===""?null:{tool:e.slice(0,t),glob:n}}function ra(e,t){let n=t.length,o=new Uint8Array(n+1);if(o[n]=1,!e.endsWith(Vc))return Fo(Ho(e,!1),t,!1,o);for(let r=0;r<n;r++)d0.includes(t[r])&&(o[r]=1);return Fo(Ho(e.slice(0,e.length-Vc.length),!1),t,!1,o)}function _0(e,t){return ra(e,t)[0]===1}function sa(e,t,n){for(let o of t){let r=oa(o);if(r===null||r.tool!==ta)continue;let s=ra(r.glob,e);for(let i=0;i<=e.length;i++)if(n[i]===1&&s[i]===1)return o}return null}var E0=/^[A-Za-z]:(?=\/)/;function Ve(e){return Uo==="/"?e:e.split(Uo).join("/")}function g0(e,t,n){if(e.startsWith(Qc)){if(n===void 0)return!1;let r=a0(n,t);return r===""||r===Zc||r.startsWith(Zc+Uo)||c0(r)?!1:ze(e.slice(Qc.length),Ve(r),!0)}let o=Ve(t);if(e.startsWith(Jc)){let r=Ve(e.slice(Jc.length-1));return ze(r,o,!0)||ze(r,o.replace(E0,""),!0)}if(e.startsWith($c)){let r=Q(process.env);return r!==null&&ze(Ve(r)+e.slice($c.length-1),o,!0)}return ze(Ve(e),o,!0)}function Re(e,t,n=f0){for(let o of t){let r=oa(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===u0?g0(r.glob,e,n.projectDir):_0(r.glob,e))return o}return null}var Ug=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),ia='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var m0="{size}",h0="{path}";function $t(e,t,n=""){return k(ia,n).split(m0).join(String(t)).split(h0).join(e)}import{extname as T0}from"node:path";var{closeSync:S0,openSync:b0,readSync:O0}=process.getBuiltinModule("node:fs");function R0(e){let t=null;try{t=b0(e,"r");let n=Buffer.alloc(Un),o=O0(t,n,0,Un,0);return n.subarray(0,o)}catch{return null}finally{t!==null&&S0(t)}}function Qt(e,t){let n=Is[e]??[];if(n.length===0)return!1;let o=T0(t).toLowerCase(),r=n.filter(i=>Mn[i].exts.includes(o));if(r.length===0)return!1;let s=R0(t);return s===null?!1:r.some(i=>Mn[i].sig.every(c=>c.bytes.every((l,a)=>s[c.at+a]===l)))}var{statSync:A0}=process.getBuiltinModule("node:fs"),fa="Bash",jo="Read",y0="WebFetch",N0="ctx_execute",I0="ctx_batch",xa="shell",C0="1",Z="-",Go="--",k0="=",D0=".",ca=",",vo="p",L0=["-e","--expression"],aa=".exe",w0=";&|(`\n\r",fe=Object.freeze({kind:"allow"}),W=e=>({kind:"deny",reason:e}),de=e=>typeof e=="string"?e:void 0,la=e=>e!=null,X=(e,t)=>e.includes(t);function pa(e,t,n){let o=e.tool;if(o===void 0)return fe;let r=o.canonicalName,s=o.input,i;if(n===null){if(process.env[Xr]===C0)return W(k(Et,t.toolNamePrefix));process.stderr.write(ps+`
35
- `),i=[]}else i=n;let c=M0(r,s,e.cwd,i);return c!==null?W(we+c):r===y0?v0(s,t):r===fa?j0(e,t,s,i):r===jo?Y0(e,t,s):fe}function _a(e,t,n,o){let r=e==="webfetch",s=r?rs.map(c=>n.toolNamePrefix+c).join(xs):n.toolNamePrefix+os,i=JSON.stringify(r?{url:t}:{language:xa,code:t,intent:o??ns});return[Dn+Qr[e]+Zr,es,ts+s,i].join(`
36
- `)}function P0(e){for(let t of ht){let n=de(e[t]);if(n!==void 0&&n!=="")return n}}function Ea(e){let t=P0(e),n=Array.isArray(e[pe])?e[pe].filter(o=>typeof o=="string"&&o!==""):[];return t===void 0?n:[t,...n]}function M0(e,t,n,o){if(o.length===0)return null;let r=s=>Re(en(n,s),o,{tool:jo,projectDir:n});if(e===fa){let s=de(t.command);return s===void 0?null:Re(s,o)}if(e===jo){for(let s of Ea(t)){let i=r(s);if(i!==null)return i}return null}if(e===N0){let s=de(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=de(t.code);return U0(t.language)&&c!==void 0?ua(c,o):null}if(e===I0&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?ua(s,o):null;if(i!==null)return i}return null}function U0(e){if(typeof e!="string")return!1;let t=e.toLowerCase(),n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return n>=0&&(t=t.slice(n+1)),t.endsWith(aa)&&(t=t.slice(0,t.length-aa.length)),t===xa||X(Gr,t)}function ua(e,t){let n=Re(e,t);if(n!==null)return n;let o=be(e);if(!o.ok)return ma(e,t);for(let r of Po(o.commands)){let s=ga(r,t);if(s!==null)return s}return null}function ga(e,t){return t.length===0?null:Re([e.argv0,...e.args].join(" "),t)??Re(e.raw,t)}function ma(e,t){if(t.length===0)return null;let n=new Uint8Array(e.length+1),o=!1;for(let r=0;r<=e.length;r++)(r===0||w0.includes(e.charAt(r-1)))&&(o=!0),o&&(r===e.length||e.charAt(r).trim()!=="")&&(n[r]=1,o=!1);return sa(e,t,n)}function H0(e,t){return ma(e,t)!==null}function F0(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return _s.some(n=>t===n||t.endsWith(D0+n))}function v0(e,t){let n=de(e.url)??"";return F0(n)?fe:W(_a("webfetch",n,t))}function j0(e,t,n,o){let r=de(n.command)??"",s=be(r);if(!s.ok)return H0(r,o)?W(k(gt,t.toolNamePrefix)):da(r,e.cwd,t)??fe;let i=Po(s.commands);for(let c of i){let l=ga(c,o);if(l!==null)return W(we+l)}if(!_e(t)||Te(e))for(let c of i){let l=G0(c);if(l!==null)return W(_a(l,r,t,de(n.description)))}return q0(i,e.cwd,t)??da(r,e.cwd,t)??fe}function G0(e){let t=e.argv0.toLowerCase();return X(Es,t)&&B0(t,e)?"curl":X0(e.raw)?"http":X(Ss,t)?"build":null}function B0(e,t){return t.redirectsToFile?!W0(e,t.args):!t.endsInBoundedSink}function W0(e,t){let n=gs[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===Go)break;if(X(ms,s)||s===hs&&t[r+1]===Z)return!1;(s===n.long||s.startsWith(Z)&&!s.startsWith(Go)&&s.includes(n.short,Z.length))&&(o=!0)}return o}function X0(e){let t=e.toLowerCase();for(let n of Ts)if(t.includes(n))return!0;for(let n=t.indexOf(Me);n>=0;n=t.indexOf(Me,n+1)){let o=t.charAt(n+Me.length);if(o!==""&&bs.includes(o)&&t.startsWith(Os,n+Me.length+o.length))return!0}return!1}var K0="cd";function Bo(e){try{let t=A0(e);return t.isFile()?t.size:-1}catch{return-1}}function Y0(e,t,n){if(!la(n.offset)&&!la(n.limit))for(let o of Ea(n)){let r=en(e.cwd,o),s=Bo(r);if(s>V&&!Qt(e.agent,r))return W($t(r,s,t.toolNamePrefix))}return fe}function q0(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&co(n))return null;let o=t,r=null;for(let s of e){let i=s.argv0.toLowerCase();if(i===K0&&s.args.length===1&&s.insideConstruct===void 0&&(o=en(o,s.args[0])),s.redirectsToFile||s.endsInBoundedSink||s.pipesOut===!0||s.insideConstruct!==void 0||!X(Rs,i))continue;let c=J0(i,s.args);if(c===null)continue;if(c.bounded){r=fe;continue}let l=en(o,c.file),a=Bo(l);if(a>V)return W($t(l,a,n.toolNamePrefix))}return r}function da(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&co(n))return null;for(let o of Uc(e,t)){let r=Bo(o);if(r>V)return W($t(o,r,n.toolNamePrefix))}return null}var Zt=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function z0(e){if(X(Pn,e))return 1;for(let t of Pn)if(t.startsWith(Go)?e.startsWith(t+k0):e.startsWith(t))return 0;return e.startsWith(Z)&&Zt(e.slice(Z.length))?0:-1}function V0(e){if(e===vo)return"all";if(!e.endsWith(vo))return null;let t=e.slice(0,e.length-vo.length),n=t.indexOf(ca);return(n<0?Zt(t):Zt(t.slice(0,n))&&Zt(t.slice(n+ca.length)))?"range":null}function J0(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(X(As,e)){let l=z0(c);if(l>=0){o=!0,i+=l;continue}}if(e===mt&&X(ys,c)){r=!0;continue}if(e===mt&&X(L0,c)){s=t[i+1],i++;continue}c.startsWith(Z)&&c!==Z||n.push(c)}if(e===mt){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:V0(s);if(i===null)return null;o=i==="range"}return e===Ns&&n.shift()!==D.identity?null:n.length===1&&n[0]!==Z?{file:n[0],bounded:o}:null}import{basename as rx,dirname as tn,join as $e,resolve as Ra}from"node:path";import{dirname as ha,join as om,relative as rm,sep as Q0}from"node:path";var{lstatSync:tm,realpathSync:$0}=process.getBuiltinModule("node:fs");function Wo(e){try{return $0.native(e)}catch{return}}function Ae(e){return e.split(Q0).filter(t=>t!=="")}function Sa(e,t){let n=Wo(e),o=Wo(t);if(n===void 0||o===void 0)return!1;let r=Ae(n),s=Ae(o);if(s.length<r.length)return!1;for(let i=0;i<r.length;i+=1)if(r[i]!==s[i])return!1;return!0}function ba(e){let t=e.map(Wo).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=Ae(n).length;for(let s of t){let i=Ae(s),c=Ae(n),l=0;for(;l<o&&l<i.length&&i[l]===c[l];)l+=1;o=l}let r=n;for(;Ae(r).length>o&&ha(r)!==r;)r=ha(r);return r}var Z0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ex=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],M=(e,t)=>e>>>t|e<<32-t;function Oa(e){let t=Buffer.from(e,"utf8"),n=t.length*8,o=Math.ceil((t.length+9)/64)*64,r=Buffer.alloc(o);t.copy(r),r[t.length]=128,r.writeUInt32BE(Math.floor(n/4294967296),o-8),r.writeUInt32BE(n>>>0,o-4);let s=ex.slice(),i=new Uint32Array(64);for(let c=0;c<o;c+=64){for(let E=0;E<16;E++)i[E]=r.readUInt32BE(c+E*4);for(let E=16;E<64;E++){let h=M(i[E-15],7)^M(i[E-15],18)^i[E-15]>>>3,S=M(i[E-2],17)^M(i[E-2],19)^i[E-2]>>>10;i[E]=i[E-16]+h+i[E-7]+S>>>0}let[l,a,d,u,f,x,p,g]=s;for(let E=0;E<64;E++){let h=g+(M(f,6)^M(f,11)^M(f,25))+(f&x^~f&p)+Z0[E]+i[E]>>>0,S=(M(l,2)^M(l,13)^M(l,22))+(l&a^l&d^a&d)>>>0;g=p,p=x,x=f,f=u+h>>>0,u=d,d=a,a=l,l=h+S>>>0}s[0]=s[0]+l>>>0,s[1]=s[1]+a>>>0,s[2]=s[2]+d>>>0,s[3]=s[3]+u>>>0,s[4]=s[4]+f>>>0,s[5]=s[5]+x>>>0,s[6]=s[6]+p>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:tx,readFileSync:nx,realpathSync:Ta,statSync:ox}=process.getBuiltinModule("node:fs");function sx(e){switch(e){case"claude-code":return"env:CLAUDE_PROJECT_DIR";case"codex":case"copilot-cli":case"kiro":return"arg:--agent+cwd";case"vscode":return"arg:workspaceFolder";case"gemini":case"qwen":case"zcode":case"opencode":return"spawn-cwd";case"pi":return"pi:ctx.cwd"}}function Je(e){return e===void 0||e===""?void 0:e}function ix(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return Je(t.env.CLAUDE_PROJECT_DIR)??Je(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return Je(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(xt);return n<0?void 0:Je(t.argv[n+1])}case"pi:ctx.cwd":return Je(t.piCwd)}}function cx(e){let t;try{t=Ta.native(e)}catch{throw new T("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=ax($e(t,Rn));if(o!==null){let s=Aa($e(o,vr));return{commonDir:Ta.native(s===null?o:Ra(o,s)),worktree:t,start:n}}let r=tn(t);if(r===t)return{commonDir:null,start:n};t=r}}function ax(e){let t;try{if(ox(e).isDirectory())t=e;else{let n=Aa(e);if(n===null||!n.startsWith(yn))return null;t=Ra(tn(e),n.slice(yn.length))}}catch{return null}return tx($e(t,jr))?t:null}function Aa(e){let t;try{t=nx(e,"utf8")}catch{return null}let n=t.indexOf(`
37
- `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function lx(e,t){let{spawnSync:n}=process.getBuiltinModule("node:child_process"),o=n("git",t,{cwd:e,shell:!1,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});if(o.error!==void 0||o.status!==0)throw new T("NO_GIT_DIR",{path:e});return o.stdout.split(`
38
- `).filter(r=>r!=="")}function ux(e,t){let n=rx(t)===Rn?tn(t):t,o=lx(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(An)).map(r=>r.slice(An.length));return ba([tn(n),...o])}function ya(e,t){let n=sx(e),o=ix(n,t);if(o===void 0)throw new T("NO_PROJECT",{kind:n});let r=cx(o),s=r.commonDir===null?r.start:void 0,i=r.commonDir??r.start,c=r.commonDir===null?r.start:r.worktree,l,a,d;return{get projectKey(){return l??=Oa(i).slice(0,Hr),l},get projectDir(){return a??=$e(vc(process.env),ft,this.projectKey),a},get dbPath(){return $e(this.projectDir,Fr)},worktree:c,get containmentRoot(){return d??=s??ux(o,i),d},agent:e,source:n}}var nn=ke,dx=`
39
- PRAGMA busy_timeout = ${J};
8
+ `),i=Ju(o,s);if(i===null)return{...e,content:t,startLine:n+r,numLines:s.length};let c=s.slice(0,i.length);return i.length<s.length&&c.push(s[s.length-1]),{...e,content:c.join(`
9
+ `),startLine:n+i.at,numLines:c.length}}function Ju(e,t){let n=null;for(let o=0;o<e.length;o++){if(e[o]!==t[0])continue;let r=1;for(;r<t.length&&o+r<e.length&&e[o+r]===t[r];)r++;if((n===null||r>n.length)&&(n={at:o,length:r}),r===t.length)break}return n}function Ei(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function $u(e){let t=e;return(t.mode==="content"||t.mode==="count")&&typeof t.content=="string"}function mi(e){let t=[],n=!1;for(let o of e){let r=typeof o=="object"&&o!==null?o:{};r.type==="text"&&typeof r.text=="string"?t.push(r.text):n=!0}return{text:t.join(`
10
+ `),keep:n}}function Qu(e){let t=zu(e),o={isError:typeof e=="object"&&e!==null&&e.is_error===!0,bytes:Buffer.byteLength(t),text:t};if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Ei(e)&&(o.shape=e),typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Ei(e)&&(ro(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,mi(e).keep&&(o.keep=!0)),typeof e=="object"&&e!==null){let r=e;typeof r.persistedOutputPath=="string"&&r.persistedOutputPath!==""&&typeof r.persistedOutputSize=="number"&&r.persistedOutputSize>o.bytes&&(o.persistedPath=r.persistedOutputPath)}return o}function ae(e,t,n,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(t+": hook payload is not a JSON object");let r=e,s=Ku.find(c=>c===r.hook_event_name);if(s===void 0)throw new Error(t+": unknown hook event "+String(r.hook_event_name));let i={event:s,agent:t,sessionId:String(r.session_id??""),cwd:String(r.cwd??"")};if(typeof r.agent_id=="string"&&(i.agentId=r.agent_id,typeof r.agent_type=="string"&&(i.agentType=r.agent_type)),s==="SessionStart"&&typeof r.source=="string"&&o[r.source]!==void 0&&(i.source=o[r.source]),s==="UserPromptSubmit"&&typeof r.prompt=="string"&&(i.prompt=r.prompt),s==="PreToolUse"||s==="PostToolUse"){let c=String(r.tool_name??""),l=typeof r.tool_input=="object"&&r.tool_input!==null?r.tool_input:{},a={name:c,canonicalName:qu(c,n),input:l};typeof r.tool_use_id=="string"&&r.tool_use_id!==""&&(a.callId=r.tool_use_id),i.tool=a}return s==="PostToolUse"&&(i.result=Qu(r.tool_response)),i}function Zu(e,t){let n=e.result?.shape;if(e.tool?.canonicalName==="Bash"){let{persistedOutputPath:r,persistedOutputSize:s,...i}=n??{};return{interrupted:!1,...i,stdout:t,stderr:""}}let o=n===void 0?null:ro(n);return n!==void 0&&o!==null?o.put(n,t):e.result?.blocks===!0?[{type:"text",text:t}]:t}function B(e,t,n){let o=r=>({stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e.event,...r}}),exitCode:0});switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return o({additionalContext:t.text});case"deny":return o({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
11
+ `+t.reason});case"replace":return n&&e.event==="PostToolUse"?o({updatedToolOutput:Zu(e,t.output)}):{stdout:"",exitCode:0}}}var ed={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function td(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function nd(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(t.hook_event_name===void 0)throw new Error("claude-code: missing required field hook_event_name");for(let n of ed[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function hi(e){nd(e);let t=ae(e,"claude-code",oo,Yu);if(t.tool!==void 0&&t.tool.name===Wu&&(t.tool.canonicalName=Xu),t.cwd===""&&(t.cwd=process.env.CLAUDE_PROJECT_DIR||process.cwd()),t.event==="PostToolUse"&&t.tool!==void 0&&t.tool.callId===void 0){let n=typeof t.tool.input.command=="string"?t.tool.input.command:JSON.stringify(t.tool.input);t.tool.callId="h"+td(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function Si(e,t,n){return B(e,t,!0)}var io="mcp__context_mode__",rd={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"},so="Stop",sd={stdout:"",exitCode:0};function bi(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===so){let t=e;return{event:so,agent:"codex",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")}}return ae(e,"codex",io,rd)}function Oi(e,t,n){return e.event===so?sd:B(e,t,!1)}var Ut="mcp_context-mode_",Ti={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},Ri={startup:"startup",resume:"resume",clear:"clear"},cd=["SessionStart","UserPromptSubmit","PostToolUse"],ad=["UserPromptSubmit","PreToolUse"],Mt={stdout:"",exitCode:0},ld=`the tool ran and succeeded; context-mode indexed its full output, and this is the part that answers the call:
12
+ `;function R(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var Ai={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function ud(e,t){if(e.startsWith(Ut))return e.slice(Ut.length);if(Object.hasOwn(Ai,e))return Ai[e];if(typeof t!="object"||t===null)return e;let n=t,o=R(n,"server_name"),r=R(n,"tool_name");return typeof o!="string"||typeof r!="string"?e:"mcp:"+o+":"+r}function dd(e){if(!Array.isArray(e)||e.length===0)return;let t=[];for(let n of e){if(typeof n=="string"){t.push(n);continue}if(typeof n!="object"||n===null)return;let o=R(n,"text");if(typeof o!="string")return;t.push(o)}return t.join("")}function fd(e){let t=typeof e=="object"&&e!==null?e:void 0,n=t===void 0?void 0:R(t,"llmContent"),o=e===void 0?"":typeof e=="string"?e:typeof n=="string"?n:dd(n)??JSON.stringify(e),r=t===void 0?void 0:R(t,"error"),s={isError:r!=null,bytes:Buffer.byteLength(o),text:o};return xd(n)&&(s.keep=!0),s}function xd(e){return(Array.isArray(e)?e:[e]).some(n=>typeof n=="object"&&n!==null&&(Object.hasOwn(n,"inlineData")||Object.hasOwn(n,"fileData")))}var pd=["https://","http://"],_d=`.,;:!?)]}>'"`,Ed=`
13
+ \r\f\v`;function gd(e){let t=[],n="";for(let o of e)Ed.includes(o)?(n!==""&&t.push(n),n=""):n+=o;return n!==""&&t.push(n),t}function md(e){if(typeof e=="string")for(let t of gd(e)){let n=t.toLowerCase(),o=pd.map(s=>n.indexOf(s)).filter(s=>s>=0).sort((s,i)=>s-i)[0];if(o===void 0)continue;let r=t.slice(o);for(;r.length>0&&_d.includes(r[r.length-1]);)r=r.slice(0,-1);return r}}function hd(e,t){if(e==="web_fetch"&&R(t,"url")===void 0){let n=md(R(t,"prompt"));return n===void 0?t:{...t,url:n}}if(e==="read_many_files"&&R(t,"file_path")===void 0){let n=R(t,"include"),o=Array.isArray(n)?n.filter(r=>typeof r=="string"):[];return o.length===0?t:{...t,file_path:o.join(" ")}}return t}function yi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("gemini: hook payload is not a JSON object");let t=e,n=R(t,"hook_event_name"),o=typeof n=="string"&&Object.hasOwn(Ti,n)?Ti[n]:void 0;if(o===void 0)throw new Error("gemini: unknown hook event "+String(n));let r={event:o,agent:"gemini",sessionId:String(R(t,"session_id")??""),cwd:String(R(t,"cwd")??"")},s=R(t,"source");o==="SessionStart"&&typeof s=="string"&&Object.hasOwn(Ri,s)&&(r.source=Ri[s]);let i=R(t,"prompt");if(o==="UserPromptSubmit"&&typeof i=="string"&&(r.prompt=i),o==="PreToolUse"||o==="PostToolUse"){let c=String(R(t,"tool_name")??""),l=R(t,"tool_input");r.tool={name:c,canonicalName:ud(c,R(t,"mcp_context")),input:hd(c,typeof l=="object"&&l!==null&&!Array.isArray(l)?l:{})}}return o==="PostToolUse"&&(r.result=fd(R(t,"tool_response"))),r}function Ni(e,t,n){switch(t.kind){case"allow":return Mt;case"hint":return cd.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:Mt;case"deny":return ad.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
14
+ `+t.reason}),exitCode:0}:Mt;case"replace":return e.event!=="PostToolUse"?Mt:{stdout:JSON.stringify({decision:"deny",reason:ld+t.output}),exitCode:0}}}var co="mcp__context-mode__",bd={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Ii={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},Od="PostToolUseFailure";function Ci(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===Od,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=ae(n,"qwen",co,bd);if(o.tool!==void 0&&Object.hasOwn(Ii,o.tool.name)&&(o.tool.canonicalName=Ii[o.tool.name]),t){let r=e.error,s=typeof r=="string"?r:r===void 0?"":JSON.stringify(r);o.result={isError:!0,bytes:Buffer.byteLength(s),text:s}}return o}function ki(e,t,n){return B(e,t,!1)}var Ft="context-mode-",Rd={sessionStart:{event:"SessionStart",casing:"camel",failure:!1},userPromptSubmitted:{event:"UserPromptSubmit",casing:"camel",failure:!1},preToolUse:{event:"PreToolUse",casing:"camel",failure:!1},postToolUse:{event:"PostToolUse",casing:"camel",failure:!1},postToolUseFailure:{event:"PostToolUse",casing:"camel",failure:!0},SessionStart:{event:"SessionStart",casing:"snake",failure:!1},UserPromptSubmit:{event:"UserPromptSubmit",casing:"snake",failure:!1},PreToolUse:{event:"PreToolUse",casing:"snake",failure:!1},PostToolUse:{event:"PostToolUse",casing:"snake",failure:!1},PostToolUseFailure:{event:"PostToolUse",casing:"snake",failure:!0}},Di={startup:"startup",resume:"resume",new:"startup"},Ad={camel:{event:"hookEventName",session:"sessionId",tool:"toolName",args:"toolArgs",result:"toolResult"},snake:{event:"hook_event_name",session:"session_id",tool:"tool_name",args:"tool_input",result:"tool_result"}},Pi="success";function vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ao=Object.freeze(["bash","powershell"]),Li=Object.fromEntries(ao.map(e=>[e,"Bash"]));function yd(e){return e.startsWith(Ft)?e.slice(Ft.length):Object.hasOwn(Li,e)?Li[e]:e}var wi=e=>typeof e=="number"&&Number.isFinite(e);function Nd(e,t){let n=t.view_range;if(e!=="view"||!Array.isArray(n)||!wi(n[0]))return t;let o={...t,offset:n[0]};return wi(n[1])&&n[1]>=n[0]&&(o.limit=n[1]-n[0]+1),o}function Id(e){if(vt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return vt(t)?t:{}}catch{return{}}}var Cd={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function kd(e,t,n){let o=Cd[t],r=vt(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==Pi,bytes:Buffer.byteLength(s),text:s}}var Dd=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function Ld(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:Dd.find(([t])=>Object.hasOwn(e,t))?.[1]}function Mi(e){if(!vt(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=Ld(e),n=typeof t=="string"?Rd[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Ad[n.casing],r=n.event,s={event:r,agent:"copilot-cli",sessionId:String(e[o.session]??""),cwd:String(e.cwd??"")};if(r==="SessionStart"&&typeof e.source=="string"&&Di[e.source]!==void 0&&(s.source=Di[e.source]),r==="UserPromptSubmit"&&typeof e.prompt=="string"&&(s.prompt=e.prompt),r==="PreToolUse"||r==="PostToolUse"){let i=String(e[o.tool]??""),c={name:i,canonicalName:yd(i),input:Nd(i,Id(e[o.args]))};s.tool=c}return r==="PostToolUse"&&(s.result=kd(e[o.result],n.casing,n.failure)),s}var Ht={stdout:"",exitCode:0};function Ui(e,t,n){switch(t.kind){case"allow":return Ht;case"hint":return e.event==="PostToolUse"?Ht:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?Ht:{stdout:JSON.stringify({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
15
+ `+t.reason}),exitCode:0};case"replace":return e.event!=="PostToolUse"?Ht:{stdout:JSON.stringify({modifiedResult:{resultType:Pi,textResultForLlm:t.output}}),exitCode:0}}}var jt="mcp_context-mode_",Bi=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],Hi="mcp_",Fi="_",Pd="new",lo=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),Bt=Object.freeze(["read_file","view"]),uo=Object.freeze(["fetch_webpage","web_fetch"]),vi=Object.fromEntries([...lo.map(e=>[e,"Bash"]),...Bt.map(e=>[e,"Read"]),...uo.map(e=>[e,"WebFetch"])]);function Wi(e){if(e.startsWith(jt))return e.slice(jt.length);if(Object.hasOwn(vi,e))return vi[e];if(!e.startsWith(Hi))return e;let t=e.slice(Hi.length),n=t.indexOf(Fi);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+Fi.length)}var Xe=e=>typeof e=="number"&&Number.isFinite(e);function Xi(e,t,n){if(t==="Read"&&Bt.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),Xe(n.startLine)&&(o.offset=n.startLine),Xe(n.startLine)&&Xe(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&Xe(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];Xe(r)&&r>=n.view_range[0]&&(o.limit=r-n.view_range[0]+1)}return o}return t==="WebFetch"&&e==="fetch_webpage"&&Array.isArray(n.urls)&&typeof n.urls[0]=="string"?{...n,url:n.urls[0]}:n}function Md(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:typeof e=="object"&&e!==null&&e.is_error===!0,bytes:Buffer.byteLength(t),text:t}}var Ud={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},Hd=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],ji={new:"startup",startup:"startup",resume:"resume"},Fd="success";function Gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vd(e){if(Gt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Gt(t)?t:{}}catch{return{}}}function jd(e){let t=Gt(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==Fd,bytes:Buffer.byteLength(n),text:n}}function Gi(e,t){let n=typeof t=="string"?Ud[t]??Bi.find(r=>r===t):void 0;if(n===void 0)throw new Error("vscode: unknown hook event "+String(t));let o={event:n,agent:"vscode",sessionId:String(e.sessionId??""),cwd:String(e.cwd??"")};if(n==="SessionStart"&&typeof e.source=="string"&&ji[e.source]!==void 0&&(o.source=ji[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=Wi(r);o.tool={name:r,canonicalName:s,input:Xi(r,s,vd(e.toolArgs))}}return n==="PostToolUse"&&(o.result=jd(e.toolResult)),o}function Ki(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("vscode: hook payload is not a JSON object");let t=e;if(t.hookEventName!==void 0)return Gi(t,t.hookEventName);if(t.hook_event_name===void 0){let r=Hd.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return Gi(t,r)}let n=Bi.find(r=>r===t.hook_event_name);if(n===void 0)throw new Error("vscode: unknown hook event "+String(t.hook_event_name));let o={event:n,agent:"vscode",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")};if(n==="SessionStart"&&t.source===Pd&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=Gt(t.tool_input)?t.tool_input:{},i=Wi(r);o.tool={name:r,canonicalName:i,input:Xi(r,i,s)}}return n==="PostToolUse"&&(o.result=Md(t.tool_response)),o}function Yi(e,t,n){return B(e,t,!1)}var Wt="mcp_context_mode_",qi="mcp_context-mode_",zi={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},Bd="prompt",Wd="USER_PROMPT",Vi="mcp_",fo=Object.freeze(["execute_bash","execute_pwsh","shell"]),Ji=Object.fromEntries(fo.map(e=>[e,"Bash"])),$i="_",Qi={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function Xd(e){if(e.startsWith(Wt))return e.slice(Wt.length);if(e.startsWith(qi))return e.slice(qi.length);if(Object.hasOwn(Ji,e))return Ji[e];if(!e.startsWith(Vi))return e;let t=e.slice(Vi.length),n=t.indexOf($i);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+$i.length)}function Kd(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function Zi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("kiro: hook payload is not a JSON object");let t=e,n=typeof t.hook_event_name=="string"?t.hook_event_name:"",o=Object.prototype.hasOwnProperty.call(zi,n)?zi[n]:void 0;if(o===void 0)throw new Error("kiro: unknown hook event "+String(t.hook_event_name));let r={event:o,agent:"kiro",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")};if(o==="SessionStart"&&typeof t.source=="string"&&Qi[t.source]!==void 0&&(r.source=Qi[t.source]),o==="UserPromptSubmit"){let s=t[Bd],i=typeof s=="string"?s:process.env[Wd];i!==void 0&&(r.prompt=i)}if(o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool_name??""),i=typeof t.tool_input=="object"&&t.tool_input!==null&&!Array.isArray(t.tool_input)?t.tool_input:{};r.tool={name:s,canonicalName:Xd(s),input:i}}return o==="PostToolUse"&&(r.result=Kd(t.tool_response)),r}function ec(e,t,n){if(e.event==="UserPromptSubmit")return{stdout:t.kind==="hint"?t.text:"",exitCode:0};switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:t.text,exitCode:0};case"deny":return{stdout:"",stderr:t.rewritten===void 0?t.reason:t.rewritten+`
16
+ `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var xo="mcp__context-mode__",tc="mcp__plugin_context-mode_context-mode__",qd={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},zd={hook_event_name:"hookEventName",session_id:"sessionId"},Vd="PostToolUseFailure";function nc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("zcode: hook payload is not a JSON object");let t={...e};for(let[i,c]of Object.entries(zd))t[i]===void 0&&(t[i]=t[c]);let n=t.hook_event_name===Vd;n&&(t.hook_event_name="PostToolUse");let r=(typeof t.tool_name=="string"?t.tool_name:"").startsWith(tc)?tc:xo,s=ae(t,"zcode",r,qd);if(n){let i=typeof t.error=="string"?t.error:t.error===void 0?"":JSON.stringify(t.error);s.result={isError:!0,bytes:Buffer.byteLength(i),text:i}}return s}function oc(e,t,n){return B(e,t,!1)}var ic="",rc={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},sc={bash:"Bash",read:"Read",edit:"Edit",write:"Write"};function $d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Qd(e){let t=e.content===void 0?"":typeof e.content=="string"?e.content:JSON.stringify(e.content),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function cc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("pi: hook payload is not an object");let t=e,n=typeof t.type=="string"?t.type:"",o=Object.prototype.hasOwnProperty.call(rc,n)?rc[n]:void 0;if(o===void 0)throw new Error("pi: unknown hook event "+String(t.type));let r={event:o.event,agent:"pi",sessionId:String(t.sessionId??""),cwd:String(t.cwd??"")};if(o.source!==void 0&&(r.source=o.source),o.event==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o.event==="PreToolUse"||o.event==="PostToolUse"){let s=String(t.toolName??"");r.tool={name:s,canonicalName:Object.hasOwn(sc,s)?sc[s]:s,input:$d(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=Qd(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Zd(e,t){switch(t?.kind){case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
17
+ `+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function ac(e,t,n){let o=Zd(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:di,content:o.stdout,timestamp:Date.now()}}function lc(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var xc="",uc=$+"_",dc={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},po="bash",_o="read",tf=Object.freeze([po,"shell"]),fc={webfetch:"WebFetch",[_o]:"Read",...Object.fromEntries(tf.map(e=>[e,"Bash"]))};function Eo(e){return e.startsWith(uc)?e.slice(uc.length):Object.prototype.hasOwnProperty.call(fc,e)?fc[e]:e}function nf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function of(e){let t=e.output===void 0?"":typeof e.output=="string"?e.output:JSON.stringify(e.output),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function pc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("opencode: hook payload is not an object");let t=e,n=typeof t.type=="string"?t.type:"",o=Object.prototype.hasOwnProperty.call(dc,n)?dc[n]:void 0;if(o===void 0)throw new Error("opencode: unknown hook event "+String(t.type));let r={event:o,agent:"opencode",sessionId:String(t.sessionID??""),cwd:String(t.directory??"")};if(o==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool??"");r.tool={name:s,canonicalName:Eo(s),input:nf(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=of(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function _c(e,t,n){switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
18
+ `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var Ke={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},Ec={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},sf={...Ec,shell:[...gi]},cf=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:oo,nativeTools:sf,execReadOnlyHint:!1,eventMap:Ke,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:j,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"skills"},decode:hi,encode:Si},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:io,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:Ke,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:j,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:bi,encode:Oi},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Ut,nativeTools:{shell:["run_shell_command"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:{UserPromptSubmit:"BeforeAgent",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",PreCompact:"PreCompress"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:j,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:yi,encode:Ni},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:co,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:Ke,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:j,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:Ci,encode:ki},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:Ft,nativeTools:{shell:[...ao]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:j,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:Mi,encode:Ui},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:jt,nativeTools:{shell:[...lo],read:[...Bt],webfetch:[...uo]},execReadOnlyHint:!1,eventMap:{...Ke,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:j,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:Ki,encode:Yi},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:Wt,nativeTools:{shell:[...fo]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:j,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:Zi,encode:ec},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:xo,nativeTools:Ec,execReadOnlyHint:!1,eventMap:Ke,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:j,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:nc,encode:oc},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:ic,nativeTools:{shell:["bash","powershell"],read:["read"]},execReadOnlyHint:!1,eventMap:{SessionStart:"session_start",UserPromptSubmit:"input",PreToolUse:"tool_call",PostToolUse:"tool_result"},compactDelivery:"pi-flag",compactSummary:"none",hookTimeoutMs:Dn,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:cc,encode:ac,checkPermission:lc},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:xc,nativeTools:{shell:[po],read:[_o]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:Dn,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:pc,encode:_c,toCanonicalTool:Eo}]),af=new Map(cf.map(e=>[e.id,e])),lf=new Set(["claude-code","gemini","copilot-cli","pi"]);function Se(e){return lf.has(e.id)}var uf=new Set(["claude-code","copilot-cli","pi"]);function go(e){return uf.has(e.id)&&Se(e)}var df=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function Xt(e){return df.has(e.id)}function le(e){return af.get(e)}import{resolve as ln}from"node:path";var ff=["&&","||",";;","|&",";","|","&","(",")"],xf=["&>>","&>"],pf=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],_f="&",Ef="<<",gc="<<-",gf=";",mc=`\r
19
+ `,hc=`\\
20
+ `,Sc=`\\\r
21
+ `,mf="$(",Tc="${",Rc="$'",Ye="((",bc="))",be="[[",Kt="]]",mo="<(",Ac=">(",P=2,yc=`
22
+ \r;&|()<>`,hf=`
23
+ \r`,Sf='$`"\\\n',bf="case",Of="esac";function Oe(e,t){e.end==="complete"&&(e.end=t)}function ho(e){return e!==""&&e>="0"&&e<="9"}function Oc(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function Nc(e){return e===""||yc.includes(e)}function So(e){return e!==""&&hf.includes(e)}function W(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function Yt(e,t){let n=e.s.indexOf("'",t+1);return n<0?(Oe(e,"unterminated-quote"),e.n):n+1}function Ic(e,t){let n=t+Rc.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=P;continue}if(o==="'")return n+1;n++}return Oe(e,"unterminated-quote"),e.n}function bo(e,t,n){let o=t+1;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(r==="\\"){o+=P;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=qe(e,o,n);continue}if(r==="$"&&s==="{"){o=Oo(e,o,n);continue}if(r==="`"){o=Te(e,o);continue}o++}return Oe(e,"unterminated-quote"),e.n}function Te(e,t){let n=t+1;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=P;continue}if(o==="`")return n+1;n++}return e.n}function Oo(e,t,n){let o=t+Tc.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=P;continue}if(s==="'"){o=Yt(e,o);continue}if(s==='"'){o=bo(e,o,n);continue}if(s==="$"&&i==="("){o=qe(e,o,n);continue}if(s==="`"){o=Te(e,o);continue}if(s==="{"&&r++,s==="}"){if(r===0)return o+1;r--}o++}return e.n}function To(e,t){let n=0,o=t+Ye.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(bc,o)?o+bc.length:-1;n--}o++}return-1}function qe(e,t,n){let o=t+mf.length-1;if(e.s.startsWith(Ye,o)){let r=To(e.s,o);if(r>0)return r}return qt(e,o+1,!0,n+1,null,null)}function Tf(e,t,n){let o=t+be.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=P;continue}if(s==="'"){o=Yt(e,o);continue}if(s==='"'){o=bo(e,o,n);continue}if(s==="$"&&i==="("){o=qe(e,o,n);continue}if(s==="$"&&i==="{"){o=Oo(e,o,n);continue}if(s==="`"){o=Te(e,o);continue}let c=So(e.s.charAt(o-1));if(c&&e.s.startsWith(Kt,o)&&Nc(e.s.charAt(o+Kt.length))){if(r===0)return o+Kt.length;r--,o+=Kt.length;continue}if(c&&e.s.startsWith(be,o)&&So(e.s.charAt(o+be.length))){r++,o+=be.length;continue}o++}return-1}function Rf(e,t){let n=t;for(;ho(e.charAt(n));)n++;if(n===t){for(let o of xf)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of pf){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(_f))if(e.charAt(r)==="-")r++;else for(;ho(e.charAt(r));)r++;return{end:r,op:o}}return null}function Af(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(yc.includes(r))break;if(r==="\\"){o+=P;continue}if(r==="'"){o=Yt(e,o);continue}if(r==='"'){o=bo(e,o,n);continue}if(r==="$"&&s==="'"){o=Ic(e,o);continue}if(r==="$"&&s==="("){o=qe(e,o,n);continue}if(r==="$"&&s==="{"){o=Oo(e,o,n);continue}if(r==="`"){o=Te(e,o);continue}o++}return Math.min(o,e.n)}function yf(e,t,n,o,r){let s=t;for(let i of n){let c=s,l=!1;for(;s<e.n;){let a=e.s.indexOf(`
24
+ `,s),d=a<0?e.n:a,u=e.s.slice(s,d);if(u.endsWith("\r")&&(u=u.slice(0,-1)),s=a<0?e.n:a+1,(i.strip?u.trim():u)===i.tag){l=!0;break}}if(o!==null&&r!==null&&r.push(o.length),W(o,"unhandled",e.s.slice(c,s),c,s),!l)return Oe(e,"unterminated-heredoc"),e.n}return n.length=0,s}function qt(e,t,n,o,r,s){if(o>G)return Oe(e,"too-deep"),e.n;let i=e.s,c=t,l=0,a=0,d=null,u=[];for(;c<e.n;){let f=i.charAt(c),x=i.charAt(c+1);if(f===" "||f===" "){c++;continue}if(i.startsWith(hc,c)){c+=hc.length;continue}if(i.startsWith(Sc,c)){c+=Sc.length;continue}if(f===`
25
+ `||f==="\r"){let S=c;c+=i.startsWith(mc,c)?mc.length:1,W(r,"op",gf,S,c),d=null,u.length>0&&(c=yf(e,c,u,r,s));continue}if(f==="#"){for(;c<e.n&&i.charAt(c)!==`
26
+ `&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(mo,c)||i.startsWith(Ac,c)){let S=qt(e,c+mo.length,!0,o+1,null,null);W(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}let p=Rf(i,c);if(p!==null){W(r,"io",i.slice(c,p.end),c,p.end),d=p.op===Ef||p.op===gc?p.op===gc:null,c=p.end;continue}if(i.startsWith(be,c)&&So(i.charAt(c+be.length))){let S=Tf(e,c,o);if(S>0){W(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}if(i.startsWith(Ye,c)){let S=To(i,c);if(S>0){W(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}let g=ff.find(S=>i.startsWith(S,c));if(g!==void 0){if(n&&g==="("&&l++,n&&g===")"){if(l>0)l--;else if(a===0)return c+1}W(r,"op",g,c,c+g.length),c+=g.length,d=null;continue}if(f==="$"&&x==="("||f==="`"){let S=f==="`"?Te(e,c):qe(e,c,o);if(Nc(i.charAt(S))){W(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}let E=c;c=Af(e,c,o);let h=i.slice(E,c);W(r,"word",h,E,c),d!==null&&(u.push({tag:Re(h),strip:d}),d=null),n&&h===bf&&a++,n&&h===Of&&a>0&&a--}return u.length>0&&Oe(e,"unterminated-heredoc"),e.n}function Cc(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return qt(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function Re(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=P;continue}if(r==="'"){let s=e.indexOf("'",n+1),i=s<0?o:s;t+=e.slice(n+1,i),n=i+1;continue}if(r==="$"&&e.charAt(n+1)==="'"){let s=n+Rc.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=P;continue}t+=e.charAt(s),s++}n=s+1;continue}if(r==='"'){let s=n+1;for(;s<o&&e.charAt(s)!=='"';){let i=e.charAt(s+1);if(e.charAt(s)==="\\"&&i!==""&&Sf.includes(i)){t+=i,s+=P;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function zt(e){let t={s:e,n:e.length,end:"complete"},n=[],o=!1,r=0;for(;r<t.n;){let s=e.charAt(r),i=e.charAt(r+1);if(s==="\\"){r+=P;continue}if(!o&&s==="'"){r=Yt(t,r);continue}if(!o&&s==="$"&&i==="'"){r=Ic(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Tc.length;continue}let c=e.startsWith(mo,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(Ac,r))){let l=r+1;if(s==="$"&&e.startsWith(Ye,l)&&To(e,l)>0){r=l+Ye.length;continue}let a=qt(t,l+1,!0,1,null,null),d=a>l+1&&e.charAt(a-1)===")"?a-1:a;n.push({wrapper:s==="$"?"$()":c?"<()":">()",body:e.slice(l+1,d)}),r=a;continue}if(s==="`"){let l=Te(t,r),a=l>r+1&&e.charAt(l-1)==="`"?l-1:l;n.push({wrapper:"`",body:e.slice(r+1,a)}),r=l;continue}r++}return n}function Vt(e){let t=e.charAt(0);if(!(Oc(t)||t==="_"))return!1;for(let n=1;n<e.length;n++){let o=e.charAt(n);if(o==="="||o==="+"&&e.charAt(n+1)==="=")return!0;if(!(Oc(o)||ho(o)||o==="_"))return!1}return!1}var wc=[";","&","&&","||"],Pc=["|","|&"],ze="(",Ve=")",Mc=";;",yo=["(",")"],Nf="!";function M(e,t){for(let n of t)e.push(n)}var b=Object.freeze({group:"{",groupEnd:"}",if:"if",then:"then",elif:"elif",else:"else",fi:"fi",while:"while",until:"until",for:"for",in:"in",do:"do",done:"done",case:"case",esac:"esac",function:"function",coproc:"coproc",select:"select"}),Uc=[],If="[[",Cf="((",Hc=[">",">>",">|","&>","&>>",">&"],kf=[...Hc,"<","<>","<<<","<<","<<-"],Df=["","1"],Fc=["-","/dev/stdout","/dev/stderr"],$t="-",Je="--",$e="=",Lf="/",wf=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),Jt=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),Ro="-c",Ao="--bytes",Pf="c",Mf="--count",ue=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],Z=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,C=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,No=e=>e!==""&&e>="0"&&e<="9",Uf=e=>No(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function Io(e){let t=e.lastIndexOf(Lf);return t>=0&&t<e.length-1?e.slice(t+1):e}function Co(e,t){let n=wf[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===Je)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+$e))s=r.slice(n.long.length+$e.length);else if(r.startsWith($t)&&!r.startsWith(Je)){let i=r.indexOf(n.short,$t.length);if(i<0)continue;s=i+n.short.length<r.length?r.slice(i+n.short.length):t[o+1]}else continue;if(s!==void 0&&!Fc.includes(s))return!0}return!1}function Hf(e){if(e==="")return!1;for(let t of e)if(!No(t))return!1;return!0}function Ff(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===Ro||n===Ao?o=e[t+1]:n.startsWith(Ao+$e)?o=n.slice(Ao.length+$e.length):n.startsWith(Ro)&&!n.startsWith(Je)&&(o=n.slice(Ro.length)),o!==void 0)return Hf(o)&&Number(o)<=ie}return!1}function vf(e){for(let t of e){if(t===Je)return!1;if(t===Mf||t.startsWith($t)&&!t.startsWith(Je)&&t.includes(Pf))return!0}return!1}function kc(e){if(!e.startsWith(L.fieldSep))return!1;for(let t of e.slice(L.fieldSep.length).split(L.fieldSep)){if(t==="")return!1;for(let n of t)if(!Uf(n))return!1}return!0}function jf(e){let t=e.trim();if(t===L.identity||t===L.length)return!0;let n=t.indexOf(L.pipeLength.charAt(0));if(n<0)return kc(t);let o=t.slice(0,n).trim(),r=L.pipeLength.slice(1).trim();return(o===L.identity||kc(o))&&t.slice(n+1).trim()===r}function Gf(e){let t=e.argv0.toLowerCase();if(t===Jt.wc)return!0;if(t===Jt.head)return Ff(e.args);if(t===Jt.grep)return vf(e.args);if(t===Jt.jq){let n=e.args.filter(o=>!o.startsWith($t));return n.length===1&&jf(n[0])}return!1}function ko(e){return zt(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function vc(e,t,n){return n<=t?[]:ko(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function jc(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function Bf(e){let t=0;for(;No(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Gc(e){let t=Bf(e.toks[e.i].text);if(e.i++,!kf.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,Hc.includes(t.op)&&Df.includes(t.fd)&&!Fc.includes(Re(n.text)))}function Bc(e){let t=!1;for(;O(e)?.kind==="io";)t=Gc(e)||t;return t}function Wc(e){for(;O(e)?.kind==="op"&&wc.includes(O(e)?.text??"");)e.i++}function Ae(e,t){if(e.depth++,e.depth>G)return e.err="nesting-too-deep",ue();let n=t();if(e.depth--,Bc(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function Xc(e){if(Wc(e),!C(O(e),b.do))return[];e.i++;let t=X(e,[b.done]);return C(O(e),b.done)&&e.i++,t}function Wf(e){e.i++;let t=X(e,[b.then]);for(;e.err===null;){let n=O(e);if(C(n,b.then)||C(n,b.else)){e.i++,M(t,X(e,[b.elif,b.else,b.fi]));continue}if(C(n,b.elif)){e.i++,M(t,X(e,[b.then]));continue}C(n,b.fi)&&e.i++;break}return t}function Xf(e){e.i++;let t=X(e,[b.do]);return M(t,Xc(e)),t}function Kf(e){e.i++;let t=[],n=O(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,C(O(e),b.in)){e.i++;let o=e.i;for(;(O(e)?.kind==="word"||O(e)?.kind==="unhandled")&&!C(O(e),b.do);)e.i++;M(t,vc(e,o,e.i))}return M(t,Xc(e)),t}function Yf(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,M(t,vc(e,e.i-1,e.i))),C(O(e),b.in)&&e.i++;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)||o.kind==="op"&&(wc.includes(o.text)||o.text===Mc)){e.i++;continue}if(C(o,b.esac)){e.i++;break}for(Z(o,ze)&&e.i++;e.i<e.toks.length&&!Z(O(e),Ve);){let s=e.toks[e.i];if(s.kind==="op"&&!Pc.includes(s.text))break;e.i++}if(!Z(O(e),Ve))break;e.i++;let r=X(e,[b.esac]);jc(r,b.case),M(t,r)}return t}function Dc(e,t){Wc(e);let n=Kc(e);return jc(n.cmds,t),{cmds:n.cmds,simple:null}}function Lc(e,t){return yo.every((n,o)=>Z(e.toks[t+o],n))}function qf(e){let t=e.i,n=[],o=!1;for(;e.i<e.toks.length;){let a=e.toks[e.i];if(a.kind==="op")break;if(a.kind==="io"){o=Gc(e)||o;continue}if(n.length===0&&a.kind==="word"&&Vt(a.text)){e.i++;let d=O(e);if(a.text.endsWith($e)&&d!==void 0&&Z(d,ze)&&d.start===a.end){let u=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,Z(f,ze)&&u++,Z(f,Ve)&&--u===0)break}}continue}n.push(a),e.i++}if(e.i===t)return ue();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:ko(r),simple:null};let s=a=>a.kind==="word"?Re(a.text):a.text,i=Io(s(n[0])),c=n.slice(1).map(s),l={argv0:i,args:c,redirectsToFile:o||Co(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[l],simple:l}}function Kc(e){let t=O(e);if(t===void 0)return ue();if(t.kind==="op")return t.text!==ze?ue():Ae(e,()=>{e.i++;let n=X(e,Uc);return Z(O(e),Ve)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(If)||t.text.startsWith(Cf)))return e.i++,Bc(e),{cmds:ko(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return Ae(e,()=>{e.i++;let n=X(e,[b.groupEnd]);return C(O(e),b.groupEnd)&&e.i++,n});case b.if:return Ae(e,()=>Wf(e));case b.while:case b.until:return Ae(e,()=>Xf(e));case b.for:return Ae(e,()=>Kf(e));case b.case:return Ae(e,()=>Yf(e));case b.coproc:return e.err="coproc",ue();case b.select:return e.err="select",ue();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=Re(n.text),e.i++),Lc(e,e.i)&&(e.i+=yo.length),Dc(e,o)}default:if(Lc(e,e.i+1))return e.i+=yo.length+1,Dc(e,Re(t.text))}return qf(e)}function zf(e){C(O(e),Nf)&&e.i++;let t=[],n=ue();for(;e.err===null;){n=Kc(e),M(t,n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&Pc.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&Gf(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function X(e,t){let n=[];for(;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)){e.i++;continue}if(o.kind==="op"){if(o.text===Ve||o.text===Mc)return n;if(o.text!==ze){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;M(n,zf(e)),e.i===r&&e.err===null&&e.i++}return n}function ye(e){let t=Cc(e);if(t.end==="unterminated-quote")return{ok:!1,construct:"unterminated-quote"};if(t.end==="unterminated-heredoc")return{ok:!1,construct:"unterminated-heredoc"};if(t.end==="too-deep")return{ok:!1,construct:"nesting-too-deep"};let n={toks:t.tokens,src:e,bodies:new Set(t.heredocBodies),i:0,depth:0,err:null},o=[];for(;n.i<n.toks.length&&n.err===null;)M(o,X(n,Uc)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as Yc}from"node:path";var Zt="'",Ne='"',en="`",Vf=" \r",Ze="([{",Po=")]}",Do=` \r
27
+ |;>`,Vc="*",qc="1",Lo="::",Qt=Lo.length,Jf=Qt;function tn(e,t){let n=e.charAt(t);for(let o=t+1;o<e.length;o++){let r=e.charAt(o);if(n===Ne&&r===en){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function $f(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===Ne&&r===en&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function Qe(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Zt||r===Ne){let s=tn(e,o);if(s<0)return-1;o=s;continue}if(r===en){o++;continue}if(Ze.includes(r))n++;else if(Po.includes(r)&&--n===0)return o}return-1}function Qf(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Zt||r===Ne){let s=tn(e,o);if(s<0)return e.length;o=s;continue}if(Ze.includes(r))n++;else if(Po.includes(r))n--;else if(n<=0&&Do.includes(r))return o}return e.length}function Zf(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===Zt||s===Ne){let i=tn(e,r);if(i<0)break;r=i;continue}Ze.includes(s)?n++:Po.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var e0=e=>e!==""&&(e===Vc||[...e].every(t=>t>="0"&&t<="9")),zc=()=>({words:[],toFile:!1,chained:!1});function Jc(e){let t=[],n=[],o=zc(),r="",s=!1,i=!0,c=null,l=e.length,a=()=>{s&&(c!==null?(c==="file"&&(o.toFile=!0),c=null):o.words.push(r),r="",s=!1,i=!0)},d=()=>{a(),(o.words.length>0||o.toFile)&&n.push(o),o=zc()},u=()=>{d(),n.length>0&&t.push(n),n=[]},f=(p,g)=>{r+=p,s=!0,g&&(i=!1)},x=0;for(;x<l;){let p=e.charAt(x),g=e.charAt(x+1);if(p===Zt||p===Ne){let E=tn(e,x);f($f(e.slice(x+1,E<0?l:E),p),!0),x=E<0?l:E+1}else if(p===en)g!==`
28
+ `&&g!==""&&f(g,!1),x+=Qt;else if(p===`
29
+ `)u(),x++;else if(Vf.includes(p))a(),x++;else if(p===";")u(),x++;else if(p==="|")g==="|"?(u(),x+=Qt):(d(),x++);else if(p==="&")g==="&"?(u(),x+=Qt):((s||o.words.length>0)&&f(p,!1),x++);else if(p==="#"&&!s)for(;x<l&&e.charAt(x)!==`
30
+ `;)x++;else if(p===">"){let E=qc;s&&i&&e0(r)?(E=r,r="",s=!1):s&&a();let h=x+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<l&&!Do.includes(e.charAt(h));)h++;else c=E===qc||E===Vc?"file":"skip";x=h}else if(p==="("&&s&&i&&r.includes(Lo)){let E=Qe(e,x),h=e.slice(x+1,E<0?l:E);a();for(let S of h.trim()===""?[]:Zf(h)){let _=Jc(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}x=E<0?l:E+1,x<l&&!Do.includes(e.charAt(x))&&(o.chained=!0,x=Qf(e,x))}else if(p==="["&&!s&&e.startsWith(Lo,Qe(e,x)+1)&&Qe(e,x)>=0){let E=Qe(e,x);f(e.slice(x,E+1),!1),x=E+1}else if(Ze.includes(p)&&(p!=="["||!s)||(p==="$"||p==="@")&&Ze.includes(g)&&g!=="["){let E=p==="$"||p==="@"?x+1:x,h=Qe(e,E);f(e.slice(x,h<0?l:h+1),!0),x=h<0?l:h+1}else f(p,!1),x++}return u(),t}var t0=["get-content","gc","cat","type"],n0=["[io.file]::","[system.io.file]::"],o0=["readalltext","readalllines","readallbytes","readlines"],Mo=["path","literalpath"],$c=["totalcount","head","first","tail","last"],Qc=[...Mo,...$c,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],r0=["raw","wait","force","asbytestream"],s0=[...Qc,...r0],i0=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],c0=["cd","chdir","sl","set-location","pushd","push-location"],a0=["powershell","powershell.exe","pwsh","pwsh.exe"],l0=["cmd","cmd.exe"],u0=["/c","/k","/r"],d0="command",de="-";function wo(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function Uo(e,t){let n=e.slice(de.length),o=n.indexOf(":"),r=(o<0?n:n.slice(0,o)).toLowerCase(),s=o<0?void 0:n.slice(o+1);if(r==="")return{full:void 0,inline:s};if(t.includes(r))return{full:r,inline:s};let i=t.filter(c=>c.startsWith(r));return{full:i.length===1?i[0]:void 0,inline:s}}function f0(e){if(e.length===0)return null;let t=wo(e[0]);if(!t0.includes(t)){let r=e[0].toLowerCase(),s=n0.find(i=>r.startsWith(i));return s===void 0||!o0.includes(r.slice(s.length))||e.length<Jf?null:{file:e[1],bounded:!1}}let n=[],o=!1;for(let r=1;r<e.length;r++){let s=e[r];if(!s.startsWith(de)||s.length===de.length){n.push(s);continue}let i=Uo(s,s0);if(i.full===void 0||!Qc.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;Mo.includes(i.full)&&n.push(c),$c.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function x0(e,t){if(a0.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(de)||o.length===de.length)continue;let r=Uo(o,[d0]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(l0.includes(e)){for(let n=1;n<t.length;n++)if(u0.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function p0(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(de)||n.length===de.length)return n;let o=Uo(n,Mo);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function Zc(e,t,n,o){let r=t;for(let s of Jc(e)){let i=s[0];if(i.words.length===0)continue;let c=wo(i.words[0]);if(s.length===1&&c0.includes(c)){let u=p0(i.words);u!==null&&(r=Yc(r,u));continue}let l=n<G?x0(c,i.words):null;if(l!==null){Zc(l,r,n+1,o);continue}if(i.toFile||i.chained)continue;let a=f0(i.words);if(a===null||a.bounded)continue;let d=!0;for(let u=1;u<s.length;u++)if(s[u].toFile||!i0.includes(wo(s[u].words[0]??""))){d=!1;break}d&&o.push(Yc(r,a.file))}}function ea(e,t){let n=[];return Zc(e,t,0,n),n}import{join as rn}from"node:path";var ta=`\r
31
+ `,_0=`
32
+ `;function nn(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(ta)<0?t:t.split(ta).join(_0)}import{basename as h0,dirname as S0,join as K,posix as oa,resolve as b0,win32 as ra}from"node:path";var E0=Object.freeze({NODE_TOO_OLD:"Context Mode needs Node 24.15.0 or newer; you have <v>. Fix: nvm install 24, or install it from https://nodejs.org.",NO_SQLITE:"node:sqlite failed to load. Fix: run ctx_doctor.",DB_GONE:"context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",NO_PROJECT:"Project source <kind> is missing. Fix: run ctx_doctor.",UNKNOWN_FIELD:'Unknown field "<f>". Fix: use "queries".',TIMEOUT:"Timed out after <ms> ms. Fix: pass background: true.",NO_GIT_BASH:"Git Bash not found. Fix: install Git for Windows.",NO_RUNTIME:"No <lang> runtime on PATH. Fix: install it or pick another language.",FETCH_FAILED:"Fetch failed: <code>. Fix: check the URL or proxy.",SSRF:"Blocked private address <host>. Fix: use a public URL.",OUTSIDE_ROOT:"Path <p> is outside the project. Fix: use a path inside <root>.",INVALID_ARGS:"Invalid argument <field>. Fix: <action>.",ONE_OF_INPUT:"Pass exactly one of <names>. Fix: drop the extra field.",SPAWN_FAILED:"Failed to start the process: <detail>. Fix: check the command and PATH.",DB_CORRUPT:"context.db failed integrity_check. Fix: run ctx_doctor.",SCHEMA_STALE:"context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.",NO_GIT_DIR:"No git repository at <path>. Fix: run context-mode inside a git repository.",NO_HOME:"Env var <name> is not set. Fix: set <name> to your home directory.",PLUGIN_ROOT_MISSING:"Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.",BUNDLE_HASH_MISMATCH:"Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.",CONFIG_PARSE_FAILED:"<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade."});function g0(e,t){let n=E0[e],o="",r=0;for(;r<n.length;){if(n[r]!=="<"){o+=n[r],r+=1;continue}let s=r+1;for(;s<n.length&&n[s]!=="<"&&n[s]!==">";)s+=1;if(s>=n.length){o+=n.slice(r);break}if(n[s]==="<"){o+="<",r+=1;continue}let i=n.slice(r+1,s),c=t[i];if(c===void 0)throw new Error("formatError: missing var "+i+" for "+e);o+=String(c),r=s+1}return o}var T=class extends Error{code;vars;constructor(t,n){super(g0(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{existsSync:Xg,mkdirSync:m0,readFileSync:Kg,readdirSync:Yg,realpathSync:na}=process.getBuiltinModule("node:fs");function U(e,t=process.platform){let n=o=>o!==void 0&&o!=="";return t==="win32"?n(e.USERPROFILE)?e.USERPROFILE:n(e.HOMEDRIVE)&&n(e.HOMEPATH)?e.HOMEDRIVE+e.HOMEPATH:n(e.HOME)?e.HOME:null:n(e.HOME)?e.HOME:n(e.USERPROFILE)?e.USERPROFILE:null}function sa(e,t){let n=e[si];return n!==void 0&&n!==""?n:K(t,...I.codex)}function ia(e,t){let n=e[ii];return n!==void 0&&n!==""?n:K(t,...I["copilot-cli"])}function ca(e,t){let n=e[ci];return K(n!==void 0&&n!==""?n:t,...I.gemini)}function aa(e,t,n=process.platform){let o=n==="win32"?ra:oa,r=o.join(t,...I.kiro),s=e[ai]?.trim();if(s===void 0||s===""||!o.isAbsolute(s)||n==="win32"&&o.parse(s).root.length<2)return r;let i=o.resolve(s),c=n===process.platform?O0:d=>d,l=c(i);if(o.parse(l).root===l)return r;let a=o.relative(l,c(o.resolve(t)));return!o.isAbsolute(a)&&a.split(o.sep)[0]!==".."?r:i}function O0(e){let t=[];for(let n=e;;)try{return K(na.native(n),...t.reverse())}catch{let o=S0(n);if(o===n)return e;t.push(h0(n)),n=o}}function Y(e,t){let n=e[Lt];return n!==void 0&&n!==""?n:K(t,...I["claude-code"])}function la(e,t){let n=e[li];if(n!==void 0&&n!=="")return n;let o=e[Pt];return o!==void 0&&o!==""?K(o,I.opencode[I.opencode.length-1]):K(t,...I.opencode)}function ua(e,t){let n=e[fi];return n!==void 0&&n!==""?n:K(t,...I.pi,ui)}function da(e,t,n=process.platform){let o=s=>s!==void 0&&s!=="",r=n==="win32"?ra:oa;return n==="win32"?r.join(o(e[no])?e[no]:r.join(t,"AppData","Roaming"),...wt):n==="darwin"?r.join(t,"Library","Application Support",...wt):r.join(o(e[Pt])?e[Pt]:r.join(t,".config"),...wt)}function T0(e,t=process.platform){let n=U(e,t);if(n!==null)return n;throw new T("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function on(e,t){let n=e[Fe];return n!==void 0&&n!==""?b0(n):K(t,es.slice(1))}function fa(e){let t=e[Fe],n=on(e,t!==void 0&&t!==""?"":T0(e));return m0(n,{recursive:!0}),na.native(n)}var{readFileSync:Ea}=process.getBuiltinModule("node:fs");function Ie(e){return e.agentId!==void 0&&e.agentId!==""}function vo(e,t){if(t===null)return"C";let n=le(e.agent),o=new Set(t);for(let r of gt)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function jo(e,t){if(!Ie(e))return null;let n=le(e.agent);if(t.manifestTools!==void 0)return _a(t.manifestTools.map(c=>Ho(n,c)));let o=e.agentType??"",r=R0(o,t);if(r===null)return null;let s=(r.tools??C0(n)).map(c=>Ho(n,c)),i=r.disallowed.map(c=>Ho(n,c));return _a(s.filter(c=>!i.some(l=>D0(l,c))))}function R0(e,t){if(!A0(e))return null;let n=y0(t.env);if(e.indexOf(ge)>=0){if(n!==null){let s=N0(Y(t.env,n),e);if(s!==null)return s}}else{let s=Fo(rn(t.projectDir,ns,Ot,e+Ee));if(s!==null)return s;if(n!==null){let i=Fo(rn(Y(t.env,n),Ot,e+Ee));if(i!==null)return i}}let r=t.cliAgents;if(r!==void 0&&Object.prototype.hasOwnProperty.call(r,e)){let s=r[e];return{tools:Array.isArray(s.tools)?s.tools:null,disallowed:Array.isArray(s.disallowedTools)?s.disallowedTools:[]}}return null}function A0(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(ge))if(t===""||t==="."||t==="..")return!1;return!0}function y0(e){return U(e)}function N0(e,t){let n=t.indexOf(ge),o=t.slice(0,n),r=t.slice(n+ge.length);if(r.indexOf(ge)>=0)return null;let s;try{s=JSON.parse(nn(Ea(rn(e,Mn,os),"utf8")))}catch{return null}let i=s?.plugins;if(i===null||typeof i!="object")return null;for(let c of Object.keys(i)){let l=c.indexOf(rs);if((l<0?c:c.slice(0,l))!==o)continue;let a=i[c];if(Array.isArray(a))for(let d of a){let u=d?.installPath;if(typeof u!="string"||u==="")continue;let f=Fo(rn(u,Ot,r+Ee));if(f!==null)return f}}return null}function Fo(e){let t;try{t=Ea(e,"utf8")}catch{return null}return I0(t)}function I0(e){let t=e.split(`
33
+ `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Un)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Un){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=xa(o,ss),s=xa(o,is);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function xa(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(t+":"))continue;let r=o.slice(t.length+1).trim();if(r===""){let s=[];for(let i=n+1;i<e.length;i++){let c=e[i].trim();if(!c.startsWith("-"))break;s.push(pa(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>pa(s.trim())).filter(s=>s!=="")}return null}function pa(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function C0(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...gt.map(n=>e.toolNamePrefix+n)]}function Ho(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(cs)?k0(o):o}function k0(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||as.indexOf(n)>=0;t+=o?n:"_"}return t}function D0(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(Hn)){let n=e.slice(Hn.length);if(n!==""&&n.indexOf(Fn)<0)return t.startsWith(e+Fn)}return!1}function _a(e){return[...new Set(e.filter(t=>t!==""))]}var fe="",ga=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:fe},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:fe},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:fe},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:fe},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:fe},command:{valueShorts:fe,valueLongs:[],assignments:!1,duration:!1,refuseShorts:"vV"},xargs:{valueShorts:"aEdILnPs",valueLongs:["--arg-file","--delimiter","--max-args","--max-procs","--max-chars"],assignments:!1,duration:!1,refuseShorts:fe}}),L0=["bash","sh","zsh"],w0="c",P0=" -c",M0=["-o","+o","-O","+O"],sn="-",U0="+",Go="--",H0="smhd",F0=".",ma=e=>e!==""&&e>="0"&&e<="9";function v0(e){if(e===""||!ma(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(ma(n)||n===F0))return t===e.length-1&&H0.includes(n)}return!0}function j0(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===Go){n++;break}if(e.assignments&&Vt(o)){n++;continue}if(o.startsWith(Go)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(sn)&&o.length>sn.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=sn.length;r<o.length;r++)if(e.valueShorts.includes(o.charAt(r))){r===o.length-1&&n++;break}continue}break}if(e.duration){if(n>=t.length||!v0(t[n]))return null;n++}return n<t.length?t.slice(n):null}function G0(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(Go)){if(o.startsWith(sn)||o.startsWith(U0)){o.includes(w0)&&(t=!0),M0.includes(o)&&n++;continue}return t?o:null}}return null}function ha(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function Bo(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let l=s.toLowerCase();if(L0.includes(l)){let u=G0(i),f=u!==null&&n<G?ye(u):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=ha(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,Bo(p,[...r,l+P0],n+1,o)}return}let a=Object.hasOwn(ga,l)?ga[l]:void 0,d=a===void 0?null:j0(a,i);if(d===null)break;r.push(l),s=Io(d[0]),i=d.slice(1),c=c||Co(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=G))for(let l of zt(e.raw)){let a=ye(l.body);if(a.ok)for(let d of a.commands)Bo(ha(d,e),[...t,l.wrapper],n+1,o)}}function Wo(e){let t=[];for(let n of e)Bo(n,[],0,t);return t}import{isAbsolute as W0,join as Xo,relative as X0,sep as Ko}from"node:path";var{readFileSync:B0}=process.getBuiltinModule("node:fs"),Sa=".claude",K0="settings.local.json",ba="settings.json",Ia="Bash",Y0="Read",Oa=":*",Ta="//",Ra="~/",Aa="./",ya="..",q0=`
34
+ \r`,z0=Object.freeze({tool:Ia});function V0(e,t){if(t!=="claude-code")return[];let n=U(process.env),o=process.env[Lt],r=o!==void 0&&o!==""?o:n===null?null:Y(process.env,n),s=[Xo(e,Sa,K0),Xo(e,Sa,ba)];return r===null?s:[...s,Xo(r,ba)]}function Na(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function J0(e){let t;try{t=nn(B0(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Na(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Na(o))return{kind:"bad"};let r=o.deny;return r===void 0?{kind:"ok",deny:[]}:!Array.isArray(r)||!r.every(s=>typeof s=="string")?{kind:"bad"}:{kind:"ok",deny:r}}function Ca(e,t){let n=[];for(let o of V0(e,t)){let r=J0(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function Yo(e,t){let n=[],o=0;for(;o<e.length;){let r=e[o];if(r==="*"&&t&&e[o+1]==="*"){let s=e[o+2]==="/";n.push({t:s?"globstarDir":"globstar"}),o+=s?3:2;continue}r==="*"?(n.length===0||n[n.length-1].t!=="star")&&n.push({t:"star"}):r==="?"?n.push({t:"any1"}):n.push({t:"lit",c:r}),o++}return n}function qo(e,t,n,o){let r=t.length,s=o,i=new Uint8Array(r+1);for(let c=e.length-1;c>=0;c--){let l=e[c];s===o&&(s=Uint8Array.from(o));let a=0;for(let u=r;u>=0;u--){let f=u<r,x=f?t[u]:"";switch(l.t){case"lit":i[u]=f&&x===l.c?s[u+1]:0;break;case"any1":i[u]=f&&!(n&&x==="/")?s[u+1]:0;break;case"star":i[u]=s[u]||(f&&!(n&&x==="/")?i[u+1]:0);break;case"globstar":i[u]=s[u]||(f?i[u+1]:0);break;case"globstarDir":f&&x==="/"&&s[u+1]&&(a=1),i[u]=s[u]||a;break}}let d=i;i=s,s=d}return s}function et(e,t,n){let o=Yo(e,n),r=o[0];if(r!==void 0&&r.t==="lit"&&t[0]!==r.c)return!1;let s=new Uint8Array(t.length+1);return s[t.length]=1,qo(o,t,n,s)[0]===1}function ka(e){let t=e.indexOf("(");if(t<1||!e.endsWith(")"))return null;let n=e.slice(t+1,e.length-1);return n===""?null:{tool:e.slice(0,t),glob:n}}function Da(e,t){let n=t.length,o=new Uint8Array(n+1);if(o[n]=1,!e.endsWith(Oa))return qo(Yo(e,!1),t,!1,o);for(let r=0;r<n;r++)q0.includes(t[r])&&(o[r]=1);return qo(Yo(e.slice(0,e.length-Oa.length),!1),t,!1,o)}function $0(e,t){return Da(e,t)[0]===1}function La(e,t,n){for(let o of t){let r=ka(o);if(r===null||r.tool!==Ia)continue;let s=Da(r.glob,e);for(let i=0;i<=e.length;i++)if(n[i]===1&&s[i]===1)return o}return null}var Q0=/^[A-Za-z]:(?=\/)/;function tt(e){return Ko==="/"?e:e.split(Ko).join("/")}function Z0(e,t,n){if(e.startsWith(Aa)){if(n===void 0)return!1;let r=X0(n,t);return r===""||r===ya||r.startsWith(ya+Ko)||W0(r)?!1:et(e.slice(Aa.length),tt(r),!0)}let o=tt(t);if(e.startsWith(Ta)){let r=tt(e.slice(Ta.length-1));return et(r,o,!0)||et(r,o.replace(Q0,""),!0)}if(e.startsWith(Ra)){let r=U(process.env);return r!==null&&et(tt(r)+e.slice(Ra.length-1),o,!0)}return et(tt(e),o,!0)}function Ce(e,t,n=z0){for(let o of t){let r=ka(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===Y0?Z0(r.glob,e,n.projectDir):$0(r.glob,e))return o}return null}var fm=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),wa='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.',Pa=`context-mode: {size}-byte file, over the one-read limit. Read "{path}" in parts with offset and limit, or sed -n '1,200p'.`;var Ma="{size}",Ua="{path}";function Ha(e,t,n=""){return D(wa,n).split(Ma).join(String(t)).split(Ua).join(e)}function Fa(e,t){return Pa.split(Ma).join(String(t)).split(Ua).join(e)}import{extname as ox,join as zo}from"node:path";import{dirname as va,join as hm,relative as Sm,sep as tx}from"node:path";var{lstatSync:gm,realpathSync:ex}=process.getBuiltinModule("node:fs");function nt(e){try{return ex.native(e)}catch{return}}function ee(e){return e.split(tx).filter(t=>t!=="")}function Ga(e,t){let n=nt(e),o=nt(t);if(n===void 0||o===void 0)return!1;let r=ee(n),s=ee(o);if(s.length<r.length)return!1;for(let i=0;i<r.length;i+=1)if(r[i]!==s[i])return!1;return!0}var ja=new Map;function nx(e){let t=ja.get(e);if(t!==void 0)return t;let n=nt(e);return n!==void 0&&ja.set(e,n),n}function ke(e,t){if(e.length===0)return!1;let n=nt(t);if(n===void 0)return!1;let o=ee(n);return e.some(r=>{let s=nx(r);if(s===void 0)return!1;let i=ee(s);return o.length>=i.length&&i.every((c,l)=>c===o[l])})}function Ba(e){let t=e.map(nt).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=ee(n).length;for(let s of t){let i=ee(s),c=ee(n),l=0;for(;l<o&&l<i.length&&i[l]===c[l];)l+=1;o=l}let r=n;for(;ee(r).length>o&&va(r)!==r;)r=va(r);return r}function rx(e,t){let n=U(t);if(n===null)return[];let o=zo(n,...ls);return[...e==="claude-code"?[Y(t,n)]:e==="codex"?[sa(t,n)]:e==="gemini"?[ca(t,n)]:e==="copilot-cli"?[ia(t,n)]:e==="kiro"?[aa(t,n)]:e==="opencode"?[la(t,n)]:e==="pi"?[ua(t,n)]:e==="vscode"?[zo(n,...I.vscode),da(t,n)]:[zo(n,...I[e])],o]}function De(e,t,n=process.env){return ox(t).toLowerCase()!==Ee?!1:ke(rx(e,n),t)}import{extname as ax}from"node:path";var{closeSync:sx,openSync:ix,readSync:cx}=process.getBuiltinModule("node:fs");function lx(e){let t=null;try{t=ix(e,"r");let n=Buffer.alloc(Xn),o=cx(t,n,0,Xn,0);return n.subarray(0,o)}catch{return null}finally{t!==null&&sx(t)}}function cn(e,t){let n=js[e]??[];if(n.length===0)return!1;let o=ax(t).toLowerCase(),r=n.filter(i=>Wn[i].exts.includes(o));if(r.length===0)return!1;let s=lx(t);return s===null?!1:r.some(i=>Wn[i].sig.every(c=>c.bytes.every((l,a)=>s[c.at+a]===l)))}var{statSync:ux}=process.getBuiltinModule("node:fs"),za="Bash",Jo="Read",dx="WebFetch",fx="ctx_execute",xx="ctx_batch",Va="shell",px="1",te="-",$o="--",_x="=",Ex=".",Wa=",",Vo="p",gx=["-e","--expression"],Xa=".exe",mx=";&|(`\n\r",_e=Object.freeze({kind:"allow"}),xe=e=>({kind:"deny",reason:e}),pe=e=>typeof e=="string"?e:void 0,Ka=e=>e!=null,q=(e,t)=>e.includes(t);function Ja(e,t,n,o=e.cwd){let r=e.tool;if(r===void 0)return _e;let s=r.canonicalName,i=r.input,c;if(n===null){if(process.env[ts]===px)return xe(D(Tt,t.toolNamePrefix));process.stderr.write(ys+`
35
+ `),c=[]}else c=n;let l=Sx(s,i,e.cwd,c);return l!==null?xe(ve+l):s===dx?Rx(i,t):s===za?Ax(e,t,i,c,o):s===Jo?Lx(e,t,i,o):_e}function $a(e,t,n,o){let r=e==="webfetch",s=r?Es.map(c=>n.toolNamePrefix+c).join(As):n.toolNamePrefix+_s,i=JSON.stringify(r?{url:t}:{language:Va,code:t,intent:o??ps});return[vn+us[e]+ds,fs,xs+s,i].join(`
36
+ `)}function hx(e){for(let t of me){let n=pe(e[t]);if(n!==void 0&&n!=="")return n}}function Qa(e){let t=hx(e),n=Array.isArray(e[he])?e[he].filter(o=>typeof o=="string"&&o!==""):[];return t===void 0?n:[t,...n]}function Sx(e,t,n,o){if(o.length===0)return null;let r=s=>Ce(ln(n,s),o,{tool:Jo,projectDir:n});if(e===za){let s=pe(t.command);return s===void 0?null:Ce(s,o)}if(e===Jo){for(let s of Qa(t)){let i=r(s);if(i!==null)return i}return null}if(e===fx){let s=pe(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=pe(t.code);return bx(t.language)&&c!==void 0?Ya(c,o):null}if(e===xx&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?Ya(s,o):null;if(i!==null)return i}return null}function bx(e){if(typeof e!="string")return!1;let t=e.toLowerCase(),n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return n>=0&&(t=t.slice(n+1)),t.endsWith(Xa)&&(t=t.slice(0,t.length-Xa.length)),t===Va||q(Qr,t)}function Ya(e,t){let n=Ce(e,t);if(n!==null)return n;let o=ye(e);if(!o.ok)return el(e,t);for(let r of Wo(o.commands)){let s=Za(r,t);if(s!==null)return s}return null}function Za(e,t){return t.length===0?null:Ce([e.argv0,...e.args].join(" "),t)??Ce(e.raw,t)}function el(e,t){if(t.length===0)return null;let n=new Uint8Array(e.length+1),o=!1;for(let r=0;r<=e.length;r++)(r===0||mx.includes(e.charAt(r-1)))&&(o=!0),o&&(r===e.length||e.charAt(r).trim()!=="")&&(n[r]=1,o=!1);return La(e,t,n)}function Ox(e,t){return el(e,t)!==null}function Tx(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return Ns.some(n=>t===n||t.endsWith(Ex+n))}function Rx(e,t){let n=pe(e.url)??"";return Tx(n)?_e:xe($a("webfetch",n,t))}function Ax(e,t,n,o,r){let s=pe(n.command)??"",i=ye(s);if(!i.ok)return Ox(s,o)?xe(D(Rt,t.toolNamePrefix)):qa(e,s,t,r)??_e;let c=Wo(i.commands);for(let l of c){let a=Za(l,o);if(a!==null)return xe(ve+a)}if(!Se(t)||Ie(e))for(let l of c){let a=yx(l);if(a!==null)return xe($a(a,s,t,pe(n.description)))}return wx(e,c,t,r)??qa(e,s,t,r)??_e}function yx(e){let t=e.argv0.toLowerCase();return q(Is,t)&&Nx(t,e)?"curl":Cx(e.raw)?"http":q(Ls,t)?"build":null}function Nx(e,t){return t.redirectsToFile?!Ix(e,t.args):!t.endsInBoundedSink}function Ix(e,t){let n=Cs[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===$o)break;if(q(ks,s)||s===Ds&&t[r+1]===te)return!1;(s===n.long||s.startsWith(te)&&!s.startsWith($o)&&s.includes(n.short,te.length))&&(o=!0)}return o}function Cx(e){let t=e.toLowerCase();for(let n of Ms)if(t.includes(n))return!0;for(let n=t.indexOf(Ge);n>=0;n=t.indexOf(Ge,n+1)){let o=t.charAt(n+Ge.length);if(o!==""&&ws.includes(o)&&t.startsWith(Ps,n+Ge.length+o.length))return!0}return!1}var kx="cd";function Qo(e){try{let t=ux(e);return t.isFile()?t.size:-1}catch{return-1}}function Zo(e,t,n,o,r){return o<=ie||De(e.agent,n)?null:xe(Dx(r,n)?Ha(n,o,t.toolNamePrefix):Fa(n,o))}function Dx(e,t){if(typeof e=="string")return ke([e],t);if(ke([e.worktree],t))return!0;try{return ke([e.containmentRoot],t)}catch{return!1}}function Lx(e,t,n,o){if(!Ka(n.offset)&&!Ka(n.limit))for(let r of Qa(n)){let s=ln(e.cwd,r),i=Qo(s);if(i>ie&&!cn(e.agent,s)){let c=Zo(e,t,s,i,o);if(c!==null)return c}}return _e}function wx(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&go(n))return null;let r=e.cwd,s=null;for(let i of t){let c=i.argv0.toLowerCase();if(c===kx&&i.args.length===1&&i.insideConstruct===void 0&&(r=ln(r,i.args[0])),i.redirectsToFile||i.endsInBoundedSink||i.pipesOut===!0||i.insideConstruct!==void 0||!q(Us,c))continue;let l=Ux(c,i.args);if(l===null)continue;if(l.bounded){s=_e;continue}let a=ln(r,l.file),d=Zo(e,n,a,Qo(a),o);if(d!==null)return d}return s}function qa(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&go(n))return null;for(let r of ea(t,e.cwd)){let s=Zo(e,n,r,Qo(r),o);if(s!==null)return s}return null}var an=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function Px(e){if(q(Bn,e))return 1;for(let t of Bn)if(t.startsWith($o)?e.startsWith(t+_x):e.startsWith(t))return 0;return e.startsWith(te)&&an(e.slice(te.length))?0:-1}function Mx(e){if(e===Vo)return"all";if(!e.endsWith(Vo))return null;let t=e.slice(0,e.length-Vo.length),n=t.indexOf(Wa);return(n<0?an(t):an(t.slice(0,n))&&an(t.slice(n+Wa.length)))?"range":null}function Ux(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(q(Hs,e)){let l=Px(c);if(l>=0){o=!0,i+=l;continue}}if(e===At&&q(Fs,c)){r=!0;continue}if(e===At&&q(gx,c)){s=t[i+1],i++;continue}c.startsWith(te)&&c!==te||n.push(c)}if(e===At){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:Mx(s);if(i===null)return null;o=i==="range"}return e===vs&&n.shift()!==L.identity?null:n.length===1&&n[0]!==te?{file:n[0],bounded:o}:null}import{basename as Bx,dirname as un,join as rt,resolve as ol}from"node:path";var Hx=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Fx=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],H=(e,t)=>e>>>t|e<<32-t;function tl(e){let t=Buffer.from(e,"utf8"),n=t.length*8,o=Math.ceil((t.length+9)/64)*64,r=Buffer.alloc(o);t.copy(r),r[t.length]=128,r.writeUInt32BE(Math.floor(n/4294967296),o-8),r.writeUInt32BE(n>>>0,o-4);let s=Fx.slice(),i=new Uint32Array(64);for(let c=0;c<o;c+=64){for(let E=0;E<16;E++)i[E]=r.readUInt32BE(c+E*4);for(let E=16;E<64;E++){let h=H(i[E-15],7)^H(i[E-15],18)^i[E-15]>>>3,S=H(i[E-2],17)^H(i[E-2],19)^i[E-2]>>>10;i[E]=i[E-16]+h+i[E-7]+S>>>0}let[l,a,d,u,f,x,p,g]=s;for(let E=0;E<64;E++){let h=g+(H(f,6)^H(f,11)^H(f,25))+(f&x^~f&p)+Hx[E]+i[E]>>>0,S=(H(l,2)^H(l,13)^H(l,22))+(l&a^l&d^a&d)>>>0;g=p,p=x,x=f,f=u+h>>>0,u=d,d=a,a=l,l=h+S>>>0}s[0]=s[0]+l>>>0,s[1]=s[1]+a>>>0,s[2]=s[2]+d>>>0,s[3]=s[3]+u>>>0,s[4]=s[4]+f>>>0,s[5]=s[5]+x>>>0,s[6]=s[6]+p>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:vx,readFileSync:jx,realpathSync:nl,statSync:Gx}=process.getBuiltinModule("node:fs");function Wx(e){switch(e){case"claude-code":return"env:CLAUDE_PROJECT_DIR";case"codex":case"copilot-cli":case"kiro":return"arg:--agent+cwd";case"vscode":return"arg:workspaceFolder";case"gemini":case"qwen":case"zcode":case"opencode":return"spawn-cwd";case"pi":return"pi:ctx.cwd"}}function ot(e){return e===void 0||e===""?void 0:e}function Xx(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return ot(t.env.CLAUDE_PROJECT_DIR)??ot(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return ot(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(bt);return n<0?void 0:ot(t.argv[n+1])}case"pi:ctx.cwd":return ot(t.piCwd)}}function Kx(e){let t;try{t=nl.native(e)}catch{throw new T("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=Yx(rt(t,Ln));if(o!==null){let s=rl(rt(o,Jr));return{commonDir:nl.native(s===null?o:ol(o,s)),worktree:t,start:n}}let r=un(t);if(r===t)return{commonDir:null,start:n};t=r}}function Yx(e){let t;try{if(Gx(e).isDirectory())t=e;else{let n=rl(e);if(n===null||!n.startsWith(Pn))return null;t=ol(un(e),n.slice(Pn.length))}}catch{return null}return vx(rt(t,$r))?t:null}function rl(e){let t;try{t=jx(e,"utf8")}catch{return null}let n=t.indexOf(`
37
+ `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function qx(e,t){let{spawnSync:n}=process.getBuiltinModule("node:child_process"),o=n("git",t,{cwd:e,shell:!1,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});if(o.error!==void 0||o.status!==0)throw new T("NO_GIT_DIR",{path:e});return o.stdout.split(`
38
+ `).filter(r=>r!=="")}function zx(e,t){let n=Bx(t)===Ln?un(t):t,o=qx(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(wn)).map(r=>r.slice(wn.length));return Ba([un(n),...o])}function sl(e,t){let n=Wx(e),o=Xx(n,t);if(o===void 0)throw new T("NO_PROJECT",{kind:n});let r=Kx(o),s=r.commonDir===null?r.start:void 0,i=r.commonDir??r.start,c=r.commonDir===null?r.start:r.worktree,l,a,d;return{get projectKey(){return l??=tl(i).slice(0,zr),l},get projectDir(){return a??=rt(fa(process.env),St,this.projectKey),a},get dbPath(){return rt(this.projectDir,Vr)},worktree:c,get containmentRoot(){return d??=s??zx(o,i),d},agent:e,source:n}}var dn=Ue,Vx=`
39
+ PRAGMA busy_timeout = ${Q};
40
40
  PRAGMA journal_mode = WAL;
41
- `,on="tokenize = 'porter unicode61 remove_diacritics 2'",fx="tokenize = 'unicode61 remove_diacritics 2'",xx=`
41
+ `,fn="tokenize = 'porter unicode61 remove_diacritics 2'",Jx="tokenize = 'unicode61 remove_diacritics 2'",$x=`
42
42
  CREATE TABLE IF NOT EXISTS events (
43
43
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
44
44
  session_id TEXT NOT NULL,
@@ -83,16 +83,16 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
83
83
  agent UNINDEXED,
84
84
  ord UNINDEXED,
85
85
  body,
86
- ${fx}
86
+ ${Jx}
87
87
  );
88
88
 
89
89
  CREATE TABLE IF NOT EXISTS meta (
90
90
  key TEXT PRIMARY KEY,
91
91
  value TEXT NOT NULL
92
92
  );
93
- `,px=`
93
+ `,Qx=`
94
94
  CREATE UNIQUE INDEX IF NOT EXISTS idx_events_cost_session_turn ON events(session_id, turn) WHERE kind = 'cost';
95
- `,_x=`
95
+ `,Zx=`
96
96
  CREATE VIRTUAL TABLE chunks_v3 USING fts5(
97
97
  source_id UNINDEXED,
98
98
  session_id UNINDEXED,
@@ -101,13 +101,13 @@ CREATE VIRTUAL TABLE chunks_v3 USING fts5(
101
101
  ord UNINDEXED,
102
102
  body,
103
103
  title,
104
- ${on}
104
+ ${fn}
105
105
  );
106
106
  INSERT INTO chunks_v3(rowid, source_id, session_id, worktree, agent, ord, body, title)
107
107
  SELECT rowid, source_id, session_id, worktree, agent, ord, body, '' FROM chunks;
108
108
  DROP TABLE chunks;
109
109
  ALTER TABLE chunks_v3 RENAME TO chunks;
110
- `,Ex=`
110
+ `,ep=`
111
111
  CREATE VIRTUAL TABLE chunks_tri USING fts5(
112
112
  body,
113
113
  title,
@@ -116,24 +116,24 @@ CREATE VIRTUAL TABLE chunks_tri USING fts5(
116
116
  );
117
117
  INSERT INTO chunks_tri(rowid, body, title) SELECT rowid, body, title FROM chunks;
118
118
  CREATE VIRTUAL TABLE chunks_vocab USING fts5vocab(chunks, 'row');
119
- `,gx=`
119
+ `,tp=`
120
120
  CREATE VIRTUAL TABLE line_units USING fts5(
121
121
  body,
122
122
  source_id UNINDEXED,
123
123
  session_id UNINDEXED,
124
124
  ord UNINDEXED,
125
- ${on}
125
+ ${fn}
126
126
  );
127
- `,mx=`
127
+ `,np=`
128
128
  UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
129
- `,hx=[{version:1,sql:xx},{version:2,sql:px},{version:3,sql:_x},{version:4,sql:Ex},{version:5,sql:gx},{version:6,sql:mx}];function Xo(e,t){if(t!==nn){if(t>nn)throw new T("SCHEMA_STALE",{found:t,want:nn});e.exec(dx),e.exec("BEGIN IMMEDIATE");try{for(let n of hx)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${nn}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}function Na(e,t,n={}){if(("bun"in n?n.bun:process.versions.bun)===void 0)return new e.DatabaseSync(t,{timeout:J,readOnly:!0});let r=new e.DatabaseSync(t,{timeout:J});return n.queryOnly!==!1&&r.exec("PRAGMA query_only = ON"),r}var{existsSync:Qe,linkSync:Sx,mkdirSync:bx,rmSync:Ox}=process.getBuiltinModule("node:fs");function Ia(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function Tx(e,t){let n=Ia(e),o=Ia(t);for(let r=0;r<o.length;r+=1){let s=n[r]??0;if(s!==o[r])return s<o[r]}return!1}function Rx(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&Pr;return n===Mr||n===Ur}async function Ax(){try{return await import("node:sqlite")}catch{throw new T("NO_SQLITE")}}function Ko(e){return e.prepare("PRAGMA user_version").get().user_version}function yx(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+wr;try{let r=new e.DatabaseSync(o,{timeout:J});try{Xo(r,Ko(r))}finally{r.close()}try{Sx(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",ut,dt])Ox(o+r,{force:!0})}}function Ca(e,t){let n=null;try{return Qe(t)||yx(e,t),n=new e.DatabaseSync(t,{timeout:J}),Xo(n,Ko(n)),n}catch(o){throw n&&n.close(),o}}function Nx(e,t){let n=Na(e,t);try{let o=Ko(n);if(o!==ke)throw new T("SCHEMA_STALE",{found:o,want:ke});return n}catch(o){throw n.close(),o}}async function N(e,t){if(Tx(process.version,De))throw new T("NODE_TOO_OLD",{v:process.version});let n=await Ax();bx(e.projectDir,{recursive:!0});let o=e.dbPath;if((Qe(o+ut)||Qe(o+dt))&&!Qe(o))throw new T("DB_GONE");try{let s;return t?.readOnly===!0?(Qe(o)||Ca(n,o).close(),s=Nx(n,o)):s=Ca(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw Rx(s)?new T("DB_CORRUPT"):s}}function U(e,t){e.raw.exec("BEGIN IMMEDIATE");try{let n=t(e);return e.raw.exec("COMMIT"),n}catch(n){throw e.raw.isTransaction&&e.raw.exec("ROLLBACK"),n}}function ka(e,t){return e.raw.isTransaction?t(e):U(e,t)}function ee(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function K(e,t,n){ka(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function rn(e,t){return ka(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var Da="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",Ix="INSERT INTO "+Da,Cx="INSERT OR IGNORE INTO "+Da,kx="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function sn(e,t){return U(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?Cx:Ix).run(t.session_id,t.worktree,t.agent,t.kind,t.tool,t.key,t.path,t.ok,t.exit_code,t.bytes,t.body,t.turn,t.sandbox_bytes,t.returned_bytes,o,o);return s.changes===1?Number(s.lastInsertRowid):n.raw.prepare(kx).get(t.session_id,t.turn).seq})}function La(e,t){let n="",o="",r=!1,s=!1;for(let i of t){if(o===""&&!r&&i.trim()===""){s=n!=="";continue}s&&(n+=" ",s=!1),n+=i,r?r=!1:i==="\\"&&o!=="'"?r=!0:o===""&&(i==="'"||i==='"')?o=i:i===o&&(o="")}return e+":"+n}function Yo(e,t,n){return t===""?[]:n===void 0?e.raw.prepare("SELECT * FROM events WHERE session_id = ? ORDER BY seq ASC").all(t):e.raw.prepare("SELECT * FROM events WHERE session_id = ? AND kind = ? ORDER BY seq ASC").all(t,n)}function wa(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq DESC LIMIT 1").get(t);return n===void 0?"":n.body}function Pa(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq ASC LIMIT 1").get(t);return n===void 0?"":n.body}function Ma(e,t,n,o){return t===""?[]:e.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND (session_id = ? OR worktree = ?) ORDER BY seq DESC LIMIT ?").all(t,n,o)}function Ua(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function Ha(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var qo=Object.freeze([170,170,178,179,181,181,185,186,188,190,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,895,895,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1327,1329,1366,1369,1369,1376,1416,1488,1514,1519,1522,1568,1610,1632,1641,1646,1647,1649,1747,1749,1749,1765,1766,1774,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1984,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2144,2154,2160,2183,2185,2191,2208,2249,2308,2361,2365,2365,2384,2384,2392,2401,2406,2415,2417,2432,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2534,2545,2548,2553,2556,2556,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2662,2671,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2790,2799,2809,2809,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2918,2927,2929,2935,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3046,3058,3077,3084,3086,3088,3090,3112,3114,3129,3133,3133,3160,3162,3164,3165,3168,3169,3174,3183,3192,3198,3200,3200,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3292,3294,3296,3297,3302,3311,3313,3314,3332,3340,3342,3344,3346,3386,3389,3389,3406,3406,3412,3414,3416,3425,3430,3448,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3558,3567,3585,3632,3634,3635,3648,3654,3664,3673,3713,3714,3716,3716,3718,3722,3724,3747,3749,3749,3751,3760,3762,3763,3773,3773,3776,3780,3782,3782,3792,3801,3804,3807,3840,3840,3872,3891,3904,3911,3913,3948,3976,3980,4096,4138,4159,4169,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4240,4249,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4969,4988,4992,5007,5024,5109,5112,5117,5121,5740,5743,5759,5761,5786,5792,5866,5870,5880,5888,5905,5919,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6112,6121,6128,6137,6160,6169,6176,6264,6272,6276,6279,6312,6314,6314,6320,6389,6400,6430,6470,6509,6512,6516,6528,6571,6576,6601,6608,6618,6656,6678,6688,6740,6784,6793,6800,6809,6823,6823,6917,6963,6981,6988,6992,7001,7043,7072,7086,7141,7168,7203,7232,7241,7245,7293,7296,7306,7312,7354,7357,7359,7401,7404,7406,7411,7413,7414,7418,7418,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8304,8305,8308,8313,8319,8329,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8528,8585,9312,9371,9450,9471,10102,10131,11264,11492,11499,11502,11506,11507,11517,11517,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12591,12593,12686,12690,12693,12704,12735,12784,12799,12832,12841,12872,12879,12881,12895,12928,12937,12977,12991,13312,19903,19968,42124,42192,42237,42240,42508,42512,42539,42560,42606,42623,42653,42656,42735,42775,42783,42786,42888,42891,42972,42993,43009,43011,43013,43015,43018,43020,43042,43056,43061,43072,43123,43138,43187,43216,43225,43250,43255,43259,43259,43261,43262,43264,43301,43312,43334,43360,43388,43396,43442,43471,43481,43488,43492,43494,43518,43520,43560,43584,43586,43588,43595,43600,43609,43616,43638,43642,43642,43646,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43824,43866,43868,43881,43888,44002,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65296,65305,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500,65536,65547,65549,65574,65576,65594,65596,65597,65599,65613,65616,65629,65664,65786,65799,65843,65856,65912,65930,65931,66176,66204,66208,66256,66273,66299,66304,66339,66349,66378,66384,66421,66432,66461,66464,66499,66504,66511,66513,66517,66560,66717,66720,66729,66736,66771,66776,66811,66816,66855,66864,66915,66928,66938,66940,66954,66956,66962,66964,66965,66967,66977,66979,66993,66995,67001,67003,67004,67008,67059,67072,67382,67392,67413,67424,67431,67456,67461,67463,67504,67506,67514,67584,67589,67592,67592,67594,67637,67639,67640,67644,67644,67647,67669,67672,67702,67705,67742,67751,67759,67808,67826,67828,67829,67835,67867,67872,67897,67904,67929,67968,68023,68028,68047,68050,68096,68112,68115,68117,68119,68121,68149,68160,68168,68192,68222,68224,68255,68288,68295,68297,68324,68331,68335,68352,68405,68416,68437,68440,68466,68472,68497,68521,68527,68608,68680,68736,68786,68800,68850,68858,68899,68912,68921,68928,68965,68975,68997,69216,69246,69248,69289,69296,69297,69314,69319,69376,69415,69424,69445,69457,69460,69488,69505,69552,69579,69600,69622,69635,69687,69714,69743,69745,69746,69749,69749,69763,69807,69840,69864,69872,69881,69891,69926,69942,69951,69956,69956,69959,69959,69968,70002,70006,70006,70019,70066,70081,70084,70096,70106,70108,70108,70113,70132,70144,70161,70163,70187,70207,70208,70272,70278,70280,70280,70282,70285,70287,70301,70303,70312,70320,70366,70384,70393,70405,70412,70415,70416,70419,70440,70442,70448,70450,70451,70453,70457,70461,70461,70480,70480,70493,70497,70528,70537,70539,70539,70542,70542,70544,70581,70583,70583,70609,70609,70611,70611,70656,70708,70727,70730,70736,70745,70751,70753,70784,70831,70852,70853,70855,70855,70864,70873,71040,71086,71128,71131,71168,71215,71236,71236,71248,71257,71296,71338,71352,71352,71360,71369,71376,71395,71424,71450,71472,71483,71488,71494,71680,71723,71840,71922,71935,71942,71945,71945,71948,71955,71957,71958,71960,71983,71999,71999,72001,72001,72016,72025,72096,72103,72106,72144,72161,72161,72163,72163,72192,72192,72203,72242,72250,72250,72272,72272,72284,72329,72349,72349,72368,72440,72640,72672,72688,72697,72704,72712,72714,72750,72768,72768,72784,72812,72818,72847,72960,72966,72968,72969,72971,73008,73030,73030,73040,73049,73056,73061,73063,73064,73066,73097,73112,73112,73120,73129,73136,73179,73184,73193,73440,73458,73474,73474,73476,73488,73490,73523,73552,73561,73648,73648,73664,73684,73728,74649,74752,74862,74880,75075,77712,77808,77824,78895,78913,78918,78944,82938,82944,83526,90368,90397,90416,90425,92160,92728,92736,92766,92768,92777,92784,92862,92864,92873,92880,92909,92928,92975,92992,92995,93008,93017,93019,93025,93027,93047,93053,93071,93504,93548,93552,93561,93760,93846,93856,93880,93883,93907,93952,94026,94032,94032,94099,94111,94176,94177,94179,94179,94194,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,113664,113770,113776,113788,113792,113800,113808,113817,118e3,118009,119488,119507,119520,119539,119648,119672,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,120782,120831,122624,122654,122661,122666,122928,122989,123136,123180,123191,123197,123200,123209,123214,123214,123536,123565,123584,123627,123632,123641,124112,124139,124144,124153,124368,124397,124400,124410,124608,124638,124640,124642,124644,124645,124647,124653,124656,124660,124670,124671,124896,124902,124904,124907,124909,124910,124912,124926,124928,125124,125127,125135,125184,125251,125259,125259,125264,125273,126065,126123,126125,126127,126129,126132,126209,126253,126255,126269,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,127232,127244,130032,130041,131072,173791,173824,178205,178208,183981,183984,191456,191472,192093,194560,195101,196608,201546,201552,210041]);function Dx(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=qo.length/2-1;for(;t<=n;){let o=t+n>>1,r=qo[2*o],s=qo[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function Lx(e,t){let n=[],o=-1,r=0;for(let s of e)t(s.codePointAt(0))?o>=0&&(n.push(e.slice(o,r)),o=-1):o<0&&(o=r),r+=s.length;return o>=0&&n.push(e.slice(o)),n}function ye(e){return Lx(e,t=>!Dx(t))}var wx=`
129
+ `,op=[{version:1,sql:$x},{version:2,sql:Qx},{version:3,sql:Zx},{version:4,sql:ep},{version:5,sql:tp},{version:6,sql:np}];function er(e,t){if(t!==dn){if(t>dn)throw new T("SCHEMA_STALE",{found:t,want:dn});e.exec(Vx),e.exec("BEGIN IMMEDIATE");try{for(let n of op)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${dn}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}function il(e,t,n={}){if(("bun"in n?n.bun:process.versions.bun)===void 0)return new e.DatabaseSync(t,{timeout:Q,readOnly:!0});let r=new e.DatabaseSync(t,{timeout:Q});return n.queryOnly!==!1&&r.exec("PRAGMA query_only = ON"),r}var{existsSync:st,linkSync:rp,mkdirSync:sp,rmSync:ip}=process.getBuiltinModule("node:fs");function cl(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function cp(e,t){let n=cl(e),o=cl(t);for(let r=0;r<o.length;r+=1){let s=n[r]??0;if(s!==o[r])return s<o[r]}return!1}function ap(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&Kr;return n===Yr||n===qr}async function lp(){try{return await import("node:sqlite")}catch{throw new T("NO_SQLITE")}}function tr(e){return e.prepare("PRAGMA user_version").get().user_version}function up(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+Xr;try{let r=new e.DatabaseSync(o,{timeout:Q});try{er(r,tr(r))}finally{r.close()}try{rp(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",mt,ht])ip(o+r,{force:!0})}}function al(e,t){let n=null;try{return st(t)||up(e,t),n=new e.DatabaseSync(t,{timeout:Q}),er(n,tr(n)),n}catch(o){throw n&&n.close(),o}}function dp(e,t){let n=il(e,t);try{let o=tr(n);if(o!==Ue)throw new T("SCHEMA_STALE",{found:o,want:Ue});return n}catch(o){throw n.close(),o}}async function N(e,t){if(cp(process.version,He))throw new T("NODE_TOO_OLD",{v:process.version});let n=await lp();sp(e.projectDir,{recursive:!0});let o=e.dbPath;if((st(o+mt)||st(o+ht))&&!st(o))throw new T("DB_GONE");try{let s;return t?.readOnly===!0?(st(o)||al(n,o).close(),s=dp(n,o)):s=al(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw ap(s)?new T("DB_CORRUPT"):s}}function F(e,t){e.raw.exec("BEGIN IMMEDIATE");try{let n=t(e);return e.raw.exec("COMMIT"),n}catch(n){throw e.raw.isTransaction&&e.raw.exec("ROLLBACK"),n}}function ll(e,t){return e.raw.isTransaction?t(e):F(e,t)}function ne(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function z(e,t,n){ll(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function xn(e,t){return ll(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var ul="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",fp="INSERT INTO "+ul,xp="INSERT OR IGNORE INTO "+ul,pp="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function pn(e,t){return F(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?xp:fp).run(t.session_id,t.worktree,t.agent,t.kind,t.tool,t.key,t.path,t.ok,t.exit_code,t.bytes,t.body,t.turn,t.sandbox_bytes,t.returned_bytes,o,o);return s.changes===1?Number(s.lastInsertRowid):n.raw.prepare(pp).get(t.session_id,t.turn).seq})}function dl(e,t){let n="",o="",r=!1,s=!1;for(let i of t){if(o===""&&!r&&i.trim()===""){s=n!=="";continue}s&&(n+=" ",s=!1),n+=i,r?r=!1:i==="\\"&&o!=="'"?r=!0:o===""&&(i==="'"||i==='"')?o=i:i===o&&(o="")}return e+":"+n}function nr(e,t,n){return t===""?[]:n===void 0?e.raw.prepare("SELECT * FROM events WHERE session_id = ? ORDER BY seq ASC").all(t):e.raw.prepare("SELECT * FROM events WHERE session_id = ? AND kind = ? ORDER BY seq ASC").all(t,n)}function fl(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq DESC LIMIT 1").get(t);return n===void 0?"":n.body}function xl(e,t,n,o){return t===""?[]:e.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND (session_id = ? OR worktree = ?) ORDER BY seq DESC LIMIT ?").all(t,n,o)}function pl(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function _l(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var or=Object.freeze([170,170,178,179,181,181,185,186,188,190,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,895,895,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1327,1329,1366,1369,1369,1376,1416,1488,1514,1519,1522,1568,1610,1632,1641,1646,1647,1649,1747,1749,1749,1765,1766,1774,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1984,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2144,2154,2160,2183,2185,2191,2208,2249,2308,2361,2365,2365,2384,2384,2392,2401,2406,2415,2417,2432,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2534,2545,2548,2553,2556,2556,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2662,2671,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2790,2799,2809,2809,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2918,2927,2929,2935,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3046,3058,3077,3084,3086,3088,3090,3112,3114,3129,3133,3133,3160,3162,3164,3165,3168,3169,3174,3183,3192,3198,3200,3200,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3292,3294,3296,3297,3302,3311,3313,3314,3332,3340,3342,3344,3346,3386,3389,3389,3406,3406,3412,3414,3416,3425,3430,3448,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3558,3567,3585,3632,3634,3635,3648,3654,3664,3673,3713,3714,3716,3716,3718,3722,3724,3747,3749,3749,3751,3760,3762,3763,3773,3773,3776,3780,3782,3782,3792,3801,3804,3807,3840,3840,3872,3891,3904,3911,3913,3948,3976,3980,4096,4138,4159,4169,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4240,4249,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4969,4988,4992,5007,5024,5109,5112,5117,5121,5740,5743,5759,5761,5786,5792,5866,5870,5880,5888,5905,5919,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6112,6121,6128,6137,6160,6169,6176,6264,6272,6276,6279,6312,6314,6314,6320,6389,6400,6430,6470,6509,6512,6516,6528,6571,6576,6601,6608,6618,6656,6678,6688,6740,6784,6793,6800,6809,6823,6823,6917,6963,6981,6988,6992,7001,7043,7072,7086,7141,7168,7203,7232,7241,7245,7293,7296,7306,7312,7354,7357,7359,7401,7404,7406,7411,7413,7414,7418,7418,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8304,8305,8308,8313,8319,8329,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8528,8585,9312,9371,9450,9471,10102,10131,11264,11492,11499,11502,11506,11507,11517,11517,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12591,12593,12686,12690,12693,12704,12735,12784,12799,12832,12841,12872,12879,12881,12895,12928,12937,12977,12991,13312,19903,19968,42124,42192,42237,42240,42508,42512,42539,42560,42606,42623,42653,42656,42735,42775,42783,42786,42888,42891,42972,42993,43009,43011,43013,43015,43018,43020,43042,43056,43061,43072,43123,43138,43187,43216,43225,43250,43255,43259,43259,43261,43262,43264,43301,43312,43334,43360,43388,43396,43442,43471,43481,43488,43492,43494,43518,43520,43560,43584,43586,43588,43595,43600,43609,43616,43638,43642,43642,43646,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43824,43866,43868,43881,43888,44002,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65296,65305,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500,65536,65547,65549,65574,65576,65594,65596,65597,65599,65613,65616,65629,65664,65786,65799,65843,65856,65912,65930,65931,66176,66204,66208,66256,66273,66299,66304,66339,66349,66378,66384,66421,66432,66461,66464,66499,66504,66511,66513,66517,66560,66717,66720,66729,66736,66771,66776,66811,66816,66855,66864,66915,66928,66938,66940,66954,66956,66962,66964,66965,66967,66977,66979,66993,66995,67001,67003,67004,67008,67059,67072,67382,67392,67413,67424,67431,67456,67461,67463,67504,67506,67514,67584,67589,67592,67592,67594,67637,67639,67640,67644,67644,67647,67669,67672,67702,67705,67742,67751,67759,67808,67826,67828,67829,67835,67867,67872,67897,67904,67929,67968,68023,68028,68047,68050,68096,68112,68115,68117,68119,68121,68149,68160,68168,68192,68222,68224,68255,68288,68295,68297,68324,68331,68335,68352,68405,68416,68437,68440,68466,68472,68497,68521,68527,68608,68680,68736,68786,68800,68850,68858,68899,68912,68921,68928,68965,68975,68997,69216,69246,69248,69289,69296,69297,69314,69319,69376,69415,69424,69445,69457,69460,69488,69505,69552,69579,69600,69622,69635,69687,69714,69743,69745,69746,69749,69749,69763,69807,69840,69864,69872,69881,69891,69926,69942,69951,69956,69956,69959,69959,69968,70002,70006,70006,70019,70066,70081,70084,70096,70106,70108,70108,70113,70132,70144,70161,70163,70187,70207,70208,70272,70278,70280,70280,70282,70285,70287,70301,70303,70312,70320,70366,70384,70393,70405,70412,70415,70416,70419,70440,70442,70448,70450,70451,70453,70457,70461,70461,70480,70480,70493,70497,70528,70537,70539,70539,70542,70542,70544,70581,70583,70583,70609,70609,70611,70611,70656,70708,70727,70730,70736,70745,70751,70753,70784,70831,70852,70853,70855,70855,70864,70873,71040,71086,71128,71131,71168,71215,71236,71236,71248,71257,71296,71338,71352,71352,71360,71369,71376,71395,71424,71450,71472,71483,71488,71494,71680,71723,71840,71922,71935,71942,71945,71945,71948,71955,71957,71958,71960,71983,71999,71999,72001,72001,72016,72025,72096,72103,72106,72144,72161,72161,72163,72163,72192,72192,72203,72242,72250,72250,72272,72272,72284,72329,72349,72349,72368,72440,72640,72672,72688,72697,72704,72712,72714,72750,72768,72768,72784,72812,72818,72847,72960,72966,72968,72969,72971,73008,73030,73030,73040,73049,73056,73061,73063,73064,73066,73097,73112,73112,73120,73129,73136,73179,73184,73193,73440,73458,73474,73474,73476,73488,73490,73523,73552,73561,73648,73648,73664,73684,73728,74649,74752,74862,74880,75075,77712,77808,77824,78895,78913,78918,78944,82938,82944,83526,90368,90397,90416,90425,92160,92728,92736,92766,92768,92777,92784,92862,92864,92873,92880,92909,92928,92975,92992,92995,93008,93017,93019,93025,93027,93047,93053,93071,93504,93548,93552,93561,93760,93846,93856,93880,93883,93907,93952,94026,94032,94032,94099,94111,94176,94177,94179,94179,94194,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,113664,113770,113776,113788,113792,113800,113808,113817,118e3,118009,119488,119507,119520,119539,119648,119672,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,120782,120831,122624,122654,122661,122666,122928,122989,123136,123180,123191,123197,123200,123209,123214,123214,123536,123565,123584,123627,123632,123641,124112,124139,124144,124153,124368,124397,124400,124410,124608,124638,124640,124642,124644,124645,124647,124653,124656,124660,124670,124671,124896,124902,124904,124907,124909,124910,124912,124926,124928,125124,125127,125135,125184,125251,125259,125259,125264,125273,126065,126123,126125,126127,126129,126132,126209,126253,126255,126269,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,127232,127244,130032,130041,131072,173791,173824,178205,178208,183981,183984,191456,191472,192093,194560,195101,196608,201546,201552,210041]);function _p(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=or.length/2-1;for(;t<=n;){let o=t+n>>1,r=or[2*o],s=or[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function Ep(e,t){let n=[],o=-1,r=0;for(let s of e)t(s.codePointAt(0))?o>=0&&(n.push(e.slice(o,r)),o=-1):o<0&&(o=r),r+=s.length;return o>=0&&n.push(e.slice(o)),n}function Le(e){return Ep(e,t=>!_p(t))}var gp=`
130
130
  INSERT INTO sources(session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts)
131
131
  VALUES (:session_id, :worktree, :agent, :kind, :label, :bytes_total, :chunk_count, :created_ts, :created_at, :created_ts)
132
- RETURNING id`,Px=`
133
- INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,va=1,Fa=" (raw)",ja=`AND (:source IS NOT NULL OR substr(s.label, -${Fa.length}) <> '${Fa}')`,Ga=`
132
+ RETURNING id`,mp=`
133
+ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,gl=1,El=" (raw)",ml=`AND (:source IS NOT NULL OR substr(s.label, -${El.length}) <> '${El}')`,hl=`
134
134
  SELECT chunks.rowid AS rid, chunks.source_id AS source_id, chunks.session_id AS session_id,
135
135
  chunks.worktree AS worktree, chunks.ord AS ord, s.created_ts AS created_ts,
136
- bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${va}) AS bm,
136
+ bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${gl}) AS bm,
137
137
  (chunks.rowid IN (SELECT rowid FROM chunks WHERE chunks MATCH :all)) AS full
138
138
  FROM chunks JOIN sources s ON s.id = chunks.source_id
139
139
  WHERE chunks MATCH :match
@@ -141,9 +141,9 @@ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VAL
141
141
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
142
142
  AND (:source IS NULL OR s.label = :source)
143
143
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
144
- ${ja}`,Ba=`
145
- ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,Km=`
146
- WITH m AS (${Ga}
144
+ ${ml}`,Sl=`
145
+ ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,Ih=`
146
+ WITH m AS (${hl}
147
147
  ), r AS (
148
148
  SELECT *,
149
149
  ROW_NUMBER() OVER (ORDER BY full DESC, bm ASC, source_id DESC, ord ASC) AS rank_a,
@@ -151,11 +151,11 @@ WITH m AS (${Ga}
151
151
  FROM m
152
152
  )
153
153
  SELECT rid, source_id, session_id, worktree, ord, full, 1.0 / (:k + rank_a) + 1.0 / (:k + rank_b) AS score
154
- FROM r${Ba}`,Ym=`
155
- WITH m AS (${Ga}
154
+ FROM r${Sl}`,Ch=`
155
+ WITH m AS (${hl}
156
156
  )
157
157
  SELECT rid, source_id, session_id, worktree, ord, full, -bm AS score
158
- FROM m${Ba}`;var qm=`
158
+ FROM m${Sl}`;var kh=`
159
159
  SELECT t.rowid AS rid, c.source_id AS source_id, c.session_id AS session_id, c.worktree AS worktree, c.ord AS ord
160
160
  FROM chunks_tri t JOIN chunks c ON c.rowid = t.rowid JOIN sources s ON s.id = c.source_id
161
161
  WHERE chunks_tri MATCH :match
@@ -163,63 +163,63 @@ WHERE chunks_tri MATCH :match
163
163
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
164
164
  AND (:source IS NULL OR s.label = :source)
165
165
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
166
- ${ja}
167
- ORDER BY bm25(chunks_tri, 1.0, ${va}) ASC, c.source_id DESC, c.ord ASC`;var Mx="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",Ux="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function Wa(e,t,n){let o=zo(e,t,n);return Ka(e,o,t,n),o}function zo(e,t,n){let o=0;for(let r of n)o+=r.bytes;return U(e,r=>{let s=r.raw.prepare(wx).get({session_id:t.sessionId,worktree:t.worktree,agent:t.agent,kind:t.kind,label:t.label,bytes_total:o,chunk_count:n.length,created_ts:t.createdAt,created_at:new Date(t.createdAt).toISOString()});return Number(s.id)})}function Xa(e,t,n,o,r){try{Ka(e,t,n,o),Jo(e,t,n.sessionId,r)}catch(s){throw U(e,i=>{Hx(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function Ka(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>mn&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)U(e,l=>{let a=l.raw.prepare(Px),d=l.raw.prepare(Mx);for(let u of c){let f=u.title??"",x=a.run(t,n.sessionId,n.worktree,n.agent,u.ord,u.text,f).lastInsertRowid;d.run(x,u.text,f)}})}function Hx(e,t){if(t==="all")return e.exec("INSERT INTO chunks_tri(chunks_tri) VALUES ('delete-all')"),e.exec("DELETE FROM line_units"),Number(e.prepare("DELETE FROM chunks").run().changes);let[n,o]="sourceId"in t?["source_id = ?",t.sourceId]:["source_id IN (SELECT id FROM sources WHERE label = ?)",t.label];return e.prepare(Ux+" WHERE "+n).run(o),e.prepare("DELETE FROM line_units WHERE "+n).run(o),Number(e.prepare("DELETE FROM chunks WHERE "+n).run(o).changes)}function Vo(e){let t=[],n="";for(let o of e)o.trim()===""||o==="\0"?(n!==""&&t.push(n),n=""):n+=o==='"'?'""':o;return n!==""&&t.push(n),t.map(o=>`"${o}"*`).join(" ")}function Fx(e){return[...new Set(Vo(e).split(" ").filter(n=>n!==""))].join(" OR ")}var vx=new Set(["a","an","the","and","or","of","to","in","on","at","by","is","be","it","as","do","i","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","who","did","get","got","let","she","too","will","with","this","that","from","they","been","have","some","them","than","each","into","your","could","would","about","which","their","there","other","should","also","very","when","what","then","these","those","being","does","both","while","where","here","were","much","any","my","me","we"]);function jx(e){let t=[...new Set(Vo(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!vx.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var cn=`
166
+ ${ml}
167
+ ORDER BY bm25(chunks_tri, 1.0, ${gl}) ASC, c.source_id DESC, c.ord ASC`;var hp="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",Sp="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function bl(e,t,n){let o=rr(e,t,n);return Tl(e,o,t,n),o}function rr(e,t,n){let o=0;for(let r of n)o+=r.bytes;return F(e,r=>{let s=r.raw.prepare(gp).get({session_id:t.sessionId,worktree:t.worktree,agent:t.agent,kind:t.kind,label:t.label,bytes_total:o,chunk_count:n.length,created_ts:t.createdAt,created_at:new Date(t.createdAt).toISOString()});return Number(s.id)})}function Ol(e,t,n,o,r){try{Tl(e,t,n,o),ir(e,t,n.sessionId,r)}catch(s){throw F(e,i=>{bp(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function Tl(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>An&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)F(e,l=>{let a=l.raw.prepare(mp),d=l.raw.prepare(hp);for(let u of c){let f=u.title??"",x=a.run(t,n.sessionId,n.worktree,n.agent,u.ord,u.text,f).lastInsertRowid;d.run(x,u.text,f)}})}function bp(e,t){if(t==="all")return e.exec("INSERT INTO chunks_tri(chunks_tri) VALUES ('delete-all')"),e.exec("DELETE FROM line_units"),Number(e.prepare("DELETE FROM chunks").run().changes);let[n,o]="sourceId"in t?["source_id = ?",t.sourceId]:["source_id IN (SELECT id FROM sources WHERE label = ?)",t.label];return e.prepare(Sp+" WHERE "+n).run(o),e.prepare("DELETE FROM line_units WHERE "+n).run(o),Number(e.prepare("DELETE FROM chunks WHERE "+n).run(o).changes)}function sr(e){let t=[],n="";for(let o of e)o.trim()===""||o==="\0"?(n!==""&&t.push(n),n=""):n+=o==='"'?'""':o;return n!==""&&t.push(n),t.map(o=>`"${o}"*`).join(" ")}function Op(e){return[...new Set(sr(e).split(" ").filter(n=>n!==""))].join(" OR ")}var Rl=new Set(["a","an","the","and","or","of","to","in","on","at","by","is","be","it","as","do","i","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","who","did","get","got","let","she","too","will","with","this","that","from","they","been","have","some","them","than","each","into","your","could","would","about","which","their","there","other","should","also","very","when","what","then","these","those","being","does","both","while","where","here","were","much","any","my","me","we"]);function Tp(e){let t=[...new Set(sr(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!Rl.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var _n=`
168
168
  AND (:scope <> 'session' OR session_id = :session_id)
169
- AND (:scope <> 'worktree' OR worktree = :worktree)`,zm=`
169
+ AND (:scope <> 'worktree' OR worktree = :worktree)`,Dh=`
170
170
  WITH e AS (
171
171
  SELECT seq, kind, key, path, body, created_at FROM events
172
- WHERE created_at > :after${cn}
172
+ WHERE created_at > :after${_n}
173
173
  AND (:source IS NULL OR kind = :source)
174
174
  )
175
175
  SELECT seq, kind, key, path, body, created_at FROM e
176
176
  WHERE created_at <= IFNULL((SELECT created_at FROM e ORDER BY created_at, seq LIMIT 1 OFFSET :off), created_at)
177
- ORDER BY created_at ASC, seq ASC`,Vm=`
177
+ ORDER BY created_at ASC, seq ASC`,Lh=`
178
178
  WITH s AS (
179
179
  SELECT id, label, created_ts FROM sources
180
- WHERE created_ts > :after${cn}
180
+ WHERE created_ts > :after${_n}
181
181
  AND (:source IS NULL OR label = :source)
182
182
  AND label <> :reserved
183
183
  )
184
184
  SELECT id, label, created_ts FROM s
185
185
  WHERE created_ts <= IFNULL((SELECT created_ts FROM s ORDER BY created_ts, id LIMIT 1 OFFSET :off), created_ts)
186
- ORDER BY created_ts ASC, id ASC`;var Jm=`
187
- SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${cn} AND (:source IS NULL OR kind = :source))
188
- OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${cn} AND (:source IS NULL OR label = :source)
189
- AND label <> :reserved) AS more`;var Gx=`CREATE VIRTUAL TABLE r USING fts5(body, ${on}, content='')`,Bx="INSERT INTO r(rowid, body) VALUES (?, ?)",Wx="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function Y(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?Fx(t):Vo(t);if(r===""||e.length===0)return o;let s=process.getBuiltinModule("node:sqlite");if(s===void 0)throw new T("NO_SQLITE");let i=new s.DatabaseSync(":memory:");try{i.exec(Gx);let c=i.prepare(Bx);i.exec("BEGIN");for(let l=0;l<e.length;l++)c.run(l+1,e[l]);i.exec("COMMIT");for(let l of i.prepare(Wx).all(r))o[Number(l.id)-1]=-l.bm;return o}finally{i.close()}}var Xx="s";function Ya(e){return Xx+e.toString(36)}function Jo(e,t,n,o){let r=0;for(;r<o.length;){let s=r,i=0;for(;s<o.length&&(s===r||i+o[s].body.length<=mn);)i+=o[s].body.length,s++;let c=r;U(e,l=>{let a=l.raw.prepare("INSERT INTO line_units(body, source_id, session_id, ord) VALUES (?, ?, ?, ?)");for(let d=c;d<s;d++){let u=o[d];a.run(u.body,t,n,u.ord)}}),r=s}}function qa(e,t){return t===e?e:e+" "+t}function za(e,t,n,o){let r=jx(n).join(" OR ");return r===""||t===""?[]:e.raw.prepare("SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? ORDER BY bm25(line_units) LIMIT ?").all(r,t,o).map(i=>({sourceId:Number(i.source_id),ord:Number(i.ord),label:i.label,body:i.body,score:i.score}))}function Kx(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function $o(e){let t=e.split(`
190
- `),n=[],o=[],r=Ps*Buffer.byteLength(e,"utf8");for(let s=0;s<t.length;s++){let i=t[s].endsWith("\r")?t[s].slice(0,-1):t[s],c=Kx(i);if(c===i.length)continue;for(;n.length>0&&n[n.length-1].indent>=c;)n.pop();let l=Buffer.byteLength(i,"utf8"),a=l,d=n.length;for(;d>0;){let u=n[d-1].bytes+1;if(a+u>He||a-l+u>r)break;a+=u,d--}r-=a-l,o.push({ord:s,body:[...n.slice(d).map(u=>u.line),i].join(`
191
- `)}),n.push({indent:c,line:i,bytes:l})}return o}function Qo(e){let t=e.indexOf(`
192
- `);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function Ne(e,t,n,o,r){let s=Buffer.byteLength(n,"utf8");if(s<1)throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");return{section:e,seq:t.seq,turn:t.turn,text:n,bytes:s,repeatCount:o,pinned:e==="last_request",query:r}}function Ze(e){return e.length>hn?e.slice(e.length-hn):e}function Yx(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function Va(e,t){if(!t)return Yx();let n=e.filter(_=>_.session_id===t).sort((_,m)=>_.seq-m.seq),o=n.filter(_=>_.kind==="prompt"),r=o.length>0?o[o.length-1]:void 0,s=r===void 0?null:Ne("last_request",r,"now: "+Qo(r.body),1,null),i=o.slice(0,o.length-1).map(_=>Ne("earlier_requests",_,"asked #"+_.seq+": "+Qo(_.body),1,null)),c=new Map,l=new Map;for(let _ of n)if(!(_.kind!=="cmd"&&_.kind!=="toolerr"||_.key===null)){if(_.ok===1){l.set(_.key,_.seq);continue}c.set(_.key,{row:_,count:(c.get(_.key)?.count??0)+1})}let a=[];for(let[_,m]of c)(l.get(_)??0)>m.row.seq||a.push(Ne("open_errors",m.row,"error #"+m.row.seq+" "+(m.row.tool??"")+": "+_,m.count,_));a.sort((_,m)=>_.seq-m.seq);let d=new Map;for(let _ of n)_.kind!=="edit"||_.path===null||d.set(_.path,{row:_,count:(d.get(_.path)?.count??0)+1});let u=[];for(let[_,m]of d){let y=Ne("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);u.push({...y,editCount:m.count})}u.sort((_,m)=>_.seq-m.seq);let f=new Map;for(let _ of n){if(_.kind!=="decision"||_.body==="")continue;let m=_.key??_.body;f.set(m,{row:_,count:(f.get(m)?.count??0)+1})}let x=[];for(let[_,m]of f)x.push(Ne("decisions",m.row,"decided #"+m.row.seq+": "+Qo(m.row.body),m.count,_));x.sort((_,m)=>_.seq-m.seq);let p=n.filter(_=>_.kind==="index").map(_=>Ne("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:Ze(a),changedFiles:Ze(u),decisions:Ze(x),earlierRequests:Ze(i),indexedSources:Ze(p)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=Sn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-Sn));return{lastRequest:s,openErrors:g.openErrors.filter(_=>!S.has(_.seq)),changedFiles:g.changedFiles.filter(_=>!S.has(_.seq)),decisions:g.decisions.filter(_=>!S.has(_.seq)),earlierRequests:g.earlierRequests.filter(_=>!S.has(_.seq)),indexedSources:g.indexedSources.filter(_=>!S.has(_.seq))}}function qx(e){if(!Object.hasOwn(bn,e.section))throw new Error(`compaction: "${String(e.section)}" has no weight; only toolerr, decision, prompt, edit and index rows are scored (ADR-0009 \xA73, DECISIONS-r11).`);let t=Math.max(0,e.currentTurn-e.itemTurn),n=On[Math.min(t,On.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(bn[e.section]*n*o/Bs)}function zx(e){switch(e){case"last_request":case"earlier_requests":return"prompt";case"open_errors":return"toolerr";case"changed_files":return"edit";case"decisions":return"decision";case"indexed_sources":return"index"}}function Ja(e,t){return e.map(n=>({...n,score:qx({section:zx(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function Za(e){return e.sourceId+":"+e.ord}function ln(e){return"@"+e.label+" line "+(e.ord+1)+`:
193
- `+e.body}function Vx(e){return new Set(ye(e.toLowerCase()))}function Jx(e,t){let n=0;for(let o of e)t.has(o)&&n++;return e.size+t.size-n===0?0:n/(e.size+t.size-n)}function er(e,t,n){let o=e.filter(a=>!t.has(Za(a))&&a.score>=Gn);if(o.length===0)return[];let r=Math.max(...o.map(a=>a.score)),s=o.map(a=>Vx(a.body)),i=[],c=new Set(o.map((a,d)=>d)),l=0;for(;c.size>0;){let a=-1,d=-1/0;for(let f of c){let x=0;for(let g of i)x=Math.max(x,Jx(s[f],s[g]));let p=kr*(o[f].score/r)-Dr*x;p>d&&(d=p,a=f)}c.delete(a);let u=an(ln(o[a]))+1;l+u>n||(l+=u,i.push(a))}return i.map(a=>o[a])}var $a={text:"",seqs:[]};function an(e){return Buffer.byteLength(e,"utf8")}function Zo(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
194
- `)}function Qa(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+Zo(e)}function el(e,t,n,o=[],r=new Set){if(t.trim()==="")return $a;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&Zo(f)!==""),i=s.length===0?[]:Y(s.map(Zo),t,"any"),c=s.map((f,x)=>({r:f,score:i[x]})).filter(f=>f.score>=Gn).sort((f,x)=>x.score-f.score||x.r.seq-f.r.seq),l=an(Wn)+1+an(Xn),a=[];for(let{r:f}of c){let x=an(Qa(f))+1;l+x>He||(l+=x,a.push(f))}let d=er(o,r,He-l);if(a.length===0&&d.length===0)return $a;a.sort((f,x)=>f.seq-x.seq);let u=[...a.map(Qa),...d.map(ln)];return{text:[Wn,...u,Xn].join(`
195
- `),seqs:a.map(f=>f.seq),...d.length>0?{units:d.map(Za)}:{}}}function te(e){return Buffer.byteLength(e,"utf8")}function tr(e,t){return e.bytes>hr?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function nr(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function tl(e,t,n,o=""){let r;for(let m of e)(r===void 0||m.seq>r.seq)&&(r=m);let s=r===void 0?"":r.session_id,i=r===void 0||s===""?0:r.seq,c=Va(e,s),l=`<context_mode_state session="${s}" upto="${i}">`,a=te(nr([],o)),d=mr-(te(l)+1+a+1+te(gn)),u=0,f=c.lastRequest===null?null:tr(c.lastRequest,o);f!==null&&(u+=te(f)+1);let x=Ja([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),p=new Map,g=[],E=[];for(;x.length>0;){let m=0,y=-1/0;for(let it=0;it<x.length;it++){let ct=x[it],_n=ct.score*Cr**(p.get(ct.section)??0)/ct.bytes;(_n>y||_n===y&&ct.seq>x[m].seq)&&(m=it,y=_n)}let C=x.splice(m,1)[0],st=te(tr(C,o))+1;u+st<=d?(u+=st,g.push(C),p.set(C.section,(p.get(C.section)??0)+1)):E.push(C)}let h=[l];f!==null&&h.push(f);for(let m of["open_errors","changed_files","decisions","earlier_requests","indexed_sources"])for(let y of g.filter(C=>C.section===m).sort((C,st)=>C.seq-st.seq))h.push(tr(y,o));if(n!==void 0){for(let m of n.sources){let y=te(m)+1;u+y>d||(u+=y,h.push(m))}for(let m of er(n.units,new Set,d-u)){let y=ln(m);u+=te(y)+1,h.push(y)}}let S=[],_=new Set;for(let m of E.sort((y,C)=>y.seq-C.seq))if(!(m.query===null||_.has(m.query))){if(te(nr([...S,m.query],o))-a>d-u)break;S.push(m.query),_.add(m.query)}return h.push(nr(S,o),gn),h.join(`
196
- `)}var $x=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Qx=new Set(["script","style"]),Zx=new TextEncoder;function un(e,t,n=re){let o=np(e);if(o.length===0)return[];let r=Math.max(4,Math.min(re,Math.floor(n)));if(t==="md")return ep(o,r,r<re);let s=t==="html"?ip(o):or(o,!1);return rr(o,s,t!=="text",r,r<re)}function ep(e,t,n){let o=[],r=[],s="",i=[],c=(a,d)=>{o.push({ord:o.length,text:a,bytes:d,title:s})},l=()=>{if(i.length!==0){for(let a of rr(e,i,!0,t,n))c(a.text,a.bytes);i=[]}};for(let a of or(e,!0)){if(a.heading!==void 0){for(l();r.length>0&&r[r.length-1].level>=a.heading.level;)r.pop();r.push(a.heading),s=r.map(d=>d.text).join(" > ")}if(a.fence!==void 0&&ne(e.slice(a.start,a.end))>t){let d=tp(e,a,a.fence,t);if(d!==void 0){l();for(let u of d)c(u,ne(u));continue}}i.push(a)}return l(),o}function tp(e,t,n,o){let r=e.slice(t.start,n.openEnd),s=n.closeStart>=0?e.slice(n.closeStart,t.end):n.fence,i=n.closeStart>=0?Math.max(n.openEnd+1,n.closeStart-1):t.end,c=e.slice(Math.min(n.openEnd+1,i),i),l=o-ne(r)-ne(s)-2;if(!(l<16||c.length===0))return rr(c,or(c,!1),!0,l,!0).map(a=>r+`
186
+ ORDER BY created_ts ASC, id ASC`;var wh=`
187
+ SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${_n} AND (:source IS NULL OR kind = :source))
188
+ OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${_n} AND (:source IS NULL OR label = :source)
189
+ AND label <> :reserved) AS more`;var Rp=`CREATE VIRTUAL TABLE r USING fts5(body, ${fn}, content='')`,Ap="INSERT INTO r(rowid, body) VALUES (?, ?)",yp="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function V(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?Op(t):sr(t);if(r===""||e.length===0)return o;let s=process.getBuiltinModule("node:sqlite");if(s===void 0)throw new T("NO_SQLITE");let i=new s.DatabaseSync(":memory:");try{i.exec(Rp);let c=i.prepare(Ap);i.exec("BEGIN");for(let l=0;l<e.length;l++)c.run(l+1,e[l]);i.exec("COMMIT");for(let l of i.prepare(yp).all(r))o[Number(l.id)-1]=-l.bm;return o}finally{i.close()}}var Np="s";function Al(e){return Np+e.toString(36)}function ir(e,t,n,o){let r=0;for(;r<o.length;){let s=r,i=0;for(;s<o.length&&(s===r||i+o[s].body.length<=An);)i+=o[s].body.length,s++;let c=r;F(e,l=>{let a=l.raw.prepare("INSERT INTO line_units(body, source_id, session_id, ord) VALUES (?, ?, ?, ?)");for(let d=c;d<s;d++){let u=o[d];a.run(u.body,t,n,u.ord)}}),r=s}}function yl(e){let t=new Set,n=new Set,o=s=>{n.size<It&&n.add(s),Rl.has(s.toLowerCase())||t.add(s)},r="";for(let s of e){if(t.size>=It)break;s.trim()===""||s==="\0"?(r!==""&&o(r),r=""):r+=s}return r!==""&&t.size<It&&o(r),[...t.size>0?t:n].join(" ")}function Nl(e,t,n,o){let r=Tp(n).join(" OR ");return r===""||t===""?[]:e.raw.prepare("SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? ORDER BY bm25(line_units) LIMIT ?").all(r,t,o).map(i=>({sourceId:Number(i.source_id),ord:Number(i.ord),label:i.label,body:i.body,score:i.score}))}function Ip(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function cr(e){let t=e.split(`
190
+ `),n=[],o=[],r=Ys*Buffer.byteLength(e,"utf8");for(let s=0;s<t.length;s++){let i=t[s].endsWith("\r")?t[s].slice(0,-1):t[s],c=Ip(i);if(c===i.length)continue;for(;n.length>0&&n[n.length-1].indent>=c;)n.pop();let l=Buffer.byteLength(i,"utf8"),a=l,d=n.length;for(;d>0;){let u=n[d-1].bytes+1;if(a+u>We||a-l+u>r)break;a+=u,d--}r-=a-l,o.push({ord:s,body:[...n.slice(d).map(u=>u.line),i].join(`
191
+ `)}),n.push({indent:c,line:i,bytes:l})}return o}function ar(e){let t=e.indexOf(`
192
+ `);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function we(e,t,n,o,r){let s=Buffer.byteLength(n,"utf8");if(s<1)throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");return{section:e,seq:t.seq,turn:t.turn,text:n,bytes:s,repeatCount:o,pinned:e==="last_request",query:r}}function it(e){return e.length>Nn?e.slice(e.length-Nn):e}function Cp(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function Il(e,t){if(!t)return Cp();let n=e.filter(_=>_.session_id===t).sort((_,m)=>_.seq-m.seq),o=n.filter(_=>_.kind==="prompt"),r=o.length>0?o[o.length-1]:void 0,s=r===void 0?null:we("last_request",r,"now: "+ar(r.body),1,null),i=o.slice(0,o.length-1).map(_=>we("earlier_requests",_,"asked #"+_.seq+": "+ar(_.body),1,null)),c=new Map,l=new Map;for(let _ of n)if(!(_.kind!=="cmd"&&_.kind!=="toolerr"||_.key===null)){if(_.ok===1){l.set(_.key,_.seq);continue}c.set(_.key,{row:_,count:(c.get(_.key)?.count??0)+1})}let a=[];for(let[_,m]of c)(l.get(_)??0)>m.row.seq||a.push(we("open_errors",m.row,"error #"+m.row.seq+" "+(m.row.tool??"")+": "+_,m.count,_));a.sort((_,m)=>_.seq-m.seq);let d=new Map;for(let _ of n)_.kind!=="edit"||_.path===null||d.set(_.path,{row:_,count:(d.get(_.path)?.count??0)+1});let u=[];for(let[_,m]of d){let y=we("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);u.push({...y,editCount:m.count})}u.sort((_,m)=>_.seq-m.seq);let f=new Map;for(let _ of n){if(_.kind!=="decision"||_.body==="")continue;let m=_.key??_.body;f.set(m,{row:_,count:(f.get(m)?.count??0)+1})}let x=[];for(let[_,m]of f)x.push(we("decisions",m.row,"decided #"+m.row.seq+": "+ar(m.row.body),m.count,_));x.sort((_,m)=>_.seq-m.seq);let p=n.filter(_=>_.kind==="index").map(_=>we("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:it(a),changedFiles:it(u),decisions:it(x),earlierRequests:it(i),indexedSources:it(p)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=In)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-In));return{lastRequest:s,openErrors:g.openErrors.filter(_=>!S.has(_.seq)),changedFiles:g.changedFiles.filter(_=>!S.has(_.seq)),decisions:g.decisions.filter(_=>!S.has(_.seq)),earlierRequests:g.earlierRequests.filter(_=>!S.has(_.seq)),indexedSources:g.indexedSources.filter(_=>!S.has(_.seq))}}function kp(e){if(!Object.hasOwn(Cn,e.section))throw new Error(`compaction: "${String(e.section)}" has no weight; only toolerr, decision, prompt, edit and index rows are scored (ADR-0009 \xA73, DECISIONS-r11).`);let t=Math.max(0,e.currentTurn-e.itemTurn),n=kn[Math.min(t,kn.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(Cn[e.section]*n*o/ei)}function Dp(e){switch(e){case"last_request":case"earlier_requests":return"prompt";case"open_errors":return"toolerr";case"changed_files":return"edit";case"decisions":return"decision";case"indexed_sources":return"index"}}function Cl(e,t){return e.map(n=>({...n,score:kp({section:Dp(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function Ll(e){return e.sourceId+":"+e.ord}function gn(e){return"@"+e.label+" line "+(e.ord+1)+`:
193
+ `+e.body}function Lp(e){return new Set(Le(e.toLowerCase()))}function wp(e,t){let n=0;for(let o of e)t.has(o)&&n++;return e.size+t.size-n===0?0:n/(e.size+t.size-n)}function ur(e,t,n){let o=e.filter(a=>!t.has(Ll(a))&&a.score>=Vn);if(o.length===0)return[];let r=Math.max(...o.map(a=>a.score)),s=o.map(a=>Lp(a.body)),i=[],c=new Set(o.map((a,d)=>d)),l=0;for(;c.size>0;){let a=-1,d=-1/0;for(let f of c){let x=0;for(let g of i)x=Math.max(x,wp(s[f],s[g]));let p=Gr*(o[f].score/r)-Br*x;p>d&&(d=p,a=f)}c.delete(a);let u=En(gn(o[a]))+1;l+u>n||(l+=u,i.push(a))}return i.map(a=>o[a])}var kl={text:"",seqs:[]};function En(e){return Buffer.byteLength(e,"utf8")}function lr(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
194
+ `)}function Dl(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+lr(e)}function wl(e,t,n,o=[],r=new Set){if(t.trim()==="")return kl;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&lr(f)!==""),i=s.length===0?[]:V(s.map(lr),t,"any"),c=s.map((f,x)=>({r:f,score:i[x]})).filter(f=>f.score>=Vn).sort((f,x)=>x.score-f.score||x.r.seq-f.r.seq),l=En($n)+1+En(Qn),a=[];for(let{r:f}of c){let x=En(Dl(f))+1;l+x>We||(l+=x,a.push(f))}let d=ur(o,r,We-l);if(a.length===0&&d.length===0)return kl;a.sort((f,x)=>f.seq-x.seq);let u=[...a.map(Dl),...d.map(gn)];return{text:[$n,...u,Qn].join(`
195
+ `),seqs:a.map(f=>f.seq),...d.length>0?{units:d.map(Ll)}:{}}}function oe(e){return Buffer.byteLength(e,"utf8")}function dr(e,t){return e.bytes>Dr?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function fr(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function Pl(e,t,n,o=""){let r;for(let m of e)(r===void 0||m.seq>r.seq)&&(r=m);let s=r===void 0?"":r.session_id,i=r===void 0||s===""?0:r.seq,c=Il(e,s),l=`<context_mode_state session="${s}" upto="${i}">`,a=oe(fr([],o)),d=kr-(oe(l)+1+a+1+oe(Rn)),u=0,f=c.lastRequest===null?null:dr(c.lastRequest,o);f!==null&&(u+=oe(f)+1);let x=Cl([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),p=new Map,g=[],E=[];for(;x.length>0;){let m=0,y=-1/0;for(let xt=0;xt<x.length;xt++){let pt=x[xt],Tn=pt.score*jr**(p.get(pt.section)??0)/pt.bytes;(Tn>y||Tn===y&&pt.seq>x[m].seq)&&(m=xt,y=Tn)}let k=x.splice(m,1)[0],ft=oe(dr(k,o))+1;u+ft<=d?(u+=ft,g.push(k),p.set(k.section,(p.get(k.section)??0)+1)):E.push(k)}let h=[l];f!==null&&h.push(f);for(let m of["open_errors","changed_files","decisions","earlier_requests","indexed_sources"])for(let y of g.filter(k=>k.section===m).sort((k,ft)=>k.seq-ft.seq))h.push(dr(y,o));if(n!==void 0){for(let m of n.sources){let y=oe(m)+1;u+y>d||(u+=y,h.push(m))}for(let m of ur(n.units,new Set,d-u)){let y=gn(m);u+=oe(y)+1,h.push(y)}}let S=[],_=new Set;for(let m of E.sort((y,k)=>y.seq-k.seq))if(!(m.query===null||_.has(m.query))){if(oe(fr([...S,m.query],o))-a>d-u)break;S.push(m.query),_.add(m.query)}return h.push(fr(S,o),Rn),h.join(`
196
+ `)}var Pp=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Mp=new Set(["script","style"]),Up=new TextEncoder;function mn(e,t,n=ce){let o=vp(e);if(o.length===0)return[];let r=Math.max(4,Math.min(ce,Math.floor(n)));if(t==="md")return Hp(o,r,r<ce);let s=t==="html"?Wp(o):xr(o,!1);return pr(o,s,t!=="text",r,r<ce)}function Hp(e,t,n){let o=[],r=[],s="",i=[],c=(a,d)=>{o.push({ord:o.length,text:a,bytes:d,title:s})},l=()=>{if(i.length!==0){for(let a of pr(e,i,!0,t,n))c(a.text,a.bytes);i=[]}};for(let a of xr(e,!0)){if(a.heading!==void 0){for(l();r.length>0&&r[r.length-1].level>=a.heading.level;)r.pop();r.push(a.heading),s=r.map(d=>d.text).join(" > ")}if(a.fence!==void 0&&re(e.slice(a.start,a.end))>t){let d=Fp(e,a,a.fence,t);if(d!==void 0){l();for(let u of d)c(u,re(u));continue}}i.push(a)}return l(),o}function Fp(e,t,n,o){let r=e.slice(t.start,n.openEnd),s=n.closeStart>=0?e.slice(n.closeStart,t.end):n.fence,i=n.closeStart>=0?Math.max(n.openEnd+1,n.closeStart-1):t.end,c=e.slice(Math.min(n.openEnd+1,i),i),l=o-re(r)-re(s)-2;if(!(l<16||c.length===0))return pr(c,xr(c,!1),!0,l,!0).map(a=>r+`
197
197
  `+a.text+`
198
- `+s)}function np(e){let t=e.split(`\r
198
+ `+s)}function vp(e){let t=e.split(`\r
199
199
  `).join(`
200
- `);return t.startsWith("\uFEFF")?t.slice(1):t}function or(e,t){let n=[],o=-1,r=-1,s=!1,i="",c,l,a=()=>{if(o>=0){let f={start:o,end:r};c!==void 0&&(f.heading=c),l!==void 0&&(f.fence=l),n.push(f)}o=-1,c=void 0,l=void 0},d=(f,x,p)=>{o<0&&(o=f),r=x,s=p},u=0;for(;u<=e.length;){let f=e.indexOf(`
201
- `,u),x=f<0?e.length:f,p=e.slice(u,x);if(i!=="")d(u,x,!1),sp(p,i)&&(i="",t&&l!==void 0&&(l.closeStart=u,a()));else if(p.length===0)a();else{let g=t?rp(p):"",E=t&&g===""?op(p):void 0,h=t&&g===""&&E===void 0&&p.includes("|");t&&o>=0&&(h!==s||g!==""||E!==void 0)&&a(),d(u,x,h),i=g,g!==""&&(l={fence:g,openEnd:x,closeStart:-1}),E!==void 0&&(c=E,a())}u=x+1}return a(),n}function op(e){let t=0;for(;t<e.length&&t<4&&e[t]===" ";)t+=1;if(t>3)return;let n=0;for(;t+n<e.length&&e[t+n]==="#";)n+=1;if(n<1||n>6)return;let o=e[t+n];if(o!==void 0&&o!==" "&&o!==" ")return;let r=e.slice(t+n).trim(),s=r.length;for(;s>0&&r[s-1]==="#";)s-=1;return s===0?r="":s<r.length&&(r[s-1]===" "||r[s-1]===" ")&&(r=r.slice(0,s).trim()),{level:n,text:r}}function rp(e){let t=e.trimStart();if(!t.startsWith("```")&&!t.startsWith("~~~"))return"";let n=0;for(;n<t.length&&t[n]===t[0];)n+=1;return t.slice(0,n)}function sp(e,t){let n=e.trim();if(n.length<t.length)return!1;for(let o=0;o<n.length;o+=1)if(n[o]!==t[0])return!1;return!0}function ip(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{ol(t,e,r,c),r=c};for(;s<e.length;){if(e[s]!=="<"){s+=1;continue}if(e.startsWith("<!--",s)){let l=e.indexOf("-->",s+4);s=l<0?e.length:l+3;continue}let c=cp(e,s);if(c===void 0){s+=1;continue}if(s=c.end,c.close){let l=n.get(c.name)??0;if(l===0)continue;n.set(c.name,l-1),o-=1,o===0&&i(s);continue}if(!(c.selfClose||$x.has(c.name))){if(Qx.has(c.name)){s=ap(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return ol(t,e,r,e.length),t}function sl(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function il(e){return sl(e)||e>="0"&&e<="9"||e==="-"||e===":"}function cp(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!sl(e[n]))return;let r=n;for(;n<e.length&&il(e[n]);)n+=1;let s=e.slice(r,n).toLowerCase(),i="";for(;n<e.length;){let c=e[n];if(i!=="")c===i&&(i="");else if(c==='"'||c==="'")i=c;else if(c===">")break;n+=1}if(!(n>=e.length))return{name:s,close:o,selfClose:e[n-1]==="/",end:n+1}}function ap(e,t,n){let o=e.indexOf("</",t);for(;o>=0;){let r=o+2+n.length;if(e.slice(o+2,r).toLowerCase()===n&&(r>=e.length||!il(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function nl(e){return e===" "||e===`
202
- `||e===" "||e==="\f"||e==="\r"}function ol(e,t,n,o){let r=n,s=o;for(;r<s&&nl(t[r]);)r+=1;for(;s>r&&nl(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function ne(e){return Buffer.byteLength(e,"utf8")}function rl(e,t,n,o){let r=Math.min(n,t+o.length);r<n&&[...e.slice(r-1,r+1)].length===1&&(r-=1);let s=Zx.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function rr(e,t,n,o,r){let s=[],i=new Uint8Array(o),c,l,a=0,d=(u,f,x)=>{s.push({ord:s.length,text:e.slice(u,f),bytes:x})};for(let u of t){if(l!==void 0&&!n&&(d(l.start,l.end,a),l=void 0),l!==void 0){let p=ne(e.slice(l.end,u.end));if(a+p<=o){l.end=u.end,a+=p;continue}d(l.start,l.end,a),l=void 0}let f=u.start,x=ne(e.slice(u.start,u.end));for(;x>o;){let p=rl(e,f,u.end,i),g=r?e.lastIndexOf(`
203
- `,p.end-1):-1;if(g>f){let E=ne(e.slice(f,g+1));d(f,g+1,E),f=g+1,x-=E;continue}if(r){let E=e.indexOf(`
204
- `,f),h=E<0||E>=u.end?u.end:E+1,S=ne(e.slice(f,h));if(S<=re){d(f,h,S),f=h,x-=S;continue}c??=new Uint8Array(re);let _=rl(e,f,h,c);d(f,_.end,_.written),f=_.end,x-=_.written;continue}d(f,p.end,p.written),f=p.end,x-=p.written}f>=u.end||(l={start:f,end:u.end},a=x)}return l!==void 0&&d(l.start,l.end,a),s}var lp=`
205
- `,up=1;function cl(e,t,n,o,r){return dp(e,t,n,o,r)}function dp(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?Y(s,t):Y(s,r,"any"),c=e.map((f,x)=>x).sort((f,x)=>i[x]-i[f]||e[x].ord-e[f].ord),l=[],a=0,d=!1;for(let f of c){let x=e[f].bytes+(l.length>0?up:0);if(a+x>n){d=!0;continue}l.push(e[f]),a+=x}return l.sort((f,x)=>f.ord-x.ord),{text:l.map(f=>f.text).join(lp),more:d?sr(t,o):null}}function sr(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>qn?"...":JSON.stringify(e))+"]"+n+"})"}var al=20,H=2,ll=9,ul=8,fp=.9,xp=.5,pp=64,_p=2,Ep=4,ir=`
206
- `,gp="(absent)",q=e=>Buffer.byteLength(e,"utf8");function dl(e,t,n){let o=Sp(e,t)??Tp(e,t)??yp(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):Y(o.units.map(a=>a.rank),t,"any"),s=o.units.map((a,d)=>d).filter(a=>r[a]>0).sort((a,d)=>r[d]-r[a]||o.units[a].pos-o.units[d].pos),i=[],c=0;for(let a of s){let d=i.length>0?q(ir):0,u=o.units[a].render(n-c-d);u===null||c+d+q(u)>n||(i.push({pos:o.units[a].pos,text:u}),c+=d+q(u))}if(i.length===0)return null;i.sort((a,d)=>a.pos-d.pos);let l=i.map(a=>a.text);return c+q(ir)+q(o.header)<=n&&l.unshift(o.header),l.join(ir)}function mp(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
207
- `&&n!=="\r"&&n!==" ")return n}return""}function hp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fl(e,t,n){if(n.size<2||n.size>ul)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=H+1)return o[0][1]<fp*e||e-o[0][1]>H?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>H),s=o.filter(([,i])=>i<=H);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function xl(e){if(mp(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<al||!t.every(hp))return null;let n=t,o=[],r=new Set;for(let s of n)for(let i of Object.keys(s))r.has(i)||(r.add(i),o.push(i));return{objs:n,keys:o}}var pl=(e,t)=>e+" objects {"+t.join(",")+"}";function Sp(e,t){let n=xl(e);if(n===null)return null;let{objs:o,keys:r}=n,s=new Map;for(let a of r){let d=new Map,u=new Map,f=!0;for(let x=0;x<o.length&&f;x++){let p=a in o[x]?o[x][a]:void 0;if(typeof p=="object"&&p!==null){f=!1;break}let g=p===void 0?gp:JSON.stringify(p);u.set(g,(u.get(g)??0)+1);let E=d.get(g)??[];if(E.length<=H&&E.push(x),d.set(g,E),u.size>ul)break}if(f)for(let x of fl(o.length,d,u))s.set(x,[...s.get(x)??[],a])}if(s.size===0||s.size>ll)return null;let i=Y(r,t,"any"),c=new Set(r.filter((a,d)=>i[d]>0)),l=[...s.entries()].map(([a,d])=>({pos:a,rank:JSON.stringify(o[a]),render:u=>_l(a,o[a],d,c,u)}));return{header:pl(o.length,r)+", "+s.size+" rare:",units:l}}function _l(e,t,n,o,r){let s="["+e+"] ",i=bp(t,n,o,r-q(s));return i===null?null:s+i}function bp(e,t,n,o){let r=JSON.stringify(e);if(q(r)<=o)return r;let s=Object.keys(e),i=u=>t.includes(u)?0:n.has(u)?1:typeof e[u]!="object"||e[u]===null?2:3,c=[...s].sort((u,f)=>i(u)-i(f)||s.indexOf(u)-s.indexOf(f)),l=u=>JSON.stringify(u)+":"+JSON.stringify(e[u]),a=new Set,d=2;for(let u of c){let f=q(l(u))+(a.size>0?1:0);d+f>o||(a.add(u),d+=f)}return t.every(u=>a.has(u))?"{"+s.filter(u=>a.has(u)).map(l).join(",")+"}":null}function Op(e,t){let n=Y(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function Tp(e,t){let n=xl(e);if(n===null)return null;let{objs:o,keys:r}=n,s=Op(r,t),i=new Map,c=0;for(let a of r){if(!s.has(a)||c>=_p||!o.every(f=>typeof f[a]=="number"&&Number.isFinite(f[a])))continue;let d=0,u=0;for(let f=1;f<o.length;f++)o[f][a]>o[d][a]&&(d=f),o[f][a]<o[u][a]&&(u=f);d!==u&&(c++,i.set(d,a),i.set(u,a))}if(i.size===0)return null;let l=[...i.entries()].map(([a,d])=>({pos:a,rank:"",render:u=>_l(a,o[a],[d],s,u)}));return{header:pl(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:l,direct:!0}}function Rp(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function Ap(e,t){let n=0;for(let o=0;o<e.length;o++)(e[o]===t[o]||e[o]==="<*>"||t[o]==="<*>")&&n++;return n/e.length}function yp(e){let t=e.split(`
208
- `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<al)return null;let n=new Map,o=[];for(let l=0;l<t.length;l++){let a=t[l].split(" ").filter(p=>p!==""),d=a.map(p=>Rp(p)?"<*>":p),u=d.length+" "+(d[0]??""),f=n.get(u)??[],x;for(let p of f)if(Ap(p.tpl,d)>=xp){x=p;break}if(x===void 0){if(x={tpl:[...d],count:0,lines:[],pos:a.map(()=>({counts:new Map,totals:new Map}))},f.push(x),n.set(u,f),o.push(x),o.length>pp)return null}else for(let p=0;p<x.tpl.length;p++)x.tpl[p]!==d[p]&&(x.tpl[p]="<*>");x.count++,x.lines.length<=H&&x.lines.push(l);for(let p=0;p<x.pos.length;p++){let g=x.pos[p];if(g===null)continue;g.totals.set(a[p],(g.totals.get(a[p])??0)+1);let E=g.counts.get(a[p])??[];E.length<=H&&E.push(l),g.counts.set(a[p],E),g.totals.size>H+1&&(x.pos[p]=null)}}let r=o.filter(l=>l.count>H);if(r.length===0||r.length>Ep||r.some(l=>l.tpl.every(a=>a==="<*>")))return null;let s=new Set(o.filter(l=>l.count<=H).flatMap(l=>l.lines));for(let l of r)for(let a of l.pos)if(a!==null)for(let d of fl(l.count,a.counts,a.totals))s.add(d);if(s.size===0||s.size>ll)return null;let i=t.length+" lines, "+s.size+" rare:",c=[...s].sort((l,a)=>l-a).map(l=>{let a=l+1+": "+t[l];return{pos:l,rank:t[l],render:d=>q(a)<=d?a:null}});return{header:i,units:c}}function Np(e,t,n,o,r,s,i,c=un(s,i)){return{sourceId:Wa(e,{projectKey:t.projectKey,sessionId:n,worktree:t.worktree,agent:t.agent,kind:o,label:r,bytes:Buffer.byteLength(s,"utf8"),chunkCount:c.length,createdAt:Date.now()},c),chunks:c.length}}function cr(e,t,n,o,r,s,i){return Np(e,t,n,"content",o,r,s,i)}async function Ip(e,t){try{let n=await N(e);sn(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
209
- `)}}function dn(e,t,n){Ip(e,n)}function El(e,t,n){let o=new Set(ye(t.toLowerCase()));for(let i of ye(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of ye(n.toLowerCase()))o.has(i)&&r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((i,c)=>i[1]-c[1]||(i[0]<c[0]?-1:i[0]>c[0]?1:0)).slice(0,Ir).map(i=>i[0]).join(" ")}function et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cp(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(Xs):""}function kp(e){return Array.isArray(e)?e.filter(et).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):et(e)?Object.entries(e):[]}function ml(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!et(t))return[];let n=[];for(let[o,r]of kp(t[Ws])){let s=Cp(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function hl(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!et(o)||!Array.isArray(o.options)))for(let r of o.options)et(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function gl(e){return e.trim().toLowerCase()}function Sl(e,t,n){let o=gl(e);if(o==="")return null;let r=t.find(s=>gl(s)===o);return r===void 0?null:{key:Rt,body:"A: "+r+`
210
- ref: #`+n}}function Dp(e,t){return"hint:"+e+":"+t}function Lp(e,t){return ee(e,t)!==null?!1:(K(e,t,"1"),!0)}function wp(e,t,n){let o=ee(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return K(e,t,String(r)),(r-1)%n===0}function fn(e,t,n,o){if(t==="")return!1;let r=Dp(t,n),s=i=>o===void 0?Lp(i,r):wp(i,r,o);return e.raw.isTransaction?s(e):U(e,s)}import{join as lr,resolve as bl}from"node:path";var ar=process.getBuiltinModule("node:fs");function ur(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function Pp(e){for(let t of cs){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(ur(n))return n}return{}}function Mp(e){return e.HOME??e.USERPROFILE??""}function Up(e){let t=e[Le];if(t!==void 0&&t!=="")return lr(zt(e,""),Ln);let n=Mp(e);return n===""?"":lr(zt(e,n),Ln)}function Tl(e){let t=ur(e)?e.code:void 0;return typeof t=="string"&&t!==""?t:e instanceof Error?e.name:"Error"}function Ie(e,t,n,o){try{let r=Up(e);if(r==="")return;ar.mkdirSync(lr(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:Tl(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});ar.appendFileSync(r,s+`
200
+ `);return t.startsWith("\uFEFF")?t.slice(1):t}function xr(e,t){let n=[],o=-1,r=-1,s=!1,i="",c,l,a=()=>{if(o>=0){let f={start:o,end:r};c!==void 0&&(f.heading=c),l!==void 0&&(f.fence=l),n.push(f)}o=-1,c=void 0,l=void 0},d=(f,x,p)=>{o<0&&(o=f),r=x,s=p},u=0;for(;u<=e.length;){let f=e.indexOf(`
201
+ `,u),x=f<0?e.length:f,p=e.slice(u,x);if(i!=="")d(u,x,!1),Bp(p,i)&&(i="",t&&l!==void 0&&(l.closeStart=u,a()));else if(p.length===0)a();else{let g=t?Gp(p):"",E=t&&g===""?jp(p):void 0,h=t&&g===""&&E===void 0&&p.includes("|");t&&o>=0&&(h!==s||g!==""||E!==void 0)&&a(),d(u,x,h),i=g,g!==""&&(l={fence:g,openEnd:x,closeStart:-1}),E!==void 0&&(c=E,a())}u=x+1}return a(),n}function jp(e){let t=0;for(;t<e.length&&t<4&&e[t]===" ";)t+=1;if(t>3)return;let n=0;for(;t+n<e.length&&e[t+n]==="#";)n+=1;if(n<1||n>6)return;let o=e[t+n];if(o!==void 0&&o!==" "&&o!==" ")return;let r=e.slice(t+n).trim(),s=r.length;for(;s>0&&r[s-1]==="#";)s-=1;return s===0?r="":s<r.length&&(r[s-1]===" "||r[s-1]===" ")&&(r=r.slice(0,s).trim()),{level:n,text:r}}function Gp(e){let t=e.trimStart();if(!t.startsWith("```")&&!t.startsWith("~~~"))return"";let n=0;for(;n<t.length&&t[n]===t[0];)n+=1;return t.slice(0,n)}function Bp(e,t){let n=e.trim();if(n.length<t.length)return!1;for(let o=0;o<n.length;o+=1)if(n[o]!==t[0])return!1;return!0}function Wp(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{Ul(t,e,r,c),r=c};for(;s<e.length;){if(e[s]!=="<"){s+=1;continue}if(e.startsWith("<!--",s)){let l=e.indexOf("-->",s+4);s=l<0?e.length:l+3;continue}let c=Xp(e,s);if(c===void 0){s+=1;continue}if(s=c.end,c.close){let l=n.get(c.name)??0;if(l===0)continue;n.set(c.name,l-1),o-=1,o===0&&i(s);continue}if(!(c.selfClose||Pp.has(c.name))){if(Mp.has(c.name)){s=Kp(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return Ul(t,e,r,e.length),t}function Fl(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function vl(e){return Fl(e)||e>="0"&&e<="9"||e==="-"||e===":"}function Xp(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!Fl(e[n]))return;let r=n;for(;n<e.length&&vl(e[n]);)n+=1;let s=e.slice(r,n).toLowerCase(),i="";for(;n<e.length;){let c=e[n];if(i!=="")c===i&&(i="");else if(c==='"'||c==="'")i=c;else if(c===">")break;n+=1}if(!(n>=e.length))return{name:s,close:o,selfClose:e[n-1]==="/",end:n+1}}function Kp(e,t,n){let o=e.indexOf("</",t);for(;o>=0;){let r=o+2+n.length;if(e.slice(o+2,r).toLowerCase()===n&&(r>=e.length||!vl(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function Ml(e){return e===" "||e===`
202
+ `||e===" "||e==="\f"||e==="\r"}function Ul(e,t,n,o){let r=n,s=o;for(;r<s&&Ml(t[r]);)r+=1;for(;s>r&&Ml(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function re(e){return Buffer.byteLength(e,"utf8")}function Hl(e,t,n,o){let r=Math.min(n,t+o.length);r<n&&[...e.slice(r-1,r+1)].length===1&&(r-=1);let s=Up.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function pr(e,t,n,o,r){let s=[],i=new Uint8Array(o),c,l,a=0,d=(u,f,x)=>{s.push({ord:s.length,text:e.slice(u,f),bytes:x})};for(let u of t){if(l!==void 0&&!n&&(d(l.start,l.end,a),l=void 0),l!==void 0){let p=re(e.slice(l.end,u.end));if(a+p<=o){l.end=u.end,a+=p;continue}d(l.start,l.end,a),l=void 0}let f=u.start,x=re(e.slice(u.start,u.end));for(;x>o;){let p=Hl(e,f,u.end,i),g=r?e.lastIndexOf(`
203
+ `,p.end-1):-1;if(g>f){let E=re(e.slice(f,g+1));d(f,g+1,E),f=g+1,x-=E;continue}if(r){let E=e.indexOf(`
204
+ `,f),h=E<0||E>=u.end?u.end:E+1,S=re(e.slice(f,h));if(S<=ce){d(f,h,S),f=h,x-=S;continue}c??=new Uint8Array(ce);let _=Hl(e,f,h,c);d(f,_.end,_.written),f=_.end,x-=_.written;continue}d(f,p.end,p.written),f=p.end,x-=p.written}f>=u.end||(l={start:f,end:u.end},a=x)}return l!==void 0&&d(l.start,l.end,a),s}var Yp=`
205
+ `,qp=1;function jl(e,t,n,o,r){return zp(e,t,n,o,r)}function zp(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?V(s,t):V(s,r,"any"),c=e.map((f,x)=>x).sort((f,x)=>i[x]-i[f]||e[x].ord-e[f].ord),l=[],a=0,d=!1;for(let f of c){let x=e[f].bytes+(l.length>0?qp:0);if(a+x>n){d=!0;continue}l.push(e[f]),a+=x}return l.sort((f,x)=>f.ord-x.ord),{text:l.map(f=>f.text).join(Yp),more:d?_r(t,o):null}}function _r(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>to?"...":JSON.stringify(e))+"]"+n+"})"}var Gl=20,v=2,Bl=9,Wl=8,Vp=.9,Jp=.5,$p=64,Qp=2,Zp=4,Er=`
206
+ `,e_="(absent)",J=e=>Buffer.byteLength(e,"utf8");function Xl(e,t,n){let o=o_(e,t)??i_(e,t)??l_(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):V(o.units.map(a=>a.rank),t,"any"),s=o.units.map((a,d)=>d).filter(a=>r[a]>0).sort((a,d)=>r[d]-r[a]||o.units[a].pos-o.units[d].pos),i=[],c=0;for(let a of s){let d=i.length>0?J(Er):0,u=o.units[a].render(n-c-d);u===null||c+d+J(u)>n||(i.push({pos:o.units[a].pos,text:u}),c+=d+J(u))}if(i.length===0)return null;i.sort((a,d)=>a.pos-d.pos);let l=i.map(a=>a.text);return c+J(Er)+J(o.header)<=n&&l.unshift(o.header),l.join(Er)}function t_(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
207
+ `&&n!=="\r"&&n!==" ")return n}return""}function n_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kl(e,t,n){if(n.size<2||n.size>Wl)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=v+1)return o[0][1]<Vp*e||e-o[0][1]>v?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>v),s=o.filter(([,i])=>i<=v);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function Yl(e){if(t_(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<Gl||!t.every(n_))return null;let n=t,o=[],r=new Set;for(let s of n)for(let i of Object.keys(s))r.has(i)||(r.add(i),o.push(i));return{objs:n,keys:o}}var ql=(e,t)=>e+" objects {"+t.join(",")+"}";function o_(e,t){let n=Yl(e);if(n===null)return null;let{objs:o,keys:r}=n,s=new Map;for(let a of r){let d=new Map,u=new Map,f=!0;for(let x=0;x<o.length&&f;x++){let p=a in o[x]?o[x][a]:void 0;if(typeof p=="object"&&p!==null){f=!1;break}let g=p===void 0?e_:JSON.stringify(p);u.set(g,(u.get(g)??0)+1);let E=d.get(g)??[];if(E.length<=v&&E.push(x),d.set(g,E),u.size>Wl)break}if(f)for(let x of Kl(o.length,d,u))s.set(x,[...s.get(x)??[],a])}if(s.size===0||s.size>Bl)return null;let i=V(r,t,"any"),c=new Set(r.filter((a,d)=>i[d]>0)),l=[...s.entries()].map(([a,d])=>({pos:a,rank:JSON.stringify(o[a]),render:u=>zl(a,o[a],d,c,u)}));return{header:ql(o.length,r)+", "+s.size+" rare:",units:l}}function zl(e,t,n,o,r){let s="["+e+"] ",i=r_(t,n,o,r-J(s));return i===null?null:s+i}function r_(e,t,n,o){let r=JSON.stringify(e);if(J(r)<=o)return r;let s=Object.keys(e),i=u=>t.includes(u)?0:n.has(u)?1:typeof e[u]!="object"||e[u]===null?2:3,c=[...s].sort((u,f)=>i(u)-i(f)||s.indexOf(u)-s.indexOf(f)),l=u=>JSON.stringify(u)+":"+JSON.stringify(e[u]),a=new Set,d=2;for(let u of c){let f=J(l(u))+(a.size>0?1:0);d+f>o||(a.add(u),d+=f)}return t.every(u=>a.has(u))?"{"+s.filter(u=>a.has(u)).map(l).join(",")+"}":null}function s_(e,t){let n=V(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function i_(e,t){let n=Yl(e);if(n===null)return null;let{objs:o,keys:r}=n,s=s_(r,t),i=new Map,c=0;for(let a of r){if(!s.has(a)||c>=Qp||!o.every(f=>typeof f[a]=="number"&&Number.isFinite(f[a])))continue;let d=0,u=0;for(let f=1;f<o.length;f++)o[f][a]>o[d][a]&&(d=f),o[f][a]<o[u][a]&&(u=f);d!==u&&(c++,i.set(d,a),i.set(u,a))}if(i.size===0)return null;let l=[...i.entries()].map(([a,d])=>({pos:a,rank:"",render:u=>zl(a,o[a],[d],s,u)}));return{header:ql(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:l,direct:!0}}function c_(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function a_(e,t){let n=0;for(let o=0;o<e.length;o++)(e[o]===t[o]||e[o]==="<*>"||t[o]==="<*>")&&n++;return n/e.length}function l_(e){let t=e.split(`
208
+ `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<Gl)return null;let n=new Map,o=[];for(let l=0;l<t.length;l++){let a=t[l].split(" ").filter(p=>p!==""),d=a.map(p=>c_(p)?"<*>":p),u=d.length+" "+(d[0]??""),f=n.get(u)??[],x;for(let p of f)if(a_(p.tpl,d)>=Jp){x=p;break}if(x===void 0){if(x={tpl:[...d],count:0,lines:[],pos:a.map(()=>({counts:new Map,totals:new Map}))},f.push(x),n.set(u,f),o.push(x),o.length>$p)return null}else for(let p=0;p<x.tpl.length;p++)x.tpl[p]!==d[p]&&(x.tpl[p]="<*>");x.count++,x.lines.length<=v&&x.lines.push(l);for(let p=0;p<x.pos.length;p++){let g=x.pos[p];if(g===null)continue;g.totals.set(a[p],(g.totals.get(a[p])??0)+1);let E=g.counts.get(a[p])??[];E.length<=v&&E.push(l),g.counts.set(a[p],E),g.totals.size>v+1&&(x.pos[p]=null)}}let r=o.filter(l=>l.count>v);if(r.length===0||r.length>Zp||r.some(l=>l.tpl.every(a=>a==="<*>")))return null;let s=new Set(o.filter(l=>l.count<=v).flatMap(l=>l.lines));for(let l of r)for(let a of l.pos)if(a!==null)for(let d of Kl(l.count,a.counts,a.totals))s.add(d);if(s.size===0||s.size>Bl)return null;let i=t.length+" lines, "+s.size+" rare:",c=[...s].sort((l,a)=>l-a).map(l=>{let a=l+1+": "+t[l];return{pos:l,rank:t[l],render:d=>J(a)<=d?a:null}});return{header:i,units:c}}function u_(e,t,n,o,r,s,i,c=mn(s,i)){return{sourceId:bl(e,{projectKey:t.projectKey,sessionId:n,worktree:t.worktree,agent:t.agent,kind:o,label:r,bytes:Buffer.byteLength(s,"utf8"),chunkCount:c.length,createdAt:Date.now()},c),chunks:c.length}}function gr(e,t,n,o,r,s,i){return u_(e,t,n,"content",o,r,s,i)}async function d_(e,t){try{let n=await N(e);pn(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
209
+ `)}}function hn(e,t,n){d_(e,n)}function Vl(e,t,n){let o=new Set(Le(t.toLowerCase()));for(let i of Le(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of Le(n.toLowerCase()))o.has(i)&&r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((i,c)=>i[1]-c[1]||(i[0]<c[0]?-1:i[0]>c[0]?1:0)).slice(0,vr).map(i=>i[0]).join(" ")}function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function f_(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(ni):""}function x_(e){return Array.isArray(e)?e.filter(ct).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):ct(e)?Object.entries(e):[]}function $l(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!ct(t))return[];let n=[];for(let[o,r]of x_(t[ti])){let s=f_(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function Ql(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!ct(o)||!Array.isArray(o.options)))for(let r of o.options)ct(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function Jl(e){return e.trim().toLowerCase()}function Zl(e,t,n){let o=Jl(e);if(o==="")return null;let r=t.find(s=>Jl(s)===o);return r===void 0?null:{key:Dt,body:"A: "+r+`
210
+ ref: #`+n}}function p_(e,t){return"hint:"+e+":"+t}function __(e,t){return ne(e,t)!==null?!1:(z(e,t,"1"),!0)}function E_(e,t,n){let o=ne(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return z(e,t,String(r)),(r-1)%n===0}function Sn(e,t,n,o){if(t==="")return!1;let r=p_(t,n),s=i=>o===void 0?__(i,r):E_(i,r,o);return e.raw.isTransaction?s(e):F(e,s)}import{join as Sr,resolve as mr}from"node:path";var hr=process.getBuiltinModule("node:fs");function br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function g_(e){for(let t of hs){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(br(n))return n}return{}}function m_(e){return e.HOME??e.USERPROFILE??""}function h_(e){let t=e[Fe];if(t!==void 0&&t!=="")return Sr(on(e,""),jn);let n=m_(e);return n===""?"":Sr(on(e,n),jn)}function tu(e){let t=br(e)?e.code:void 0;return typeof t=="string"&&t!==""?t:e instanceof Error?e.name:"Error"}function Pe(e,t,n,o){try{let r=h_(e);if(r==="")return;hr.mkdirSync(Sr(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:tu(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});hr.appendFileSync(r,s+`
211
211
  `)}catch{process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
212
- `)}}var Ol=!1;function tt(e,t){if(!(Ol||e[us]!==t))throw Ol=!0,new Error("injected fault at "+t)}function Rl(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=De.split(".");for(let o=0;o<n.length;o++){let r=Number(t[o]??0)||0,s=Number(n[o]);if(r!==s)return r<s}return!1}function oe(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function Hp(e,t){let n=t.toLowerCase();return oe(e.nativeTools.shell,n)||oe(Pe.shell,n)?"shell":oe(e.nativeTools.read,n)||oe(Pe.read,n)?"read":oe(e.nativeTools.grep,n)||oe(Pe.grep,n)?"grep":oe(e.nativeTools.webfetch,n)||oe(Pe.fetch,n)?"fetch":null}function Fp(e,t){let n=t.toLowerCase();return ls.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function vp(e){try{let t=ar.statSync(e);return t.isFile()&&t.size>V}catch{return!1}}function jp(e,t,n){if((t.offset??null)!==null||(t.limit??null)!==null)return!1;let o=Array.isArray(t[pe])?t[pe].filter(r=>typeof r=="string"):[];return[xn(t,ht),...o].some(r=>r!==""&&vp(bl(n,r))&&!Qt(e,bl(n,r)))}function nt(e,t,n,o=""){let r=ie(e),s=()=>r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"});try{if(!ur(t)||!Fp(r,xn(t,is)))return s();let i=xn(t,ss);if(i===""||i.includes(St))return s();let c=Hp(r,i);if(c===null)return s();let l=xn(t,as)||o;if(c==="read"&&!jp(e,Pp(t),l))return s();let a=c==="read"?wn.read:wn[c],d=k(a,r.toolNamePrefix)+`
213
- `+ds(Tl(n),r.toolNamePrefix);return r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:l,turn:0},{kind:"deny",reason:d})}catch{return{stdout:"",exitCode:0}}}var{read:Gp,writeSync:Bp}=process.getBuiltinModule("node:fs"),Al=65536;function Wp(e){let t=Buffer.allocUnsafe(Al);return new Promise(n=>{let o=()=>{Gp(0,t,0,Al,null,(r,s)=>{if(r)return n(r.code==="EOF");if(s===0)return n(!0);e.push(Buffer.from(t.subarray(0,s))),o()})};o()})}async function dr(){let e=[];if(!await Wp(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function fr(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=Bp(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{lstatSync:Xp,readFileSync:Kp}=process.getBuiltinModule("node:fs"),A={kind:"allow"},Vp={stdout:"",exitCode:0},Jp=48;function $p(e){return Ce.includes(e)}function ot(e){return e instanceof Error?e.message:String(e)}function rt(e){return typeof e=="string"?e:""}async function Cl(e,t,n){if(!$p(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
214
- `),Vp;let o=ie(e),r=(a,d,u)=>(Ie(n,e,a,d),process.stderr.write(u??"hooks: "+a+" failed: "+ot(d)+`
215
- `),nt(e,t,d));if(Rl(process.version))return r("node",new T("NODE_TOO_OLD",{v:process.version}));let s;try{tt(n,"decode"),s=o.decode(t)}catch(a){return r("decode",a)}if(s.event==="Stop")return o.encode(s,A);let i;try{tt(n,"project");let a=e==="vscode"?[xt,s.cwd]:process.argv;i=ya(e,{env:n,argv:a,cwd:s.cwd,piCwd:e==="pi"?s.cwd:void 0})}catch(a){return r("project",a,"hooks: no project: "+String(a.code??"ERROR")+" "+ot(a)+`
216
- `)}let c,l={};try{tt(n,"policy"),c=await Qp(s,o,i,n,l)}catch(a){return r("store",a)}try{tt(n,"encode");let a=o.encode(s,c);return l.run?.(!0),a}catch(a){return l.run?.(!1),r("encode",a)}}function Qp(e,t,n,o,r){switch(e.event){case"SessionStart":return Zp(e,t,n);case"UserPromptSubmit":return e_(e,t,n);case"PreToolUse":return a_(e,t,n,o);case"PostToolUse":return x_(e,t,n,o,r);case"PreCompact":return O_(e,t,n);case"Usage":return T_(e,n)}return Promise.resolve(A)}function kl(e,t){return e.split(fs).join(t.toolNamePrefix)}function pr(e,t,n){return n.compactSummary==="host"?k(Lr,n.toolNamePrefix):tl(Yo(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function Zp(e,t,n){if(e.source==="compact"&&Mt(t)&&Dl(await N(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await N(n);return fn(r,e.sessionId,Fn)?{kind:"hint",text:pr(r,e,t),onceKey:Fn}:A}let o=await N(n);return t.compactDelivery==="opencode-cache"&&rn(o,bt+e.sessionId)!==null?{kind:"hint",text:pr(o,e,t),onceKey:vn}:fn(o,e.sessionId,Ue)?{kind:"hint",text:kl(Kn,t),onceKey:Ue}:A}async function e_(e,t,n){let o=e.prompt??"",r=await t_(e,t,n);if(dn(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:"prompt",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(o),body:o,turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),i_(e,n,o),t.compactDelivery==="pending-flag"){let s=await N(n);if(rn(s,bt+e.sessionId)!==null)return{kind:"hint",text:pr(s,e,t),onceKey:vn}}return r!==null?r:r_(e,t,n,o)}async function t_(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await N(n);return Ha(o,e.sessionId)||!fn(o,e.sessionId,Ue)||!Ua(o,n.worktree,e.agent)?null:{kind:"hint",text:kl(Kn,t),onceKey:Ue}}function Dl(e,t){t!==""&&K(e,Bn+t,jn)}function n_(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function o_(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}async function r_(e,t,n,o){if(!Mt(t)||e.sessionId==="")return A;let r=await N(n);if(ee(r,Bn+e.sessionId)===null)return A;let s=Us+e.sessionId,i=n_(ee(r,s)),c=ws+e.sessionId,l=o_(ee(r,c)),a=Pa(r,e.sessionId),d=za(r,e.sessionId,qa(o,a),Ms),u=el(Ma(r,e.sessionId,n.worktree,Ls),o,new Set(i),d,new Set(l));return u.text===""?A:(u.seqs.length>0&&K(r,s,JSON.stringify([...i,...u.seqs])),u.units!==void 0&&K(r,c,JSON.stringify([...l,...u.units])),{kind:"hint",text:u.text,onceKey:Hs})}function Ll(e){return Tt+":"+Rt+":"+e}function s_(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;let{seq:n,labels:o}=t;return typeof n!="number"||!Array.isArray(o)?null:{seq:n,labels:o.filter(r=>typeof r=="string")}}catch{return null}}function i_(e,t,n){if(e.sessionId==="")return;let o=Ll(e.sessionId);N(t).then(r=>{if(ee(r,o)===null)return;let s=rn(r,o),i=s===null?null:s_(s);if(i===null)return;let c=Sl(n,i.labels,i.seq);c!==null&&wl(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+ot(r)+`
217
- `)})}function wl(e,t,n,o){for(let r of o)sn(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:Yn,key:r.key,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(r.body),body:r.body,turn:t.turn??0,sandbox_bytes:0,returned_bytes:0}),cr(e,n,t.sessionId,Tt,r.body,"text")}function c_(e,t,n,o){let r=ml(o),s=r.length===0?hl(n.input):[];r.length===0&&s.length===0||N(t).then(i=>{if(r.length>0)return wl(i,e,t,r);let c=Yo(i,e.sessionId,"prompt"),l=c[c.length-1];l===void 0||e.sessionId===""||K(i,Ll(e.sessionId),JSON.stringify({seq:l.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+ot(i)+`
218
- `)})}async function a_(e,t,n,o){let r=na(n.worktree,e.agent),s=pa(e,t,r),i=s;if(s.kind==="deny"&&Te(e)&&!Pl(s.reason,t)){let c=Do(e,{projectDir:n.worktree,env:o}),l=ko(e,c),a=e.tool,d=c!==null||(e.agentType??"")!==""&&_e(t);l==="B"&&a!==void 0&&Er(a,t)?i=l_(e,t,s,r):l!=="A"&&d&&(i=A)}return i}function Er(e,t){return e.canonicalName===Cs||t.nativeTools.shell.includes(e.name)}function Pl(e,t){return e.startsWith(we)||e===k(Et,t.toolNamePrefix)||e===k(gt,t.toolNamePrefix)}function xr(e){return Buffer.from(e,"utf8").toString("base64url")}function l_(e,t,n,o){let r=e.tool;if(r===void 0||!Er(r,t)||Pl(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+Il(Yp(process.argv[1]??""),vs)+'"',c=[js,i,xr(s),xr(JSON.stringify(o??[])),xr(rt(r.input.description))].join(" ");return{kind:"deny",reason:Gs,rewritten:c}}function u_(e,t,n){return n?"toolerr":ks.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":Er(e,t)?"cmd":null}function _r(e){if(Array.isArray(e))return"["+e.map(_r).join(",")+"]";if(typeof e=="object"&&e!==null){let t=e;return"{"+Object.keys(t).filter(o=>t[o]!==void 0).sort().map(o=>JSON.stringify(o)+":"+_r(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function d_(e){let t=e.indexOf(`
219
- `),n=t<0?e:e.slice(0,t);if(!n.startsWith(Hn))return null;let o=0,r=0;for(let s of n.slice(Hn.length)){let i=s.charCodeAt(0)-Jp;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function f_(e){for(let t of Ds)if(typeof e[t]=="string")return e[t];return null}async function x_(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(St))return A;let i=e.result??{isError:!1,bytes:0},c=m_(i,e.sessionId,o);i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(c)),s.canonicalName===Yn&&c_(e,n,s,c);let l=u_(s,t,i.isError),a=f=>{if(l===null)return;let x=l==="cmd"?La(s.canonicalName,rt(s.input.command)):l==="toolerr"?s.canonicalName+":"+_r(s.input):null;dn(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:l,tool:s.canonicalName,key:x,path:f_(s.input),ok:i.isError?0:1,exit_code:d_(c),bytes:i.bytes,body:c,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:f})},d;try{d=await p_(e,t,n,o,s,i,c)}catch(f){throw a(i.bytes),f}let u=d;return r.run=f=>a(f&&u.kind==="replace"?Buffer.byteLength(u.output):i.bytes),d}async function p_(e,t,n,o,r,s,i){if(s.bytes<=br||__(r)||s.keep===!0||!_e(t))return A;let c;if(Te(e)){if(ko(e,Do(e,{projectDir:n.worktree,env:o}))==="A")return A;c=Fs+r.canonicalName+":"+String(e.turn??0)}else c=S_(r,e);let l=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url].map(rt).find(_=>_.trim()!=="")??"",a=un(i,"text",yr),d=await N(n),u;s.bytes<=Sr?(u=cr(d,n,e.sessionId,c,i,"text",a).sourceId,Jo(d,u,e.sessionId,$o(i))):(u=zo(d,Ml(n,e.sessionId,c),a),b_(n,e.sessionId,u,c,i,a));let f=Ya(u),x=await h_(n,e.sessionId),p=x.trim()===""?void 0:l+" "+x,g=Nr(l,f,s.bytes,t.toolNamePrefix,El(l,x,i)),E=E_(g,sr(l,c)),h=dl(i,p??l,Ar);if(h!==null)return{kind:"replace",output:Nl(h,g)};let S=cl(a,l,E,c,p);return{kind:"replace",output:S.more!==null?Nl(S.text,g):S.text}}function __(e){return Or.includes(e.canonicalName)&&Tr.some(t=>e.input[t]!==void 0&&e.input[t]!==null)}function Nl(e,t){return e===""?t:e+`
220
- `+t}function E_(e,t){return Math.max(0,Rr+Buffer.byteLength(`
221
- `+t)-1-Buffer.byteLength(e))}function g_(e,t,n){if(t===""||t.includes(yl)||t.includes("/"))return!1;let o=Il(le(n,Q(n)??""),ft),r=qp(o,zp(e)).split(yl);if(r.length!==4||r.includes("..")||r.includes("")||r[1]!==t||r[2]!==Ys)return!1;let s=Xp(e);return s.isFile()&&s.size<=qs&&Sa(o,e)}function m_(e,t,n){let o=e.text??"";if(e.persistedPath===void 0)return o;try{return g_(e.persistedPath,t,n)?Kp(e.persistedPath,"utf8"):(Ie(n,"claude-code","persisted-output",new Error("persisted output path is outside this session's tool-results dir or too large; kept the head")),o)}catch{return o}}async function h_(e,t){try{return wa(await N(e),t)}catch{return""}}function S_(e,t){let n=rt(e.input.command)??rt(e.input.file_path)??"",o=n.indexOf(`
222
- `);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,Br)+"#"+(e.callId??String(t.turn??0))}function b_(e,t,n,o,r,s){N(e).then(i=>{Xa(i,n,Ml(e,t,o),s,$o(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+ot(i)+`
223
- `)})}function Ml(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function O_(e,t,n){let o=await N(n);return K(o,bt+e.sessionId,jn),Mt(t)&&Dl(o,e.sessionId),A}function T_(e,t){return dn(t,e.sessionId,{session_id:e.sessionId,worktree:t.worktree,agent:e.agent,kind:"cost",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:0,body:"",turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),Promise.resolve(A)}var Hl={stdout:"",exitCode:0};function R_(e){return Ce.includes(e)}function pn(e){process.exitCode=e.exitCode,e.stdout!==""&&fr(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
224
- `)}function Ul(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
225
- `);try{return Ie(r,e,n,o),nt(e,t,o)}catch{return Hl}}async function A_(e,t){let n=e.indexOf(Ot),o=n>=0?e[n+1]??"":"";if(!R_(o))return console.error("hooks: unknown "+Ot+" "+JSON.stringify(o)+". Fix: pass "+Ot+" with one of "+Ce.join(", ")+"."),pn(Hl);let r;try{r=JSON.parse(await dr())}catch(s){return pn(Ul(o,void 0,"stdin",s,t))}try{return pn(await Cl(o,r,t))}catch(s){return pn(Ul(o,r,"load",s,t))}}A_(process.argv.slice(2),process.env);export{A_ as main};
212
+ `)}}var eu=!1;function at(e,t){if(!(eu||e[Os]!==t))throw eu=!0,new Error("injected fault at "+t)}function nu(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=He.split(".");for(let o=0;o<n.length;o++){let r=Number(t[o]??0)||0,s=Number(n[o]);if(r!==s)return r<s}return!1}function se(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function S_(e,t){let n=t.toLowerCase();return se(e.nativeTools.shell,n)||se(je.shell,n)?"shell":se(e.nativeTools.read,n)||se(je.read,n)?"read":se(e.nativeTools.grep,n)||se(je.grep,n)?"grep":se(e.nativeTools.webfetch,n)||se(je.fetch,n)?"fetch":null}function b_(e,t){let n=t.toLowerCase();return bs.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function O_(e){try{let t=hr.statSync(e);return t.isFile()&&t.size>ie}catch{return!1}}function T_(e,t,n){if((t.offset??null)!==null||(t.limit??null)!==null)return!1;let o=Array.isArray(t[he])?t[he].filter(r=>typeof r=="string"):[];return[bn(t,me),...o].some(r=>r!==""&&O_(mr(n,r))&&!cn(e,mr(n,r))&&!De(e,mr(n,r)))}function lt(e,t,n,o=""){let r=le(e),s=()=>r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"});try{if(!br(t)||!b_(r,bn(t,ms)))return s();let i=bn(t,gs);if(i===""||i.includes(yt))return s();let c=S_(r,i);if(c===null)return s();let l=bn(t,Ss)||o;if(c==="read"&&!T_(e,g_(t),l))return s();let a=c==="read"?Gn.read:Gn[c],d=D(a,r.toolNamePrefix)+`
213
+ `+Ts(tu(n),r.toolNamePrefix);return r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:l,turn:0},{kind:"deny",reason:d})}catch{return{stdout:"",exitCode:0}}}var{read:R_,writeSync:A_}=process.getBuiltinModule("node:fs"),ou=65536;function y_(e){let t=Buffer.allocUnsafe(ou);return new Promise(n=>{let o=()=>{R_(0,t,0,ou,null,(r,s)=>{if(r)return n(r.code==="EOF");if(s===0)return n(!0);e.push(Buffer.from(t.subarray(0,s))),o()})};o()})}async function Or(){let e=[];if(!await y_(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function Tr(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=A_(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{lstatSync:N_,readFileSync:I_}=process.getBuiltinModule("node:fs"),A={kind:"allow"},D_={stdout:"",exitCode:0},L_=48;function w_(e){return Me.includes(e)}function ut(e){return e instanceof Error?e.message:String(e)}function dt(e){return typeof e=="string"?e:""}async function au(e,t,n){if(!w_(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
214
+ `),D_;let o=le(e),r=(a,d,u)=>(Pe(n,e,a,d),process.stderr.write(u??"hooks: "+a+" failed: "+ut(d)+`
215
+ `),lt(e,t,d));if(nu(process.version))return r("node",new T("NODE_TOO_OLD",{v:process.version}));let s;try{at(n,"decode"),s=o.decode(t)}catch(a){return r("decode",a)}if(s.event==="Stop")return o.encode(s,A);let i;try{at(n,"project");let a=e==="vscode"?[bt,s.cwd]:process.argv;i=sl(e,{env:n,argv:a,cwd:s.cwd,piCwd:e==="pi"?s.cwd:void 0})}catch(a){return r("project",a,"hooks: no project: "+String(a.code??"ERROR")+" "+ut(a)+`
216
+ `)}let c,l={};try{at(n,"policy"),c=await P_(s,o,i,n,l)}catch(a){return r("store",a)}try{at(n,"encode");let a=o.encode(s,c);return l.run?.(!0),a}catch(a){return l.run?.(!1),r("encode",a)}}function P_(e,t,n,o,r){switch(e.event){case"SessionStart":return M_(e,t,n);case"UserPromptSubmit":return U_(e,t,n);case"PreToolUse":return X_(e,t,n,o);case"PostToolUse":return V_(e,t,n,o,r);case"PreCompact":return sE(e,t,n);case"Usage":return iE(e,n)}return Promise.resolve(A)}function lu(e,t){return e.split(Rs).join(t.toolNamePrefix)}function Ar(e,t,n){return n.compactSummary==="host"?D(Wr,n.toolNamePrefix):Pl(nr(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function M_(e,t,n){if(e.source==="compact"&&Xt(t)&&uu(await N(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await N(n);return Sn(r,e.sessionId,Yn)?{kind:"hint",text:Ar(r,e,t),onceKey:Yn}:A}let o=await N(n);return t.compactDelivery==="opencode-cache"&&xn(o,Nt+e.sessionId)!==null?{kind:"hint",text:Ar(o,e,t),onceKey:qn}:Sn(o,e.sessionId,Be)?{kind:"hint",text:lu(Zn,t),onceKey:Be}:A}async function U_(e,t,n){let o=e.prompt??"",r=await H_(e,t,n);if(hn(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:"prompt",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(o),body:o,turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),B_(e,n,o),t.compactDelivery==="pending-flag"){let s=await N(n);if(xn(s,Nt+e.sessionId)!==null)return{kind:"hint",text:Ar(s,e,t),onceKey:qn}}return r!==null?r:j_(e,t,n,o)}async function H_(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await N(n);return _l(o,e.sessionId)||!Sn(o,e.sessionId,Be)||!pl(o,n.worktree,e.agent)?null:{kind:"hint",text:lu(Zn,t),onceKey:Be}}function uu(e,t){t!==""&&z(e,Jn+t,zn)}function F_(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function v_(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}async function j_(e,t,n,o){if(!Xt(t)||e.sessionId==="")return A;let r=await N(n);if(ne(r,Jn+e.sessionId)===null)return A;let s=zs+e.sessionId,i=F_(ne(r,s)),c=Ks+e.sessionId,l=v_(ne(r,c)),a=Nl(r,e.sessionId,yl(o),qs),d=wl(xl(r,e.sessionId,n.worktree,Xs),o,new Set(i),a,new Set(l));return d.text===""?A:(d.seqs.length>0&&z(r,s,JSON.stringify([...i,...d.seqs])),d.units!==void 0&&z(r,c,JSON.stringify([...l,...d.units])),{kind:"hint",text:d.text,onceKey:Vs})}function du(e){return kt+":"+Dt+":"+e}function G_(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;let{seq:n,labels:o}=t;return typeof n!="number"||!Array.isArray(o)?null:{seq:n,labels:o.filter(r=>typeof r=="string")}}catch{return null}}function B_(e,t,n){if(e.sessionId==="")return;let o=du(e.sessionId);N(t).then(r=>{if(ne(r,o)===null)return;let s=xn(r,o),i=s===null?null:G_(s);if(i===null)return;let c=Zl(n,i.labels,i.seq);c!==null&&fu(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+ut(r)+`
217
+ `)})}function fu(e,t,n,o){for(let r of o)pn(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:eo,key:r.key,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(r.body),body:r.body,turn:t.turn??0,sandbox_bytes:0,returned_bytes:0}),gr(e,n,t.sessionId,kt,r.body,"text")}function W_(e,t,n,o){let r=$l(o),s=r.length===0?Ql(n.input):[];r.length===0&&s.length===0||N(t).then(i=>{if(r.length>0)return fu(i,e,t,r);let c=nr(i,e.sessionId,"prompt"),l=c[c.length-1];l===void 0||e.sessionId===""||z(i,du(e.sessionId),JSON.stringify({seq:l.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+ut(i)+`
218
+ `)})}async function X_(e,t,n,o){let r=Ca(n.worktree,e.agent),s=Ja(e,t,r,n),i=s;if(s.kind==="deny"&&Ie(e)&&!xu(s.reason,t)){let c=jo(e,{projectDir:n.worktree,env:o}),l=vo(e,c),a=e.tool,d=c!==null||(e.agentType??"")!==""&&Se(t);l==="B"&&a!==void 0&&Nr(a,t)?i=K_(e,t,s,r):l!=="A"&&d&&(i=A)}return i}function Nr(e,t){return e.canonicalName===Gs||t.nativeTools.shell.includes(e.name)}function xu(e,t){return e.startsWith(ve)||e===D(Tt,t.toolNamePrefix)||e===D(Rt,t.toolNamePrefix)}function Rr(e){return Buffer.from(e,"utf8").toString("base64url")}function K_(e,t,n,o){let r=e.tool;if(r===void 0||!Nr(r,t)||xu(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+iu(C_(process.argv[1]??""),$s)+'"',c=[Qs,i,Rr(s),Rr(JSON.stringify(o??[])),Rr(dt(r.input.description))].join(" ");return{kind:"deny",reason:Zs,rewritten:c}}function Y_(e,t,n){return n?"toolerr":Bs.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":Nr(e,t)?"cmd":null}function yr(e){if(Array.isArray(e))return"["+e.map(yr).join(",")+"]";if(typeof e=="object"&&e!==null){let t=e;return"{"+Object.keys(t).filter(o=>t[o]!==void 0).sort().map(o=>JSON.stringify(o)+":"+yr(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function q_(e){let t=e.indexOf(`
219
+ `),n=t<0?e:e.slice(0,t);if(!n.startsWith(Kn))return null;let o=0,r=0;for(let s of n.slice(Kn.length)){let i=s.charCodeAt(0)-L_;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function z_(e){for(let t of Ws)if(typeof e[t]=="string")return e[t];return null}async function V_(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(yt))return A;let i=e.result??{isError:!1,bytes:0},c=tE(i,e.sessionId,o);i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(c)),s.canonicalName===eo&&W_(e,n,s,c);let l=Y_(s,t,i.isError),a=f=>{if(l===null)return;let x=l==="cmd"?dl(s.canonicalName,dt(s.input.command)):l==="toolerr"?s.canonicalName+":"+yr(s.input):null;hn(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:l,tool:s.canonicalName,key:x,path:z_(s.input),ok:i.isError?0:1,exit_code:q_(c),bytes:i.bytes,body:c,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:f})},d;try{d=await $_(e,t,n,o,s,i,c)}catch(f){throw a(i.bytes),f}let u=d;return r.run=f=>a(f&&u.kind==="replace"?Buffer.byteLength(u.output):i.bytes),d}function J_(e,t,n){if(!yn.includes(t.canonicalName))return!1;let o=me.map(r=>t.input[r]).find(r=>typeof r=="string"&&r!=="");return o!==void 0&&De(e.agent,cu(e.cwd,o),n)}async function $_(e,t,n,o,r,s,i){if(s.bytes<=wr||Q_(r)||J_(e,r,o)||s.keep===!0||!Se(t))return A;let c;if(Ie(e)){if(vo(e,jo(e,{projectDir:n.worktree,env:o}))==="A")return A;c=Js+r.canonicalName+":"+String(e.turn??0)}else c=oE(r,e);let l=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url].map(dt).find(_=>_.trim()!=="")??"",a=mn(i,"text",Hr),d=await N(n),u;s.bytes<=Lr?(u=gr(d,n,e.sessionId,c,i,"text",a).sourceId,ir(d,u,e.sessionId,cr(i))):(u=rr(d,pu(n,e.sessionId,c),a),rE(n,e.sessionId,u,c,i,a));let f=Al(u),x=await nE(n,e.sessionId),p=x.trim()===""?void 0:l+" "+x,g=Fr(l,f,s.bytes,t.toolNamePrefix,Vl(l,x,i)),E=Z_(g,_r(l,c)),h=Xl(i,p??l,Ur);if(h!==null)return{kind:"replace",output:su(h,g)};let S=jl(a,l,E,c,p);return{kind:"replace",output:S.more!==null?su(S.text,g):S.text}}function Q_(e){return yn.includes(e.canonicalName)&&Pr.some(t=>e.input[t]!==void 0&&e.input[t]!==null)}function su(e,t){return e===""?t:e+`
220
+ `+t}function Z_(e,t){return Math.max(0,Mr+Buffer.byteLength(`
221
+ `+t)-1-Buffer.byteLength(e))}function eE(e,t,n){if(t===""||t.includes(ru)||t.includes("/"))return!1;let o=iu(Y(n,U(n)??""),St),r=k_(o,cu(e)).split(ru);if(r.length!==4||r.includes("..")||r.includes("")||r[1]!==t||r[2]!==oi)return!1;let s=N_(e);return s.isFile()&&s.size<=ri&&Ga(o,e)}function tE(e,t,n){let o=e.text??"";if(e.persistedPath===void 0)return o;try{return eE(e.persistedPath,t,n)?I_(e.persistedPath,"utf8"):(Pe(n,"claude-code","persisted-output",new Error("persisted output path is outside this session's tool-results dir or too large; kept the head")),o)}catch{return o}}async function nE(e,t){try{return fl(await N(e),t)}catch{return""}}function oE(e,t){let n=dt(e.input.command)??dt(e.input.file_path)??"",o=n.indexOf(`
222
+ `);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,Zr)+"#"+(e.callId??String(t.turn??0))}function rE(e,t,n,o,r,s){N(e).then(i=>{Ol(i,n,pu(e,t,o),s,cr(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+ut(i)+`
223
+ `)})}function pu(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function sE(e,t,n){let o=await N(n);return z(o,Nt+e.sessionId,zn),Xt(t)&&uu(o,e.sessionId),A}function iE(e,t){return hn(t,e.sessionId,{session_id:e.sessionId,worktree:t.worktree,agent:e.agent,kind:"cost",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:0,body:"",turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),Promise.resolve(A)}var Eu={stdout:"",exitCode:0};function cE(e){return Me.includes(e)}function On(e){process.exitCode=e.exitCode,e.stdout!==""&&Tr(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
224
+ `)}function _u(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
225
+ `);try{return Pe(r,e,n,o),lt(e,t,o)}catch{return Eu}}async function aE(e,t){let n=e.indexOf(Ct),o=n>=0?e[n+1]??"":"";if(!cE(o))return console.error("hooks: unknown "+Ct+" "+JSON.stringify(o)+". Fix: pass "+Ct+" with one of "+Me.join(", ")+"."),On(Eu);let r;try{r=JSON.parse(await Or())}catch(s){return On(_u(o,void 0,"stdin",s,t))}try{return On(await au(o,r,t))}catch(s){return On(_u(o,r,"load",s,t))}}aE(process.argv.slice(2),process.env);export{aE as main};