context-mode 2.1.2 → 2.1.4

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,42 +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 Te=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode"];var K="context-mode",ot=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 ot)n=n.split(o).join(t+o);return n}var q=16384;var tr=2048;var nr=640,ln="</context_mode_state>",un=1048576,or=65536,rr=4096,sr=96,ir=256,cr=48;function ar(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 lr=3,ne=4096;var dn=85,fn=340,xn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var ur=.7,dr=.7,fr=.3,pn=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]),xr='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var nl=6e5;var ue=5e3,rt="-wal",st="-shm",pr=".tmp",_r=255,Er=11,gr=26;var U=5e3;var _n=0;var mr=16,Ae=6;var hr="projects",Sr="context.db";var En=".git",gn="worktree ",mn="gitdir: ",br="commondir",Or="HEAD",it="--workspace-folder",Rp=Object.freeze(["shell","powershell","javascript","typescript","python"]);var Tr=80;var Ap=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var Np=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),Ne="24.15.0",ct="~/.context-mode";var Rr="CONTEXT_MODE_REQUIRE_SECURITY",Ar=".claude",at="agents",lt=".md",hn="plugins",Nr="installed_plugins.json",de=":",yr="@";var yp=Object.freeze(["local","project"]),Ip=Object.freeze({local:0,project:1,user:2,managed:2}),Sn="---",Ir="tools",Cr="disallowedTools",bn="mcp__",On="__",kr="mcp_",Dr="_-.:",er=10;function ol(e){if(e===void 0||e.trim()==="")return er;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:er}var Cp=ol(process.env.CTX_MCP_HINT_EVERY);var H=32;var Tn="context-mode: ",Lr=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),wr=" sends its body into the conversation.",Pr="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",Mr="Tool: ",Ur="state what you need",Hr="ctx_execute",Fr=Object.freeze(["ctx_index","ctx_search"]),ye="Blocked by security policy: matches deny pattern ",ut="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",dt="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",vr="hook-errors.log";var jr=Object.freeze(["tool_name","toolName","tool"]),Gr=Object.freeze(["hook_event_name","hookEventName","type"]),Br=Object.freeze(["tool_input","toolArgs","input","args"]),Wr=Object.freeze(["cwd","directory"]),Xr=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),Kr="CM_HOOK_FAULT",kp=Object.freeze(["decode","project","policy","store","encode"]),Ie=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 qr(e,t){return`${Tn}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var Rn=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 Dp=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),Lp=Object.freeze(["status"]),wp=Object.freeze(["--version","-v"]),Pp=Object.freeze(["cp","mv","rm"]),Mp=Object.freeze(["-v","--verbose"]),D=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),Yr="{prefix}",Vr=", then ",zr="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",Jr=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),$r=Object.freeze(["curl","wget"]),Qr=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),Zr=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),es="-D",ts=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),Ce="fetch(",ns="'\"`",os="http",rs=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),ss=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),is=Object.freeze(["head","tail"]),An=Object.freeze(["-n","-c","--lines","--bytes"]),ft="sed",cs=Object.freeze(["-n","--quiet","--silent"]),as="jq",xt=Object.freeze(["file_path","absolute_path","path"]),pt="ctx_",ls="Bash",us=Object.freeze(["Write","Edit"]),ds=Object.freeze(["file_path","path"]),Nn="Exit code ",ke="resume-hint",yn="compact-state",In="pending-compact",_t="pending_compact:",Cn="1",kn=2048,Dn=5,fs=340,Ln="compacted:",xs="recall_units_seen:",ps=64,_s="recall_seen:",wn="<context_mode_recall>",Pn="</context_mode_recall>",Es="recall",Mn="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",gs="subagent:",ms="run.mjs",hs="node",Ss=`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.`,Et="--agent",bs=1e3;var Up=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var Hp=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."]),Fp=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),vp=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 jp=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),Gp=Object.freeze(["ctx_index","ctx_search"]);var Bp=Object.freeze(["session","source","project"]);var gt="decision";var Un="AskUserQuestion",Os="answers",mt="option",Ts=" | ",rl="https://github.com/mksglu/context-mode.git";var Wp=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),Xp=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 Hn=256;var sl="ctx_doctor:report";var Kp=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(sl)}})`;var qp=Object.freeze(["--tags","--refs"]),il="v*";var Yp=`git ls-remote --tags --refs ${rl} "${il}"`;var Vp=`install Node ${Ne} or later`;var zp=Object.freeze(["MCP entry","hook entries","hook timeout"]);var Rs=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 Jp=Object.freeze(["upgrade","uninstall"]);var $p=Object.freeze(["clone","--depth","1","--branch"]),Qp=Object.freeze(["rev-parse","HEAD"]);var Zp=Object.freeze(["pi","opencode"]);var e_=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),t_=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var n_=Object.freeze(["shell","bash","sh"]),o_=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var r_=Object.freeze(["doctor-env.ts","doctor-config.ts","doctor-hook.ts","doctor-db.ts","doctor-heal.ts","release-fetch.ts","verify-sums.ts","plugin-swap.ts","host-write.ts","v1-remove.ts","uninstall.ts"]);var s_=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}),i_=Object.freeze(["PreToolUse","PostToolUse"]);var c_=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var a_=Object.freeze(["features","hooks"]);var l_=Object.freeze(["",rt,st]);var u_=Object.freeze({"claude-code":"claude plugin marketplace update context-mode && claude plugin update context-mode@context-mode",codex:"rewrite config.toml's [mcp_servers.context-mode*] block to the v2 entry, then restart Codex",gemini:"gemini extensions install https://github.com/mksglu/context-mode --auto-update",qwen:"qwen extensions install https://github.com/mksglu/context-mode --auto-update"});var d_=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 f_=Object.freeze(["hooks","codex"]);var x_=Object.freeze([".mjs",".sh"]);var ht="CLAUDE_CONFIG_DIR";var cl=Object.freeze(["Code","User"]);var al="mcp.json",p_=Object.freeze(["agents","default.json"]);var __=Object.freeze(["steering","KIRO.md"]);var E_=Object.freeze(["opencode.jsonc","opencode.json"]);var g_=`${K}@`;var m_=Object.freeze(["content","platform.json"]);var As="custom";var ll=Object.freeze(["/","\\"]),ul="${/}",h_=Object.freeze([...ll,ul]),Re=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",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"}),S_=Object.freeze([Re.statusLine,Re.vscodeMcp,Re.dataDirShared,Re.tmpFile,Re.kiroSteering]);var b_=K+"_";var O_=Object.freeze(["opencode","plugin.js"]);var dl=Object.freeze(["features","mcp"]),fl="omit_tools_from",xl=Object.freeze(["deferred"]),pl="default_tools_approval_mode",_l="approve",T_=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",K],fields:{[fl]:xl,[pl]:_l}},vscode:{file:[al],key:["servers",K]},kiro:{file:[".kiro","settings","mcp.json"],key:["mcpServers",K]},zcode:{file:[".zcode","cli","config.json"],key:["mcp","servers",K],fields:{type:"stdio",enabled:!0,timeoutMs:nl},also:[[dl,!0]]}});var R_=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),El="Environment: ";var gl="Docs: ";var ml="Report file: ",hl="File it: ",Sl="Or open: ",bl="Rules: ",Ol=" --",A_=Object.freeze([El,gl,ml,hl,Ol.trim(),Sl,bl]),Ns="mksglu/context-mode",Tl="agent-report.yml",N_=`https://github.com/${Ns}/blob/main/.github/AGENT_ISSUE.md`,y_=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 I_=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var C_=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"]),k_=Object.freeze(["node","git","sh"]),D_=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var L_=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:["npm i -g context-mode","context-mode setup --agents zcode"]}),w_=`https://github.com/${Ns}/issues/new?template=${Tl}`;import{dirname as qx,join as Yx}from"node:path";var Fn="mcp__plugin_context-mode_context-mode__",ks=Object.freeze(["Bash","PowerShell"]),Rl="PowerShell",Al="Bash",Nl=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],ys="mcp__",Is="__",yl={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function Il(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(ys))return e;let n=e.slice(ys.length),o=n.indexOf(Is);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+Is.length)}function Cl(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return Ds(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:kl(n.file,o)})}:Ll(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 Ce=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode"];var z="context-mode",at=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 at)n=n.split(o).join(t+o);return n}var V=16384;var fr=2048;var xr=640,pn="</context_mode_state>",_n=1048576,pr=65536,_r=4096,Er=Object.freeze(["Read","view"]),gr=Object.freeze(["offset","limit","view_range"]),mr=96,hr=256,Sr=48;function br(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 Or=3,re=4096;var En=85,gn=340,mn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var Tr=.7,Rr=.7,Ar=.3,hn=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]),Nr='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var kl=6e5;var J=5e3,lt="-wal",ut="-shm",yr=".tmp",Ir=255,Cr=11,kr=26;var F=5e3;var Sn=0;var Dr=16,ke=6;var dt="projects",Lr="context.db";var bn=".git",On="worktree ",Tn="gitdir: ",wr="commondir",Pr="HEAD",ft="--workspace-folder",x_=Object.freeze(["shell","powershell","javascript","typescript","python"]),Mr=Object.freeze(["sh","bash","zsh","dash","ksh","fish"]);var Ur=80;var p_=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var __=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),De="24.15.0",Hr="~/.context-mode",Le="CONTEXT_MODE_DATA_DIR";var Fr="CONTEXT_MODE_REQUIRE_SECURITY",vr=".claude",xt="agents",pt=".md",Rn="plugins",jr="installed_plugins.json",xe=":",Gr="@";var E_=Object.freeze(["local","project"]),g_=Object.freeze({local:0,project:1,user:2,managed:2}),An="---",Br="tools",Wr="disallowedTools",Nn="mcp__",yn="__",Xr="mcp_",Kr="_-.:",dr=10;function Dl(e){if(e===void 0||e.trim()==="")return dr;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:dr}var m_=Dl(process.env.CTX_MCP_HINT_EVERY);var v=32;var In="context-mode: ",Yr=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),qr=" sends its body into the conversation.",zr="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",Vr="Tool: ",Jr="state what you need",$r="ctx_execute",Qr=Object.freeze(["ctx_index","ctx_search"]),we="Blocked by security policy: matches deny pattern ",_t="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",Et="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",Cn="hook-errors.log";var Zr=Object.freeze(["tool_name","toolName","tool"]),es=Object.freeze(["hook_event_name","hookEventName","type"]),ts=Object.freeze(["tool_input","toolArgs","input","args"]),ns=Object.freeze(["cwd","directory"]),os=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),rs="CM_HOOK_FAULT",h_=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 ss(e,t){return`${In}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var kn=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 S_=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),b_=Object.freeze(["status"]),O_=Object.freeze(["--version","-v"]),T_=Object.freeze(["cp","mv","rm"]),R_=Object.freeze(["-v","--verbose"]),D=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),is="{prefix}",cs=", then ",as="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",ls=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),us=Object.freeze(["curl","wget"]),ds=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),fs=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),xs="-D",ps=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),Me="fetch(",_s="'\"`",Es="http",gs=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),ms=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),hs=Object.freeze(["head","tail"]),Dn=Object.freeze(["-n","-c","--lines","--bytes"]),gt="sed",Ss=Object.freeze(["-n","--quiet","--silent"]),bs="jq",mt=Object.freeze(["file_path","absolute_path","path","filePath"]),pe="filePaths",ht="ctx_",Os="Bash",Ts=Object.freeze(["Write","Edit"]),Rs=Object.freeze(["file_path","path"]),Ln="Exit code ",Ue="resume-hint",wn="compact-state",Pn="pending-compact",St="pending_compact:",Mn="1",He=2048,Un=5,As=340,Hn="compacted:",Ns="recall_units_seen:",ys=8,Is=64,Cs="recall_seen:",Fn="<context_mode_recall>",vn="</context_mode_recall>",ks="recall",jn="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",Ds="subagent:",Ls="run.mjs",ws="node",Ps=`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.`,bt="--agent",Ms=1e3;var A_=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var N_=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."]),y_=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),I_=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 C_=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),k_=Object.freeze(["ctx_index","ctx_search"]);var D_=Object.freeze(["session","source","project"]);var Ot="decision";var Gn="AskUserQuestion",Us="answers",Tt="option",Hs=" | ",Ll="https://github.com/mksglu/context-mode.git";var L_=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),w_=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 Bn=256;var wl="ctx_doctor:report";var P_=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(wl)}})`;var M_=Object.freeze(["--tags","--refs"]),Pl="v*";var U_=`git ls-remote --tags --refs ${Ll} "${Pl}"`;var H_=`install Node ${De} or later`;var F_=Object.freeze(["MCP entry","hook entries","hook timeout"]);var Fs=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 v_=Object.freeze(["upgrade","uninstall"]);var j_=Object.freeze(["clone","--depth","1","--branch"]),G_=Object.freeze(["rev-parse","HEAD"]);var B_=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),W_=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var X_=Object.freeze(["shell","bash","sh"]),K_=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var vs="tool-results",js=16*1024*1024;var Y_=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 q_=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}),z_=Object.freeze(["PreToolUse","PostToolUse"]);var V_=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var J_=Object.freeze(["features","hooks"]);var $_=Object.freeze(["",lt,ut]);var Q_=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 Z_=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 eE=Object.freeze(["hooks","codex"]);var tE=Object.freeze([".mjs",".sh"]);var Ml="npm:context-mode";var Rt="CLAUDE_CONFIG_DIR";var Ul=Object.freeze(["Code","User"]);var Hl="mcp.json",nE=Object.freeze(["agents","default.json"]);var oE=Object.freeze(["steering","KIRO.md"]);var rE=Object.freeze(["opencode.jsonc","opencode.json"]);var Fl=`${z}@`,vl="@",sE=`${Fl}latest`,iE=`${Ml}${vl}latest`;var cE=Object.freeze(["content","platform.json"]);var Gs="custom";var jl=Object.freeze(["/","\\"]),Gl="${/}",aE=Object.freeze([...jl,Gl]),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"}),lE=Object.freeze([L.statusLine,L.vscodeMcp,L.dataDirShared,L.tmpFile,L.kiroSteering,L.piGit,L.opencodeGit,L.projectLink]),uE=Object.freeze([L.dataDir,L.dataRoot]);var dE=z+"_";var fE=Object.freeze(["opencode","plugin.js"]);var Bl=Object.freeze(["features","mcp"]),Wl="omit_tools_from",Xl=Object.freeze(["deferred"]),Kl="default_tools_approval_mode",Yl="approve",xE=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",z],fields:{[Wl]:Xl,[Kl]:Yl}},vscode:{file:[Hl],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:kl},also:[[Bl,!0]]}});var pE=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),ql="Environment: ";var zl="Docs: ";var Vl="Report file: ",Jl="File it: ",$l="Or open: ",Ql="Rules: ",Zl=" --",_E=Object.freeze([ql,zl,Vl,Jl,Zl.trim(),$l,Ql]),Bs="mksglu/context-mode",eu="agent-report.yml",EE=`https://github.com/${Bs}/blob/main/.github/AGENT_ISSUE.md`,gE=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 mE=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var hE=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"]),SE=Object.freeze(["node","git","sh"]),bE=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var OE=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"]}),TE=`https://github.com/${Bs}/issues/new?template=${eu}`;import{dirname as Lp,join as Sl,relative as wp,resolve as Pp,sep as ml}from"node:path";var Wn="mcp__plugin_context-mode_context-mode__",Ys=Object.freeze(["Bash","PowerShell"]),tu="PowerShell",nu="Bash",ou=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],Ws="mcp__",Xs="__",ru={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function su(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(Ws))return e;let n=e.slice(Ws.length),o=n.indexOf(Xs);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+Xs.length)}function iu(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return qs(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=Xn(e);if(t!==null)return t.text}return JSON.stringify(e)}function Xn(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:cu(n.file,o)})}:lu(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 kl(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 cu(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=Dl(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 Dl(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 Cs(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function Ll(e){let t=e;return(t.mode==="content"||t.mode==="count")&&typeof t.content=="string"}function Ds(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 wl(e){let t=Cl(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)&&Cs(e)&&(o.shape=e),typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Cs(e)&&(vn(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,Ds(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 oe(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=Nl.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??""),a=typeof r.tool_input=="object"&&r.tool_input!==null?r.tool_input:{},l={name:c,canonicalName:Il(c,n),input:a};typeof r.tool_use_id=="string"&&r.tool_use_id!==""&&(l.callId=r.tool_use_id),i.tool=l}return s==="PostToolUse"&&(i.result=wl(r.tool_response)),i}function Pl(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 F(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:Pl(e,t.output)}):{stdout:"",exitCode:0}}}var Ml={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function Ul(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 Hl(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 Ml[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function Ls(e){Hl(e);let t=oe(e,"claude-code",Fn,yl);if(t.tool!==void 0&&t.tool.name===Rl&&(t.tool.canonicalName=Al),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"+Ul(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function ws(e,t,n){return F(e,t,!0)}var jn="mcp__context_mode__",vl={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"};function Ps(e){return oe(e,"codex",jn,vl)}function Ms(e,t,n){return F(e,t,!1)}var bt="mcp_context-mode_",Us={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},Hs={startup:"startup",resume:"resume",clear:"clear"},Gl=["SessionStart","UserPromptSubmit","PostToolUse"],Bl=["UserPromptSubmit","PreToolUse"],St={stdout:"",exitCode:0};function y(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var Fs={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function Wl(e,t){if(e.startsWith(bt))return e.slice(bt.length);if(Object.hasOwn(Fs,e))return Fs[e];if(typeof t!="object"||t===null)return e;let n=t,o=y(n,"server_name"),r=y(n,"tool_name");return typeof o!="string"||typeof r!="string"?e:"mcp:"+o+":"+r}function Xl(e){let t=typeof e=="object"&&e!==null?e:void 0,n=t===void 0?void 0:y(t,"llmContent"),o=e===void 0?"":typeof e=="string"?e:typeof n=="string"?n:JSON.stringify(e),r=t===void 0?void 0:y(t,"error");return{isError:r!=null,bytes:Buffer.byteLength(o),text:o}}function vs(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=y(t,"hook_event_name"),o=typeof n=="string"&&Object.hasOwn(Us,n)?Us[n]:void 0;if(o===void 0)throw new Error("gemini: unknown hook event "+String(n));let r={event:o,agent:"gemini",sessionId:String(y(t,"session_id")??""),cwd:String(y(t,"cwd")??"")},s=y(t,"source");o==="SessionStart"&&typeof s=="string"&&Object.hasOwn(Hs,s)&&(r.source=Hs[s]);let i=y(t,"prompt");if(o==="UserPromptSubmit"&&typeof i=="string"&&(r.prompt=i),o==="PreToolUse"||o==="PostToolUse"){let c=String(y(t,"tool_name")??""),a=y(t,"tool_input");r.tool={name:c,canonicalName:Wl(c,y(t,"mcp_context")),input:typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{}}}return o==="PostToolUse"&&(r.result=Xl(y(t,"tool_response"))),r}function js(e,t,n){switch(t.kind){case"allow":return St;case"hint":return Gl.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:St;case"deny":return Bl.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
12
- `+t.reason}),exitCode:0}:St;case"replace":return e.event!=="PostToolUse"?St:{stdout:JSON.stringify({decision:"deny",reason:t.output}),exitCode:0}}}var Gn="mcp__context-mode__",ql={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Gs={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},Yl="PostToolUseFailure";function Bs(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===Yl,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=oe(n,"qwen",Gn,ql);if(o.tool!==void 0&&Object.hasOwn(Gs,o.tool.name)&&(o.tool.canonicalName=Gs[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 Ws(e,t,n){return F(e,t,!1)}var Tt="context-mode-",zl={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}},Xs={startup:"startup",resume:"resume",new:"startup"},Jl={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"}},qs="success";function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Bn=Object.freeze(["bash","powershell"]),Ks=Object.fromEntries(Bn.map(e=>[e,"Bash"]));function $l(e){return e.startsWith(Tt)?e.slice(Tt.length):Object.hasOwn(Ks,e)?Ks[e]:e}function Ql(e){if(Rt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Rt(t)?t:{}}catch{return{}}}var Zl={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function eu(e,t,n){let o=Zl[t],r=Rt(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==qs,bytes:Buffer.byteLength(s),text:s}}var tu=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function nu(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:tu.find(([t])=>Object.hasOwn(e,t))?.[1]}function Ys(e){if(!Rt(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=nu(e),n=typeof t=="string"?zl[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Jl[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"&&Xs[e.source]!==void 0&&(s.source=Xs[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:$l(i),input:Ql(e[o.args])};s.tool=c}return r==="PostToolUse"&&(s.result=eu(e[o.result],n.casing,n.failure)),s}var Ot={stdout:"",exitCode:0};function Vs(e,t,n){switch(t.kind){case"allow":return Ot;case"hint":return e.event==="PostToolUse"?Ot:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?Ot:{stdout:JSON.stringify({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
13
- `+t.reason}),exitCode:0};case"replace":return e.event!=="PostToolUse"?Ot:{stdout:JSON.stringify({modifiedResult:{resultType:qs,textResultForLlm:t.output}}),exitCode:0}}}var At="mcp_context-mode_",ei=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],zs="mcp_",Js="_",ru="new",Wn=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),yt=Object.freeze(["read_file","view"]),Xn=Object.freeze(["fetch_webpage","web_fetch"]),$s=Object.fromEntries([...Wn.map(e=>[e,"Bash"]),...yt.map(e=>[e,"Read"]),...Xn.map(e=>[e,"WebFetch"])]);function ti(e){if(e.startsWith(At))return e.slice(At.length);if(Object.hasOwn($s,e))return $s[e];if(!e.startsWith(zs))return e;let t=e.slice(zs.length),n=t.indexOf(Js);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+Js.length)}var De=e=>typeof e=="number"&&Number.isFinite(e);function ni(e,t,n){if(t==="Read"&&yt.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),De(n.startLine)&&(o.offset=n.startLine),De(n.startLine)&&De(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&De(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];De(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 su(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 iu={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},cu=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],Qs={new:"startup",startup:"startup",resume:"resume"},au="success";function Nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lu(e){if(Nt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Nt(t)?t:{}}catch{return{}}}function uu(e){let t=Nt(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==au,bytes:Buffer.byteLength(n),text:n}}function Zs(e,t){let n=typeof t=="string"?iu[t]??ei.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"&&Qs[e.source]!==void 0&&(o.source=Qs[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=ti(r);o.tool={name:r,canonicalName:s,input:ni(r,s,lu(e.toolArgs))}}return n==="PostToolUse"&&(o.result=uu(e.toolResult)),o}function oi(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 Zs(t,t.hookEventName);if(t.hook_event_name===void 0){let r=cu.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return Zs(t,r)}let n=ei.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===ru&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=Nt(t.tool_input)?t.tool_input:{},i=ti(r);o.tool={name:r,canonicalName:i,input:ni(r,i,s)}}return n==="PostToolUse"&&(o.result=su(t.tool_response)),o}function ri(e,t,n){return F(e,t,!1)}var It="mcp_context_mode_",si="mcp_context-mode_",ii={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},fu="prompt",xu="USER_PROMPT",ci="mcp_",Kn=Object.freeze(["execute_bash","execute_pwsh","shell"]),ai=Object.fromEntries(Kn.map(e=>[e,"Bash"])),li="_",ui={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function pu(e){if(e.startsWith(It))return e.slice(It.length);if(e.startsWith(si))return e.slice(si.length);if(Object.hasOwn(ai,e))return ai[e];if(!e.startsWith(ci))return e;let t=e.slice(ci.length),n=t.indexOf(li);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+li.length)}function _u(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function di(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(ii,n)?ii[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"&&ui[t.source]!==void 0&&(r.source=ui[t.source]),o==="UserPromptSubmit"){let s=t[fu],i=typeof s=="string"?s:process.env[xu];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:pu(s),input:i}}return o==="PostToolUse"&&(r.result=_u(t.tool_response)),r}function fi(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+`
14
- `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var qn="mcp__context-mode__",gu={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},mu={hook_event_name:"hookEventName",session_id:"sessionId"},hu="PostToolUseFailure";function xi(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[r,s]of Object.entries(mu))t[r]===void 0&&(t[r]=t[s]);let n=t.hook_event_name===hu;n&&(t.hook_event_name="PostToolUse");let o=oe(t,"zcode",qn,gu);if(n){let r=typeof t.error=="string"?t.error:t.error===void 0?"":JSON.stringify(t.error);o.result={isError:!0,bytes:Buffer.byteLength(r),text:r}}return o}function pi(e,t,n){return F(e,t,!1)}var gi="",_i={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},Ei={bash:"Bash",read:"Read",edit:"Edit",write:"Write"};function bu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Ou(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 mi(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(_i,n)?_i[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(Ei,s)?Ei[s]:s,input:bu(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=Ou(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Tu(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+`
15
- `+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function hi(e,t,n){let o=Tu(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:As,content:o.stdout,timestamp:Date.now()}}function Si(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var Ri="",bi=K+"_",Oi={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},Yn="bash",Au=Object.freeze([Yn,"shell"]),Ti={webfetch:"WebFetch",...Object.fromEntries(Au.map(e=>[e,"Bash"]))};function Vn(e){return e.startsWith(bi)?e.slice(bi.length):Object.prototype.hasOwnProperty.call(Ti,e)?Ti[e]:e}function Nu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function yu(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 Ai(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(Oi,n)?Oi[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:Vn(s),input:Nu(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=yu(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Ni(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+`
16
- `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var Le={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},yi={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},Cu={...yi,shell:[...ks]},ku=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:Fn,nativeTools:Cu,execReadOnlyHint:!1,eventMap:Le,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"skills"},decode:Ls,encode:ws},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:jn,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:Le,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:Ps,encode:Ms},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:bt,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:U,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:vs,encode:js},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Gn,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:Le,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:Bs,encode:Ws},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:Tt,nativeTools:{shell:[...Bn]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:Ys,encode:Vs},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:At,nativeTools:{shell:[...Wn],read:[...yt],webfetch:[...Xn]},execReadOnlyHint:!1,eventMap:{...Le,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:oi,encode:ri},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:It,nativeTools:{shell:[...Kn]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:U,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:di,encode:fi},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:qn,nativeTools:yi,execReadOnlyHint:!1,eventMap:Le,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:xi,encode:pi},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:gi,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:_n,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:mi,encode:hi,checkPermission:Si},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:Ri,nativeTools:{shell:[Yn]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:_n,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:Ai,encode:Ni,toCanonicalTool:Vn}]),Du=new Map(ku.map(e=>[e.id,e])),Lu=new Set(["claude-code","gemini","copilot-cli","pi"]);function fe(e){return Lu.has(e.id)}var wu=new Set(["claude-code","copilot-cli","pi"]);function zn(e){return wu.has(e.id)&&fe(e)}var Pu=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function Ct(e){return Pu.has(e.id)}function re(e){return Du.get(e)}import{resolve as qt}from"node:path";var Mu=["&&","||",";;","|&",";","|","&","(",")"],Uu=["&>>","&>"],Hu=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],Fu="&",vu="<<",Ii="<<-",ju=";",Ci=`\r
17
- `,ki=`\\
18
- `,Di=`\\\r
19
- `,Gu="$(",Pi="${",Mi="$'",we="((",Li="))",xe="[[",kt="]]",Jn="<(",Ui=">(",L=2,Hi=`
20
- \r;&|()<>`,Bu=`
21
- \r`,Wu='$`"\\\n',Xu="case",Ku="esac";function pe(e,t){e.end==="complete"&&(e.end=t)}function $n(e){return e!==""&&e>="0"&&e<="9"}function wi(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function Fi(e){return e===""||Hi.includes(e)}function Qn(e){return e!==""&&Bu.includes(e)}function v(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function Dt(e,t){let n=e.s.indexOf("'",t+1);return n<0?(pe(e,"unterminated-quote"),e.n):n+1}function vi(e,t){let n=t+Mi.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=L;continue}if(o==="'")return n+1;n++}return pe(e,"unterminated-quote"),e.n}function Zn(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+=L;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=Pe(e,o,n);continue}if(r==="$"&&s==="{"){o=eo(e,o,n);continue}if(r==="`"){o=_e(e,o);continue}o++}return pe(e,"unterminated-quote"),e.n}function _e(e,t){let n=t+1;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=L;continue}if(o==="`")return n+1;n++}return e.n}function eo(e,t,n){let o=t+Pi.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=L;continue}if(s==="'"){o=Dt(e,o);continue}if(s==='"'){o=Zn(e,o,n);continue}if(s==="$"&&i==="("){o=Pe(e,o,n);continue}if(s==="`"){o=_e(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+we.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(Li,o)?o+Li.length:-1;n--}o++}return-1}function Pe(e,t,n){let o=t+Gu.length-1;if(e.s.startsWith(we,o)){let r=to(e.s,o);if(r>0)return r}return Lt(e,o+1,!0,n+1,null,null)}function qu(e,t,n){let o=t+xe.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=L;continue}if(s==="'"){o=Dt(e,o);continue}if(s==='"'){o=Zn(e,o,n);continue}if(s==="$"&&i==="("){o=Pe(e,o,n);continue}if(s==="$"&&i==="{"){o=eo(e,o,n);continue}if(s==="`"){o=_e(e,o);continue}let c=Qn(e.s.charAt(o-1));if(c&&e.s.startsWith(kt,o)&&Fi(e.s.charAt(o+kt.length))){if(r===0)return o+kt.length;r--,o+=kt.length;continue}if(c&&e.s.startsWith(xe,o)&&Qn(e.s.charAt(o+xe.length))){r++,o+=xe.length;continue}o++}return-1}function Yu(e,t){let n=t;for(;$n(e.charAt(n));)n++;if(n===t){for(let o of Uu)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of Hu){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(Fu))if(e.charAt(r)==="-")r++;else for(;$n(e.charAt(r));)r++;return{end:r,op:o}}return null}function Vu(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(Hi.includes(r))break;if(r==="\\"){o+=L;continue}if(r==="'"){o=Dt(e,o);continue}if(r==='"'){o=Zn(e,o,n);continue}if(r==="$"&&s==="'"){o=vi(e,o);continue}if(r==="$"&&s==="("){o=Pe(e,o,n);continue}if(r==="$"&&s==="{"){o=eo(e,o,n);continue}if(r==="`"){o=_e(e,o);continue}o++}return Math.min(o,e.n)}function zu(e,t,n,o,r){let s=t;for(let i of n){let c=s,a=!1;for(;s<e.n;){let l=e.s.indexOf(`
22
- `,s),u=l<0?e.n:l,d=e.s.slice(s,u);if(d.endsWith("\r")&&(d=d.slice(0,-1)),s=l<0?e.n:l+1,(i.strip?d.trim():d)===i.tag){a=!0;break}}if(o!==null&&r!==null&&r.push(o.length),v(o,"unhandled",e.s.slice(c,s),c,s),!a)return pe(e,"unterminated-heredoc"),e.n}return n.length=0,s}function Lt(e,t,n,o,r,s){if(o>H)return pe(e,"too-deep"),e.n;let i=e.s,c=t,a=0,l=0,u=null,d=[];for(;c<e.n;){let f=i.charAt(c),x=i.charAt(c+1);if(f===" "||f===" "){c++;continue}if(i.startsWith(ki,c)){c+=ki.length;continue}if(i.startsWith(Di,c)){c+=Di.length;continue}if(f===`
23
- `||f==="\r"){let S=c;c+=i.startsWith(Ci,c)?Ci.length:1,v(r,"op",ju,S,c),u=null,d.length>0&&(c=zu(e,c,d,r,s));continue}if(f==="#"){for(;c<e.n&&i.charAt(c)!==`
24
- `&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(Jn,c)||i.startsWith(Ui,c)){let S=Lt(e,c+Jn.length,!0,o+1,null,null);v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}let p=Yu(i,c);if(p!==null){v(r,"io",i.slice(c,p.end),c,p.end),u=p.op===vu||p.op===Ii?p.op===Ii:null,c=p.end;continue}if(i.startsWith(xe,c)&&Qn(i.charAt(c+xe.length))){let S=qu(e,c,o);if(S>0){v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}if(i.startsWith(we,c)){let S=to(i,c);if(S>0){v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let g=Mu.find(S=>i.startsWith(S,c));if(g!==void 0){if(n&&g==="("&&a++,n&&g===")"){if(a>0)a--;else if(l===0)return c+1}v(r,"op",g,c,c+g.length),c+=g.length,u=null;continue}if(f==="$"&&x==="("||f==="`"){let S=f==="`"?_e(e,c):Pe(e,c,o);if(Fi(i.charAt(S))){v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let E=c;c=Vu(e,c,o);let h=i.slice(E,c);v(r,"word",h,E,c),u!==null&&(d.push({tag:Ee(h),strip:u}),u=null),n&&h===Xu&&l++,n&&h===Ku&&l>0&&l--}return d.length>0&&pe(e,"unterminated-heredoc"),e.n}function ji(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return Lt(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function Ee(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=L;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+Mi.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=L;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!==""&&Wu.includes(i)){t+=i,s+=L;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function wt(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+=L;continue}if(!o&&s==="'"){r=Dt(t,r);continue}if(!o&&s==="$"&&i==="'"){r=vi(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Pi.length;continue}let c=e.startsWith(Jn,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(Ui,r))){let a=r+1;if(s==="$"&&e.startsWith(we,a)&&to(e,a)>0){r=a+we.length;continue}let l=Lt(t,a+1,!0,1,null,null),u=l>a+1&&e.charAt(l-1)===")"?l-1:l;n.push({wrapper:s==="$"?"$()":c?"<()":">()",body:e.slice(a+1,u)}),r=l;continue}if(s==="`"){let a=_e(t,r),l=a>r+1&&e.charAt(a-1)==="`"?a-1:a;n.push({wrapper:"`",body:e.slice(r+1,l)}),r=a;continue}r++}return n}function Pt(e){let t=e.charAt(0);if(!(wi(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(!(wi(o)||$n(o)||o==="_"))return!1}return!1}var Xi=[";","&","&&","||"],Ki=["|","|&"],Me="(",Ue=")",qi=";;",ro=["(",")"],Ju="!",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"}),Yi=[],$u="[[",Qu="((",Vi=[">",">>",">|","&>","&>>",">&"],Zu=[...Vi,"<","<>","<<<","<<","<<-"],ed=["","1"],zi=["-","/dev/stdout","/dev/stderr"],Ut="-",He="--",Fe="=",td="/",nd=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),Mt=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),no="-c",oo="--bytes",od="c",rd="--count",se=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],Y=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,I=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,so=e=>e!==""&&e>="0"&&e<="9",sd=e=>so(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function io(e){let t=e.lastIndexOf(td);return t>=0&&t<e.length-1?e.slice(t+1):e}function co(e,t){let n=nd[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===He)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+Fe))s=r.slice(n.long.length+Fe.length);else if(r.startsWith(Ut)&&!r.startsWith(He)){let i=r.indexOf(n.short,Ut.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&&!zi.includes(s))return!0}return!1}function id(e){if(e==="")return!1;for(let t of e)if(!so(t))return!1;return!0}function cd(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===no||n===oo?o=e[t+1]:n.startsWith(oo+Fe)?o=n.slice(oo.length+Fe.length):n.startsWith(no)&&!n.startsWith(He)&&(o=n.slice(no.length)),o!==void 0)return id(o)&&Number(o)<=q}return!1}function ad(e){for(let t of e){if(t===He)return!1;if(t===rd||t.startsWith(Ut)&&!t.startsWith(He)&&t.includes(od))return!0}return!1}function Gi(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(!sd(n))return!1}return!0}function ld(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 Gi(t);let o=t.slice(0,n).trim(),r=D.pipeLength.slice(1).trim();return(o===D.identity||Gi(o))&&t.slice(n+1).trim()===r}function ud(e){let t=e.argv0.toLowerCase();if(t===Mt.wc)return!0;if(t===Mt.head)return cd(e.args);if(t===Mt.grep)return ad(e.args);if(t===Mt.jq){let n=e.args.filter(o=>!o.startsWith(Ut));return n.length===1&&ld(n[0])}return!1}function ao(e){return wt(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function Ji(e,t,n){return n<=t?[]:ao(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function $i(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function dd(e){let t=0;for(;so(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Qi(e){let t=dd(e.toks[e.i].text);if(e.i++,!Zu.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,Vi.includes(t.op)&&ed.includes(t.fd)&&!zi.includes(Ee(n.text)))}function Zi(e){let t=!1;for(;O(e)?.kind==="io";)t=Qi(e)||t;return t}function ec(e){for(;O(e)?.kind==="op"&&Xi.includes(O(e)?.text??"");)e.i++}function ge(e,t){if(e.depth++,e.depth>H)return e.err="nesting-too-deep",se();let n=t();if(e.depth--,Zi(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function tc(e){if(ec(e),!I(O(e),b.do))return[];e.i++;let t=j(e,[b.done]);return I(O(e),b.done)&&e.i++,t}function fd(e){e.i++;let t=j(e,[b.then]);for(;e.err===null;){let n=O(e);if(I(n,b.then)||I(n,b.else)){e.i++,t.push(...j(e,[b.elif,b.else,b.fi]));continue}if(I(n,b.elif)){e.i++,t.push(...j(e,[b.then]));continue}I(n,b.fi)&&e.i++;break}return t}function xd(e){e.i++;let t=j(e,[b.do]);return t.push(...tc(e)),t}function pd(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++;t.push(...Ji(e,o,e.i))}return t.push(...tc(e)),t}function _d(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,t.push(...Ji(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"&&(Xi.includes(o.text)||o.text===qi)){e.i++;continue}if(I(o,b.esac)){e.i++;break}for(Y(o,Me)&&e.i++;e.i<e.toks.length&&!Y(O(e),Ue);){let s=e.toks[e.i];if(s.kind==="op"&&!Ki.includes(s.text))break;e.i++}if(!Y(O(e),Ue))break;e.i++;let r=j(e,[b.esac]);$i(r,b.case),t.push(...r)}return t}function Bi(e,t){ec(e);let n=nc(e);return $i(n.cmds,t),{cmds:n.cmds,simple:null}}function Wi(e,t){return ro.every((n,o)=>Y(e.toks[t+o],n))}function Ed(e){let t=e.i,n=[],o=!1;for(;e.i<e.toks.length;){let l=e.toks[e.i];if(l.kind==="op")break;if(l.kind==="io"){o=Qi(e)||o;continue}if(n.length===0&&l.kind==="word"&&Pt(l.text)){e.i++;let u=O(e);if(l.text.endsWith(Fe)&&u!==void 0&&Y(u,Me)&&u.start===l.end){let d=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,Y(f,Me)&&d++,Y(f,Ue)&&--d===0)break}}continue}n.push(l),e.i++}if(e.i===t)return se();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:ao(r),simple:null};let s=l=>l.kind==="word"?Ee(l.text):l.text,i=io(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||co(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function nc(e){let t=O(e);if(t===void 0)return se();if(t.kind==="op")return t.text!==Me?se():ge(e,()=>{e.i++;let n=j(e,Yi);return Y(O(e),Ue)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith($u)||t.text.startsWith(Qu)))return e.i++,Zi(e),{cmds:ao(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return ge(e,()=>{e.i++;let n=j(e,[b.groupEnd]);return I(O(e),b.groupEnd)&&e.i++,n});case b.if:return ge(e,()=>fd(e));case b.while:case b.until:return ge(e,()=>xd(e));case b.for:return ge(e,()=>pd(e));case b.case:return ge(e,()=>_d(e));case b.coproc:return e.err="coproc",se();case b.select:return e.err="select",se();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=Ee(n.text),e.i++),Wi(e,e.i)&&(e.i+=ro.length),Bi(e,o)}default:if(Wi(e,e.i+1))return e.i+=ro.length+1,Bi(e,Ee(t.text))}return Ed(e)}function gd(e){I(O(e),Ju)&&e.i++;let t=[],n=se();for(;e.err===null;){n=nc(e),t.push(...n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&Ki.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&ud(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function j(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===Ue||o.text===qi)return n;if(o.text!==Me){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;n.push(...gd(e)),e.i===r&&e.err===null&&e.i++}return n}function ve(e){let t=ji(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;)o.push(...j(n,Yi)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as oc}from"node:path";var Ft="'",me='"',vt="`",md=" \r",Ge="([{",xo=")]}",lo=` \r
25
- |;>`,ic="*",rc="1",uo="::",Ht=uo.length,hd=Ht;function jt(e,t){let n=e.charAt(t);for(let o=t+1;o<e.length;o++){let r=e.charAt(o);if(n===me&&r===vt){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function Sd(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===me&&r===vt&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function je(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Ft||r===me){let s=jt(e,o);if(s<0)return-1;o=s;continue}if(r===vt){o++;continue}if(Ge.includes(r))n++;else if(xo.includes(r)&&--n===0)return o}return-1}function bd(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Ft||r===me){let s=jt(e,o);if(s<0)return e.length;o=s;continue}if(Ge.includes(r))n++;else if(xo.includes(r))n--;else if(n<=0&&lo.includes(r))return o}return e.length}function Od(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===Ft||s===me){let i=jt(e,r);if(i<0)break;r=i;continue}Ge.includes(s)?n++:xo.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var Td=e=>e!==""&&(e===ic||[...e].every(t=>t>="0"&&t<="9")),sc=()=>({words:[],toFile:!1,chained:!1});function cc(e){let t=[],n=[],o=sc(),r="",s=!1,i=!0,c=null,a=e.length,l=()=>{s&&(c!==null?(c==="file"&&(o.toFile=!0),c=null):o.words.push(r),r="",s=!1,i=!0)},u=()=>{l(),(o.words.length>0||o.toFile)&&n.push(o),o=sc()},d=()=>{u(),n.length>0&&t.push(n),n=[]},f=(p,g)=>{r+=p,s=!0,g&&(i=!1)},x=0;for(;x<a;){let p=e.charAt(x),g=e.charAt(x+1);if(p===Ft||p===me){let E=jt(e,x);f(Sd(e.slice(x+1,E<0?a:E),p),!0),x=E<0?a:E+1}else if(p===vt)g!==`
26
- `&&g!==""&&f(g,!1),x+=Ht;else if(p===`
27
- `)d(),x++;else if(md.includes(p))l(),x++;else if(p===";")d(),x++;else if(p==="|")g==="|"?(d(),x+=Ht):(u(),x++);else if(p==="&")g==="&"?(d(),x+=Ht):((s||o.words.length>0)&&f(p,!1),x++);else if(p==="#"&&!s)for(;x<a&&e.charAt(x)!==`
28
- `;)x++;else if(p===">"){let E=rc;s&&i&&Td(r)?(E=r,r="",s=!1):s&&l();let h=x+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<a&&!lo.includes(e.charAt(h));)h++;else c=E===rc||E===ic?"file":"skip";x=h}else if(p==="("&&s&&i&&r.includes(uo)){let E=je(e,x),h=e.slice(x+1,E<0?a:E);l();for(let S of h.trim()===""?[]:Od(h)){let _=cc(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}x=E<0?a:E+1,x<a&&!lo.includes(e.charAt(x))&&(o.chained=!0,x=bd(e,x))}else if(p==="["&&!s&&e.startsWith(uo,je(e,x)+1)&&je(e,x)>=0){let E=je(e,x);f(e.slice(x,E+1),!1),x=E+1}else if(Ge.includes(p)&&(p!=="["||!s)||(p==="$"||p==="@")&&Ge.includes(g)&&g!=="["){let E=p==="$"||p==="@"?x+1:x,h=je(e,E);f(e.slice(x,h<0?a:h+1),!0),x=h<0?a:h+1}else f(p,!1),x++}return d(),t}var Rd=["get-content","gc","cat","type"],Ad=["[io.file]::","[system.io.file]::"],Nd=["readalltext","readalllines","readallbytes","readlines"],po=["path","literalpath"],ac=["totalcount","head","first","tail","last"],lc=[...po,...ac,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],yd=["raw","wait","force","asbytestream"],Id=[...lc,...yd],Cd=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],kd=["cd","chdir","sl","set-location","pushd","push-location"],Dd=["powershell","powershell.exe","pwsh","pwsh.exe"],Ld=["cmd","cmd.exe"],wd=["/c","/k","/r"],Pd="command",ie="-";function fo(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function _o(e,t){let n=e.slice(ie.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 Md(e){if(e.length===0)return null;let t=fo(e[0]);if(!Rd.includes(t)){let r=e[0].toLowerCase(),s=Ad.find(i=>r.startsWith(i));return s===void 0||!Nd.includes(r.slice(s.length))||e.length<hd?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(ie)||s.length===ie.length){n.push(s);continue}let i=_o(s,Id);if(i.full===void 0||!lc.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;po.includes(i.full)&&n.push(c),ac.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function Ud(e,t){if(Dd.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(ie)||o.length===ie.length)continue;let r=_o(o,[Pd]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(Ld.includes(e)){for(let n=1;n<t.length;n++)if(wd.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function Hd(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(ie)||n.length===ie.length)return n;let o=_o(n,po);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function uc(e,t,n,o){let r=t;for(let s of cc(e)){let i=s[0];if(i.words.length===0)continue;let c=fo(i.words[0]);if(s.length===1&&kd.includes(c)){let d=Hd(i.words);d!==null&&(r=oc(r,d));continue}let a=n<H?Ud(c,i.words):null;if(a!==null){uc(a,r,n+1,o);continue}if(i.toFile||i.chained)continue;let l=Md(i.words);if(l===null||l.bounded)continue;let u=!0;for(let d=1;d<s.length;d++)if(s[d].toFile||!Cd.includes(fo(s[d].words[0]??""))){u=!1;break}u&&o.push(oc(r,l.file))}}function dc(e,t){let n=[];return uc(e,t,0,n),n}import{join as Bt}from"node:path";var fc=`\r
29
- `,Fd=`
30
- `;function Gt(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(fc)<0?t:t.split(fc).join(Fd)}import{basename as lE,dirname as uE,join as xc,posix as dE,resolve as fE,win32 as xE}from"node:path";var vd=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 jd(e,t){let n=vd[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(jd(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{mkdirSync:Gd,realpathSync:Bd}=process.getBuiltinModule("node:fs");function he(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 Be(e,t){let n=e[ht];return n!==void 0&&n!==""?n:xc(t,...Rs["claude-code"])}function Wd(e,t=process.platform){let n=he(e,t);if(n!==null)return n;throw new T("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function pc(e){let t=xc(Wd(e),ct.slice(1));return Gd(t,{recursive:!0}),Bd.native(t)}var{readFileSync:mc}=process.getBuiltinModule("node:fs");function Se(e){return e.agentId!==void 0&&e.agentId!==""}function mo(e,t){if(t===null)return"C";let n=re(e.agent),o=new Set(t);for(let r of ot)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function ho(e,t){if(!Se(e))return null;let n=re(e.agent);if(t.manifestTools!==void 0)return gc(t.manifestTools.map(c=>Eo(n,c)));let o=e.agentType??"",r=Xd(o,t);if(r===null)return null;let s=(r.tools??zd(n)).map(c=>Eo(n,c)),i=r.disallowed.map(c=>Eo(n,c));return gc(s.filter(c=>!i.some(a=>$d(a,c))))}function Xd(e,t){if(!Kd(e))return null;let n=qd(t.env);if(e.indexOf(de)>=0){if(n!==null){let s=Yd(Be(t.env,n),e);if(s!==null)return s}}else{let s=go(Bt(t.projectDir,Ar,at,e+lt));if(s!==null)return s;if(n!==null){let i=go(Bt(Be(t.env,n),at,e+lt));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 Kd(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(de))if(t===""||t==="."||t==="..")return!1;return!0}function qd(e){return he(e)}function Yd(e,t){let n=t.indexOf(de),o=t.slice(0,n),r=t.slice(n+de.length);if(r.indexOf(de)>=0)return null;let s;try{s=JSON.parse(Gt(mc(Bt(e,hn,Nr),"utf8")))}catch{return null}let i=s?.plugins;if(i===null||typeof i!="object")return null;for(let c of Object.keys(i)){let a=c.indexOf(yr);if((a<0?c:c.slice(0,a))!==o)continue;let l=i[c];if(Array.isArray(l))for(let u of l){let d=u?.installPath;if(typeof d!="string"||d==="")continue;let f=go(Bt(d,at,r+lt));if(f!==null)return f}}return null}function go(e){let t;try{t=mc(e,"utf8")}catch{return null}return Vd(t)}function Vd(e){let t=e.split(`
31
- `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Sn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Sn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=_c(o,Ir),s=_c(o,Cr);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function _c(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(Ec(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>Ec(s.trim())).filter(s=>s!=="")}return null}function Ec(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function zd(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...ot.map(n=>e.toolNamePrefix+n)]}function Eo(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(kr)?Jd(o):o}function Jd(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||Dr.indexOf(n)>=0;t+=o?n:"_"}return t}function $d(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(bn)){let n=e.slice(bn.length);if(n!==""&&n.indexOf(On)<0)return t.startsWith(e+On)}return!1}function gc(e){return[...new Set(e.filter(t=>t!==""))]}var ce="",hc=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:ce},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:ce},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:ce},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:ce},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:ce},command:{valueShorts:ce,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:ce}}),Qd=["bash","sh","zsh"],Zd="c",ef=" -c",tf=["-o","+o","-O","+O"],Wt="-",nf="+",So="--",of="smhd",rf=".",Sc=e=>e!==""&&e>="0"&&e<="9";function sf(e){if(e===""||!Sc(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(Sc(n)||n===rf))return t===e.length-1&&of.includes(n)}return!0}function cf(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===So){n++;break}if(e.assignments&&Pt(o)){n++;continue}if(o.startsWith(So)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(Wt)&&o.length>Wt.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=Wt.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||!sf(t[n]))return null;n++}return n<t.length?t.slice(n):null}function af(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(So)){if(o.startsWith(Wt)||o.startsWith(nf)){o.includes(Zd)&&(t=!0),tf.includes(o)&&n++;continue}return t?o:null}}return null}function bc(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 a=s.toLowerCase();if(Qd.includes(a)){let d=af(i),f=d!==null&&n<H?ve(d):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=bc(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,bo(p,[...r,a+ef],n+1,o)}return}let l=Object.hasOwn(hc,a)?hc[a]:void 0,u=l===void 0?null:cf(l,i);if(u===null)break;r.push(a),s=io(u[0]),i=u.slice(1),c=c||co(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=H))for(let a of wt(e.raw)){let l=ve(a.body);if(l.ok)for(let u of l.commands)bo(bc(u,e),[...t,a.wrapper],n+1,o)}}function Oc(e){let t=[];for(let n of e)bo(n,[],0,t);return t}import{isAbsolute as uf,join as Oo,relative as df,sep as To}from"node:path";var{readFileSync:lf}=process.getBuiltinModule("node:fs"),Tc=".claude",ff="settings.local.json",Rc="settings.json",xf="Bash",pf="Read",Ac=":*",Nc="//",yc="~/",Ic="./",Cc="..",_f=`
32
- \r`,Ef=Object.freeze({tool:xf});function gf(e,t){if(t!=="claude-code")return[];let n=he(process.env),o=process.env[ht],r=o!==void 0&&o!==""?o:n===null?null:Be(process.env,n),s=[Oo(e,Tc,ff),Oo(e,Tc,Rc)];return r===null?s:[...s,Oo(r,Rc)]}function kc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mf(e){let t;try{t=Gt(lf(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!kc(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!kc(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 Dc(e,t){let n=[];for(let o of gf(e,t)){let r=mf(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function hf(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 V(e,t,n){let o=hf(e,n),r=t.length,s=new Uint8Array(r+1);s[r]=1;for(let i=o.length-1;i>=0;i--){let c=o[i],a=new Uint8Array(r+1),l=0;for(let u=r;u>=0;u--){let d=u<r,f=d?t[u]:"";switch(c.t){case"lit":a[u]=d&&f===c.c?s[u+1]:0;break;case"any1":a[u]=d&&!(n&&f==="/")?s[u+1]:0;break;case"star":a[u]=s[u]||(d&&!(n&&f==="/")?a[u+1]:0);break;case"globstar":a[u]=s[u]||(d?a[u+1]:0);break;case"globstarDir":d&&f==="/"&&s[u+1]&&(l=1),a[u]=s[u]||l;break}}s=a}return s[0]===1}function Sf(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 bf(e,t){if(!e.endsWith(Ac))return V(e,t,!1);let n=e.slice(0,e.length-Ac.length);if(V(n,t,!1))return!0;for(let o=0;o<t.length;o++)if(_f.includes(t[o])&&V(n,t.slice(0,o),!1))return!0;return!1}var Of=/^[A-Za-z]:(?=\/)/;function We(e){return To==="/"?e:e.split(To).join("/")}function Tf(e,t,n){if(e.startsWith(Ic)){if(n===void 0)return!1;let r=df(n,t);return r===""||r===Cc||r.startsWith(Cc+To)||uf(r)?!1:V(e.slice(Ic.length),We(r),!0)}let o=We(t);if(e.startsWith(Nc)){let r=We(e.slice(Nc.length-1));return V(r,o,!0)||V(r,o.replace(Of,""),!0)}if(e.startsWith(yc)){let r=he(process.env);return r!==null&&V(We(r)+e.slice(yc.length-1),o,!0)}return V(We(e),o,!0)}function z(e,t,n=Ef){for(let o of t){let r=Sf(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===pf?Tf(r.glob,e,n.projectDir):bf(r.glob,e))return o}return null}var LE=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.'}),Lc='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var Rf="{size}",Af="{path}";function Xt(e,t,n=""){return k(Lc,n).split(Rf).join(String(t)).split(Af).join(e)}var{statSync:Nf}=process.getBuiltinModule("node:fs"),Uc="Bash",Ao="Read",yf="WebFetch",If="ctx_execute",Cf="ctx_batch",Hc="shell",kf="1",J="-",No="--",Df="=",Lf=".",wc=",",Ro="p",wf=["-e","--expression"],Pf=";&|(`\n\r",le=Object.freeze({kind:"allow"}),G=e=>({kind:"deny",reason:e}),ae=e=>typeof e=="string"?e:void 0,Pc=e=>e!=null,$=(e,t)=>e.includes(t);function Fc(e,t,n){let o=e.tool;if(o===void 0)return le;let r=o.canonicalName,s=o.input,i;if(n===null){if(process.env[Rr]===kf)return G(k(ut,t.toolNamePrefix));process.stderr.write(zr+`
33
- `),i=[]}else i=n;let c=Mf(r,s,e.cwd,i);return c!==null?G(ye+c):r===yf?vf(s,t):r===Uc?jf(e,t,s,i):r===Ao?qf(e,t,s):le}function vc(e,t,n,o){let r=e==="webfetch",s=r?Fr.map(c=>n.toolNamePrefix+c).join(Vr):n.toolNamePrefix+Hr,i=JSON.stringify(r?{url:t}:{language:Hc,code:t,intent:o??Ur});return[Tn+Lr[e]+wr,Pr,Mr+s,i].join(`
34
- `)}function jc(e){for(let t of xt){let n=ae(e[t]);if(n!==void 0&&n!=="")return n}}function Mf(e,t,n,o){if(o.length===0)return null;let r=s=>z(qt(n,s),o,{tool:Ao,projectDir:n});if(e===Uc){let s=ae(t.command);return s===void 0?null:z(s,o)}if(e===Ao){let s=jc(t);return s===void 0?null:r(s)}if(e===If){let s=ae(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=ae(t.code);return t.language===Hc&&c!==void 0?z(c,o):null}if(e===Cf&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?z(s,o):null;if(i!==null)return i}return null}function Uf(e,t){return t.length===0?null:z([e.argv0,...e.args].join(" "),t)??z(e.raw,t)}function Hf(e,t){if(t.length===0)return!1;for(let n=0;n<=e.length;n++)if(!(n>0&&!Pf.includes(e.charAt(n-1)))&&z(e.slice(n).trimStart(),t)!==null)return!0;return!1}function Ff(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return Jr.some(n=>t===n||t.endsWith(Lf+n))}function vf(e,t){let n=ae(e.url)??"";return Ff(n)?le:G(vc("webfetch",n,t))}function jf(e,t,n,o){let r=ae(n.command)??"",s=ve(r);if(!s.ok)return Hf(r,o)?G(k(dt,t.toolNamePrefix)):Mc(r,e.cwd,t)??le;let i=Oc(s.commands);for(let c of i){let a=Uf(c,o);if(a!==null)return G(ye+a)}if(!fe(t)||Se(e))for(let c of i){let a=Gf(c);if(a!==null)return G(vc(a,r,t,ae(n.description)))}return Yf(i,e.cwd,t)??Mc(r,e.cwd,t)??le}function Gf(e){let t=e.argv0.toLowerCase();return $($r,t)&&Bf(t,e)?"curl":Xf(e.raw)?"http":$(ts,t)?"build":null}function Bf(e,t){return t.redirectsToFile?!Wf(e,t.args):!t.endsInBoundedSink}function Wf(e,t){let n=Qr[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===No)break;if($(Zr,s)||s===es&&t[r+1]===J)return!1;(s===n.long||s.startsWith(J)&&!s.startsWith(No)&&s.includes(n.short,J.length))&&(o=!0)}return o}function Xf(e){let t=e.toLowerCase();for(let n of rs)if(t.includes(n))return!0;for(let n=t.indexOf(Ce);n>=0;n=t.indexOf(Ce,n+1)){let o=t.charAt(n+Ce.length);if(o!==""&&ns.includes(o)&&t.startsWith(os,n+Ce.length+o.length))return!0}return!1}var Kf="cd";function yo(e){try{let t=Nf(e);return t.isFile()?t.size:-1}catch{return-1}}function qf(e,t,n){if(!Pc(n.offset)&&!Pc(n.limit)){let o=jc(n);if(o!==void 0){let r=qt(e.cwd,o),s=yo(r);if(s>q)return G(Xt(r,s,t.toolNamePrefix))}}return le}function Yf(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&zn(n))return null;let o=t,r=null;for(let s of e){let i=s.argv0.toLowerCase();if(i===Kf&&s.args.length===1&&s.insideConstruct===void 0&&(o=qt(o,s.args[0])),s.redirectsToFile||s.endsInBoundedSink||s.pipesOut===!0||s.insideConstruct!==void 0||!$(ss,i))continue;let c=Jf(i,s.args);if(c===null)continue;if(c.bounded){r=le;continue}let a=qt(o,c.file),l=yo(a);if(l>q)return G(Xt(a,l,n.toolNamePrefix))}return r}function Mc(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&zn(n))return null;for(let o of dc(e,t)){let r=yo(o);if(r>q)return G(Xt(o,r,n.toolNamePrefix))}return null}var Kt=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function Vf(e){if($(An,e))return 1;for(let t of An)if(t.startsWith(No)?e.startsWith(t+Df):e.startsWith(t))return 0;return e.startsWith(J)&&Kt(e.slice(J.length))?0:-1}function zf(e){if(e===Ro)return"all";if(!e.endsWith(Ro))return null;let t=e.slice(0,e.length-Ro.length),n=t.indexOf(wc);return(n<0?Kt(t):Kt(t.slice(0,n))&&Kt(t.slice(n+wc.length)))?"range":null}function Jf(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if($(is,e)){let a=Vf(c);if(a>=0){o=!0,i+=a;continue}}if(e===ft&&$(cs,c)){r=!0;continue}if(e===ft&&$(wf,c)){s=t[i+1],i++;continue}c.startsWith(J)&&c!==J||n.push(c)}if(e===ft){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:zf(s);if(i===null)return null;o=i==="range"}return e===as&&n.shift()!==D.identity?null:n.length===1&&n[0]!==J?{file:n[0],bounded:o}:null}import{basename as s0,dirname as Vt,join as Ke,resolve as Kc}from"node:path";import{dirname as Gc,sep as Qf}from"node:path";var{realpathSync:$f}=process.getBuiltinModule("node:fs");function Zf(e){try{return $f.native(e)}catch{return}}function Yt(e){return e.split(Qf).filter(t=>t!=="")}function Bc(e){let t=e.map(Zf).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=Yt(n).length;for(let s of t){let i=Yt(s),c=Yt(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;Yt(r).length>o&&Gc(r)!==r;)r=Gc(r);return r}var e0=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]),t0=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],w=(e,t)=>e>>>t|e<<32-t;function Wc(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=t0.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=w(i[E-15],7)^w(i[E-15],18)^i[E-15]>>>3,S=w(i[E-2],17)^w(i[E-2],19)^i[E-2]>>>10;i[E]=i[E-16]+h+i[E-7]+S>>>0}let[a,l,u,d,f,x,p,g]=s;for(let E=0;E<64;E++){let h=g+(w(f,6)^w(f,11)^w(f,25))+(f&x^~f&p)+e0[E]+i[E]>>>0,S=(w(a,2)^w(a,13)^w(a,22))+(a&l^a&u^l&u)>>>0;g=p,p=x,x=f,f=d+h>>>0,d=u,u=l,l=a,a=h+S>>>0}s[0]=s[0]+a>>>0,s[1]=s[1]+l>>>0,s[2]=s[2]+u>>>0,s[3]=s[3]+d>>>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:n0,readFileSync:o0,realpathSync:Xc,statSync:r0}=process.getBuiltinModule("node:fs");function i0(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 Xe(e){return e===void 0||e===""?void 0:e}function c0(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return Xe(t.env.CLAUDE_PROJECT_DIR)??Xe(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return Xe(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(it);return n<0?void 0:Xe(t.argv[n+1])}case"pi:ctx.cwd":return Xe(t.piCwd)}}function a0(e){let t;try{t=Xc.native(e)}catch{throw new T("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=l0(Ke(t,En));if(o!==null){let s=qc(Ke(o,br));return{commonDir:Xc.native(s===null?o:Kc(o,s)),worktree:t,start:n}}let r=Vt(t);if(r===t)return{commonDir:null,start:n};t=r}}function l0(e){let t;try{if(r0(e).isDirectory())t=e;else{let n=qc(e);if(n===null||!n.startsWith(mn))return null;t=Kc(Vt(e),n.slice(mn.length))}}catch{return null}return n0(Ke(t,Or))?t:null}function qc(e){let t;try{t=o0(e,"utf8")}catch{return null}let n=t.indexOf(`
35
- `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function u0(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(`
36
- `).filter(r=>r!=="")}function d0(e,t){let n=s0(t)===En?Vt(t):t,o=u0(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(gn)).map(r=>r.slice(gn.length));return Bc([Vt(n),...o])}function Yc(e,t){let n=i0(e),o=c0(n,t);if(o===void 0)throw new T("NO_PROJECT",{kind:n});let r=a0(o),s=r.commonDir===null?r.start:void 0,i=r.commonDir??r.start,c=r.commonDir===null?r.start:r.worktree,a,l,u;return{get projectKey(){return a??=Wc(i).slice(0,mr),a},get projectDir(){return l??=Ke(pc(process.env),hr,this.projectKey),l},get dbPath(){return Ke(this.projectDir,Sr)},worktree:c,get containmentRoot(){return u??=s??d0(o,i),u},agent:e,source:n}}var zt=Ae,f0=`
37
- PRAGMA busy_timeout = ${ue};
8
+ `),i=au(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 au(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 Ks(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function lu(e){let t=e;return(t.mode==="content"||t.mode==="count")&&typeof t.content=="string"}function qs(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 uu(e){let t=iu(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)&&Ks(e)&&(o.shape=e),typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Ks(e)&&(Xn(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,qs(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=ou.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:su(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=uu(r.tool_response)),i}function du(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:Xn(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:du(e,t.output)}):{stdout:"",exitCode:0}}}var fu={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function xu(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 pu(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 fu[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function zs(e){pu(e);let t=se(e,"claude-code",Wn,ru);if(t.tool!==void 0&&t.tool.name===tu&&(t.tool.canonicalName=nu),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"+xu(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function Vs(e,t,n){return j(e,t,!0)}var Kn="mcp__context_mode__",Eu={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"};function Js(e){return se(e,"codex",Kn,Eu)}function $s(e,t,n){return j(e,t,!1)}var Nt="mcp_context-mode_",Qs={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},Zs={startup:"startup",resume:"resume",clear:"clear"},mu=["SessionStart","UserPromptSubmit","PostToolUse"],hu=["UserPromptSubmit","PreToolUse"],At={stdout:"",exitCode:0},Su=`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 ei={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function bu(e,t){if(e.startsWith(Nt))return e.slice(Nt.length);if(Object.hasOwn(ei,e))return ei[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 Ou(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 Tu(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:Ou(n)??JSON.stringify(e),r=t===void 0?void 0:R(t,"error");return{isError:r!=null,bytes:Buffer.byteLength(o),text:o}}var Ru=["https://","http://"],Au=`.,;:!?)]}>'"`,Nu=`
13
+ \r\f\v`;function yu(e){let t=[],n="";for(let o of e)Nu.includes(o)?(n!==""&&t.push(n),n=""):n+=o;return n!==""&&t.push(n),t}function Iu(e){if(typeof e=="string")for(let t of yu(e)){let n=t.toLowerCase(),o=Ru.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&&Au.includes(r[r.length-1]);)r=r.slice(0,-1);return r}}function Cu(e,t){if(e==="web_fetch"&&R(t,"url")===void 0){let n=Iu(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 ti(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(Qs,n)?Qs[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(Zs,s)&&(r.source=Zs[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:bu(c,R(t,"mcp_context")),input:Cu(c,typeof l=="object"&&l!==null&&!Array.isArray(l)?l:{})}}return o==="PostToolUse"&&(r.result=Tu(R(t,"tool_response"))),r}function ni(e,t,n){switch(t.kind){case"allow":return At;case"hint":return mu.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:At;case"deny":return hu.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
14
+ `+t.reason}),exitCode:0}:At;case"replace":return e.event!=="PostToolUse"?At:{stdout:JSON.stringify({decision:"deny",reason:Su+t.output}),exitCode:0}}}var Yn="mcp__context-mode__",Du={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},oi={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},Lu="PostToolUseFailure";function ri(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===Lu,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=se(n,"qwen",Yn,Du);if(o.tool!==void 0&&Object.hasOwn(oi,o.tool.name)&&(o.tool.canonicalName=oi[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 si(e,t,n){return j(e,t,!1)}var It="context-mode-",Pu={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}},ii={startup:"startup",resume:"resume",new:"startup"},Mu={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"}},li="success";function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var qn=Object.freeze(["bash","powershell"]),ci=Object.fromEntries(qn.map(e=>[e,"Bash"]));function Uu(e){return e.startsWith(It)?e.slice(It.length):Object.hasOwn(ci,e)?ci[e]:e}var ai=e=>typeof e=="number"&&Number.isFinite(e);function Hu(e,t){let n=t.view_range;if(e!=="view"||!Array.isArray(n)||!ai(n[0]))return t;let o={...t,offset:n[0]};return ai(n[1])&&n[1]>=n[0]&&(o.limit=n[1]-n[0]+1),o}function Fu(e){if(Ct(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Ct(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=Ct(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==li,bytes:Buffer.byteLength(s),text:s}}var Gu=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function Bu(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:Gu.find(([t])=>Object.hasOwn(e,t))?.[1]}function ui(e){if(!Ct(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=Bu(e),n=typeof t=="string"?Pu[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Mu[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"&&ii[e.source]!==void 0&&(s.source=ii[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:Uu(i),input:Hu(i,Fu(e[o.args]))};s.tool=c}return r==="PostToolUse"&&(s.result=ju(e[o.result],n.casing,n.failure)),s}var yt={stdout:"",exitCode:0};function di(e,t,n){switch(t.kind){case"allow":return yt;case"hint":return e.event==="PostToolUse"?yt:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?yt:{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"?yt:{stdout:JSON.stringify({modifiedResult:{resultType:li,textResultForLlm:t.output}}),exitCode:0}}}var kt="mcp_context-mode_",gi=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],fi="mcp_",xi="_",Xu="new",zn=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),Lt=Object.freeze(["read_file","view"]),Vn=Object.freeze(["fetch_webpage","web_fetch"]),pi=Object.fromEntries([...zn.map(e=>[e,"Bash"]),...Lt.map(e=>[e,"Read"]),...Vn.map(e=>[e,"WebFetch"])]);function mi(e){if(e.startsWith(kt))return e.slice(kt.length);if(Object.hasOwn(pi,e))return pi[e];if(!e.startsWith(fi))return e;let t=e.slice(fi.length),n=t.indexOf(xi);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+xi.length)}var Fe=e=>typeof e=="number"&&Number.isFinite(e);function hi(e,t,n){if(t==="Read"&&Lt.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 Ku(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 Yu={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},qu=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],_i={new:"startup",startup:"startup",resume:"resume"},zu="success";function Dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vu(e){if(Dt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Dt(t)?t:{}}catch{return{}}}function Ju(e){let t=Dt(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==zu,bytes:Buffer.byteLength(n),text:n}}function Ei(e,t){let n=typeof t=="string"?Yu[t]??gi.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"&&_i[e.source]!==void 0&&(o.source=_i[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=mi(r);o.tool={name:r,canonicalName:s,input:hi(r,s,Vu(e.toolArgs))}}return n==="PostToolUse"&&(o.result=Ju(e.toolResult)),o}function Si(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 Ei(t,t.hookEventName);if(t.hook_event_name===void 0){let r=qu.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return Ei(t,r)}let n=gi.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===Xu&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=Dt(t.tool_input)?t.tool_input:{},i=mi(r);o.tool={name:r,canonicalName:i,input:hi(r,i,s)}}return n==="PostToolUse"&&(o.result=Ku(t.tool_response)),o}function bi(e,t,n){return j(e,t,!1)}var wt="mcp_context_mode_",Oi="mcp_context-mode_",Ti={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},Qu="prompt",Zu="USER_PROMPT",Ri="mcp_",Jn=Object.freeze(["execute_bash","execute_pwsh","shell"]),Ai=Object.fromEntries(Jn.map(e=>[e,"Bash"])),Ni="_",yi={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function ed(e){if(e.startsWith(wt))return e.slice(wt.length);if(e.startsWith(Oi))return e.slice(Oi.length);if(Object.hasOwn(Ai,e))return Ai[e];if(!e.startsWith(Ri))return e;let t=e.slice(Ri.length),n=t.indexOf(Ni);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+Ni.length)}function td(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function Ii(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(Ti,n)?Ti[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"&&yi[t.source]!==void 0&&(r.source=yi[t.source]),o==="UserPromptSubmit"){let s=t[Qu],i=typeof s=="string"?s:process.env[Zu];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:ed(s),input:i}}return o==="PostToolUse"&&(r.result=td(t.tool_response)),r}function Ci(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 $n="mcp__context-mode__",ki="mcp__plugin_context-mode_context-mode__",od={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},rd={hook_event_name:"hookEventName",session_id:"sessionId"},sd="PostToolUseFailure";function Di(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(rd))t[i]===void 0&&(t[i]=t[c]);let n=t.hook_event_name===sd;n&&(t.hook_event_name="PostToolUse");let r=(typeof t.tool_name=="string"?t.tool_name:"").startsWith(ki)?ki:$n,s=se(t,"zcode",r,od);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 Li(e,t,n){return j(e,t,!1)}var Mi="",wi={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},Pi={bash:"Bash",read:"Read",edit:"Edit",write:"Write"};function cd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function ad(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 Ui(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(wi,n)?wi[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(Pi,s)?Pi[s]:s,input:cd(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=ad(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function ld(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 Hi(e,t,n){let o=ld(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:Gs,content:o.stdout,timestamp:Date.now()}}function Fi(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var Bi="",vi=z+"_",ji={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},Qn="bash",Zn="read",dd=Object.freeze([Qn,"shell"]),Gi={webfetch:"WebFetch",[Zn]:"Read",...Object.fromEntries(dd.map(e=>[e,"Bash"]))};function eo(e){return e.startsWith(vi)?e.slice(vi.length):Object.prototype.hasOwnProperty.call(Gi,e)?Gi[e]:e}function fd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function xd(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 Wi(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(ji,n)?ji[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:fd(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=xd(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Xi(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"},Ki={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},_d={...Ki,shell:[...Ys]},Ed=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:Wn,nativeTools:_d,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:zs,encode:Vs},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:Kn,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:Js,encode:$s},{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:ti,encode:ni},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Yn,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:ri,encode:si},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:It,nativeTools:{shell:[...qn]},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:ui,encode:di},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:kt,nativeTools:{shell:[...zn],read:[...Lt],webfetch:[...Vn]},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:Si,encode:bi},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:wt,nativeTools:{shell:[...Jn]},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:Ii,encode:Ci},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:$n,nativeTools:Ki,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:Di,encode:Li},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:Mi,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:Sn,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:Ui,encode:Hi,checkPermission:Fi},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:Bi,nativeTools:{shell:[Qn],read:[Zn]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:Sn,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:Wi,encode:Xi,toCanonicalTool:eo}]),gd=new Map(Ed.map(e=>[e.id,e])),md=new Set(["claude-code","gemini","copilot-cli","pi"]);function _e(e){return md.has(e.id)}var hd=new Set(["claude-code","copilot-cli","pi"]);function to(e){return hd.has(e.id)&&_e(e)}var Sd=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function Pt(e){return Sd.has(e.id)}function ie(e){return gd.get(e)}import{resolve as Qt}from"node:path";var bd=["&&","||",";;","|&",";","|","&","(",")"],Od=["&>>","&>"],Td=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],Rd="&",Ad="<<",Yi="<<-",Nd=";",qi=`\r
19
+ `,zi=`\\
20
+ `,Vi=`\\\r
21
+ `,yd="$(",Qi="${",Zi="$'",je="((",Ji="))",Ee="[[",Mt="]]",no="<(",ec=">(",w=2,tc=`
22
+ \r;&|()<>`,Id=`
23
+ \r`,Cd='$`"\\\n',kd="case",Dd="esac";function ge(e,t){e.end==="complete"&&(e.end=t)}function oo(e){return e!==""&&e>="0"&&e<="9"}function $i(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function nc(e){return e===""||tc.includes(e)}function ro(e){return e!==""&&Id.includes(e)}function G(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function Ut(e,t){let n=e.s.indexOf("'",t+1);return n<0?(ge(e,"unterminated-quote"),e.n):n+1}function oc(e,t){let n=t+Zi.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 so(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=io(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 io(e,t,n){let o=t+Qi.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=Ut(e,o);continue}if(s==='"'){o=so(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 co(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(Ji,o)?o+Ji.length:-1;n--}o++}return-1}function Ge(e,t,n){let o=t+yd.length-1;if(e.s.startsWith(je,o)){let r=co(e.s,o);if(r>0)return r}return Ht(e,o+1,!0,n+1,null,null)}function Ld(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=Ut(e,o);continue}if(s==='"'){o=so(e,o,n);continue}if(s==="$"&&i==="("){o=Ge(e,o,n);continue}if(s==="$"&&i==="{"){o=io(e,o,n);continue}if(s==="`"){o=me(e,o);continue}let c=ro(e.s.charAt(o-1));if(c&&e.s.startsWith(Mt,o)&&nc(e.s.charAt(o+Mt.length))){if(r===0)return o+Mt.length;r--,o+=Mt.length;continue}if(c&&e.s.startsWith(Ee,o)&&ro(e.s.charAt(o+Ee.length))){r++,o+=Ee.length;continue}o++}return-1}function wd(e,t){let n=t;for(;oo(e.charAt(n));)n++;if(n===t){for(let o of Od)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of Td){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(Rd))if(e.charAt(r)==="-")r++;else for(;oo(e.charAt(r));)r++;return{end:r,op:o}}return null}function Pd(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(tc.includes(r))break;if(r==="\\"){o+=w;continue}if(r==="'"){o=Ut(e,o);continue}if(r==='"'){o=so(e,o,n);continue}if(r==="$"&&s==="'"){o=oc(e,o);continue}if(r==="$"&&s==="("){o=Ge(e,o,n);continue}if(r==="$"&&s==="{"){o=io(e,o,n);continue}if(r==="`"){o=me(e,o);continue}o++}return Math.min(o,e.n)}function Md(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 Ht(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(zi,c)){c+=zi.length;continue}if(i.startsWith(Vi,c)){c+=Vi.length;continue}if(f===`
25
+ `||f==="\r"){let S=c;c+=i.startsWith(qi,c)?qi.length:1,G(r,"op",Nd,S,c),d=null,u.length>0&&(c=Md(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(no,c)||i.startsWith(ec,c)){let S=Ht(e,c+no.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===Ad||p.op===Yi?p.op===Yi:null,c=p.end;continue}if(i.startsWith(Ee,c)&&ro(i.charAt(c+Ee.length))){let S=Ld(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=co(i,c);if(S>0){G(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}let g=bd.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(nc(i.charAt(S))){G(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}let E=c;c=Pd(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===kd&&a++,n&&h===Dd&&a>0&&a--}return u.length>0&&ge(e,"unterminated-heredoc"),e.n}function rc(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return Ht(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+Zi.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!==""&&Cd.includes(i)){t+=i,s+=w;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function Ft(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=Ut(t,r);continue}if(!o&&s==="$"&&i==="'"){r=oc(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Qi.length;continue}let c=e.startsWith(no,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(ec,r))){let l=r+1;if(s==="$"&&e.startsWith(je,l)&&co(e,l)>0){r=l+je.length;continue}let a=Ht(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 vt(e){let t=e.charAt(0);if(!($i(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(!($i(o)||oo(o)||o==="_"))return!1}return!1}var ac=[";","&","&&","||"],lc=["|","|&"],Be="(",We=")",uc=";;",uo=["(",")"],Ud="!";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"}),dc=[],Hd="[[",Fd="((",fc=[">",">>",">|","&>","&>>",">&"],vd=[...fc,"<","<>","<<<","<<","<<-"],jd=["","1"],xc=["-","/dev/stdout","/dev/stderr"],Gt="-",Xe="--",Ke="=",Gd="/",Bd=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),jt=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),ao="-c",lo="--bytes",Wd="c",Xd="--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,fo=e=>e!==""&&e>="0"&&e<="9",Kd=e=>fo(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function xo(e){let t=e.lastIndexOf(Gd);return t>=0&&t<e.length-1?e.slice(t+1):e}function po(e,t){let n=Bd[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(Gt)&&!r.startsWith(Xe)){let i=r.indexOf(n.short,Gt.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&&!xc.includes(s))return!0}return!1}function Yd(e){if(e==="")return!1;for(let t of e)if(!fo(t))return!1;return!0}function qd(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===ao||n===lo?o=e[t+1]:n.startsWith(lo+Ke)?o=n.slice(lo.length+Ke.length):n.startsWith(ao)&&!n.startsWith(Xe)&&(o=n.slice(ao.length)),o!==void 0)return Yd(o)&&Number(o)<=V}return!1}function zd(e){for(let t of e){if(t===Xe)return!1;if(t===Xd||t.startsWith(Gt)&&!t.startsWith(Xe)&&t.includes(Wd))return!0}return!1}function sc(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(!Kd(n))return!1}return!0}function Vd(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 sc(t);let o=t.slice(0,n).trim(),r=D.pipeLength.slice(1).trim();return(o===D.identity||sc(o))&&t.slice(n+1).trim()===r}function Jd(e){let t=e.argv0.toLowerCase();if(t===jt.wc)return!0;if(t===jt.head)return qd(e.args);if(t===jt.grep)return zd(e.args);if(t===jt.jq){let n=e.args.filter(o=>!o.startsWith(Gt));return n.length===1&&Vd(n[0])}return!1}function _o(e){return Ft(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function pc(e,t,n){return n<=t?[]:_o(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function _c(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function $d(e){let t=0;for(;fo(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Ec(e){let t=$d(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++,fc.includes(t.op)&&jd.includes(t.fd)&&!xc.includes(he(n.text)))}function gc(e){let t=!1;for(;O(e)?.kind==="io";)t=Ec(e)||t;return t}function mc(e){for(;O(e)?.kind==="op"&&ac.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--,gc(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function hc(e){if(mc(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 Qd(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 Zd(e){e.i++;let t=B(e,[b.do]);return P(t,hc(e)),t}function ef(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,pc(e,o,e.i))}return P(t,hc(e)),t}function tf(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,P(t,pc(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"&&(ac.includes(o.text)||o.text===uc)){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"&&!lc.includes(s.text))break;e.i++}if(!$(O(e),We))break;e.i++;let r=B(e,[b.esac]);_c(r,b.case),P(t,r)}return t}function ic(e,t){mc(e);let n=Sc(e);return _c(n.cmds,t),{cmds:n.cmds,simple:null}}function cc(e,t){return uo.every((n,o)=>$(e.toks[t+o],n))}function nf(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=Ec(e)||o;continue}if(n.length===0&&a.kind==="word"&&vt(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:_o(r),simple:null};let s=a=>a.kind==="word"?he(a.text):a.text,i=xo(s(n[0])),c=n.slice(1).map(s),l={argv0:i,args:c,redirectsToFile:o||po(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[l],simple:l}}function Sc(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,dc);return $(O(e),We)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(Hd)||t.text.startsWith(Fd)))return e.i++,gc(e),{cmds:_o(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,()=>Qd(e));case b.while:case b.until:return Se(e,()=>Zd(e));case b.for:return Se(e,()=>ef(e));case b.case:return Se(e,()=>tf(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++),cc(e,e.i)&&(e.i+=uo.length),ic(e,o)}default:if(cc(e,e.i+1))return e.i+=uo.length+1,ic(e,he(t.text))}return nf(e)}function of(e){I(O(e),Ud)&&e.i++;let t=[],n=ce();for(;e.err===null;){n=Sc(e),P(t,n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&lc.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&Jd(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===uc)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,of(e)),e.i===r&&e.err===null&&e.i++}return n}function be(e){let t=rc(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,dc)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as bc}from"node:path";var Wt="'",Oe='"',Xt="`",rf=" \r",qe="([{",ho=")]}",Eo=` \r
27
+ |;>`,Rc="*",Oc="1",go="::",Bt=go.length,sf=Bt;function Kt(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===Xt){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function cf(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===Oe&&r===Xt&&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===Wt||r===Oe){let s=Kt(e,o);if(s<0)return-1;o=s;continue}if(r===Xt){o++;continue}if(qe.includes(r))n++;else if(ho.includes(r)&&--n===0)return o}return-1}function af(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Wt||r===Oe){let s=Kt(e,o);if(s<0)return e.length;o=s;continue}if(qe.includes(r))n++;else if(ho.includes(r))n--;else if(n<=0&&Eo.includes(r))return o}return e.length}function lf(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===Wt||s===Oe){let i=Kt(e,r);if(i<0)break;r=i;continue}qe.includes(s)?n++:ho.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var uf=e=>e!==""&&(e===Rc||[...e].every(t=>t>="0"&&t<="9")),Tc=()=>({words:[],toFile:!1,chained:!1});function Ac(e){let t=[],n=[],o=Tc(),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=Tc()},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===Wt||p===Oe){let E=Kt(e,x);f(cf(e.slice(x+1,E<0?l:E),p),!0),x=E<0?l:E+1}else if(p===Xt)g!==`
28
+ `&&g!==""&&f(g,!1),x+=Bt;else if(p===`
29
+ `)u(),x++;else if(rf.includes(p))a(),x++;else if(p===";")u(),x++;else if(p==="|")g==="|"?(u(),x+=Bt):(d(),x++);else if(p==="&")g==="&"?(u(),x+=Bt):((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=Oc;s&&i&&uf(r)?(E=r,r="",s=!1):s&&a();let h=x+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<l&&!Eo.includes(e.charAt(h));)h++;else c=E===Oc||E===Rc?"file":"skip";x=h}else if(p==="("&&s&&i&&r.includes(go)){let E=Ye(e,x),h=e.slice(x+1,E<0?l:E);a();for(let S of h.trim()===""?[]:lf(h)){let _=Ac(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}x=E<0?l:E+1,x<l&&!Eo.includes(e.charAt(x))&&(o.chained=!0,x=af(e,x))}else if(p==="["&&!s&&e.startsWith(go,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 df=["get-content","gc","cat","type"],ff=["[io.file]::","[system.io.file]::"],xf=["readalltext","readalllines","readallbytes","readlines"],So=["path","literalpath"],Nc=["totalcount","head","first","tail","last"],yc=[...So,...Nc,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],pf=["raw","wait","force","asbytestream"],_f=[...yc,...pf],Ef=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],gf=["cd","chdir","sl","set-location","pushd","push-location"],mf=["powershell","powershell.exe","pwsh","pwsh.exe"],hf=["cmd","cmd.exe"],Sf=["/c","/k","/r"],bf="command",ae="-";function mo(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function bo(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 Of(e){if(e.length===0)return null;let t=mo(e[0]);if(!df.includes(t)){let r=e[0].toLowerCase(),s=ff.find(i=>r.startsWith(i));return s===void 0||!xf.includes(r.slice(s.length))||e.length<sf?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=bo(s,_f);if(i.full===void 0||!yc.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;So.includes(i.full)&&n.push(c),Nc.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function Tf(e,t){if(mf.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=bo(o,[bf]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(hf.includes(e)){for(let n=1;n<t.length;n++)if(Sf.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function Rf(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=bo(n,So);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function Ic(e,t,n,o){let r=t;for(let s of Ac(e)){let i=s[0];if(i.words.length===0)continue;let c=mo(i.words[0]);if(s.length===1&&gf.includes(c)){let u=Rf(i.words);u!==null&&(r=bc(r,u));continue}let l=n<v?Tf(c,i.words):null;if(l!==null){Ic(l,r,n+1,o);continue}if(i.toFile||i.chained)continue;let a=Of(i.words);if(a===null||a.bounded)continue;let d=!0;for(let u=1;u<s.length;u++)if(s[u].toFile||!Ef.includes(mo(s[u].words[0]??""))){d=!1;break}d&&o.push(bc(r,a.file))}}function Cc(e,t){let n=[];return Ic(e,t,0,n),n}import{join as zt}from"node:path";var kc=`\r
31
+ `,Af=`
32
+ `;function Yt(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(kc)<0?t:t.split(kc).join(Af)}import{basename as eg,dirname as tg,join as Dc,posix as ng,resolve as kf,win32 as og}from"node:path";var Nf=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 yf(e,t){let n=Nf[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(yf(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{mkdirSync:If,realpathSync:Cf}=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[Rt];return n!==void 0&&n!==""?n:Dc(t,...Fs["claude-code"])}function Df(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 qt(e,t){let n=e[Le];return n!==void 0&&n!==""?kf(n):Dc(t,Hr.slice(1))}function Lc(e){let t=e[Le],n=qt(e,t!==void 0&&t!==""?"":Df(e));return If(n,{recursive:!0}),Cf.native(n)}var{readFileSync:Uc}=process.getBuiltinModule("node:fs");function Te(e){return e.agentId!==void 0&&e.agentId!==""}function Ro(e,t){if(t===null)return"C";let n=ie(e.agent),o=new Set(t);for(let r of at)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function Ao(e,t){if(!Te(e))return null;let n=ie(e.agent);if(t.manifestTools!==void 0)return Mc(t.manifestTools.map(c=>Oo(n,c)));let o=e.agentType??"",r=Lf(o,t);if(r===null)return null;let s=(r.tools??Hf(n)).map(c=>Oo(n,c)),i=r.disallowed.map(c=>Oo(n,c));return Mc(s.filter(c=>!i.some(l=>vf(l,c))))}function Lf(e,t){if(!wf(e))return null;let n=Pf(t.env);if(e.indexOf(xe)>=0){if(n!==null){let s=Mf(le(t.env,n),e);if(s!==null)return s}}else{let s=To(zt(t.projectDir,vr,xt,e+pt));if(s!==null)return s;if(n!==null){let i=To(zt(le(t.env,n),xt,e+pt));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 Pf(e){return Q(e)}function Mf(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(Yt(Uc(zt(e,Rn,jr),"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(Gr);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=To(zt(u,xt,r+pt));if(f!==null)return f}}return null}function To(e){let t;try{t=Uc(e,"utf8")}catch{return null}return Uf(t)}function Uf(e){let t=e.split(`
33
+ `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==An)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===An){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=wc(o,Br),s=wc(o,Wr);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function wc(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(Pc(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>Pc(s.trim())).filter(s=>s!=="")}return null}function Pc(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function Hf(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...at.map(n=>e.toolNamePrefix+n)]}function Oo(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(Xr)?Ff(o):o}function Ff(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||Kr.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(Nn)){let n=e.slice(Nn.length);if(n!==""&&n.indexOf(yn)<0)return t.startsWith(e+yn)}return!1}function Mc(e){return[...new Set(e.filter(t=>t!==""))]}var ue="",Hc=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"],Gf="c",Bf=" -c",Wf=["-o","+o","-O","+O"],Vt="-",Xf="+",No="--",Kf="smhd",Yf=".",Fc=e=>e!==""&&e>="0"&&e<="9";function qf(e){if(e===""||!Fc(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(Fc(n)||n===Yf))return t===e.length-1&&Kf.includes(n)}return!0}function zf(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===No){n++;break}if(e.assignments&&vt(o)){n++;continue}if(o.startsWith(No)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(Vt)&&o.length>Vt.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=Vt.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||!qf(t[n]))return null;n++}return n<t.length?t.slice(n):null}function Vf(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(No)){if(o.startsWith(Vt)||o.startsWith(Xf)){o.includes(Gf)&&(t=!0),Wf.includes(o)&&n++;continue}return t?o:null}}return null}function vc(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function yo(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=Vf(i),f=u!==null&&n<v?be(u):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=vc(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,yo(p,[...r,l+Bf],n+1,o)}return}let a=Object.hasOwn(Hc,l)?Hc[l]:void 0,d=a===void 0?null:zf(a,i);if(d===null)break;r.push(l),s=xo(d[0]),i=d.slice(1),c=c||po(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=v))for(let l of Ft(e.raw)){let a=be(l.body);if(a.ok)for(let d of a.commands)yo(vc(d,e),[...t,l.wrapper],n+1,o)}}function Io(e){let t=[];for(let n of e)yo(n,[],0,t);return t}import{isAbsolute as $f,join as Co,relative as Qf,sep as ko}from"node:path";var{readFileSync:Jf}=process.getBuiltinModule("node:fs"),jc=".claude",Zf="settings.local.json",Gc="settings.json",zc="Bash",e0="Read",Bc=":*",Wc="//",Xc="~/",Kc="./",Yc="..",t0=`
34
+ \r`,n0=Object.freeze({tool:zc});function o0(e,t){if(t!=="claude-code")return[];let n=Q(process.env),o=process.env[Rt],r=o!==void 0&&o!==""?o:n===null?null:le(process.env,n),s=[Co(e,jc,Zf),Co(e,jc,Gc)];return r===null?s:[...s,Co(r,Gc)]}function qc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function r0(e){let t;try{t=Yt(Jf(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!qc(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!qc(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 Vc(e,t){let n=[];for(let o of o0(e,t)){let r=r0(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function Do(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 Lo(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=Do(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,Lo(o,t,n,s)[0]===1}function Jc(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 $c(e,t){let n=t.length,o=new Uint8Array(n+1);if(o[n]=1,!e.endsWith(Bc))return Lo(Do(e,!1),t,!1,o);for(let r=0;r<n;r++)t0.includes(t[r])&&(o[r]=1);return Lo(Do(e.slice(0,e.length-Bc.length),!1),t,!1,o)}function s0(e,t){return $c(e,t)[0]===1}function Qc(e,t,n){for(let o of t){let r=Jc(o);if(r===null||r.tool!==zc)continue;let s=$c(r.glob,e);for(let i=0;i<=e.length;i++)if(n[i]===1&&s[i]===1)return o}return null}var i0=/^[A-Za-z]:(?=\/)/;function Ve(e){return ko==="/"?e:e.split(ko).join("/")}function c0(e,t,n){if(e.startsWith(Kc)){if(n===void 0)return!1;let r=Qf(n,t);return r===""||r===Yc||r.startsWith(Yc+ko)||$f(r)?!1:ze(e.slice(Kc.length),Ve(r),!0)}let o=Ve(t);if(e.startsWith(Wc)){let r=Ve(e.slice(Wc.length-1));return ze(r,o,!0)||ze(r,o.replace(i0,""),!0)}if(e.startsWith(Xc)){let r=Q(process.env);return r!==null&&ze(Ve(r)+e.slice(Xc.length-1),o,!0)}return ze(Ve(e),o,!0)}function Re(e,t,n=n0){for(let o of t){let r=Jc(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===e0?c0(r.glob,e,n.projectDir):s0(r.glob,e))return o}return null}var Og=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.'}),Zc='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var a0="{size}",l0="{path}";function Jt(e,t,n=""){return k(Zc,n).split(a0).join(String(t)).split(l0).join(e)}var{statSync:u0}=process.getBuiltinModule("node:fs"),sa="Bash",Po="Read",d0="WebFetch",f0="ctx_execute",x0="ctx_batch",ia="shell",p0="1",Z="-",Mo="--",_0="=",E0=".",ea=",",wo="p",g0=["-e","--expression"],ta=".exe",m0=";&|(`\n\r",fe=Object.freeze({kind:"allow"}),W=e=>({kind:"deny",reason:e}),de=e=>typeof e=="string"?e:void 0,na=e=>e!=null,X=(e,t)=>e.includes(t);function ca(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[Fr]===p0)return W(k(_t,t.toolNamePrefix));process.stderr.write(as+`
35
+ `),i=[]}else i=n;let c=S0(r,s,e.cwd,i);return c!==null?W(we+c):r===d0?R0(s,t):r===sa?A0(e,t,s,i):r===Po?D0(e,t,s):fe}function aa(e,t,n,o){let r=e==="webfetch",s=r?Qr.map(c=>n.toolNamePrefix+c).join(cs):n.toolNamePrefix+$r,i=JSON.stringify(r?{url:t}:{language:ia,code:t,intent:o??Jr});return[In+Yr[e]+qr,zr,Vr+s,i].join(`
36
+ `)}function h0(e){for(let t of mt){let n=de(e[t]);if(n!==void 0&&n!=="")return n}}function la(e){let t=h0(e),n=Array.isArray(e[pe])?e[pe].filter(o=>typeof o=="string"&&o!==""):[];return t===void 0?n:[t,...n]}function S0(e,t,n,o){if(o.length===0)return null;let r=s=>Re(Qt(n,s),o,{tool:Po,projectDir:n});if(e===sa){let s=de(t.command);return s===void 0?null:Re(s,o)}if(e===Po){for(let s of la(t)){let i=r(s);if(i!==null)return i}return null}if(e===f0){let s=de(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=de(t.code);return b0(t.language)&&c!==void 0?oa(c,o):null}if(e===x0&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?oa(s,o):null;if(i!==null)return i}return null}function b0(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(ta)&&(t=t.slice(0,t.length-ta.length)),t===ia||X(Mr,t)}function oa(e,t){let n=Re(e,t);if(n!==null)return n;let o=be(e);if(!o.ok)return da(e,t);for(let r of Io(o.commands)){let s=ua(r,t);if(s!==null)return s}return null}function ua(e,t){return t.length===0?null:Re([e.argv0,...e.args].join(" "),t)??Re(e.raw,t)}function da(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||m0.includes(e.charAt(r-1)))&&(o=!0),o&&(r===e.length||e.charAt(r).trim()!=="")&&(n[r]=1,o=!1);return Qc(e,t,n)}function O0(e,t){return da(e,t)!==null}function T0(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return ls.some(n=>t===n||t.endsWith(E0+n))}function R0(e,t){let n=de(e.url)??"";return T0(n)?fe:W(aa("webfetch",n,t))}function A0(e,t,n,o){let r=de(n.command)??"",s=be(r);if(!s.ok)return O0(r,o)?W(k(Et,t.toolNamePrefix)):ra(r,e.cwd,t)??fe;let i=Io(s.commands);for(let c of i){let l=ua(c,o);if(l!==null)return W(we+l)}if(!_e(t)||Te(e))for(let c of i){let l=N0(c);if(l!==null)return W(aa(l,r,t,de(n.description)))}return L0(i,e.cwd,t)??ra(r,e.cwd,t)??fe}function N0(e){let t=e.argv0.toLowerCase();return X(us,t)&&y0(t,e)?"curl":C0(e.raw)?"http":X(ps,t)?"build":null}function y0(e,t){return t.redirectsToFile?!I0(e,t.args):!t.endsInBoundedSink}function I0(e,t){let n=ds[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===Mo)break;if(X(fs,s)||s===xs&&t[r+1]===Z)return!1;(s===n.long||s.startsWith(Z)&&!s.startsWith(Mo)&&s.includes(n.short,Z.length))&&(o=!0)}return o}function C0(e){let t=e.toLowerCase();for(let n of gs)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!==""&&_s.includes(o)&&t.startsWith(Es,n+Me.length+o.length))return!0}return!1}var k0="cd";function Uo(e){try{let t=u0(e);return t.isFile()?t.size:-1}catch{return-1}}function D0(e,t,n){if(!na(n.offset)&&!na(n.limit))for(let o of la(n)){let r=Qt(e.cwd,o),s=Uo(r);if(s>V)return W(Jt(r,s,t.toolNamePrefix))}return fe}function L0(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&to(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=Qt(o,s.args[0])),s.redirectsToFile||s.endsInBoundedSink||s.pipesOut===!0||s.insideConstruct!==void 0||!X(ms,i))continue;let c=M0(i,s.args);if(c===null)continue;if(c.bounded){r=fe;continue}let l=Qt(o,c.file),a=Uo(l);if(a>V)return W(Jt(l,a,n.toolNamePrefix))}return r}function ra(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&to(n))return null;for(let o of Cc(e,t)){let r=Uo(o);if(r>V)return W(Jt(o,r,n.toolNamePrefix))}return null}var $t=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function w0(e){if(X(Dn,e))return 1;for(let t of Dn)if(t.startsWith(Mo)?e.startsWith(t+_0):e.startsWith(t))return 0;return e.startsWith(Z)&&$t(e.slice(Z.length))?0:-1}function P0(e){if(e===wo)return"all";if(!e.endsWith(wo))return null;let t=e.slice(0,e.length-wo.length),n=t.indexOf(ea);return(n<0?$t(t):$t(t.slice(0,n))&&$t(t.slice(n+ea.length)))?"range":null}function M0(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(X(hs,e)){let l=w0(c);if(l>=0){o=!0,i+=l;continue}}if(e===gt&&X(Ss,c)){r=!0;continue}if(e===gt&&X(g0,c)){s=t[i+1],i++;continue}c.startsWith(Z)&&c!==Z||n.push(c)}if(e===gt){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:P0(s);if(i===null)return null;o=i==="range"}return e===bs&&n.shift()!==D.identity?null:n.length===1&&n[0]!==Z?{file:n[0],bounded:o}:null}import{basename as W0,dirname as Zt,join as $e,resolve as ga}from"node:path";import{dirname as fa,join as vg,relative as jg,sep as H0}from"node:path";var{lstatSync:Hg,realpathSync:U0}=process.getBuiltinModule("node:fs");function Ho(e){try{return U0.native(e)}catch{return}}function Ae(e){return e.split(H0).filter(t=>t!=="")}function xa(e,t){let n=Ho(e),o=Ho(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 pa(e){let t=e.map(Ho).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&&fa(r)!==r;)r=fa(r);return r}var F0=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]),v0=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],M=(e,t)=>e>>>t|e<<32-t;function _a(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=v0.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)+F0[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:j0,readFileSync:G0,realpathSync:Ea,statSync:B0}=process.getBuiltinModule("node:fs");function X0(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 K0(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(ft);return n<0?void 0:Je(t.argv[n+1])}case"pi:ctx.cwd":return Je(t.piCwd)}}function Y0(e){let t;try{t=Ea.native(e)}catch{throw new T("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=q0($e(t,bn));if(o!==null){let s=ma($e(o,wr));return{commonDir:Ea.native(s===null?o:ga(o,s)),worktree:t,start:n}}let r=Zt(t);if(r===t)return{commonDir:null,start:n};t=r}}function q0(e){let t;try{if(B0(e).isDirectory())t=e;else{let n=ma(e);if(n===null||!n.startsWith(Tn))return null;t=ga(Zt(e),n.slice(Tn.length))}}catch{return null}return j0($e(t,Pr))?t:null}function ma(e){let t;try{t=G0(e,"utf8")}catch{return null}let n=t.indexOf(`
37
+ `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function z0(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 V0(e,t){let n=W0(t)===bn?Zt(t):t,o=z0(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(On)).map(r=>r.slice(On.length));return pa([Zt(n),...o])}function ha(e,t){let n=X0(e),o=K0(n,t);if(o===void 0)throw new T("NO_PROJECT",{kind:n});let r=Y0(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??=_a(i).slice(0,Dr),l},get projectDir(){return a??=$e(Lc(process.env),dt,this.projectKey),a},get dbPath(){return $e(this.projectDir,Lr)},worktree:c,get containmentRoot(){return d??=s??V0(o,i),d},agent:e,source:n}}var en=ke,J0=`
39
+ PRAGMA busy_timeout = ${J};
38
40
  PRAGMA journal_mode = WAL;
39
- `,Jt="tokenize = 'porter unicode61 remove_diacritics 2'",x0="tokenize = 'unicode61 remove_diacritics 2'",p0=`
41
+ `,tn="tokenize = 'porter unicode61 remove_diacritics 2'",$0="tokenize = 'unicode61 remove_diacritics 2'",Q0=`
40
42
  CREATE TABLE IF NOT EXISTS events (
41
43
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
42
44
  session_id TEXT NOT NULL,
@@ -81,16 +83,16 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
81
83
  agent UNINDEXED,
82
84
  ord UNINDEXED,
83
85
  body,
84
- ${x0}
86
+ ${$0}
85
87
  );
86
88
 
87
89
  CREATE TABLE IF NOT EXISTS meta (
88
90
  key TEXT PRIMARY KEY,
89
91
  value TEXT NOT NULL
90
92
  );
91
- `,_0=`
93
+ `,Z0=`
92
94
  CREATE UNIQUE INDEX IF NOT EXISTS idx_events_cost_session_turn ON events(session_id, turn) WHERE kind = 'cost';
93
- `,E0=`
95
+ `,ex=`
94
96
  CREATE VIRTUAL TABLE chunks_v3 USING fts5(
95
97
  source_id UNINDEXED,
96
98
  session_id UNINDEXED,
@@ -99,13 +101,13 @@ CREATE VIRTUAL TABLE chunks_v3 USING fts5(
99
101
  ord UNINDEXED,
100
102
  body,
101
103
  title,
102
- ${Jt}
104
+ ${tn}
103
105
  );
104
106
  INSERT INTO chunks_v3(rowid, source_id, session_id, worktree, agent, ord, body, title)
105
107
  SELECT rowid, source_id, session_id, worktree, agent, ord, body, '' FROM chunks;
106
108
  DROP TABLE chunks;
107
109
  ALTER TABLE chunks_v3 RENAME TO chunks;
108
- `,g0=`
110
+ `,tx=`
109
111
  CREATE VIRTUAL TABLE chunks_tri USING fts5(
110
112
  body,
111
113
  title,
@@ -114,24 +116,24 @@ CREATE VIRTUAL TABLE chunks_tri USING fts5(
114
116
  );
115
117
  INSERT INTO chunks_tri(rowid, body, title) SELECT rowid, body, title FROM chunks;
116
118
  CREATE VIRTUAL TABLE chunks_vocab USING fts5vocab(chunks, 'row');
117
- `,m0=`
119
+ `,nx=`
118
120
  CREATE VIRTUAL TABLE line_units USING fts5(
119
121
  body,
120
122
  source_id UNINDEXED,
121
123
  session_id UNINDEXED,
122
124
  ord UNINDEXED,
123
- ${Jt}
125
+ ${tn}
124
126
  );
125
- `,h0=`
127
+ `,ox=`
126
128
  UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
127
- `,S0=[{version:1,sql:p0},{version:2,sql:_0},{version:3,sql:E0},{version:4,sql:g0},{version:5,sql:m0},{version:6,sql:h0}];function Io(e,t){if(t!==zt){if(t>zt)throw new T("SCHEMA_STALE",{found:t,want:zt});e.exec(f0),e.exec("BEGIN IMMEDIATE");try{for(let n of S0)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${zt}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}var{existsSync:qe,linkSync:b0,mkdirSync:O0,rmSync:T0}=process.getBuiltinModule("node:fs");function Vc(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function R0(e,t){let n=Vc(e),o=Vc(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 A0(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&_r;return n===Er||n===gr}async function N0(){try{return await import("node:sqlite")}catch{throw new T("NO_SQLITE")}}function Co(e){return e.prepare("PRAGMA user_version").get().user_version}function y0(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+pr;try{let r=new e.DatabaseSync(o,{timeout:ue});try{Io(r,Co(r))}finally{r.close()}try{b0(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",rt,st])T0(o+r,{force:!0})}}function zc(e,t){let n=null;try{return qe(t)||y0(e,t),n=new e.DatabaseSync(t,{timeout:ue}),Io(n,Co(n)),n}catch(o){throw n&&n.close(),o}}function I0(e,t){let n=new e.DatabaseSync(t,{timeout:ue,readOnly:!0});try{let o=Co(n);if(o!==Ae)throw new T("SCHEMA_STALE",{found:o,want:Ae});return n}catch(o){throw n.close(),o}}async function A(e,t){if(R0(process.version,Ne))throw new T("NODE_TOO_OLD",{v:process.version});let n=await N0();O0(e.projectDir,{recursive:!0});let o=e.dbPath;if((qe(o+rt)||qe(o+st))&&!qe(o))throw new T("DB_GONE");try{let s;return t?.readOnly===!0?(qe(o)||zc(n,o).close(),s=I0(n,o)):s=zc(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw A0(s)?new T("DB_CORRUPT"):s}}function P(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 Jc(e,t){return e.raw.isTransaction?t(e):P(e,t)}function Q(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function B(e,t,n){Jc(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function $t(e,t){return Jc(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var $c="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",C0="INSERT INTO "+$c,k0="INSERT OR IGNORE INTO "+$c,D0="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function Qt(e,t){return P(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?k0:C0).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(D0).get(t.session_id,t.turn).seq})}function Qc(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 ko(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 Zc(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 ea(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 ta(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 na(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function oa(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var Do=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 L0(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=Do.length/2-1;for(;t<=n;){let o=t+n>>1,r=Do[2*o],s=Do[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function w0(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 be(e){return w0(e,t=>!L0(t))}var P0=`
129
+ `,rx=[{version:1,sql:Q0},{version:2,sql:Z0},{version:3,sql:ex},{version:4,sql:tx},{version:5,sql:nx},{version:6,sql:ox}];function Fo(e,t){if(t!==en){if(t>en)throw new T("SCHEMA_STALE",{found:t,want:en});e.exec(J0),e.exec("BEGIN IMMEDIATE");try{for(let n of rx)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${en}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}function Sa(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:ix,rmSync:cx}=process.getBuiltinModule("node:fs");function ba(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function ax(e,t){let n=ba(e),o=ba(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 lx(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&Ir;return n===Cr||n===kr}async function ux(){try{return await import("node:sqlite")}catch{throw new T("NO_SQLITE")}}function vo(e){return e.prepare("PRAGMA user_version").get().user_version}function dx(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+yr;try{let r=new e.DatabaseSync(o,{timeout:J});try{Fo(r,vo(r))}finally{r.close()}try{sx(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",lt,ut])cx(o+r,{force:!0})}}function Oa(e,t){let n=null;try{return Qe(t)||dx(e,t),n=new e.DatabaseSync(t,{timeout:J}),Fo(n,vo(n)),n}catch(o){throw n&&n.close(),o}}function fx(e,t){let n=Sa(e,t);try{let o=vo(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(ax(process.version,De))throw new T("NODE_TOO_OLD",{v:process.version});let n=await ux();ix(e.projectDir,{recursive:!0});let o=e.dbPath;if((Qe(o+lt)||Qe(o+ut))&&!Qe(o))throw new T("DB_GONE");try{let s;return t?.readOnly===!0?(Qe(o)||Oa(n,o).close(),s=fx(n,o)):s=Oa(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw lx(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 Ta(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){Ta(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function nn(e,t){return Ta(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var Ra="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",xx="INSERT INTO "+Ra,px="INSERT OR IGNORE INTO "+Ra,_x="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function on(e,t){return U(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?px:xx).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(_x).get(t.session_id,t.turn).seq})}function Aa(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 jo(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 Na(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 ya(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 Ia(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 Ca(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function ka(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var Go=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 Ex(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=Go.length/2-1;for(;t<=n;){let o=t+n>>1,r=Go[2*o],s=Go[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function gx(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 Ne(e){return gx(e,t=>!Ex(t))}var mx=`
128
130
  INSERT INTO sources(session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts)
129
131
  VALUES (:session_id, :worktree, :agent, :kind, :label, :bytes_total, :chunk_count, :created_ts, :created_at, :created_ts)
130
- RETURNING id`,M0=`
131
- INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,sa=1,ra=" (raw)",ia=`AND (:source IS NOT NULL OR substr(s.label, -${ra.length}) <> '${ra}')`,ca=`
132
+ RETURNING id`,hx=`
133
+ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,La=1,Da=" (raw)",wa=`AND (:source IS NOT NULL OR substr(s.label, -${Da.length}) <> '${Da}')`,Pa=`
132
134
  SELECT chunks.rowid AS rid, chunks.source_id AS source_id, chunks.session_id AS session_id,
133
135
  chunks.worktree AS worktree, chunks.ord AS ord, s.created_ts AS created_ts,
134
- bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${sa}) AS bm,
136
+ bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${La}) AS bm,
135
137
  (chunks.rowid IN (SELECT rowid FROM chunks WHERE chunks MATCH :all)) AS full
136
138
  FROM chunks JOIN sources s ON s.id = chunks.source_id
137
139
  WHERE chunks MATCH :match
@@ -139,9 +141,9 @@ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VAL
139
141
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
140
142
  AND (:source IS NULL OR s.label = :source)
141
143
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
142
- ${ia}`,aa=`
143
- ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,Dg=`
144
- WITH m AS (${ca}
144
+ ${wa}`,Ma=`
145
+ ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,ym=`
146
+ WITH m AS (${Pa}
145
147
  ), r AS (
146
148
  SELECT *,
147
149
  ROW_NUMBER() OVER (ORDER BY full DESC, bm ASC, source_id DESC, ord ASC) AS rank_a,
@@ -149,11 +151,11 @@ WITH m AS (${ca}
149
151
  FROM m
150
152
  )
151
153
  SELECT rid, source_id, session_id, worktree, ord, full, 1.0 / (:k + rank_a) + 1.0 / (:k + rank_b) AS score
152
- FROM r${aa}`,Lg=`
153
- WITH m AS (${ca}
154
+ FROM r${Ma}`,Im=`
155
+ WITH m AS (${Pa}
154
156
  )
155
157
  SELECT rid, source_id, session_id, worktree, ord, full, -bm AS score
156
- FROM m${aa}`;var wg=`
158
+ FROM m${Ma}`;var Cm=`
157
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
158
160
  FROM chunks_tri t JOIN chunks c ON c.rowid = t.rowid JOIN sources s ON s.id = c.source_id
159
161
  WHERE chunks_tri MATCH :match
@@ -161,63 +163,63 @@ WHERE chunks_tri MATCH :match
161
163
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
162
164
  AND (:source IS NULL OR s.label = :source)
163
165
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
164
- ${ia}
165
- ORDER BY bm25(chunks_tri, 1.0, ${sa}) ASC, c.source_id DESC, c.ord ASC`;var U0="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",H0="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function la(e,t,n){let o=Lo(e,t,n);return da(e,o,t,n),o}function Lo(e,t,n){let o=0;for(let r of n)o+=r.bytes;return P(e,r=>{let s=r.raw.prepare(P0).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 ua(e,t,n,o,r){try{da(e,t,n,o),Po(e,t,n.sessionId,r)}catch(s){throw P(e,i=>{F0(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function da(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>un&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)P(e,a=>{let l=a.raw.prepare(M0),u=a.raw.prepare(U0);for(let d of c){let f=d.title??"",x=l.run(t,n.sessionId,n.worktree,n.agent,d.ord,d.text,f).lastInsertRowid;u.run(x,d.text,f)}})}function F0(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(H0+" 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 wo(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 v0(e){return[...new Set(wo(e).split(" ").filter(n=>n!==""))].join(" OR ")}var j0=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 G0(e){let t=[...new Set(wo(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!j0.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var Zt=`
166
+ ${wa}
167
+ ORDER BY bm25(chunks_tri, 1.0, ${La}) ASC, c.source_id DESC, c.ord ASC`;var Sx="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",bx="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function Ua(e,t,n){let o=Bo(e,t,n);return Fa(e,o,t,n),o}function Bo(e,t,n){let o=0;for(let r of n)o+=r.bytes;return U(e,r=>{let s=r.raw.prepare(mx).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 Ha(e,t,n,o,r){try{Fa(e,t,n,o),Xo(e,t,n.sessionId,r)}catch(s){throw U(e,i=>{Ox(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function Fa(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>_n&&(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(hx),d=l.raw.prepare(Sx);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 Ox(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(bx+" 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 Wo(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 Tx(e){return[...new Set(Wo(e).split(" ").filter(n=>n!==""))].join(" OR ")}var Rx=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 Ax(e){let t=[...new Set(Wo(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!Rx.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var rn=`
166
168
  AND (:scope <> 'session' OR session_id = :session_id)
167
- AND (:scope <> 'worktree' OR worktree = :worktree)`,Pg=`
169
+ AND (:scope <> 'worktree' OR worktree = :worktree)`,km=`
168
170
  WITH e AS (
169
171
  SELECT seq, kind, key, path, body, created_at FROM events
170
- WHERE created_at > :after${Zt}
172
+ WHERE created_at > :after${rn}
171
173
  AND (:source IS NULL OR kind = :source)
172
174
  )
173
175
  SELECT seq, kind, key, path, body, created_at FROM e
174
176
  WHERE created_at <= IFNULL((SELECT created_at FROM e ORDER BY created_at, seq LIMIT 1 OFFSET :off), created_at)
175
- ORDER BY created_at ASC, seq ASC`,Mg=`
177
+ ORDER BY created_at ASC, seq ASC`,Dm=`
176
178
  WITH s AS (
177
179
  SELECT id, label, created_ts FROM sources
178
- WHERE created_ts > :after${Zt}
180
+ WHERE created_ts > :after${rn}
179
181
  AND (:source IS NULL OR label = :source)
180
182
  AND label <> :reserved
181
183
  )
182
184
  SELECT id, label, created_ts FROM s
183
185
  WHERE created_ts <= IFNULL((SELECT created_ts FROM s ORDER BY created_ts, id LIMIT 1 OFFSET :off), created_ts)
184
- ORDER BY created_ts ASC, id ASC`;var Ug=`
185
- SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${Zt} AND (:source IS NULL OR kind = :source))
186
- OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${Zt} AND (:source IS NULL OR label = :source)
187
- AND label <> :reserved) AS more`;var B0=`CREATE VIRTUAL TABLE r USING fts5(body, ${Jt}, content='')`,W0="INSERT INTO r(rowid, body) VALUES (?, ?)",X0="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function W(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?v0(t):wo(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(B0);let c=i.prepare(W0);i.exec("BEGIN");for(let a=0;a<e.length;a++)c.run(a+1,e[a]);i.exec("COMMIT");for(let a of i.prepare(X0).all(r))o[Number(a.id)-1]=-a.bm;return o}finally{i.close()}}var K0="s";function fa(e){return K0+e.toString(36)}function Po(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<=un);)i+=o[s].body.length,s++;let c=r;P(e,a=>{let l=a.raw.prepare("INSERT INTO line_units(body, source_id, session_id, ord) VALUES (?, ?, ?, ?)");for(let u=c;u<s;u++){let d=o[u];l.run(d.body,t,n,d.ord)}}),r=s}}function xa(e,t){return t===e?e:e+" "+t}function pa(e,t,n,o){let r=G0(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 q0(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function Mo(e){let t=e.split(`
188
- `),n=[],o=[];for(let r=0;r<t.length;r++){let s=t[r].endsWith("\r")?t[r].slice(0,-1):t[r],i=q0(s);if(i!==s.length){for(;n.length>0&&n[n.length-1].indent>=i;)n.pop();o.push({ord:r,body:[...n.map(c=>c.line),s].join(`
189
- `)}),n.push({indent:i,line:s})}}return o}function Uo(e){let t=e.indexOf(`
190
- `);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function Oe(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 Ye(e){return e.length>dn?e.slice(e.length-dn):e}function Y0(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function _a(e,t){if(!t)return Y0();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:Oe("last_request",r,"now: "+Uo(r.body),1,null),i=o.slice(0,o.length-1).map(_=>Oe("earlier_requests",_,"asked #"+_.seq+": "+Uo(_.body),1,null)),c=new Map,a=new Map;for(let _ of n)if(!(_.kind!=="cmd"&&_.kind!=="toolerr"||_.key===null)){if(_.ok===1){a.set(_.key,_.seq);continue}c.set(_.key,{row:_,count:(c.get(_.key)?.count??0)+1})}let l=[];for(let[_,m]of c)(a.get(_)??0)>m.row.seq||l.push(Oe("open_errors",m.row,"error #"+m.row.seq+" "+(m.row.tool??"")+": "+_,m.count,_));l.sort((_,m)=>_.seq-m.seq);let u=new Map;for(let _ of n)_.kind!=="edit"||_.path===null||u.set(_.path,{row:_,count:(u.get(_.path)?.count??0)+1});let d=[];for(let[_,m]of u){let R=Oe("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);d.push({...R,editCount:m.count})}d.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(Oe("decisions",m.row,"decided #"+m.row.seq+": "+Uo(m.row.body),m.count,_));x.sort((_,m)=>_.seq-m.seq);let p=n.filter(_=>_.kind==="index").map(_=>Oe("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:Ye(l),changedFiles:Ye(d),decisions:Ye(x),earlierRequests:Ye(i),indexedSources:Ye(p)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=fn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-fn));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 V0(e){if(!Object.hasOwn(xn,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=pn[Math.min(t,pn.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(xn[e.section]*n*o/bs)}function z0(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 Ea(e,t){return e.map(n=>({...n,score:V0({section:z0(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function ha(e){return e.sourceId+":"+e.ord}function tn(e){return"@"+e.label+" line "+(e.ord+1)+`:
191
- `+e.body}function J0(e){return new Set(be(e.toLowerCase()))}function $0(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 Fo(e,t,n){let o=e.filter(l=>!t.has(ha(l))&&l.score>=Dn);if(o.length===0)return[];let r=Math.max(...o.map(l=>l.score)),s=o.map(l=>J0(l.body)),i=[],c=new Set(o.map((l,u)=>u)),a=0;for(;c.size>0;){let l=-1,u=-1/0;for(let f of c){let x=0;for(let g of i)x=Math.max(x,$0(s[f],s[g]));let p=dr*(o[f].score/r)-fr*x;p>u&&(u=p,l=f)}c.delete(l);let d=en(tn(o[l]))+1;a+d>n||(a+=d,i.push(l))}return i.map(l=>o[l])}var ga={text:"",seqs:[]};function en(e){return Buffer.byteLength(e,"utf8")}function Ho(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
192
- `)}function ma(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+Ho(e)}function Sa(e,t,n,o=[],r=new Set){if(t.trim()==="")return ga;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&Ho(f)!==""),i=s.length===0?[]:W(s.map(Ho),t,"any"),c=s.map((f,x)=>({r:f,score:i[x]})).filter(f=>f.score>=Dn).sort((f,x)=>x.score-f.score||x.r.seq-f.r.seq),a=en(wn)+1+en(Pn),l=[];for(let{r:f}of c){let x=en(ma(f))+1;a+x>kn||(a+=x,l.push(f))}let u=Fo(o,r,kn-a);if(l.length===0&&u.length===0)return ga;l.sort((f,x)=>f.seq-x.seq);let d=[...l.map(ma),...u.map(tn)];return{text:[wn,...d,Pn].join(`
193
- `),seqs:l.map(f=>f.seq),...u.length>0?{units:u.map(ha)}:{}}}function Z(e){return Buffer.byteLength(e,"utf8")}function vo(e,t){return e.bytes>nr?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function jo(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function ba(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=_a(e,s),a=`<context_mode_state session="${s}" upto="${i}">`,l=Z(jo([],o)),u=tr-(Z(a)+1+l+1+Z(ln)),d=0,f=c.lastRequest===null?null:vo(c.lastRequest,o);f!==null&&(d+=Z(f)+1);let x=Ea([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),p=new Map,g=[],E=[];for(;x.length>0;){let m=0,R=-1/0;for(let tt=0;tt<x.length;tt++){let nt=x[tt],an=nt.score*ur**(p.get(nt.section)??0)/nt.bytes;(an>R||an===R&&nt.seq>x[m].seq)&&(m=tt,R=an)}let C=x.splice(m,1)[0],et=Z(vo(C,o))+1;d+et<=u?(d+=et,g.push(C),p.set(C.section,(p.get(C.section)??0)+1)):E.push(C)}let h=[a];f!==null&&h.push(f);for(let m of["open_errors","changed_files","decisions","earlier_requests","indexed_sources"])for(let R of g.filter(C=>C.section===m).sort((C,et)=>C.seq-et.seq))h.push(vo(R,o));if(n!==void 0){for(let m of n.sources){let R=Z(m)+1;d+R>u||(d+=R,h.push(m))}for(let m of Fo(n.units,new Set,u-d)){let R=tn(m);d+=Z(R)+1,h.push(R)}}let S=[],_=new Set;for(let m of E.sort((R,C)=>R.seq-C.seq))if(!(m.query===null||_.has(m.query))){if(Z(jo([...S,m.query],o))-l>u-d)break;S.push(m.query),_.add(m.query)}return h.push(jo(S,o),ln),h.join(`
194
- `)}var Q0=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Z0=new Set(["script","style"]),ex=new TextEncoder;function nn(e,t,n=ne){let o=ox(e);if(o.length===0)return[];let r=Math.max(4,Math.min(ne,Math.floor(n)));if(t==="md")return tx(o,r,r<ne);let s=t==="html"?cx(o):Go(o,!1);return Bo(o,s,t!=="text",r,r<ne)}function tx(e,t,n){let o=[],r=[],s="",i=[],c=(l,u)=>{o.push({ord:o.length,text:l,bytes:u,title:s})},a=()=>{if(i.length!==0){for(let l of Bo(e,i,!0,t,n))c(l.text,l.bytes);i=[]}};for(let l of Go(e,!0)){if(l.heading!==void 0){for(a();r.length>0&&r[r.length-1].level>=l.heading.level;)r.pop();r.push(l.heading),s=r.map(u=>u.text).join(" > ")}if(l.fence!==void 0&&ee(e.slice(l.start,l.end))>t){let u=nx(e,l,l.fence,t);if(u!==void 0){a();for(let d of u)c(d,ee(d));continue}}i.push(l)}return a(),o}function nx(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),a=o-ee(r)-ee(s)-2;if(!(a<16||c.length===0))return Bo(c,Go(c,!1),!0,a,!0).map(l=>r+`
195
- `+l.text+`
196
- `+s)}function ox(e){let t=e.split(`\r
186
+ ORDER BY created_ts ASC, id ASC`;var Lm=`
187
+ SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${rn} AND (:source IS NULL OR kind = :source))
188
+ OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${rn} AND (:source IS NULL OR label = :source)
189
+ AND label <> :reserved) AS more`;var Nx=`CREATE VIRTUAL TABLE r USING fts5(body, ${tn}, content='')`,yx="INSERT INTO r(rowid, body) VALUES (?, ?)",Ix="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"?Tx(t):Wo(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(Nx);let c=i.prepare(yx);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(Ix).all(r))o[Number(l.id)-1]=-l.bm;return o}finally{i.close()}}var Cx="s";function va(e){return Cx+e.toString(36)}function Xo(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<=_n);)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 ja(e,t){return t===e?e:e+" "+t}function Ga(e,t,n,o){let r=Ax(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 Ko(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=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 Yo(e){let t=e.indexOf(`
192
+ `);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function ye(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>En?e.slice(e.length-En):e}function Dx(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function Ba(e,t){if(!t)return Dx();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:ye("last_request",r,"now: "+Yo(r.body),1,null),i=o.slice(0,o.length-1).map(_=>ye("earlier_requests",_,"asked #"+_.seq+": "+Yo(_.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(ye("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 A=ye("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);u.push({...A,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(ye("decisions",m.row,"decided #"+m.row.seq+": "+Yo(m.row.body),m.count,_));x.sort((_,m)=>_.seq-m.seq);let p=n.filter(_=>_.kind==="index").map(_=>ye("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<=gn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-gn));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 Lx(e){if(!Object.hasOwn(mn,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=hn[Math.min(t,hn.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(mn[e.section]*n*o/Ms)}function wx(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 Wa(e,t){return e.map(n=>({...n,score:Lx({section:wx(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function Ya(e){return e.sourceId+":"+e.ord}function cn(e){return"@"+e.label+" line "+(e.ord+1)+`:
193
+ `+e.body}function Px(e){return new Set(Ne(e.toLowerCase()))}function Mx(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 zo(e,t,n){let o=e.filter(a=>!t.has(Ya(a))&&a.score>=Un);if(o.length===0)return[];let r=Math.max(...o.map(a=>a.score)),s=o.map(a=>Px(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,Mx(s[f],s[g]));let p=Rr*(o[f].score/r)-Ar*x;p>d&&(d=p,a=f)}c.delete(a);let u=sn(cn(o[a]))+1;l+u>n||(l+=u,i.push(a))}return i.map(a=>o[a])}var Xa={text:"",seqs:[]};function sn(e){return Buffer.byteLength(e,"utf8")}function qo(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
194
+ `)}function Ka(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+qo(e)}function qa(e,t,n,o=[],r=new Set){if(t.trim()==="")return Xa;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&qo(f)!==""),i=s.length===0?[]:Y(s.map(qo),t,"any"),c=s.map((f,x)=>({r:f,score:i[x]})).filter(f=>f.score>=Un).sort((f,x)=>x.score-f.score||x.r.seq-f.r.seq),l=sn(Fn)+1+sn(vn),a=[];for(let{r:f}of c){let x=sn(Ka(f))+1;l+x>He||(l+=x,a.push(f))}let d=zo(o,r,He-l);if(a.length===0&&d.length===0)return Xa;a.sort((f,x)=>f.seq-x.seq);let u=[...a.map(Ka),...d.map(cn)];return{text:[Fn,...u,vn].join(`
195
+ `),seqs:a.map(f=>f.seq),...d.length>0?{units:d.map(Ya)}:{}}}function te(e){return Buffer.byteLength(e,"utf8")}function Vo(e,t){return e.bytes>xr?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function Jo(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function za(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=Ba(e,s),l=`<context_mode_state session="${s}" upto="${i}">`,a=te(Jo([],o)),d=fr-(te(l)+1+a+1+te(pn)),u=0,f=c.lastRequest===null?null:Vo(c.lastRequest,o);f!==null&&(u+=te(f)+1);let x=Wa([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),p=new Map,g=[],E=[];for(;x.length>0;){let m=0,A=-1/0;for(let it=0;it<x.length;it++){let ct=x[it],xn=ct.score*Tr**(p.get(ct.section)??0)/ct.bytes;(xn>A||xn===A&&ct.seq>x[m].seq)&&(m=it,A=xn)}let C=x.splice(m,1)[0],st=te(Vo(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 A of g.filter(C=>C.section===m).sort((C,st)=>C.seq-st.seq))h.push(Vo(A,o));if(n!==void 0){for(let m of n.sources){let A=te(m)+1;u+A>d||(u+=A,h.push(m))}for(let m of zo(n.units,new Set,d-u)){let A=cn(m);u+=te(A)+1,h.push(A)}}let S=[],_=new Set;for(let m of E.sort((A,C)=>A.seq-C.seq))if(!(m.query===null||_.has(m.query))){if(te(Jo([...S,m.query],o))-a>d-u)break;S.push(m.query),_.add(m.query)}return h.push(Jo(S,o),pn),h.join(`
196
+ `)}var Ux=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Hx=new Set(["script","style"]),Fx=new TextEncoder;function an(e,t,n=re){let o=Gx(e);if(o.length===0)return[];let r=Math.max(4,Math.min(re,Math.floor(n)));if(t==="md")return vx(o,r,r<re);let s=t==="html"?Kx(o):$o(o,!1);return Qo(o,s,t!=="text",r,r<re)}function vx(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 Qo(e,i,!0,t,n))c(a.text,a.bytes);i=[]}};for(let a of $o(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=jx(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 jx(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 Qo(c,$o(c,!1),!0,l,!0).map(a=>r+`
197
+ `+a.text+`
198
+ `+s)}function Gx(e){let t=e.split(`\r
197
199
  `).join(`
198
- `);return t.startsWith("\uFEFF")?t.slice(1):t}function Go(e,t){let n=[],o=-1,r=-1,s=!1,i="",c,a,l=()=>{if(o>=0){let f={start:o,end:r};c!==void 0&&(f.heading=c),a!==void 0&&(f.fence=a),n.push(f)}o=-1,c=void 0,a=void 0},u=(f,x,p)=>{o<0&&(o=f),r=x,s=p},d=0;for(;d<=e.length;){let f=e.indexOf(`
199
- `,d),x=f<0?e.length:f,p=e.slice(d,x);if(i!=="")u(d,x,!1),ix(p,i)&&(i="",t&&a!==void 0&&(a.closeStart=d,l()));else if(p.length===0)l();else{let g=t?sx(p):"",E=t&&g===""?rx(p):void 0,h=t&&g===""&&E===void 0&&p.includes("|");t&&o>=0&&(h!==s||g!==""||E!==void 0)&&l(),u(d,x,h),i=g,g!==""&&(a={fence:g,openEnd:x,closeStart:-1}),E!==void 0&&(c=E,l())}d=x+1}return l(),n}function rx(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 sx(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 ix(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 cx(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{Ta(t,e,r,c),r=c};for(;s<e.length;){if(e[s]!=="<"){s+=1;continue}if(e.startsWith("<!--",s)){let a=e.indexOf("-->",s+4);s=a<0?e.length:a+3;continue}let c=ax(e,s);if(c===void 0){s+=1;continue}if(s=c.end,c.close){let a=n.get(c.name)??0;if(a===0)continue;n.set(c.name,a-1),o-=1,o===0&&i(s);continue}if(!(c.selfClose||Q0.has(c.name))){if(Z0.has(c.name)){s=lx(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return Ta(t,e,r,e.length),t}function Aa(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function Na(e){return Aa(e)||e>="0"&&e<="9"||e==="-"||e===":"}function ax(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!Aa(e[n]))return;let r=n;for(;n<e.length&&Na(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 lx(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||!Na(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function Oa(e){return e===" "||e===`
200
- `||e===" "||e==="\f"||e==="\r"}function Ta(e,t,n,o){let r=n,s=o;for(;r<s&&Oa(t[r]);)r+=1;for(;s>r&&Oa(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function ee(e){return Buffer.byteLength(e,"utf8")}function Ra(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=ex.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function Bo(e,t,n,o,r){let s=[],i=new Uint8Array(o),c,a,l=0,u=(d,f,x)=>{s.push({ord:s.length,text:e.slice(d,f),bytes:x})};for(let d of t){if(a!==void 0&&!n&&(u(a.start,a.end,l),a=void 0),a!==void 0){let p=ee(e.slice(a.end,d.end));if(l+p<=o){a.end=d.end,l+=p;continue}u(a.start,a.end,l),a=void 0}let f=d.start,x=ee(e.slice(d.start,d.end));for(;x>o;){let p=Ra(e,f,d.end,i),g=r?e.lastIndexOf(`
201
- `,p.end-1):-1;if(g>f){let E=ee(e.slice(f,g+1));u(f,g+1,E),f=g+1,x-=E;continue}if(r){let E=e.indexOf(`
202
- `,f),h=E<0||E>=d.end?d.end:E+1,S=ee(e.slice(f,h));if(S<=ne){u(f,h,S),f=h,x-=S;continue}c??=new Uint8Array(ne);let _=Ra(e,f,h,c);u(f,_.end,_.written),f=_.end,x-=_.written;continue}u(f,p.end,p.written),f=p.end,x-=p.written}f>=d.end||(a={start:f,end:d.end},l=x)}return a!==void 0&&u(a.start,a.end,l),s}var ux=`
203
- `,dx=1;function ya(e,t,n,o,r){return fx(e,t,n,o,r)}function fx(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?W(s,t):W(s,r,"any"),c=e.map((f,x)=>x).sort((f,x)=>i[x]-i[f]||e[x].ord-e[f].ord),a=[],l=0,u=!1;for(let f of c){let x=e[f].bytes+(a.length>0?dx:0);if(l+x>n){u=!0;continue}a.push(e[f]),l+=x}return a.sort((f,x)=>f.ord-x.ord),{text:a.map(f=>f.text).join(ux),more:u?Wo(t,o):null}}function Wo(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>Hn?"...":JSON.stringify(e))+"]"+n+"})"}var Ia=20,M=2,Ca=9,ka=8,xx=.9,px=.5,_x=64,Ex=2,gx=4,Xo=`
204
- `,mx="(absent)",X=e=>Buffer.byteLength(e,"utf8");function Da(e,t,n){let o=bx(e,t)??Rx(e,t)??yx(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):W(o.units.map(l=>l.rank),t,"any"),s=o.units.map((l,u)=>u).filter(l=>r[l]>0).sort((l,u)=>r[u]-r[l]||o.units[l].pos-o.units[u].pos),i=[],c=0;for(let l of s){let u=i.length>0?X(Xo):0,d=o.units[l].render(n-c-u);d===null||c+u+X(d)>n||(i.push({pos:o.units[l].pos,text:d}),c+=u+X(d))}if(i.length===0)return null;i.sort((l,u)=>l.pos-u.pos);let a=i.map(l=>l.text);return c+X(Xo)+X(o.header)<=n&&a.unshift(o.header),a.join(Xo)}function hx(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
205
- `&&n!=="\r"&&n!==" ")return n}return""}function Sx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function La(e,t,n){if(n.size<2||n.size>ka)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=M+1)return o[0][1]<xx*e||e-o[0][1]>M?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>M),s=o.filter(([,i])=>i<=M);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function wa(e){if(hx(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<Ia||!t.every(Sx))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 Pa=(e,t)=>e+" objects {"+t.join(",")+"}";function bx(e,t){let n=wa(e);if(n===null)return null;let{objs:o,keys:r}=n,s=new Map;for(let l of r){let u=new Map,d=new Map,f=!0;for(let x=0;x<o.length&&f;x++){let p=l in o[x]?o[x][l]:void 0;if(typeof p=="object"&&p!==null){f=!1;break}let g=p===void 0?mx:JSON.stringify(p);d.set(g,(d.get(g)??0)+1);let E=u.get(g)??[];if(E.length<=M&&E.push(x),u.set(g,E),d.size>ka)break}if(f)for(let x of La(o.length,u,d))s.set(x,[...s.get(x)??[],l])}if(s.size===0||s.size>Ca)return null;let i=W(r,t,"any"),c=new Set(r.filter((l,u)=>i[u]>0)),a=[...s.entries()].map(([l,u])=>({pos:l,rank:JSON.stringify(o[l]),render:d=>Ma(l,o[l],u,c,d)}));return{header:Pa(o.length,r)+", "+s.size+" rare:",units:a}}function Ma(e,t,n,o,r){let s="["+e+"] ",i=Ox(t,n,o,r-X(s));return i===null?null:s+i}function Ox(e,t,n,o){let r=JSON.stringify(e);if(X(r)<=o)return r;let s=Object.keys(e),i=d=>t.includes(d)?0:n.has(d)?1:typeof e[d]!="object"||e[d]===null?2:3,c=[...s].sort((d,f)=>i(d)-i(f)||s.indexOf(d)-s.indexOf(f)),a=d=>JSON.stringify(d)+":"+JSON.stringify(e[d]),l=new Set,u=2;for(let d of c){let f=X(a(d))+(l.size>0?1:0);u+f>o||(l.add(d),u+=f)}return t.every(d=>l.has(d))?"{"+s.filter(d=>l.has(d)).map(a).join(",")+"}":null}function Tx(e,t){let n=W(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function Rx(e,t){let n=wa(e);if(n===null)return null;let{objs:o,keys:r}=n,s=Tx(r,t),i=new Map,c=0;for(let l of r){if(!s.has(l)||c>=Ex||!o.every(f=>typeof f[l]=="number"&&Number.isFinite(f[l])))continue;let u=0,d=0;for(let f=1;f<o.length;f++)o[f][l]>o[u][l]&&(u=f),o[f][l]<o[d][l]&&(d=f);u!==d&&(c++,i.set(u,l),i.set(d,l))}if(i.size===0)return null;let a=[...i.entries()].map(([l,u])=>({pos:l,rank:"",render:d=>Ma(l,o[l],[u],s,d)}));return{header:Pa(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:a,direct:!0}}function Ax(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function Nx(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 yx(e){let t=e.split(`
206
- `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<Ia)return null;let n=new Map,o=[];for(let a=0;a<t.length;a++){let l=t[a].split(" ").filter(p=>p!==""),u=l.map(p=>Ax(p)?"<*>":p),d=u.length+" "+(u[0]??""),f=n.get(d)??[],x;for(let p of f)if(Nx(p.tpl,u)>=px){x=p;break}if(x===void 0){if(x={tpl:[...u],count:0,lines:[],pos:l.map(()=>({counts:new Map,totals:new Map}))},f.push(x),n.set(d,f),o.push(x),o.length>_x)return null}else for(let p=0;p<x.tpl.length;p++)x.tpl[p]!==u[p]&&(x.tpl[p]="<*>");x.count++,x.lines.length<=M&&x.lines.push(a);for(let p=0;p<x.pos.length;p++){let g=x.pos[p];if(g===null)continue;g.totals.set(l[p],(g.totals.get(l[p])??0)+1);let E=g.counts.get(l[p])??[];E.length<=M&&E.push(a),g.counts.set(l[p],E),g.totals.size>M+1&&(x.pos[p]=null)}}let r=o.filter(a=>a.count>M);if(r.length===0||r.length>gx||r.some(a=>a.tpl.every(l=>l==="<*>")))return null;let s=new Set(o.filter(a=>a.count<=M).flatMap(a=>a.lines));for(let a of r)for(let l of a.pos)if(l!==null)for(let u of La(a.count,l.counts,l.totals))s.add(u);if(s.size===0||s.size>Ca)return null;let i=t.length+" lines, "+s.size+" rare:",c=[...s].sort((a,l)=>a-l).map(a=>{let l=a+1+": "+t[a];return{pos:a,rank:t[a],render:u=>X(l)<=u?l:null}});return{header:i,units:c}}function Ix(e,t,n,o,r,s,i,c=nn(s,i)){return{sourceId:la(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 Ko(e,t,n,o,r,s,i){return Ix(e,t,n,"content",o,r,s,i)}async function Cx(e,t){try{let n=await A(e);Qt(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
207
- `)}}function on(e,t,n){Cx(e,n)}function Ua(e,t,n){let o=new Set(be(t.toLowerCase()));for(let i of be(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of be(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,lr).map(i=>i[0]).join(" ")}function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kx(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(Ts):""}function Dx(e){return Array.isArray(e)?e.filter(Ve).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):Ve(e)?Object.entries(e):[]}function Fa(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!Ve(t))return[];let n=[];for(let[o,r]of Dx(t[Os])){let s=kx(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function va(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!Ve(o)||!Array.isArray(o.options)))for(let r of o.options)Ve(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function Ha(e){return e.trim().toLowerCase()}function ja(e,t,n){let o=Ha(e);if(o==="")return null;let r=t.find(s=>Ha(s)===o);return r===void 0?null:{key:mt,body:"A: "+r+`
208
- ref: #`+n}}function Lx(e,t){return"hint:"+e+":"+t}function wx(e,t){return Q(e,t)!==null?!1:(B(e,t,"1"),!0)}function Px(e,t,n){let o=Q(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return B(e,t,String(r)),(r-1)%n===0}function rn(e,t,n,o){if(t==="")return!1;let r=Lx(t,n),s=i=>o===void 0?wx(i,r):Px(i,r,o);return e.raw.isTransaction?s(e):P(e,s)}import{join as Ba,resolve as Mx}from"node:path";var qo=process.getBuiltinModule("node:fs");function Yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function Ux(e){for(let t of Br){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(Yo(n))return n}return{}}function Hx(e){return e.HOME??e.USERPROFILE??""}function Fx(e){let t=Hx(e);return t===""?"":Ba(t,ct.slice(1),vr)}function Wa(e){let t=Yo(e)?e.code:void 0;return typeof t=="string"&&t!==""?t:e instanceof Error?e.name:"Error"}function ze(e,t,n,o){try{let r=Fx(e);if(r==="")return;qo.mkdirSync(Ba(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:Wa(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});qo.appendFileSync(r,s+`
200
+ `);return t.startsWith("\uFEFF")?t.slice(1):t}function $o(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),Xx(p,i)&&(i="",t&&l!==void 0&&(l.closeStart=u,a()));else if(p.length===0)a();else{let g=t?Wx(p):"",E=t&&g===""?Bx(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 Bx(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 Wx(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 Xx(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 Kx(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{Ja(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=Yx(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||Ux.has(c.name))){if(Hx.has(c.name)){s=qx(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return Ja(t,e,r,e.length),t}function Qa(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function Za(e){return Qa(e)||e>="0"&&e<="9"||e==="-"||e===":"}function Yx(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!Qa(e[n]))return;let r=n;for(;n<e.length&&Za(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 qx(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||!Za(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function Va(e){return e===" "||e===`
202
+ `||e===" "||e==="\f"||e==="\r"}function Ja(e,t,n,o){let r=n,s=o;for(;r<s&&Va(t[r]);)r+=1;for(;s>r&&Va(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function ne(e){return Buffer.byteLength(e,"utf8")}function $a(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=Fx.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function Qo(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=$a(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 _=$a(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 zx=`
205
+ `,Vx=1;function el(e,t,n,o,r){return Jx(e,t,n,o,r)}function Jx(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?Vx: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(zx),more:d?Zo(t,o):null}}function Zo(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>Bn?"...":JSON.stringify(e))+"]"+n+"})"}var tl=20,H=2,nl=9,ol=8,$x=.9,Qx=.5,Zx=64,ep=2,tp=4,er=`
206
+ `,np="(absent)",q=e=>Buffer.byteLength(e,"utf8");function rl(e,t,n){let o=sp(e,t)??ap(e,t)??dp(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(er):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(er)+q(o.header)<=n&&l.unshift(o.header),l.join(er)}function op(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
207
+ `&&n!=="\r"&&n!==" ")return n}return""}function rp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sl(e,t,n){if(n.size<2||n.size>ol)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=H+1)return o[0][1]<$x*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 il(e){if(op(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<tl||!t.every(rp))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 cl=(e,t)=>e+" objects {"+t.join(",")+"}";function sp(e,t){let n=il(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?np: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>ol)break}if(f)for(let x of sl(o.length,d,u))s.set(x,[...s.get(x)??[],a])}if(s.size===0||s.size>nl)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=>al(a,o[a],d,c,u)}));return{header:cl(o.length,r)+", "+s.size+" rare:",units:l}}function al(e,t,n,o,r){let s="["+e+"] ",i=ip(t,n,o,r-q(s));return i===null?null:s+i}function ip(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 cp(e,t){let n=Y(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function ap(e,t){let n=il(e);if(n===null)return null;let{objs:o,keys:r}=n,s=cp(r,t),i=new Map,c=0;for(let a of r){if(!s.has(a)||c>=ep||!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=>al(a,o[a],[d],s,u)}));return{header:cl(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:l,direct:!0}}function lp(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function up(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 dp(e){let t=e.split(`
208
+ `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<tl)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=>lp(p)?"<*>":p),u=d.length+" "+(d[0]??""),f=n.get(u)??[],x;for(let p of f)if(up(p.tpl,d)>=Qx){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>Zx)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>tp||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 sl(l.count,a.counts,a.totals))s.add(d);if(s.size===0||s.size>nl)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 fp(e,t,n,o,r,s,i,c=an(s,i)){return{sourceId:Ua(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 tr(e,t,n,o,r,s,i){return fp(e,t,n,"content",o,r,s,i)}async function xp(e,t){try{let n=await N(e);on(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
209
+ `)}}function ln(e,t,n){xp(e,n)}function ll(e,t,n){let o=new Set(Ne(t.toLowerCase()));for(let i of Ne(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of Ne(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,Or).map(i=>i[0]).join(" ")}function et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pp(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(Hs):""}function _p(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 dl(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!et(t))return[];let n=[];for(let[o,r]of _p(t[Us])){let s=pp(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function fl(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 ul(e){return e.trim().toLowerCase()}function xl(e,t,n){let o=ul(e);if(o==="")return null;let r=t.find(s=>ul(s)===o);return r===void 0?null:{key:Tt,body:"A: "+r+`
210
+ ref: #`+n}}function Ep(e,t){return"hint:"+e+":"+t}function gp(e,t){return ee(e,t)!==null?!1:(K(e,t,"1"),!0)}function mp(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 un(e,t,n,o){if(t==="")return!1;let r=Ep(t,n),s=i=>o===void 0?gp(i,r):mp(i,r,o);return e.raw.isTransaction?s(e):U(e,s)}import{join as or,resolve as hp}from"node:path";var nr=process.getBuiltinModule("node:fs");function rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function Sp(e){for(let t of ts){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(rr(n))return n}return{}}function bp(e){return e.HOME??e.USERPROFILE??""}function Op(e){let t=e[Le];if(t!==void 0&&t!=="")return or(qt(e,""),Cn);let n=bp(e);return n===""?"":or(qt(e,n),Cn)}function _l(e){let t=rr(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=Op(e);if(r==="")return;nr.mkdirSync(or(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:_l(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});nr.appendFileSync(r,s+`
209
211
  `)}catch{process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
210
- `)}}var Ga=!1;function Je(e,t){if(!(Ga||e[Kr]!==t))throw Ga=!0,new Error("injected fault at "+t)}function Xa(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=Ne.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 te(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function vx(e,t){let n=t.toLowerCase();return te(e.nativeTools.shell,n)||te(Ie.shell,n)?"shell":te(e.nativeTools.read,n)||te(Ie.read,n)?"read":te(e.nativeTools.grep,n)||te(Ie.grep,n)?"grep":te(e.nativeTools.webfetch,n)||te(Ie.fetch,n)?"fetch":null}function jx(e,t){let n=t.toLowerCase();return Xr.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function Gx(e,t){if((e.offset??null)!==null||(e.limit??null)!==null)return!1;let n=sn(e,xt);if(n==="")return!1;try{let o=qo.statSync(Mx(t,n));return o.isFile()&&o.size>q}catch{return!1}}function $e(e,t,n,o=""){let r=re(e),s=()=>r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"});try{if(!Yo(t)||!jx(r,sn(t,Gr)))return s();let i=sn(t,jr);if(i===""||i.includes(pt))return s();let c=vx(r,i);if(c===null)return s();let a=sn(t,Wr)||o;if(c==="read"&&!Gx(Ux(t),a))return s();let l=c==="read"?Rn.read:Rn[c],u=k(l,r.toolNamePrefix)+`
211
- `+qr(Wa(n),r.toolNamePrefix);return r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:a,turn:0},{kind:"deny",reason:u})}catch{return{stdout:"",exitCode:0}}}var{read:Bx,writeSync:Wx}=process.getBuiltinModule("node:fs"),Ka=65536;function Xx(e){let t=Buffer.allocUnsafe(Ka);return new Promise(n=>{let o=()=>{Bx(0,t,0,Ka,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 Vo(){let e=[];if(!await Xx(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function zo(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=Wx(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{readFileSync:Kx}=process.getBuiltinModule("node:fs"),N={kind:"allow"},Vx={stdout:"",exitCode:0},zx=48;function Jx(e){return Te.includes(e)}function Qe(e){return e instanceof Error?e.message:String(e)}function Ze(e){return typeof e=="string"?e:""}async function Ya(e,t,n){if(!Jx(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
212
- `),Vx;let o=re(e),r=(l,u,d)=>(ze(n,e,l,u),process.stderr.write(d??"hooks: "+l+" failed: "+Qe(u)+`
213
- `),$e(e,t,u));if(Xa(process.version))return r("node",new T("NODE_TOO_OLD",{v:process.version}));let s;try{Je(n,"decode"),s=o.decode(t)}catch(l){return r("decode",l)}let i;try{Je(n,"project");let l=e==="vscode"?[it,s.cwd]:process.argv;i=Yc(e,{env:n,argv:l,cwd:s.cwd,piCwd:e==="pi"?s.cwd:void 0})}catch(l){return r("project",l,"hooks: no project: "+String(l.code??"ERROR")+" "+Qe(l)+`
214
- `)}let c,a={};try{Je(n,"policy"),c=await $x(s,o,i,n,a)}catch(l){return r("store",l)}try{Je(n,"encode");let l=o.encode(s,c);return a.run?.(!0),l}catch(l){return a.run?.(!1),r("encode",l)}}function $x(e,t,n,o,r){switch(e.event){case"SessionStart":return Qx(e,t,n);case"UserPromptSubmit":return Zx(e,t,n);case"PreToolUse":return cp(e,t,n,o);case"PostToolUse":return fp(e,t,n,o,r);case"PreCompact":return hp(e,t,n);case"Usage":return Sp(e,n)}return Promise.resolve(N)}function Va(e,t){return e.split(Yr).join(t.toolNamePrefix)}function $o(e,t,n){return n.compactSummary==="host"?k(xr,n.toolNamePrefix):ba(ko(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function Qx(e,t,n){if(e.source==="compact"&&Ct(t)&&za(await A(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await A(n);return rn(r,e.sessionId,yn)?{kind:"hint",text:$o(r,e,t),onceKey:yn}:N}let o=await A(n);return t.compactDelivery==="opencode-cache"&&$t(o,_t+e.sessionId)!==null?{kind:"hint",text:$o(o,e,t),onceKey:In}:rn(o,e.sessionId,ke)?{kind:"hint",text:Va(Mn,t),onceKey:ke}:N}async function Zx(e,t,n){let o=e.prompt??"",r=await ep(e,t,n);if(on(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}),sp(e,n,o),t.compactDelivery==="pending-flag"){let s=await A(n);if($t(s,_t+e.sessionId)!==null)return{kind:"hint",text:$o(s,e,t),onceKey:In}}return r!==null?r:op(e,t,n,o)}async function ep(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await A(n);return oa(o,e.sessionId)||!rn(o,e.sessionId,ke)||!na(o,n.worktree,e.agent)?null:{kind:"hint",text:Va(Mn,t),onceKey:ke}}function za(e,t){t!==""&&B(e,Ln+t,Cn)}function tp(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function np(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 op(e,t,n,o){if(!Ct(t)||e.sessionId==="")return N;let r=await A(n);if(Q(r,Ln+e.sessionId)===null)return N;let s=_s+e.sessionId,i=tp(Q(r,s)),c=xs+e.sessionId,a=np(Q(r,c)),l=ea(r,e.sessionId),u=pa(r,e.sessionId,xa(o,l),ps),d=Sa(ta(r,e.sessionId,n.worktree,fs),o,new Set(i),u,new Set(a));return d.text===""?N:(d.seqs.length>0&&B(r,s,JSON.stringify([...i,...d.seqs])),d.units!==void 0&&B(r,c,JSON.stringify([...a,...d.units])),{kind:"hint",text:d.text,onceKey:Es})}function Ja(e){return gt+":"+mt+":"+e}function rp(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 sp(e,t,n){if(e.sessionId==="")return;let o=Ja(e.sessionId);A(t).then(r=>{if(Q(r,o)===null)return;let s=$t(r,o),i=s===null?null:rp(s);if(i===null)return;let c=ja(n,i.labels,i.seq);c!==null&&$a(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+Qe(r)+`
215
- `)})}function $a(e,t,n,o){for(let r of o)Qt(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:Un,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}),Ko(e,n,t.sessionId,gt,r.body,"text")}function ip(e,t,n,o){let r=Fa(o),s=r.length===0?va(n.input):[];r.length===0&&s.length===0||A(t).then(i=>{if(r.length>0)return $a(i,e,t,r);let c=ko(i,e.sessionId,"prompt"),a=c[c.length-1];a===void 0||e.sessionId===""||B(i,Ja(e.sessionId),JSON.stringify({seq:a.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+Qe(i)+`
216
- `)})}async function cp(e,t,n,o){let r=Dc(n.worktree,e.agent),s=Fc(e,t,r),i=s;if(s.kind==="deny"&&Se(e)&&!Qa(s.reason,t)){let c=ho(e,{projectDir:n.worktree,env:o}),a=mo(e,c),l=e.tool,u=c!==null||(e.agentType??"")!==""&&fe(t);a==="B"&&l!==void 0&&Zo(l,t)?i=ap(e,t,s,r):a!=="A"&&u&&(i=N)}return i}function Zo(e,t){return e.canonicalName===ls||t.nativeTools.shell.includes(e.name)}function Qa(e,t){return e.startsWith(ye)||e===k(ut,t.toolNamePrefix)||e===k(dt,t.toolNamePrefix)}function Jo(e){return Buffer.from(e,"utf8").toString("base64url")}function ap(e,t,n,o){let r=e.tool;if(r===void 0||!Zo(r,t)||Qa(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+Yx(qx(process.argv[1]??""),ms)+'"',c=[hs,i,Jo(s),Jo(JSON.stringify(o??[])),Jo(Ze(r.input.description))].join(" ");return{kind:"deny",reason:Ss,rewritten:c}}function lp(e,t,n){return n?"toolerr":us.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":Zo(e,t)?"cmd":null}function Qo(e){if(Array.isArray(e))return"["+e.map(Qo).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)+":"+Qo(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function up(e){let t=e.indexOf(`
217
- `),n=t<0?e:e.slice(0,t);if(!n.startsWith(Nn))return null;let o=0,r=0;for(let s of n.slice(Nn.length)){let i=s.charCodeAt(0)-zx;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function dp(e){for(let t of ds)if(typeof e[t]=="string")return e[t];return null}async function fp(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(pt))return N;let i=e.result??{isError:!1,bytes:0},c=_p(i);i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(c)),s.canonicalName===Un&&ip(e,n,s,c);let a=lp(s,t,i.isError),l=f=>{if(a===null)return;let x=a==="cmd"?Qc(s.canonicalName,Ze(s.input.command)):a==="toolerr"?s.canonicalName+":"+Qo(s.input):null;on(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:a,tool:s.canonicalName,key:x,path:dp(s.input),ok:i.isError?0:1,exit_code:up(c),bytes:i.bytes,body:c,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:f})},u;try{u=await xp(e,t,n,o,s,i,c)}catch(f){throw l(i.bytes),f}let d=u;return r.run=f=>l(f&&d.kind==="replace"?Buffer.byteLength(d.output):i.bytes),u}async function xp(e,t,n,o,r,s,i){if(s.bytes<=rr||s.keep===!0||!fe(t))return N;let c;if(Se(e)){if(mo(e,ho(e,{projectDir:n.worktree,env:o}))==="A")return N;c=gs+r.canonicalName+":"+String(e.turn??0)}else c=gp(r,e);let a=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url].map(Ze).find(_=>_.trim()!=="")??"",l=nn(i,"text",cr),u=await A(n),d;s.bytes<=or?(d=Ko(u,n,e.sessionId,c,i,"text",l).sourceId,Po(u,d,e.sessionId,Mo(i))):(d=Lo(u,Za(n,e.sessionId,c),l),mp(n,e.sessionId,d,c,i,l));let f=fa(d),x=await Ep(n,e.sessionId),p=x.trim()===""?void 0:a+" "+x,g=ar(a,f,s.bytes,t.toolNamePrefix,Ua(a,x,i)),E=pp(g,Wo(a,c)),h=Da(i,p??a,ir);if(h!==null)return{kind:"replace",output:qa(h,g)};let S=ya(l,a,E,c,p);return{kind:"replace",output:S.more!==null?qa(S.text,g):S.text}}function qa(e,t){return e===""?t:e+`
218
- `+t}function pp(e,t){return Math.max(0,sr+Buffer.byteLength(`
219
- `+t)-1-Buffer.byteLength(e))}function _p(e){let t=e.text??"";if(e.persistedPath===void 0)return t;try{return Kx(e.persistedPath,"utf8")}catch{return t}}async function Ep(e,t){try{return Zc(await A(e),t)}catch{return""}}function gp(e,t){let n=Ze(e.input.command)??Ze(e.input.file_path)??"",o=n.indexOf(`
220
- `);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,Tr)+"#"+(e.callId??String(t.turn??0))}function mp(e,t,n,o,r,s){A(e).then(i=>{ua(i,n,Za(e,t,o),s,Mo(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+Qe(i)+`
221
- `)})}function Za(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function hp(e,t,n){let o=await A(n);return B(o,_t+e.sessionId,Cn),Ct(t)&&za(o,e.sessionId),N}function Sp(e,t){return on(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(N)}var tl={stdout:"",exitCode:0};function bp(e){return Te.includes(e)}function cn(e){process.exitCode=e.exitCode,e.stdout!==""&&zo(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
222
- `)}function el(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
223
- `);try{return ze(r,e,n,o),$e(e,t,o)}catch{return tl}}async function Op(e,t){let n=e.indexOf(Et),o=n>=0?e[n+1]??"":"";if(!bp(o))return console.error("hooks: unknown "+Et+" "+JSON.stringify(o)+". Fix: pass "+Et+" with one of "+Te.join(", ")+"."),cn(tl);let r;try{r=JSON.parse(await Vo())}catch(s){return cn(el(o,void 0,"stdin",s,t))}try{return cn(await Ya(o,r,t))}catch(s){return cn(el(o,r,"load",s,t))}}Op(process.argv.slice(2),process.env);export{Op as main};
212
+ `)}}var pl=!1;function tt(e,t){if(!(pl||e[rs]!==t))throw pl=!0,new Error("injected fault at "+t)}function El(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 Tp(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 Rp(e,t){let n=t.toLowerCase();return os.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function Ap(e){try{let t=nr.statSync(e);return t.isFile()&&t.size>V}catch{return!1}}function Np(e,t){if((e.offset??null)!==null||(e.limit??null)!==null)return!1;let n=Array.isArray(e[pe])?e[pe].filter(o=>typeof o=="string"):[];return[dn(e,mt),...n].some(o=>o!==""&&Ap(hp(t,o)))}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(!rr(t)||!Rp(r,dn(t,es)))return s();let i=dn(t,Zr);if(i===""||i.includes(ht))return s();let c=Tp(r,i);if(c===null)return s();let l=dn(t,ns)||o;if(c==="read"&&!Np(Sp(t),l))return s();let a=c==="read"?kn.read:kn[c],d=k(a,r.toolNamePrefix)+`
213
+ `+ss(_l(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:yp,writeSync:Ip}=process.getBuiltinModule("node:fs"),gl=65536;function Cp(e){let t=Buffer.allocUnsafe(gl);return new Promise(n=>{let o=()=>{yp(0,t,0,gl,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 sr(){let e=[];if(!await Cp(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function ir(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=Ip(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{lstatSync:kp,readFileSync:Dp}=process.getBuiltinModule("node:fs"),y={kind:"allow"},Mp={stdout:"",exitCode:0},Up=48;function Hp(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 bl(e,t,n){if(!Hp(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
214
+ `),Mp;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(El(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)}let i;try{tt(n,"project");let a=e==="vscode"?[ft,s.cwd]:process.argv;i=ha(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 Fp(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 Fp(e,t,n,o,r){switch(e.event){case"SessionStart":return vp(e,t,n);case"UserPromptSubmit":return jp(e,t,n);case"PreToolUse":return zp(e,t,n,o);case"PostToolUse":return Zp(e,t,n,o,r);case"PreCompact":return a_(e,t,n);case"Usage":return l_(e,n)}return Promise.resolve(y)}function Ol(e,t){return e.split(is).join(t.toolNamePrefix)}function ar(e,t,n){return n.compactSummary==="host"?k(Nr,n.toolNamePrefix):za(jo(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function vp(e,t,n){if(e.source==="compact"&&Pt(t)&&Tl(await N(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await N(n);return un(r,e.sessionId,wn)?{kind:"hint",text:ar(r,e,t),onceKey:wn}:y}let o=await N(n);return t.compactDelivery==="opencode-cache"&&nn(o,St+e.sessionId)!==null?{kind:"hint",text:ar(o,e,t),onceKey:Pn}:un(o,e.sessionId,Ue)?{kind:"hint",text:Ol(jn,t),onceKey:Ue}:y}async function jp(e,t,n){let o=e.prompt??"",r=await Gp(e,t,n);if(ln(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}),Yp(e,n,o),t.compactDelivery==="pending-flag"){let s=await N(n);if(nn(s,St+e.sessionId)!==null)return{kind:"hint",text:ar(s,e,t),onceKey:Pn}}return r!==null?r:Xp(e,t,n,o)}async function Gp(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await N(n);return ka(o,e.sessionId)||!un(o,e.sessionId,Ue)||!Ca(o,n.worktree,e.agent)?null:{kind:"hint",text:Ol(jn,t),onceKey:Ue}}function Tl(e,t){t!==""&&K(e,Hn+t,Mn)}function Bp(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function Wp(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 Xp(e,t,n,o){if(!Pt(t)||e.sessionId==="")return y;let r=await N(n);if(ee(r,Hn+e.sessionId)===null)return y;let s=Cs+e.sessionId,i=Bp(ee(r,s)),c=Ns+e.sessionId,l=Wp(ee(r,c)),a=ya(r,e.sessionId),d=Ga(r,e.sessionId,ja(o,a),Is),u=qa(Ia(r,e.sessionId,n.worktree,As),o,new Set(i),d,new Set(l));return u.text===""?y:(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:ks})}function Rl(e){return Ot+":"+Tt+":"+e}function Kp(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 Yp(e,t,n){if(e.sessionId==="")return;let o=Rl(e.sessionId);N(t).then(r=>{if(ee(r,o)===null)return;let s=nn(r,o),i=s===null?null:Kp(s);if(i===null)return;let c=xl(n,i.labels,i.seq);c!==null&&Al(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+ot(r)+`
217
+ `)})}function Al(e,t,n,o){for(let r of o)on(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:Gn,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}),tr(e,n,t.sessionId,Ot,r.body,"text")}function qp(e,t,n,o){let r=dl(o),s=r.length===0?fl(n.input):[];r.length===0&&s.length===0||N(t).then(i=>{if(r.length>0)return Al(i,e,t,r);let c=jo(i,e.sessionId,"prompt"),l=c[c.length-1];l===void 0||e.sessionId===""||K(i,Rl(e.sessionId),JSON.stringify({seq:l.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+ot(i)+`
218
+ `)})}async function zp(e,t,n,o){let r=Vc(n.worktree,e.agent),s=ca(e,t,r),i=s;if(s.kind==="deny"&&Te(e)&&!Nl(s.reason,t)){let c=Ao(e,{projectDir:n.worktree,env:o}),l=Ro(e,c),a=e.tool,d=c!==null||(e.agentType??"")!==""&&_e(t);l==="B"&&a!==void 0&&ur(a,t)?i=Vp(e,t,s,r):l!=="A"&&d&&(i=y)}return i}function ur(e,t){return e.canonicalName===Os||t.nativeTools.shell.includes(e.name)}function Nl(e,t){return e.startsWith(we)||e===k(_t,t.toolNamePrefix)||e===k(Et,t.toolNamePrefix)}function cr(e){return Buffer.from(e,"utf8").toString("base64url")}function Vp(e,t,n,o){let r=e.tool;if(r===void 0||!ur(r,t)||Nl(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+Sl(Lp(process.argv[1]??""),Ls)+'"',c=[ws,i,cr(s),cr(JSON.stringify(o??[])),cr(rt(r.input.description))].join(" ");return{kind:"deny",reason:Ps,rewritten:c}}function Jp(e,t,n){return n?"toolerr":Ts.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":ur(e,t)?"cmd":null}function lr(e){if(Array.isArray(e))return"["+e.map(lr).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)+":"+lr(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function $p(e){let t=e.indexOf(`
219
+ `),n=t<0?e:e.slice(0,t);if(!n.startsWith(Ln))return null;let o=0,r=0;for(let s of n.slice(Ln.length)){let i=s.charCodeAt(0)-Up;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function Qp(e){for(let t of Rs)if(typeof e[t]=="string")return e[t];return null}async function Zp(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(ht))return y;let i=e.result??{isError:!1,bytes:0},c=r_(i,e.sessionId,o);i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(c)),s.canonicalName===Gn&&qp(e,n,s,c);let l=Jp(s,t,i.isError),a=f=>{if(l===null)return;let x=l==="cmd"?Aa(s.canonicalName,rt(s.input.command)):l==="toolerr"?s.canonicalName+":"+lr(s.input):null;ln(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:l,tool:s.canonicalName,key:x,path:Qp(s.input),ok:i.isError?0:1,exit_code:$p(c),bytes:i.bytes,body:c,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:f})},d;try{d=await e_(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 e_(e,t,n,o,r,s,i){if(s.bytes<=_r||t_(r)||s.keep===!0||!_e(t))return y;let c;if(Te(e)){if(Ro(e,Ao(e,{projectDir:n.worktree,env:o}))==="A")return y;c=Ds+r.canonicalName+":"+String(e.turn??0)}else c=i_(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=an(i,"text",Sr),d=await N(n),u;s.bytes<=pr?(u=tr(d,n,e.sessionId,c,i,"text",a).sourceId,Xo(d,u,e.sessionId,Ko(i))):(u=Bo(d,yl(n,e.sessionId,c),a),c_(n,e.sessionId,u,c,i,a));let f=va(u),x=await s_(n,e.sessionId),p=x.trim()===""?void 0:l+" "+x,g=br(l,f,s.bytes,t.toolNamePrefix,ll(l,x,i)),E=n_(g,Zo(l,c)),h=rl(i,p??l,hr);if(h!==null)return{kind:"replace",output:hl(h,g)};let S=el(a,l,E,c,p);return{kind:"replace",output:S.more!==null?hl(S.text,g):S.text}}function t_(e){return Er.includes(e.canonicalName)&&gr.some(t=>e.input[t]!==void 0&&e.input[t]!==null)}function hl(e,t){return e===""?t:e+`
220
+ `+t}function n_(e,t){return Math.max(0,mr+Buffer.byteLength(`
221
+ `+t)-1-Buffer.byteLength(e))}function o_(e,t,n){if(t===""||t.includes(ml)||t.includes("/"))return!1;let o=Sl(le(n,Q(n)??""),dt),r=wp(o,Pp(e)).split(ml);if(r.length!==4||r.includes("..")||r.includes("")||r[1]!==t||r[2]!==vs)return!1;let s=kp(e);return s.isFile()&&s.size<=js&&xa(o,e)}function r_(e,t,n){let o=e.text??"";if(e.persistedPath===void 0)return o;try{return o_(e.persistedPath,t,n)?Dp(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 s_(e,t){try{return Na(await N(e),t)}catch{return""}}function i_(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,Ur)+"#"+(e.callId??String(t.turn??0))}function c_(e,t,n,o,r,s){N(e).then(i=>{Ha(i,n,yl(e,t,o),s,Ko(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+ot(i)+`
223
+ `)})}function yl(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function a_(e,t,n){let o=await N(n);return K(o,St+e.sessionId,Mn),Pt(t)&&Tl(o,e.sessionId),y}function l_(e,t){return ln(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(y)}var Cl={stdout:"",exitCode:0};function u_(e){return Ce.includes(e)}function fn(e){process.exitCode=e.exitCode,e.stdout!==""&&ir(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
224
+ `)}function Il(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 Cl}}async function d_(e,t){let n=e.indexOf(bt),o=n>=0?e[n+1]??"":"";if(!u_(o))return console.error("hooks: unknown "+bt+" "+JSON.stringify(o)+". Fix: pass "+bt+" with one of "+Ce.join(", ")+"."),fn(Cl);let r;try{r=JSON.parse(await sr())}catch(s){return fn(Il(o,void 0,"stdin",s,t))}try{return fn(await bl(o,r,t))}catch(s){return fn(Il(o,r,"load",s,t))}}d_(process.argv.slice(2),process.env);export{d_ as main};