context-mode 2.1.8 → 2.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/hook.mjs CHANGED
@@ -1,44 +1,44 @@
1
1
  import{createRequire as __cmRequire}from"node:module";if(typeof process.getBuiltinModule!=="function")process.getBuiltinModule=(id)=>__cmRequire(import.meta.url)(id);
2
- var Ue=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode"];var Z="context-mode",ht=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function L(e,t){if(t==="")return e;let n=e;for(let o of ht)n=n.split(o).join(t+o);return n}var ce=16384;var kr=2048;var Dr=640,An="</context_mode_state>",yn=1048576,Lr=65536,Ir=4096,Ru="CTX_REPLACE_TRIGGER_BYTES";function Au(e){if(e===void 0||e.trim()==="")return Ir;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Ir}var wr=Au(process.env[Ru]),Nn=Object.freeze(["Read","view"]),Pr=Object.freeze(["offset","limit","view_range"]),Mr=96,Ur=256,Hr=48;function Fr(e,t,n,o="",r=""){let s=r===""?[e]:[e,r];return o+"ctx_search({queries:["+s.map(i=>JSON.stringify(i)).join(",")+"], source:"+JSON.stringify(t)+"}) searches the whole output ("+n+" B)."}var vr=3,ae=4096;var In=85,Cn=340,kn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var jr=.7,Gr=.7,Br=.3,Dn=Object.freeze([1e3,881,780,696,625,565,515,473,438,408,383,361,344,329,316,306,297,289,283,278,273,270,267,264,262,260,258,257,256,255,254,253,253,252,252,252,251,251,251,251,251,251,251,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250]),Wr='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var yu=6e5;var ee=5e3,St="-wal",bt="-shm",Xr=".tmp",Kr=255,Yr=11,qr=26;var G=5e3;var Ln=0;var Vr=16,He=6;var Ot="projects",zr="context.db";var wn=".git",Pn="worktree ",Mn="gitdir: ",Jr="commondir",$r="HEAD",Tt="--workspace-folder",SE=Object.freeze(["shell","powershell","javascript","typescript","python"]),Qr=Object.freeze(["sh","bash","zsh","dash","ksh","fish"]);var Zr=80;var bE=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var OE=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),Fe="24.15.0",es="~/.context-mode",ve="CONTEXT_MODE_DATA_DIR";var ts="CONTEXT_MODE_REQUIRE_SECURITY",ns=".claude",Rt="agents",ge=".md",Un="plugins",os="installed_plugins.json",me=":",rs="@";var TE=Object.freeze(["local","project"]),RE=Object.freeze({local:0,project:1,user:2,managed:2}),Hn="---",ss="tools",is="disallowedTools",Fn="mcp__",vn="__",cs="mcp_",as="_-.:",Cr=10;function Nu(e){if(e===void 0||e.trim()==="")return Cr;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Cr}var AE=Nu(process.env.CTX_MCP_HINT_EVERY);var B=32;var ls=Object.freeze([".agents","skills"]),jn="context-mode: ",us=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),ds=" sends its body into the conversation.",fs="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",xs="Tool: ",ps="state what you need",_s="ctx_execute",Es=Object.freeze(["ctx_index","ctx_search"]),je="Blocked by security policy: matches deny pattern ",At="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",yt="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",Gn="hook-errors.log";var gs=Object.freeze(["tool_name","toolName","tool"]),ms=Object.freeze(["hook_event_name","hookEventName","type"]),hs=Object.freeze(["tool_input","toolArgs","input","args"]),Ss=Object.freeze(["cwd","directory"]),bs=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),Os="CM_HOOK_FAULT",yE=Object.freeze(["decode","project","policy","store","encode"]),Ge=Object.freeze({shell:Object.freeze(["Bash","bash","shell"]),read:Object.freeze(["Read","read_file"]),grep:Object.freeze(["Grep","grep_search"]),fetch:Object.freeze(["WebFetch","web_fetch","fetch"])});function Ts(e,t){return`${jn}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var Bn=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 NE=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),IE=Object.freeze(["status"]),CE=Object.freeze(["--version","-v"]),kE=Object.freeze(["cp","mv","rm"]),DE=Object.freeze(["-v","--verbose"]),w=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),Rs="{prefix}",As=", then ",ys="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",Ns=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),Is=Object.freeze(["curl","wget"]),Cs=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),ks=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),Ds="-D",Ls=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),Be="fetch(",ws="'\"`",Ps="http",Ms=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),Us=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),Hs=Object.freeze(["head","tail"]),Wn=Object.freeze(["-n","-c","--lines","--bytes"]),Nt="sed",Fs=Object.freeze(["-n","--quiet","--silent"]),vs="jq",he=Object.freeze(["file_path","absolute_path","path","filePath"]),Se="filePaths",Xn=Object.freeze({png:{exts:[".png"],sig:[{at:0,bytes:[137,80,78,71,13,10,26,10]}]},jpeg:{exts:[".jpg",".jpeg"],sig:[{at:0,bytes:[255,216,255]}]},gif:{exts:[".gif"],sig:[{at:0,bytes:[71,73,70,56]}]},webp:{exts:[".webp"],sig:[{at:0,bytes:[82,73,70,70]},{at:8,bytes:[87,69,66,80]}]},pdf:{exts:[".pdf"],sig:[{at:0,bytes:[37,80,68,70,45]}]}}),Kn=12,mt=Object.freeze(["png","jpeg","gif","webp"]),gt=Object.freeze([...mt,"pdf"]),js=Object.freeze({"claude-code":gt,gemini:gt,qwen:gt,opencode:gt,pi:mt,vscode:mt,zcode:mt,"copilot-cli":[],codex:[],kiro:[]}),It="ctx_",Gs="Bash",Bs=Object.freeze(["Write","Edit"]),Ws=Object.freeze(["file_path","path"]),Yn="Exit code ",We="resume-hint",qn="compact-state",Vn="pending-compact",Ct="pending_compact:",zn="1",Xe=2048,Jn=5,Xs=340,$n="compacted:",Ks="recall_units_seen:",Ys=8,kt=64,qs=64,Vs="recall_seen:",Qn="<context_mode_recall>",Zn="</context_mode_recall>",zs="recall",eo="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",Js="subagent:",$s="run.mjs",Qs="node",Zs=`context-mode: This command sends its body into the conversation.
3
- Run the command on the line above with Bash instead. It runs the same command in the same folder, indexes the full output and prints only the part that matches your intent, with the same exit code.`,Dt="--agent",ei=1e3;var LE=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var wE=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."]),PE=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),ME=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 UE=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),HE=Object.freeze(["ctx_index","ctx_search"]);var FE=Object.freeze(["session","source","project"]);var Lt="decision";var to="AskUserQuestion",ti="answers",wt="option",ni=" | ",Iu="https://github.com/mksglu/context-mode.git";var vE=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),jE=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 no=256;var Cu="ctx_doctor:report";var GE=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(Cu)}})`;var BE=Object.freeze(["--tags","--refs"]),ku="v*";var WE=`git ls-remote --tags --refs ${Iu} "${ku}"`;var XE=`nvm install ${Fe.split(".")[0]}, or install it from https://nodejs.org`;var KE=Object.freeze(["MCP entry","hook entries","hook timeout"]);var C=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 YE=Object.freeze(["upgrade","uninstall"]);var qE=Object.freeze(["clone","--depth","1","--branch"]),VE=Object.freeze(["rev-parse","HEAD"]);var zE=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),JE=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var $E=Object.freeze(["shell","bash","sh"]),QE=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var oi="tool-results",ri=16*1024*1024;var ZE=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=e=>Object.freeze(e),eg=Object.freeze([Q({id:"antigravity",name:"Antigravity",clientNames:["antigravity","antigravity-client","antigravity-cli","agy"],envVars:["ANTIGRAVITY_CLI_ALIAS"],pluginPaths:[[".gemini","config","plugins"],[".gemini","antigravity","plugins"],[".gemini","antigravity-cli","plugins"],[".gemini","antigravity-ide","plugins"]],configDirs:[".gemini/antigravity",".gemini/antigravity-cli",".gemini/config"],binaries:["agy"],source:"v1.0.169:src/adapters/client-map.ts:15-17; detect.ts:156,481-483; #1340"}),Q({id:"cursor",name:"Cursor",clientNames:["cursor-vscode"],envVars:["CURSOR_TRACE_ID","CURSOR_CLI","CURSOR_CWD"],pluginPaths:[],configDirs:[".cursor"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:18; detect.ts:163-165,584"}),Q({id:"omp",name:"OMP (oh-my-pi)",clientNames:["omp-coding-agent"],envVars:[],pluginPaths:[],configDirs:[".omp"],binaries:["omp"],source:"v1.0.169:src/adapters/client-map.ts:37; detect.ts:543 (PI_CODING_AGENT_DIR is not a signal: supported Pi reads it too)"}),Q({id:"openclaw",name:"OpenClaw",clientNames:[],envVars:[],pluginPaths:[],configDirs:[".openclaw"],binaries:[],source:"v1.0.169:src/adapters/detect.ts:252,575 (the runtime sets no env var)"}),Q({id:"kimi",name:"Kimi Code",clientNames:["kimi-code","kimi"],envVars:[],pluginPaths:[],configDirs:[".kimi-code"],binaries:["kimi"],source:"v1.0.169:src/adapters/client-map.ts:42-44; detect.ts:567; adapters/kimi/index.ts:127"}),Q({id:"kilo",name:"Kilo Code",clientNames:["kilo code"],envVars:["KILO","KILO_PID"],pluginPaths:[],configDirs:[".config/kilo"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:28; detect.ts:170-171,592"}),Q({id:"zed",name:"Zed",clientNames:["zed"],envVars:["ZED_SESSION_ID","ZED_TERM"],pluginPaths:[],configDirs:[".config/zed"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:38-39; detect.ts:189-190,616"}),Q({id:"jetbrains-copilot",name:"JetBrains Copilot",clientNames:["jetbrains client","intellij idea","pycharm"],envVars:["IDEA_INITIAL_DIRECTORY"],pluginPaths:[],configDirs:[".config/JetBrains"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:23-25; detect.ts:213,600"})]);var tg=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}),ng=Object.freeze(["PreToolUse","PostToolUse"]);var og=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var rg=Object.freeze(["features","hooks"]);var sg=Object.freeze(["",St,bt]);var Du=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 ig=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 cg=Object.freeze(["hooks","codex"]),ag=Object.freeze(["pretooluse.mjs","posttooluse.mjs","sessionstart.mjs","precompact.mjs","userpromptsubmit.mjs","stop.mjs"]);var lg=Object.freeze([".mjs",".sh"]);var Lu="npm:context-mode";var Pt="CLAUDE_CONFIG_DIR";var si="CODEX_HOME",ii="COPILOT_HOME",ci="GEMINI_CLI_HOME",ai="KIRO_HOME",li="OPENCODE_CONFIG_DIR",oo="APPDATA",Mt=Object.freeze(["Code","User"]),Ut="XDG_CONFIG_HOME";var wu="mcp.json",ug=Object.freeze(["agents","default.json"]);var dg=Object.freeze(["steering","KIRO.md"]),ui="agent",fg=Object.freeze(["opencode.jsonc","opencode.json"]);var Pu=`${Z}@`,Mu="@",xg=`${Pu}latest`,pg=`${Lu}${Mu}latest`;var _g=Object.freeze(["content","platform.json"]);var di="custom",fi="PI_CODING_AGENT_DIR";var Uu=Object.freeze(["/","\\"]),Hu="${/}",Eg=Object.freeze([...Uu,Hu]),P=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/<event>.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"}),gg=Object.freeze([P.statusLine,P.vscodeMcp,P.dataDirShared,P.tmpFile,P.kiroSteering,P.piGit,P.opencodeGit,P.projectLink]),mg=Object.freeze([P.dataDir,P.dataRoot]);var hg=Z+"_";var Sg=Object.freeze(["opencode","plugin.js"]);var Fu=Object.freeze(["features","mcp"]),vu="omit_tools_from",ju=Object.freeze(["deferred"]),Gu="default_tools_approval_mode",Bu="approve",bg=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",Z],fields:{[vu]:ju,[Gu]:Bu}},vscode:{file:[wu],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:yu},also:[[Fu,!0]]}});var Og=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),Wu="Environment: ";var Xu="Docs: ";var Ku="Report file: ",Yu="File it: ",qu="Or open: ",Vu="Rules: ",zu=" --",Tg=Object.freeze([Wu,Xu,Ku,Yu,zu.trim(),qu,Vu]),xi="mksglu/context-mode",Ju="agent-report.yml",Rg=`https://github.com/${xi}/blob/main/.github/AGENT_ISSUE.md`,Ag=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 yg=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var Ng=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"]),Ig=Object.freeze(["node","git","sh"]),Cg=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var kg=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"]}),Dg=`https://github.com/${xi}/issues/new?template=${Ju}`;import{dirname as F_,join as xu,relative as v_,resolve as j_,sep as du}from"node:path";var ro="mcp__plugin_context-mode_context-mode__",gi=Object.freeze(["Bash","PowerShell"]),$u="PowerShell",Qu="Bash",Zu=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],pi="mcp__",_i="__",ed={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function td(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(pi))return e;let n=e.slice(pi.length),o=n.indexOf(_i);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+_i.length)}function nd(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return mi(e).text;if(typeof e=="object"&&e!==null){let t=e;if(typeof t.stdout=="string"||typeof t.stderr=="string"){let n=typeof t.stdout=="string"?t.stdout:"",o=typeof t.stderr=="string"?t.stderr:"";return o===""?n:n===""?o:n+`
4
- `+o}}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=so(e);if(t!==null)return t.text}return JSON.stringify(e)}function so(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:od(n.file,o)})}:sd(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 Ge=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode"];var Z="context-mode",Tt=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function L(e,t){if(t==="")return e;let n=e;for(let o of Tt)n=n.split(o).join(t+o);return n}var le=16384;var wr=2048;var Pr=640,Dn="</context_mode_state>",Ln=1048576,Mr=65536,Dr=4096,Pu="CTX_REPLACE_TRIGGER_BYTES";function Mu(e){if(e===void 0||e.trim()==="")return Dr;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Dr}var Ur=Mu(process.env[Pu]),Rt=Object.freeze(["Read","view"]),Hr=Object.freeze(["offset","limit","view_range"]),Fr=96,vr=256,jr=48;function Gr(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)."}function Br(e,t,n){return"The full output ("+t+" B) is stored as "+e+"; above is the best-matching part."+(n?" Read the file with offset and limit for other lines.":"")}function Wr(e,t,n,o){return" Or run: node "+kn(e)+" "+t+" "+kn(n)+" "+kn(o)}function kn(e){return"'"+e.split("'").join("'\\''")+"'"}var Xr=3,ue=4096;var wn=85,Pn=340,Mn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var Kr=.7,Yr=.7,qr=.3,Un=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]),zr='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var Uu=6e5;var ee=5e3,At="-wal",yt="-shm",Vr=".tmp",Jr=255,$r=11,Qr=26;var G=5e3;var Hn=0;var Zr=16,Be=6;var Nt="projects",es="context.db";var Fn=".git",vn="worktree ",jn="gitdir: ",ts="commondir",ns="HEAD",It="--workspace-folder",ME=Object.freeze(["shell","powershell","javascript","typescript","python"]),os=Object.freeze(["sh","bash","zsh","dash","ksh","fish"]);var rs=80;var UE=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var ss="search.mjs",is="claude-code";var HE=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),We="24.15.0",cs="~/.context-mode",Xe="CONTEXT_MODE_DATA_DIR";var as="CONTEXT_MODE_REQUIRE_SECURITY",ls=".claude",Ke="agents",de=".md",us="synced",Ct="plugins",ds="installed_plugins.json",Oe=":",fs="@";var FE=Object.freeze(["local","project"]),vE=Object.freeze({local:0,project:1,user:2,managed:2}),Gn="---",xs="tools",ps="disallowedTools",Bn="mcp__",Wn="__",_s="mcp_",Es="_-.:",Lr=10;function Hu(e){if(e===void 0||e.trim()==="")return Lr;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Lr}var jE=Hu(process.env.CTX_MCP_HINT_EVERY);var B=32;var gs=Object.freeze([".agents","skills"]),Xn="context-mode: ",ms=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),hs=" sends its body into the conversation.",Ss="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",bs="Tool: ",Os="state what you need",Ts="ctx_execute",Rs=Object.freeze(["ctx_index","ctx_search"]),Ye="Blocked by security policy: matches deny pattern ",kt="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.",Kn="hook-errors.log";var As=Object.freeze(["tool_name","toolName","tool"]),ys=Object.freeze(["hook_event_name","hookEventName","type"]),Ns=Object.freeze(["tool_input","toolArgs","input","args"]),Is=Object.freeze(["cwd","directory"]),Cs=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),ks="CM_HOOK_FAULT",GE=Object.freeze(["decode","project","policy","store","encode"]),qe=Object.freeze({shell:Object.freeze(["Bash","bash","shell"]),read:Object.freeze(["Read","read_file"]),grep:Object.freeze(["Grep","grep_search"]),fetch:Object.freeze(["WebFetch","web_fetch","fetch"])});function Ds(e,t){return`${Xn}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var Yn=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 BE=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),WE=Object.freeze(["status"]),XE=Object.freeze(["--version","-v"]),KE=Object.freeze(["cp","mv","rm"]),YE=Object.freeze(["-v","--verbose"]),w=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),Ls="{prefix}",ws=", then ",Ps="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",Ms=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),Us=Object.freeze(["curl","wget"]),Hs=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),Fs=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),vs="-D",js=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),ze="fetch(",Gs="'\"`",Bs="http",Ws=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),Xs=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),Ks=Object.freeze(["head","tail"]),qn=Object.freeze(["-n","-c","--lines","--bytes"]),Lt="sed",Ys=Object.freeze(["-n","--quiet","--silent"]),qs="jq",Te=Object.freeze(["file_path","absolute_path","path","filePath"]),Re="filePaths",zn=Object.freeze({png:{exts:[".png"],sig:[{at:0,bytes:[137,80,78,71,13,10,26,10]}]},jpeg:{exts:[".jpg",".jpeg"],sig:[{at:0,bytes:[255,216,255]}]},gif:{exts:[".gif"],sig:[{at:0,bytes:[71,73,70,56]}]},webp:{exts:[".webp"],sig:[{at:0,bytes:[82,73,70,70]},{at:8,bytes:[87,69,66,80]}]},pdf:{exts:[".pdf"],sig:[{at:0,bytes:[37,80,68,70,45]}]}}),Vn=12,Ot=Object.freeze(["png","jpeg","gif","webp"]),bt=Object.freeze([...Ot,"pdf"]),zs=Object.freeze({"claude-code":bt,gemini:bt,qwen:bt,opencode:bt,pi:Ot,vscode:Ot,zcode:Ot,"copilot-cli":[],codex:[],kiro:[]}),wt="ctx_",Vs="Bash",Js=Object.freeze(["Write","Edit"]),$s=Object.freeze(["file_path","path"]),Jn="Exit code ",Ve="resume-hint",$n="compact-state",Qn="pending-compact",Pt="pending_compact:",Zn="1",Je=2048,eo=5,Qs=340,to="compacted:",Zs="recall_units_seen:",ei=8,Mt=64,ti=64,ni="recall_seen:",no="<context_mode_recall>",oo="</context_mode_recall>",oi="recall",ro="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",ri="subagent:",si="run.mjs",ii="node",ci=`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.`,Ut="--agent",ai=1e3;var qE=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var zE=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."]),VE=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),JE=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 $E=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),QE=Object.freeze(["ctx_index","ctx_search"]);var ZE=Object.freeze(["session","source","project"]);var Ht="decision";var so="AskUserQuestion",li="answers",Ft="option",ui=" | ",Fu="https://github.com/mksglu/context-mode.git";var eg=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),tg=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 $e=256;var vu="ctx_doctor:report";var ng=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(vu)}})`;var og=Object.freeze(["--tags","--refs"]),ju="v*";var rg=`git ls-remote --tags --refs ${Fu} "${ju}"`;var sg=`nvm install ${We.split(".")[0]}, or install it from https://nodejs.org`;var ig=Object.freeze(["MCP entry","hook entries","hook timeout"]);var k=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 cg=Object.freeze(["upgrade","uninstall"]);var ag=Object.freeze(["clone","--depth","1","--branch"]),lg=Object.freeze(["rev-parse","HEAD"]);var ug=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),dg=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var fg=Object.freeze(["shell","bash","sh"]),xg=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var di="tool-results",fi=16*1024*1024;var pg=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=e=>Object.freeze(e),_g=Object.freeze([Q({id:"antigravity",name:"Antigravity",clientNames:["antigravity","antigravity-client","antigravity-cli","agy"],envVars:["ANTIGRAVITY_CLI_ALIAS"],pluginPaths:[[".gemini","config","plugins"],[".gemini","antigravity","plugins"],[".gemini","antigravity-cli","plugins"],[".gemini","antigravity-ide","plugins"]],configDirs:[".gemini/antigravity",".gemini/antigravity-cli",".gemini/config"],binaries:["agy"],source:"v1.0.169:src/adapters/client-map.ts:15-17; detect.ts:156,481-483; #1340"}),Q({id:"cursor",name:"Cursor",clientNames:["cursor-vscode"],envVars:["CURSOR_TRACE_ID","CURSOR_CLI","CURSOR_CWD"],pluginPaths:[],configDirs:[".cursor"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:18; detect.ts:163-165,584"}),Q({id:"omp",name:"OMP (oh-my-pi)",clientNames:["omp-coding-agent"],envVars:[],pluginPaths:[],configDirs:[".omp"],binaries:["omp"],source:"v1.0.169:src/adapters/client-map.ts:37; detect.ts:543 (PI_CODING_AGENT_DIR is not a signal: supported Pi reads it too)"}),Q({id:"openclaw",name:"OpenClaw",clientNames:[],envVars:[],pluginPaths:[],configDirs:[".openclaw"],binaries:[],source:"v1.0.169:src/adapters/detect.ts:252,575 (the runtime sets no env var)"}),Q({id:"kimi",name:"Kimi Code",clientNames:["kimi-code","kimi"],envVars:[],pluginPaths:[],configDirs:[".kimi-code"],binaries:["kimi"],source:"v1.0.169:src/adapters/client-map.ts:42-44; detect.ts:567; adapters/kimi/index.ts:127"}),Q({id:"kilo",name:"Kilo Code",clientNames:["kilo code"],envVars:["KILO","KILO_PID"],pluginPaths:[],configDirs:[".config/kilo"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:28; detect.ts:170-171,592"}),Q({id:"zed",name:"Zed",clientNames:["zed"],envVars:["ZED_SESSION_ID","ZED_TERM"],pluginPaths:[],configDirs:[".config/zed"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:38-39; detect.ts:189-190,616"}),Q({id:"jetbrains-copilot",name:"JetBrains Copilot",clientNames:["jetbrains client","intellij idea","pycharm"],envVars:["IDEA_INITIAL_DIRECTORY"],pluginPaths:[],configDirs:[".config/JetBrains"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:23-25; detect.ts:213,600"})]);var Eg=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}),gg=Object.freeze(["PreToolUse","PostToolUse"]);var mg=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var hg=Object.freeze(["features","hooks"]);var Sg=Object.freeze(["",At,yt]);var Gu=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 bg=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 Og=Object.freeze(["hooks","codex"]),Tg=Object.freeze(["pretooluse.mjs","posttooluse.mjs","sessionstart.mjs","precompact.mjs","userpromptsubmit.mjs","stop.mjs"]);var Rg=Object.freeze([".mjs",".sh"]);var Bu="npm:context-mode";var vt="CLAUDE_CONFIG_DIR";var xi="CODEX_HOME",pi="COPILOT_HOME",_i="GEMINI_CLI_HOME",Ei="KIRO_HOME",gi="OPENCODE_CONFIG_DIR",io="APPDATA",jt=Object.freeze(["Code","User"]),Gt="XDG_CONFIG_HOME";var Wu="mcp.json",Ag=Object.freeze(["agents","default.json"]);var yg=Object.freeze(["steering","KIRO.md"]),mi="agent",Ng=Object.freeze(["opencode.jsonc","opencode.json"]);var Xu=`${Z}@`,Ku="@",Ig=`${Xu}latest`,Cg=`${Bu}${Ku}latest`;var kg=Object.freeze(["content","platform.json"]);var hi="custom",Si="PI_CODING_AGENT_DIR";var Yu=Object.freeze(["/","\\"]),qu="${/}",Dg=Object.freeze([...Yu,qu]),P=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/<event>.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"}),Lg=Object.freeze([P.statusLine,P.vscodeMcp,P.dataDirShared,P.tmpFile,P.kiroSteering,P.piGit,P.opencodeGit,P.projectLink]),wg=Object.freeze([P.dataDir,P.dataRoot]);var Pg=Z+"_";var Mg=Object.freeze(["opencode","plugin.js"]);var zu=Object.freeze(["features","mcp"]),Vu="omit_tools_from",Ju=Object.freeze(["deferred"]),$u="default_tools_approval_mode",Qu="approve",Ug=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",Z],fields:{[Vu]:Ju,[$u]:Qu}},vscode:{file:[Wu],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:Uu},also:[[zu,!0]]}});var Hg=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),Zu="Environment: ";var ed="Docs: ";var td="Report file: ",nd="File it: ",od="Or open: ",rd="Rules: ",sd=" --",Fg=Object.freeze([Zu,ed,td,nd,sd.trim(),od,rd]),bi="mksglu/context-mode",id="agent-report.yml",vg=`https://github.com/${bi}/blob/main/.github/AGENT_ISSUE.md`,jg=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 Gg=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var Bg=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"]),Wg=Object.freeze(["node","git","sh"]),Xg=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var Kg=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"]}),Yg=`https://github.com/${bi}/issues/new?template=${id}`;import{dirname as Tu,join as Cr,relative as Z_,resolve as eE,sep as bu}from"node:path";var co="mcp__plugin_context-mode_context-mode__",Ai=Object.freeze(["Bash","PowerShell"]),cd="PowerShell",ad="Bash",ld=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],Oi="mcp__",Ti="__",ud={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function dd(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(Oi))return e;let n=e.slice(Oi.length),o=n.indexOf(Ti);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+Ti.length)}function fd(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return yi(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=ao(e);if(t!==null)return t.text}return JSON.stringify(e)}function ao(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:xd(n.file,o)})}:_d(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 od(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 xd(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=rd(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 rd(e,t){let n=null;for(let o=0;o<e.length;o++){if(e[o]!==t[0])continue;let r=1;for(;r<t.length&&o+r<e.length&&e[o+r]===t[r];)r++;if((n===null||r>n.length)&&(n={at:o,length:r}),r===t.length)break}return n}function Ei(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function sd(e){let t=e;return(t.mode==="content"||t.mode==="count")&&typeof t.content=="string"}function mi(e){let t=[],n=!1;for(let o of e){let r=typeof o=="object"&&o!==null?o:{};r.type==="text"&&typeof r.text=="string"?t.push(r.text):n=!0}return{text:t.join(`
10
- `),keep:n}}function id(e){let t=nd(e),o={isError:typeof e=="object"&&e!==null&&e.is_error===!0,bytes:Buffer.byteLength(t),text:t};if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Ei(e)&&(o.shape=e),typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Ei(e)&&(so(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,mi(e).keep&&(o.keep=!0)),typeof e=="object"&&e!==null){let r=e;typeof r.persistedOutputPath=="string"&&r.persistedOutputPath!==""&&typeof r.persistedOutputSize=="number"&&r.persistedOutputSize>o.bytes&&(o.persistedPath=r.persistedOutputPath)}return o}function le(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=Zu.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:td(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=id(r.tool_response)),i}function cd(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:so(n);return n!==void 0&&o!==null?o.put(n,t):e.result?.blocks===!0?[{type:"text",text:t}]:t}function W(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:cd(e,t.output)}):{stdout:"",exitCode:0}}}var ad={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function ld(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 ud(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 ad[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function hi(e){ud(e);let t=le(e,"claude-code",ro,ed);if(t.tool!==void 0&&t.tool.name===$u&&(t.tool.canonicalName=Qu),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"+ld(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function Si(e,t,n){return W(e,t,!0)}var co="mcp__context_mode__",fd={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"},io="Stop",xd={stdout:"",exitCode:0};function bi(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===io){let t=e;return{event:io,agent:"codex",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")}}return le(e,"codex",co,fd)}function Oi(e,t,n){return e.event===io?xd:W(e,t,!1)}var Ft="mcp_context-mode_",Ti={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},Ri={startup:"startup",resume:"resume",clear:"clear"},_d=["SessionStart","UserPromptSubmit","PostToolUse"],Ed=["UserPromptSubmit","PreToolUse"],Ht={stdout:"",exitCode:0},gd=`the tool ran and succeeded; context-mode indexed its full output, and this is the part that answers the call:
12
- `;function R(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var Ai={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function md(e,t){if(e.startsWith(Ft))return e.slice(Ft.length);if(Object.hasOwn(Ai,e))return Ai[e];if(typeof t!="object"||t===null)return e;let n=t,o=R(n,"server_name"),r=R(n,"tool_name");return typeof o!="string"||typeof r!="string"?e:"mcp:"+o+":"+r}function hd(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 Sd(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:hd(n)??JSON.stringify(e),r=t===void 0?void 0:R(t,"error"),s={isError:r!=null,bytes:Buffer.byteLength(o),text:o};return bd(n)&&(s.keep=!0),s}function bd(e){return(Array.isArray(e)?e:[e]).some(n=>typeof n=="object"&&n!==null&&(Object.hasOwn(n,"inlineData")||Object.hasOwn(n,"fileData")))}var Od=["https://","http://"],Td=`.,;:!?)]}>'"`,Rd=`
13
- \r\f\v`;function Ad(e){let t=[],n="";for(let o of e)Rd.includes(o)?(n!==""&&t.push(n),n=""):n+=o;return n!==""&&t.push(n),t}function yd(e){if(typeof e=="string")for(let t of Ad(e)){let n=t.toLowerCase(),o=Od.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&&Td.includes(r[r.length-1]);)r=r.slice(0,-1);return r}}function Nd(e,t){if(e==="web_fetch"&&R(t,"url")===void 0){let n=yd(R(t,"prompt"));return n===void 0?t:{...t,url:n}}if(e==="read_many_files"&&R(t,"file_path")===void 0){let n=R(t,"include"),o=Array.isArray(n)?n.filter(r=>typeof r=="string"):[];return o.length===0?t:{...t,file_path:o.join(" ")}}return t}function yi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("gemini: hook payload is not a JSON object");let t=e,n=R(t,"hook_event_name"),o=typeof n=="string"&&Object.hasOwn(Ti,n)?Ti[n]:void 0;if(o===void 0)throw new Error("gemini: unknown hook event "+String(n));let r={event:o,agent:"gemini",sessionId:String(R(t,"session_id")??""),cwd:String(R(t,"cwd")??"")},s=R(t,"source");o==="SessionStart"&&typeof s=="string"&&Object.hasOwn(Ri,s)&&(r.source=Ri[s]);let i=R(t,"prompt");if(o==="UserPromptSubmit"&&typeof i=="string"&&(r.prompt=i),o==="PreToolUse"||o==="PostToolUse"){let c=String(R(t,"tool_name")??""),l=R(t,"tool_input");r.tool={name:c,canonicalName:md(c,R(t,"mcp_context")),input:Nd(c,typeof l=="object"&&l!==null&&!Array.isArray(l)?l:{})}}return o==="PostToolUse"&&(r.result=Sd(R(t,"tool_response"))),r}function Ni(e,t,n){switch(t.kind){case"allow":return Ht;case"hint":return _d.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:Ht;case"deny":return Ed.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
14
- `+t.reason}),exitCode:0}:Ht;case"replace":return e.event!=="PostToolUse"?Ht:{stdout:JSON.stringify({decision:"deny",reason:gd+t.output}),exitCode:0}}}var ao="mcp__context-mode__",Cd={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Ii={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},kd="PostToolUseFailure";function Ci(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===kd,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=le(n,"qwen",ao,Cd);if(o.tool!==void 0&&Object.hasOwn(Ii,o.tool.name)&&(o.tool.canonicalName=Ii[o.tool.name]),t){let r=e.error,s=typeof r=="string"?r:r===void 0?"":JSON.stringify(r);o.result={isError:!0,bytes:Buffer.byteLength(s),text:s}}return o}function ki(e,t,n){return W(e,t,!1)}var jt="context-mode-",Ld={sessionStart:{event:"SessionStart",casing:"camel",failure:!1},userPromptSubmitted:{event:"UserPromptSubmit",casing:"camel",failure:!1},preToolUse:{event:"PreToolUse",casing:"camel",failure:!1},postToolUse:{event:"PostToolUse",casing:"camel",failure:!1},postToolUseFailure:{event:"PostToolUse",casing:"camel",failure:!0},SessionStart:{event:"SessionStart",casing:"snake",failure:!1},UserPromptSubmit:{event:"UserPromptSubmit",casing:"snake",failure:!1},PreToolUse:{event:"PreToolUse",casing:"snake",failure:!1},PostToolUse:{event:"PostToolUse",casing:"snake",failure:!1},PostToolUseFailure:{event:"PostToolUse",casing:"snake",failure:!0}},Di={startup:"startup",resume:"resume",new:"startup"},wd={camel:{event:"hookEventName",session:"sessionId",tool:"toolName",args:"toolArgs",result:"toolResult"},snake:{event:"hook_event_name",session:"session_id",tool:"tool_name",args:"tool_input",result:"tool_result"}},Pi="success";function Gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var lo=Object.freeze(["bash","powershell"]),Li=Object.fromEntries(lo.map(e=>[e,"Bash"]));function Pd(e){return e.startsWith(jt)?e.slice(jt.length):Object.hasOwn(Li,e)?Li[e]:e}var wi=e=>typeof e=="number"&&Number.isFinite(e);function Md(e,t){let n=t.view_range;if(e!=="view"||!Array.isArray(n)||!wi(n[0]))return t;let o={...t,offset:n[0]};return wi(n[1])&&n[1]>=n[0]&&(o.limit=n[1]-n[0]+1),o}function Ud(e){if(Gt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Gt(t)?t:{}}catch{return{}}}var Hd={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function Fd(e,t,n){let o=Hd[t],r=Gt(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==Pi,bytes:Buffer.byteLength(s),text:s}}var vd=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function jd(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:vd.find(([t])=>Object.hasOwn(e,t))?.[1]}function Mi(e){if(!Gt(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=jd(e),n=typeof t=="string"?Ld[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=wd[n.casing],r=n.event,s={event:r,agent:"copilot-cli",sessionId:String(e[o.session]??""),cwd:String(e.cwd??"")};if(r==="SessionStart"&&typeof e.source=="string"&&Di[e.source]!==void 0&&(s.source=Di[e.source]),r==="UserPromptSubmit"&&typeof e.prompt=="string"&&(s.prompt=e.prompt),r==="PreToolUse"||r==="PostToolUse"){let i=String(e[o.tool]??""),c={name:i,canonicalName:Pd(i),input:Md(i,Ud(e[o.args]))};s.tool=c}return r==="PostToolUse"&&(s.result=Fd(e[o.result],n.casing,n.failure)),s}var vt={stdout:"",exitCode:0};function Ui(e,t,n){switch(t.kind){case"allow":return vt;case"hint":return e.event==="PostToolUse"?vt:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?vt:{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"?vt:{stdout:JSON.stringify({modifiedResult:{resultType:Pi,textResultForLlm:t.output}}),exitCode:0}}}var Bt="mcp_context-mode_",Bi=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],Hi="mcp_",Fi="_",Bd="new",uo=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),Xt=Object.freeze(["read_file","view"]),fo=Object.freeze(["fetch_webpage","web_fetch"]),vi=Object.fromEntries([...uo.map(e=>[e,"Bash"]),...Xt.map(e=>[e,"Read"]),...fo.map(e=>[e,"WebFetch"])]);function Wi(e){if(e.startsWith(Bt))return e.slice(Bt.length);if(Object.hasOwn(vi,e))return vi[e];if(!e.startsWith(Hi))return e;let t=e.slice(Hi.length),n=t.indexOf(Fi);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+Fi.length)}var Ke=e=>typeof e=="number"&&Number.isFinite(e);function Xi(e,t,n){if(t==="Read"&&Xt.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),Ke(n.startLine)&&(o.offset=n.startLine),Ke(n.startLine)&&Ke(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&Ke(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];Ke(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 Wd(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 Xd={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},Kd=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],ji={new:"startup",startup:"startup",resume:"resume"},Yd="success";function Wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qd(e){if(Wt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Wt(t)?t:{}}catch{return{}}}function Vd(e){let t=Wt(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==Yd,bytes:Buffer.byteLength(n),text:n}}function Gi(e,t){let n=typeof t=="string"?Xd[t]??Bi.find(r=>r===t):void 0;if(n===void 0)throw new Error("vscode: unknown hook event "+String(t));let o={event:n,agent:"vscode",sessionId:String(e.sessionId??""),cwd:String(e.cwd??"")};if(n==="SessionStart"&&typeof e.source=="string"&&ji[e.source]!==void 0&&(o.source=ji[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=Wi(r);o.tool={name:r,canonicalName:s,input:Xi(r,s,qd(e.toolArgs))}}return n==="PostToolUse"&&(o.result=Vd(e.toolResult)),o}function Ki(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("vscode: hook payload is not a JSON object");let t=e;if(t.hookEventName!==void 0)return Gi(t,t.hookEventName);if(t.hook_event_name===void 0){let r=Kd.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return Gi(t,r)}let n=Bi.find(r=>r===t.hook_event_name);if(n===void 0)throw new Error("vscode: unknown hook event "+String(t.hook_event_name));let o={event:n,agent:"vscode",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")};if(n==="SessionStart"&&t.source===Bd&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=Wt(t.tool_input)?t.tool_input:{},i=Wi(r);o.tool={name:r,canonicalName:i,input:Xi(r,i,s)}}return n==="PostToolUse"&&(o.result=Wd(t.tool_response)),o}function Yi(e,t,n){return W(e,t,!1)}var Kt="mcp_context_mode_",qi="mcp_context-mode_",Vi={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},Jd="prompt",$d="USER_PROMPT",zi="mcp_",xo=Object.freeze(["execute_bash","execute_pwsh","shell"]),Ji=Object.fromEntries(xo.map(e=>[e,"Bash"])),$i="_",Qi={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function Qd(e){if(e.startsWith(Kt))return e.slice(Kt.length);if(e.startsWith(qi))return e.slice(qi.length);if(Object.hasOwn(Ji,e))return Ji[e];if(!e.startsWith(zi))return e;let t=e.slice(zi.length),n=t.indexOf($i);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+$i.length)}function Zd(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function Zi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("kiro: hook payload is not a JSON object");let t=e,n=typeof t.hook_event_name=="string"?t.hook_event_name:"",o=Object.prototype.hasOwnProperty.call(Vi,n)?Vi[n]:void 0;if(o===void 0)throw new Error("kiro: unknown hook event "+String(t.hook_event_name));let r={event:o,agent:"kiro",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")};if(o==="SessionStart"&&typeof t.source=="string"&&Qi[t.source]!==void 0&&(r.source=Qi[t.source]),o==="UserPromptSubmit"){let s=t[Jd],i=typeof s=="string"?s:process.env[$d];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:Qd(s),input:i}}return o==="PostToolUse"&&(r.result=Zd(t.tool_response)),r}function ec(e,t,n){if(e.event==="UserPromptSubmit")return{stdout:t.kind==="hint"?t.text:"",exitCode:0};switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:t.text,exitCode:0};case"deny":return{stdout:"",stderr:t.rewritten===void 0?t.reason:t.rewritten+`
16
- `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var po="mcp__context-mode__",tc="mcp__plugin_context-mode_context-mode__",tf={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},nf={hook_event_name:"hookEventName",session_id:"sessionId"},of="PostToolUseFailure";function nc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("zcode: hook payload is not a JSON object");let t={...e};for(let[i,c]of Object.entries(nf))t[i]===void 0&&(t[i]=t[c]);let n=t.hook_event_name===of;n&&(t.hook_event_name="PostToolUse");let r=(typeof t.tool_name=="string"?t.tool_name:"").startsWith(tc)?tc:po,s=le(t,"zcode",r,tf);if(n){let i=typeof t.error=="string"?t.error:t.error===void 0?"":JSON.stringify(t.error);s.result={isError:!0,bytes:Buffer.byteLength(i),text:i}}return s}function oc(e,t,n){return W(e,t,!1)}var ic="",rc={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},sc={bash:"Bash",read:"Read",edit:"Edit",write:"Write"};function sf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function cf(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),e.keep===!0&&(n.keep=!0),n}function cc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("pi: hook payload is not an object");let t=e,n=typeof t.type=="string"?t.type:"",o=Object.prototype.hasOwnProperty.call(rc,n)?rc[n]:void 0;if(o===void 0)throw new Error("pi: unknown hook event "+String(t.type));let r={event:o.event,agent:"pi",sessionId:String(t.sessionId??""),cwd:String(t.cwd??"")};if(o.source!==void 0&&(r.source=o.source),o.event==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o.event==="PreToolUse"||o.event==="PostToolUse"){let s=String(t.toolName??"");r.tool={name:s,canonicalName:Object.hasOwn(sc,s)?sc[s]:s,input:sf(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=cf(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function af(e,t){switch(t?.kind){case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
17
- `+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function ac(e,t,n){let o=af(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:di,content:o.stdout,timestamp:Date.now()}}function lc(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var xc="",uc=Z+"_",dc={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},_o="bash",Eo="read",uf=Object.freeze([_o,"shell"]),fc={webfetch:"WebFetch",[Eo]:"Read",...Object.fromEntries(uf.map(e=>[e,"Bash"]))};function go(e){return e.startsWith(uc)?e.slice(uc.length):Object.prototype.hasOwnProperty.call(fc,e)?fc[e]:e}function df(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function ff(e){let t=e.output===void 0?"":typeof e.output=="string"?e.output:JSON.stringify(e.output),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function pc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("opencode: hook payload is not an object");let t=e,n=typeof t.type=="string"?t.type:"",o=Object.prototype.hasOwnProperty.call(dc,n)?dc[n]:void 0;if(o===void 0)throw new Error("opencode: unknown hook event "+String(t.type));let r={event:o,agent:"opencode",sessionId:String(t.sessionID??""),cwd:String(t.directory??"")};if(typeof t.agentID=="string"&&t.agentID!==""&&(r.agentId=t.agentID,r.agentType=t.agentID),Array.isArray(t.agentTools)&&(r.agentTools=t.agentTools.filter(s=>typeof s=="string")),o==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool??"");r.tool={name:s,canonicalName:go(s),input:df(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=ff(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function _c(e,t,n){switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
18
- `+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}}var Ye={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},Ec={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},pf={...Ec,shell:[...gi]},_f=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:ro,nativeTools:pf,execReadOnlyHint:!1,eventMap:Ye,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"skills"},decode:hi,encode:Si},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:co,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:Ye,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:bi,encode:Oi},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Ft,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:G,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:yi,encode:Ni},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:ao,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:Ye,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:Ci,encode:ki},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:jt,nativeTools:{shell:[...lo]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:Mi,encode:Ui},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:Bt,nativeTools:{shell:[...uo],read:[...Xt],webfetch:[...fo]},execReadOnlyHint:!1,eventMap:{...Ye,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:Ki,encode:Yi},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:Kt,nativeTools:{shell:[...xo]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:G,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:Zi,encode:ec},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:po,nativeTools:Ec,execReadOnlyHint:!1,eventMap:Ye,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:nc,encode:oc},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:ic,nativeTools:{shell:["bash","powershell"],read:["read"]},execReadOnlyHint:!1,eventMap:{SessionStart:"session_start",UserPromptSubmit:"input",PreToolUse:"tool_call",PostToolUse:"tool_result"},compactDelivery:"pi-flag",compactSummary:"none",hookTimeoutMs:Ln,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:cc,encode:ac,checkPermission:lc},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:xc,nativeTools:{shell:[_o],read:[Eo]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:Ln,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:pc,encode:_c,toCanonicalTool:go}]),Ef=new Map(_f.map(e=>[e.id,e])),gf=new Set(["claude-code","gemini","copilot-cli","pi","opencode"]);function be(e){return gf.has(e.id)}var mf=new Set(["claude-code","copilot-cli","pi"]);function mo(e){return mf.has(e.id)&&be(e)}var hf=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function Yt(e){return hf.has(e.id)}function ue(e){return Ef.get(e)}import{resolve as rt}from"node:path";var Sf=["&&","||",";;","|&",";","|","&","(",")"],bf=["&>>","&>"],Of=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],Tf="&",Rf="<<",gc="<<-",Af=";",mc=`\r
19
- `,hc=`\\
20
- `,Sc=`\\\r
21
- `,yf="$(",Tc="${",Rc="$'",qe="((",bc="))",Oe="[[",qt="]]",ho="<(",Ac=">(",M=2,yc=`
22
- \r;&|()<>`,Nf=`
23
- \r`,If='$`"\\\n',Cf="case",kf="esac";function Te(e,t){e.end==="complete"&&(e.end=t)}function So(e){return e!==""&&e>="0"&&e<="9"}function Oc(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function Nc(e){return e===""||yc.includes(e)}function bo(e){return e!==""&&Nf.includes(e)}function X(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function Vt(e,t){let n=e.s.indexOf("'",t+1);return n<0?(Te(e,"unterminated-quote"),e.n):n+1}function Ic(e,t){let n=t+Rc.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=M;continue}if(o==="'")return n+1;n++}return Te(e,"unterminated-quote"),e.n}function Oo(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+=M;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=Ve(e,o,n);continue}if(r==="$"&&s==="{"){o=To(e,o,n);continue}if(r==="`"){o=Re(e,o);continue}o++}return Te(e,"unterminated-quote"),e.n}function Re(e,t){let n=t+1;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=M;continue}if(o==="`")return n+1;n++}return e.n}function To(e,t,n){let o=t+Tc.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=M;continue}if(s==="'"){o=Vt(e,o);continue}if(s==='"'){o=Oo(e,o,n);continue}if(s==="$"&&i==="("){o=Ve(e,o,n);continue}if(s==="`"){o=Re(e,o);continue}if(s==="{"&&r++,s==="}"){if(r===0)return o+1;r--}o++}return e.n}function Ro(e,t){let n=0,o=t+qe.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(bc,o)?o+bc.length:-1;n--}o++}return-1}function Ve(e,t,n){let o=t+yf.length-1;if(e.s.startsWith(qe,o)){let r=Ro(e.s,o);if(r>0)return r}return zt(e,o+1,!0,n+1,null,null)}function Df(e,t,n){let o=t+Oe.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=M;continue}if(s==="'"){o=Vt(e,o);continue}if(s==='"'){o=Oo(e,o,n);continue}if(s==="$"&&i==="("){o=Ve(e,o,n);continue}if(s==="$"&&i==="{"){o=To(e,o,n);continue}if(s==="`"){o=Re(e,o);continue}let c=bo(e.s.charAt(o-1));if(c&&e.s.startsWith(qt,o)&&Nc(e.s.charAt(o+qt.length))){if(r===0)return o+qt.length;r--,o+=qt.length;continue}if(c&&e.s.startsWith(Oe,o)&&bo(e.s.charAt(o+Oe.length))){r++,o+=Oe.length;continue}o++}return-1}function Lf(e,t){let n=t;for(;So(e.charAt(n));)n++;if(n===t){for(let o of bf)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of Of){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(Tf))if(e.charAt(r)==="-")r++;else for(;So(e.charAt(r));)r++;return{end:r,op:o}}return null}function wf(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(yc.includes(r))break;if(r==="\\"){o+=M;continue}if(r==="'"){o=Vt(e,o);continue}if(r==='"'){o=Oo(e,o,n);continue}if(r==="$"&&s==="'"){o=Ic(e,o);continue}if(r==="$"&&s==="("){o=Ve(e,o,n);continue}if(r==="$"&&s==="{"){o=To(e,o,n);continue}if(r==="`"){o=Re(e,o);continue}o++}return Math.min(o,e.n)}function Pf(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),X(o,"unhandled",e.s.slice(c,s),c,s),!l)return Te(e,"unterminated-heredoc"),e.n}return n.length=0,s}function zt(e,t,n,o,r,s){if(o>B)return Te(e,"too-deep"),e.n;let i=e.s,c=t,l=0,a=0,d=null,u=[];for(;c<e.n;){let f=i.charAt(c),x=i.charAt(c+1);if(f===" "||f===" "){c++;continue}if(i.startsWith(hc,c)){c+=hc.length;continue}if(i.startsWith(Sc,c)){c+=Sc.length;continue}if(f===`
25
- `||f==="\r"){let S=c;c+=i.startsWith(mc,c)?mc.length:1,X(r,"op",Af,S,c),d=null,u.length>0&&(c=Pf(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(ho,c)||i.startsWith(Ac,c)){let S=zt(e,c+ho.length,!0,o+1,null,null);X(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}let p=Lf(i,c);if(p!==null){X(r,"io",i.slice(c,p.end),c,p.end),d=p.op===Rf||p.op===gc?p.op===gc:null,c=p.end;continue}if(i.startsWith(Oe,c)&&bo(i.charAt(c+Oe.length))){let S=Df(e,c,o);if(S>0){X(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}if(i.startsWith(qe,c)){let S=Ro(i,c);if(S>0){X(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}let g=Sf.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}X(r,"op",g,c,c+g.length),c+=g.length,d=null;continue}if(f==="$"&&x==="("||f==="`"){let S=f==="`"?Re(e,c):Ve(e,c,o);if(Nc(i.charAt(S))){X(r,"unhandled",i.slice(c,S),c,S),c=S,d=null;continue}}let E=c;c=wf(e,c,o);let h=i.slice(E,c);X(r,"word",h,E,c),d!==null&&(u.push({tag:Ae(h),strip:d}),d=null),n&&h===Cf&&a++,n&&h===kf&&a>0&&a--}return u.length>0&&Te(e,"unterminated-heredoc"),e.n}function Cc(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return zt(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function Ae(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=M;continue}if(r==="'"){let s=e.indexOf("'",n+1),i=s<0?o:s;t+=e.slice(n+1,i),n=i+1;continue}if(r==="$"&&e.charAt(n+1)==="'"){let s=n+Rc.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=M;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!==""&&If.includes(i)){t+=i,s+=M;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function Jt(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+=M;continue}if(!o&&s==="'"){r=Vt(t,r);continue}if(!o&&s==="$"&&i==="'"){r=Ic(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Tc.length;continue}let c=e.startsWith(ho,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(Ac,r))){let l=r+1;if(s==="$"&&e.startsWith(qe,l)&&Ro(e,l)>0){r=l+qe.length;continue}let a=zt(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=Re(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 $t(e){let t=e.charAt(0);if(!(Oc(t)||t==="_"))return!1;for(let n=1;n<e.length;n++){let o=e.charAt(n);if(o==="="||o==="+"&&e.charAt(n+1)==="=")return!0;if(!(Oc(o)||So(o)||o==="_"))return!1}return!1}var wc=[";","&","&&","||"],Pc=["|","|&"],ze="(",Je=")",Mc=";;",No=["(",")"],Mf="!";function U(e,t){for(let n of t)e.push(n)}var b=Object.freeze({group:"{",groupEnd:"}",if:"if",then:"then",elif:"elif",else:"else",fi:"fi",while:"while",until:"until",for:"for",in:"in",do:"do",done:"done",case:"case",esac:"esac",function:"function",coproc:"coproc",select:"select"}),Uc=[],Uf="[[",Hf="((",Hc=[">",">>",">|","&>","&>>",">&"],Ff=[...Hc,"<","<>","<<<","<<","<<-"],vf=["","1"],Fc=["-","/dev/stdout","/dev/stderr"],Zt="-",$e="--",Qe="=",jf="/",Gf=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),Qt=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),Ao="-c",yo="--bytes",Bf="c",Wf="--count",de=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],te=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,k=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,Io=e=>e!==""&&e>="0"&&e<="9",Xf=e=>Io(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function Co(e){let t=e.lastIndexOf(jf);return t>=0&&t<e.length-1?e.slice(t+1):e}function ko(e,t){let n=Gf[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===$e)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+Qe))s=r.slice(n.long.length+Qe.length);else if(r.startsWith(Zt)&&!r.startsWith($e)){let i=r.indexOf(n.short,Zt.length);if(i<0)continue;s=i+n.short.length<r.length?r.slice(i+n.short.length):t[o+1]}else continue;if(s!==void 0&&!Fc.includes(s))return!0}return!1}function Kf(e){if(e==="")return!1;for(let t of e)if(!Io(t))return!1;return!0}function Yf(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===Ao||n===yo?o=e[t+1]:n.startsWith(yo+Qe)?o=n.slice(yo.length+Qe.length):n.startsWith(Ao)&&!n.startsWith($e)&&(o=n.slice(Ao.length)),o!==void 0)return Kf(o)&&Number(o)<=ce}return!1}function qf(e){for(let t of e){if(t===$e)return!1;if(t===Wf||t.startsWith(Zt)&&!t.startsWith($e)&&t.includes(Bf))return!0}return!1}function kc(e){if(!e.startsWith(w.fieldSep))return!1;for(let t of e.slice(w.fieldSep.length).split(w.fieldSep)){if(t==="")return!1;for(let n of t)if(!Xf(n))return!1}return!0}function Vf(e){let t=e.trim();if(t===w.identity||t===w.length)return!0;let n=t.indexOf(w.pipeLength.charAt(0));if(n<0)return kc(t);let o=t.slice(0,n).trim(),r=w.pipeLength.slice(1).trim();return(o===w.identity||kc(o))&&t.slice(n+1).trim()===r}function zf(e){let t=e.argv0.toLowerCase();if(t===Qt.wc)return!0;if(t===Qt.head)return Yf(e.args);if(t===Qt.grep)return qf(e.args);if(t===Qt.jq){let n=e.args.filter(o=>!o.startsWith(Zt));return n.length===1&&Vf(n[0])}return!1}function Do(e){return Jt(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function vc(e,t,n){return n<=t?[]:Do(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function jc(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function Jf(e){let t=0;for(;Io(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Gc(e){let t=Jf(e.toks[e.i].text);if(e.i++,!Ff.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,Hc.includes(t.op)&&vf.includes(t.fd)&&!Fc.includes(Ae(n.text)))}function Bc(e){let t=!1;for(;O(e)?.kind==="io";)t=Gc(e)||t;return t}function Wc(e){for(;O(e)?.kind==="op"&&wc.includes(O(e)?.text??"");)e.i++}function ye(e,t){if(e.depth++,e.depth>B)return e.err="nesting-too-deep",de();let n=t();if(e.depth--,Bc(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function Xc(e){if(Wc(e),!k(O(e),b.do))return[];e.i++;let t=K(e,[b.done]);return k(O(e),b.done)&&e.i++,t}function $f(e){e.i++;let t=K(e,[b.then]);for(;e.err===null;){let n=O(e);if(k(n,b.then)||k(n,b.else)){e.i++,U(t,K(e,[b.elif,b.else,b.fi]));continue}if(k(n,b.elif)){e.i++,U(t,K(e,[b.then]));continue}k(n,b.fi)&&e.i++;break}return t}function Qf(e){e.i++;let t=K(e,[b.do]);return U(t,Xc(e)),t}function Zf(e){e.i++;let t=[],n=O(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,k(O(e),b.in)){e.i++;let o=e.i;for(;(O(e)?.kind==="word"||O(e)?.kind==="unhandled")&&!k(O(e),b.do);)e.i++;U(t,vc(e,o,e.i))}return U(t,Xc(e)),t}function e0(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,U(t,vc(e,e.i-1,e.i))),k(O(e),b.in)&&e.i++;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)||o.kind==="op"&&(wc.includes(o.text)||o.text===Mc)){e.i++;continue}if(k(o,b.esac)){e.i++;break}for(te(o,ze)&&e.i++;e.i<e.toks.length&&!te(O(e),Je);){let s=e.toks[e.i];if(s.kind==="op"&&!Pc.includes(s.text))break;e.i++}if(!te(O(e),Je))break;e.i++;let r=K(e,[b.esac]);jc(r,b.case),U(t,r)}return t}function Dc(e,t){Wc(e);let n=Kc(e);return jc(n.cmds,t),{cmds:n.cmds,simple:null}}function Lc(e,t){return No.every((n,o)=>te(e.toks[t+o],n))}function t0(e){let t=e.i,n=[],o=!1;for(;e.i<e.toks.length;){let a=e.toks[e.i];if(a.kind==="op")break;if(a.kind==="io"){o=Gc(e)||o;continue}if(n.length===0&&a.kind==="word"&&$t(a.text)){e.i++;let d=O(e);if(a.text.endsWith(Qe)&&d!==void 0&&te(d,ze)&&d.start===a.end){let u=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,te(f,ze)&&u++,te(f,Je)&&--u===0)break}}continue}n.push(a),e.i++}if(e.i===t)return de();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:Do(r),simple:null};let s=a=>a.kind==="word"?Ae(a.text):a.text,i=Co(s(n[0])),c=n.slice(1).map(s),l={argv0:i,args:c,redirectsToFile:o||ko(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[l],simple:l}}function Kc(e){let t=O(e);if(t===void 0)return de();if(t.kind==="op")return t.text!==ze?de():ye(e,()=>{e.i++;let n=K(e,Uc);return te(O(e),Je)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(Uf)||t.text.startsWith(Hf)))return e.i++,Bc(e),{cmds:Do(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return ye(e,()=>{e.i++;let n=K(e,[b.groupEnd]);return k(O(e),b.groupEnd)&&e.i++,n});case b.if:return ye(e,()=>$f(e));case b.while:case b.until:return ye(e,()=>Qf(e));case b.for:return ye(e,()=>Zf(e));case b.case:return ye(e,()=>e0(e));case b.coproc:return e.err="coproc",de();case b.select:return e.err="select",de();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=Ae(n.text),e.i++),Lc(e,e.i)&&(e.i+=No.length),Dc(e,o)}default:if(Lc(e,e.i+1))return e.i+=No.length+1,Dc(e,Ae(t.text))}return t0(e)}function n0(e){k(O(e),Mf)&&e.i++;let t=[],n=de();for(;e.err===null;){n=Kc(e),U(t,n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&Pc.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&zf(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function K(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===Je||o.text===Mc)return n;if(o.text!==ze){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;U(n,n0(e)),e.i===r&&e.err===null&&e.i++}return n}function Ne(e){let t=Cc(e);if(t.end==="unterminated-quote")return{ok:!1,construct:"unterminated-quote"};if(t.end==="unterminated-heredoc")return{ok:!1,construct:"unterminated-heredoc"};if(t.end==="too-deep")return{ok:!1,construct:"nesting-too-deep"};let n={toks:t.tokens,src:e,bodies:new Set(t.heredocBodies),i:0,depth:0,err:null},o=[];for(;n.i<n.toks.length&&n.err===null;)U(o,K(n,Uc)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as Yc}from"node:path";var tn="'",Ie='"',nn="`",o0=" \r",et="([{",Mo=")]}",Lo=` \r
27
- |;>`,zc="*",qc="1",wo="::",en=wo.length,r0=en;function on(e,t){let n=e.charAt(t);for(let o=t+1;o<e.length;o++){let r=e.charAt(o);if(n===Ie&&r===nn){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function s0(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===Ie&&r===nn&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function Ze(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===tn||r===Ie){let s=on(e,o);if(s<0)return-1;o=s;continue}if(r===nn){o++;continue}if(et.includes(r))n++;else if(Mo.includes(r)&&--n===0)return o}return-1}function i0(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===tn||r===Ie){let s=on(e,o);if(s<0)return e.length;o=s;continue}if(et.includes(r))n++;else if(Mo.includes(r))n--;else if(n<=0&&Lo.includes(r))return o}return e.length}function c0(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===tn||s===Ie){let i=on(e,r);if(i<0)break;r=i;continue}et.includes(s)?n++:Mo.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var a0=e=>e!==""&&(e===zc||[...e].every(t=>t>="0"&&t<="9")),Vc=()=>({words:[],toFile:!1,chained:!1});function Jc(e){let t=[],n=[],o=Vc(),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=Vc()},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===tn||p===Ie){let E=on(e,x);f(s0(e.slice(x+1,E<0?l:E),p),!0),x=E<0?l:E+1}else if(p===nn)g!==`
28
- `&&g!==""&&f(g,!1),x+=en;else if(p===`
29
- `)u(),x++;else if(o0.includes(p))a(),x++;else if(p===";")u(),x++;else if(p==="|")g==="|"?(u(),x+=en):(d(),x++);else if(p==="&")g==="&"?(u(),x+=en):((s||o.words.length>0)&&f(p,!1),x++);else if(p==="#"&&!s)for(;x<l&&e.charAt(x)!==`
30
- `;)x++;else if(p===">"){let E=qc;s&&i&&a0(r)?(E=r,r="",s=!1):s&&a();let h=x+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<l&&!Lo.includes(e.charAt(h));)h++;else c=E===qc||E===zc?"file":"skip";x=h}else if(p==="("&&s&&i&&r.includes(wo)){let E=Ze(e,x),h=e.slice(x+1,E<0?l:E);a();for(let S of h.trim()===""?[]:c0(h)){let _=Jc(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}x=E<0?l:E+1,x<l&&!Lo.includes(e.charAt(x))&&(o.chained=!0,x=i0(e,x))}else if(p==="["&&!s&&e.startsWith(wo,Ze(e,x)+1)&&Ze(e,x)>=0){let E=Ze(e,x);f(e.slice(x,E+1),!1),x=E+1}else if(et.includes(p)&&(p!=="["||!s)||(p==="$"||p==="@")&&et.includes(g)&&g!=="["){let E=p==="$"||p==="@"?x+1:x,h=Ze(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 l0=["get-content","gc","cat","type"],u0=["[io.file]::","[system.io.file]::"],d0=["readalltext","readalllines","readallbytes","readlines"],Uo=["path","literalpath"],$c=["totalcount","head","first","tail","last"],Qc=[...Uo,...$c,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],f0=["raw","wait","force","asbytestream"],x0=[...Qc,...f0],p0=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],_0=["cd","chdir","sl","set-location","pushd","push-location"],E0=["powershell","powershell.exe","pwsh","pwsh.exe"],g0=["cmd","cmd.exe"],m0=["/c","/k","/r"],h0="command",fe="-";function Po(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function Ho(e,t){let n=e.slice(fe.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 S0(e){if(e.length===0)return null;let t=Po(e[0]);if(!l0.includes(t)){let r=e[0].toLowerCase(),s=u0.find(i=>r.startsWith(i));return s===void 0||!d0.includes(r.slice(s.length))||e.length<r0?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(fe)||s.length===fe.length){n.push(s);continue}let i=Ho(s,x0);if(i.full===void 0||!Qc.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;Uo.includes(i.full)&&n.push(c),$c.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function b0(e,t){if(E0.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(fe)||o.length===fe.length)continue;let r=Ho(o,[h0]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(g0.includes(e)){for(let n=1;n<t.length;n++)if(m0.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function O0(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(fe)||n.length===fe.length)return n;let o=Ho(n,Uo);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function Zc(e,t,n,o){let r=t;for(let s of Jc(e)){let i=s[0];if(i.words.length===0)continue;let c=Po(i.words[0]);if(s.length===1&&_0.includes(c)){let u=O0(i.words);u!==null&&(r=Yc(r,u));continue}let l=n<B?b0(c,i.words):null;if(l!==null){Zc(l,r,n+1,o);continue}if(i.toFile||i.chained)continue;let a=S0(i.words);if(a===null||a.bounded)continue;let d=!0;for(let u=1;u<s.length;u++)if(s[u].toFile||!p0.includes(Po(s[u].words[0]??""))){d=!1;break}d&&o.push(Yc(r,a.file))}}function ea(e,t){let n=[];return Zc(e,t,0,n),n}import{join as cn}from"node:path";var ta=`\r
31
- `,T0=`
32
- `;function rn(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(ta)<0?t:t.split(ta).join(T0)}import{basename as N0,dirname as I0,join as Y,posix as oa,resolve as C0,win32 as ra}from"node:path";var R0=Object.freeze({NODE_TOO_OLD:"Context Mode needs Node 24.15.0 or newer; you have <v>. Fix: nvm install 24, or install it from https://nodejs.org.",NO_SQLITE:"node:sqlite failed to load. Fix: run ctx_doctor.",DB_GONE:"context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",NO_PROJECT:"Project source <kind> is missing. Fix: run ctx_doctor.",UNKNOWN_FIELD:'Unknown field "<f>". Fix: use "queries".',TIMEOUT:"Timed out after <ms> ms. Fix: pass background: true.",NO_GIT_BASH:"Git Bash not found. Fix: install Git for Windows.",NO_RUNTIME:"No <lang> runtime on PATH. Fix: install it or pick another language.",FETCH_FAILED:"Fetch failed: <code>. Fix: check the URL or proxy.",SSRF:"Blocked private address <host>. Fix: use a public URL.",OUTSIDE_ROOT:"Path <p> is outside the project. Fix: use a path inside <root>.",INVALID_ARGS:"Invalid argument <field>. Fix: <action>.",ONE_OF_INPUT:"Pass exactly one of <names>. Fix: drop the extra field.",SPAWN_FAILED:"Failed to start the process: <detail>. Fix: check the command and PATH.",DB_CORRUPT:"context.db failed integrity_check. Fix: run ctx_doctor.",SCHEMA_STALE:"context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.",NO_GIT_DIR:"No git repository at <path>. Fix: run context-mode inside a git repository.",NO_HOME:"Env var <name> is not set. Fix: set <name> to your home directory.",PLUGIN_ROOT_MISSING:"Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.",BUNDLE_HASH_MISMATCH:"Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.",CONFIG_PARSE_FAILED:"<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade."});function A0(e,t){let n=R0[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(A0(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{existsSync:tm,mkdirSync:y0,readFileSync:nm,readdirSync:om,realpathSync:na}=process.getBuiltinModule("node:fs");function H(e,t=process.platform){let n=o=>o!==void 0&&o!=="";return t==="win32"?n(e.USERPROFILE)?e.USERPROFILE:n(e.HOMEDRIVE)&&n(e.HOMEPATH)?e.HOMEDRIVE+e.HOMEPATH:n(e.HOME)?e.HOME:null:n(e.HOME)?e.HOME:n(e.USERPROFILE)?e.USERPROFILE:null}function sa(e,t){let n=e[si];return n!==void 0&&n!==""?n:Y(t,...C.codex)}function ia(e,t){let n=e[ii];return n!==void 0&&n!==""?n:Y(t,...C["copilot-cli"])}function ca(e,t){let n=e[ci];return Y(n!==void 0&&n!==""?n:t,...C.gemini)}function aa(e,t,n=process.platform){let o=n==="win32"?ra:oa,r=o.join(t,...C.kiro),s=e[ai]?.trim();if(s===void 0||s===""||!o.isAbsolute(s)||n==="win32"&&o.parse(s).root.length<2)return r;let i=o.resolve(s),c=n===process.platform?k0:d=>d,l=c(i);if(o.parse(l).root===l)return r;let a=o.relative(l,c(o.resolve(t)));return!o.isAbsolute(a)&&a.split(o.sep)[0]!==".."?r:i}function k0(e){let t=[];for(let n=e;;)try{return Y(na.native(n),...t.reverse())}catch{let o=I0(n);if(o===n)return e;t.push(N0(n)),n=o}}function q(e,t){let n=e[Pt];return n!==void 0&&n!==""?n:Y(t,...C["claude-code"])}function la(e,t){let n=e[li];if(n!==void 0&&n!=="")return n;let o=e[Ut];return o!==void 0&&o!==""?Y(o,C.opencode[C.opencode.length-1]):Y(t,...C.opencode)}function ua(e,t){let n=e[fi];return n!==void 0&&n!==""?n:Y(t,...C.pi,ui)}function da(e,t,n=process.platform){let o=s=>s!==void 0&&s!=="",r=n==="win32"?ra:oa;return n==="win32"?r.join(o(e[oo])?e[oo]:r.join(t,"AppData","Roaming"),...Mt):n==="darwin"?r.join(t,"Library","Application Support",...Mt):r.join(o(e[Ut])?e[Ut]:r.join(t,".config"),...Mt)}function D0(e,t=process.platform){let n=H(e,t);if(n!==null)return n;throw new T("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function sn(e,t){let n=e[ve];return n!==void 0&&n!==""?C0(n):Y(t,es.slice(1))}function fa(e){let t=e[ve],n=sn(e,t!==void 0&&t!==""?"":D0(e));return y0(n,{recursive:!0}),na.native(n)}var{readFileSync:Ea}=process.getBuiltinModule("node:fs");function Ce(e){return e.agentId!==void 0&&e.agentId!==""}function jo(e,t){if(t===null)return"C";let n=ue(e.agent),o=new Set(t);for(let r of ht)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function Go(e,t){if(!Ce(e))return null;let n=ue(e.agent);if(t.manifestTools!==void 0)return _a(t.manifestTools.map(c=>Fo(n,c)));let o=e.agentType??"",r=L0(o,t);if(r===null)return null;let s=(r.tools??H0(n)).map(c=>Fo(n,c)),i=r.disallowed.map(c=>Fo(n,c));return _a(s.filter(c=>!i.some(l=>v0(l,c))))}function L0(e,t){if(!w0(e))return null;let n=P0(t.env);if(e.indexOf(me)>=0){if(n!==null){let s=M0(q(t.env,n),e);if(s!==null)return s}}else{let s=vo(cn(t.projectDir,ns,Rt,e+ge));if(s!==null)return s;if(n!==null){let i=vo(cn(q(t.env,n),Rt,e+ge));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 w0(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(me))if(t===""||t==="."||t==="..")return!1;return!0}function P0(e){return H(e)}function M0(e,t){let n=t.indexOf(me),o=t.slice(0,n),r=t.slice(n+me.length);if(r.indexOf(me)>=0)return null;let s;try{s=JSON.parse(rn(Ea(cn(e,Un,os),"utf8")))}catch{return null}let i=s?.plugins;if(i===null||typeof i!="object")return null;for(let c of Object.keys(i)){let l=c.indexOf(rs);if((l<0?c:c.slice(0,l))!==o)continue;let a=i[c];if(Array.isArray(a))for(let d of a){let u=d?.installPath;if(typeof u!="string"||u==="")continue;let f=vo(cn(u,Rt,r+ge));if(f!==null)return f}}return null}function vo(e){let t;try{t=Ea(e,"utf8")}catch{return null}return U0(t)}function U0(e){let t=e.split(`
33
- `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Hn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Hn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=xa(o,ss),s=xa(o,is);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function xa(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(t+":"))continue;let r=o.slice(t.length+1).trim();if(r===""){let s=[];for(let i=n+1;i<e.length;i++){let c=e[i].trim();if(!c.startsWith("-"))break;s.push(pa(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>pa(s.trim())).filter(s=>s!=="")}return null}function pa(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function H0(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...ht.map(n=>e.toolNamePrefix+n)]}function Fo(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(cs)?F0(o):o}function F0(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||as.indexOf(n)>=0;t+=o?n:"_"}return t}function v0(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(Fn)){let n=e.slice(Fn.length);if(n!==""&&n.indexOf(vn)<0)return t.startsWith(e+vn)}return!1}function _a(e){return[...new Set(e.filter(t=>t!==""))]}var xe="",ga=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:xe},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:xe},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:xe},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:xe},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:xe},command:{valueShorts:xe,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:xe}}),j0=["bash","sh","zsh"],G0="c",B0=" -c",W0=["-o","+o","-O","+O"],an="-",X0="+",Bo="--",K0="smhd",Y0=".",ma=e=>e!==""&&e>="0"&&e<="9";function q0(e){if(e===""||!ma(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(ma(n)||n===Y0))return t===e.length-1&&K0.includes(n)}return!0}function V0(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===Bo){n++;break}if(e.assignments&&$t(o)){n++;continue}if(o.startsWith(Bo)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(an)&&o.length>an.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=an.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||!q0(t[n]))return null;n++}return n<t.length?t.slice(n):null}function z0(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(Bo)){if(o.startsWith(an)||o.startsWith(X0)){o.includes(G0)&&(t=!0),W0.includes(o)&&n++;continue}return t?o:null}}return null}function ha(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function Wo(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let l=s.toLowerCase();if(j0.includes(l)){let u=z0(i),f=u!==null&&n<B?Ne(u):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=ha(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,Wo(p,[...r,l+B0],n+1,o)}return}let a=Object.hasOwn(ga,l)?ga[l]:void 0,d=a===void 0?null:V0(a,i);if(d===null)break;r.push(l),s=Co(d[0]),i=d.slice(1),c=c||ko(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=B))for(let l of Jt(e.raw)){let a=Ne(l.body);if(a.ok)for(let d of a.commands)Wo(ha(d,e),[...t,l.wrapper],n+1,o)}}function Xo(e){let t=[];for(let n of e)Wo(n,[],0,t);return t}import{isAbsolute as $0,join as Ko,relative as Q0,sep as Yo}from"node:path";var{readFileSync:J0}=process.getBuiltinModule("node:fs"),Sa=".claude",Z0="settings.local.json",ba="settings.json",Ia="Bash",ex="Read",Oa=":*",Ta="//",Ra="~/",Aa="./",ya="..",tx=`
34
- \r`,nx=Object.freeze({tool:Ia});function ox(e,t){if(t!=="claude-code")return[];let n=H(process.env),o=process.env[Pt],r=o!==void 0&&o!==""?o:n===null?null:q(process.env,n),s=[Ko(e,Sa,Z0),Ko(e,Sa,ba)];return r===null?s:[...s,Ko(r,ba)]}function Na(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rx(e){let t;try{t=rn(J0(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Na(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Na(o))return{kind:"bad"};let r=o.deny;return r===void 0?{kind:"ok",deny:[]}:!Array.isArray(r)||!r.every(s=>typeof s=="string")?{kind:"bad"}:{kind:"ok",deny:r}}function Ca(e,t){let n=[];for(let o of ox(e,t)){let r=rx(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function qo(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 Vo(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 tt(e,t,n){let o=qo(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,Vo(o,t,n,s)[0]===1}function ka(e){let t=e.indexOf("(");if(t<1||!e.endsWith(")"))return null;let n=e.slice(t+1,e.length-1);return n===""?null:{tool:e.slice(0,t),glob:n}}function Da(e,t){let n=t.length,o=new Uint8Array(n+1);if(o[n]=1,!e.endsWith(Oa))return Vo(qo(e,!1),t,!1,o);for(let r=0;r<n;r++)tx.includes(t[r])&&(o[r]=1);return Vo(qo(e.slice(0,e.length-Oa.length),!1),t,!1,o)}function sx(e,t){return Da(e,t)[0]===1}function La(e,t,n){for(let o of t){let r=ka(o);if(r===null||r.tool!==Ia)continue;let s=Da(r.glob,e);for(let i=0;i<=e.length;i++)if(n[i]===1&&s[i]===1)return o}return null}var ix=/^[A-Za-z]:(?=\/)/;function nt(e){return Yo==="/"?e:e.split(Yo).join("/")}function cx(e,t,n){if(e.startsWith(Aa)){if(n===void 0)return!1;let r=Q0(n,t);return r===""||r===ya||r.startsWith(ya+Yo)||$0(r)?!1:tt(e.slice(Aa.length),nt(r),!0)}let o=nt(t);if(e.startsWith(Ta)){let r=nt(e.slice(Ta.length-1));return tt(r,o,!0)||tt(r,o.replace(ix,""),!0)}if(e.startsWith(Ra)){let r=H(process.env);return r!==null&&tt(nt(r)+e.slice(Ra.length-1),o,!0)}return tt(nt(e),o,!0)}function ke(e,t,n=nx){for(let o of t){let r=ka(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===ex?cx(r.glob,e,n.projectDir):sx(r.glob,e))return o}return null}var Tm=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),wa='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.',Pa=`context-mode: {size}-byte file, over the one-read limit. Read "{path}" in parts with offset and limit, or sed -n '1,200p'.`;var Ma="{size}",Ua="{path}";function Ha(e,t,n=""){return L(wa,n).split(Ma).join(String(t)).split(Ua).join(e)}function Fa(e,t){return Pa.split(Ma).join(String(t)).split(Ua).join(e)}import{extname as dx,join as zo,resolve as fx}from"node:path";import{dirname as va,isAbsolute as Ba,join as km,relative as Dm,resolve as Wa,sep as Xa}from"node:path";var{lstatSync:Im,realpathSync:ax}=process.getBuiltinModule("node:fs");function ot(e){try{return ax.native(e)}catch{return}}function I(e){return e.split(Xa).filter(t=>t!=="")}function Ka(e,t){let n=ot(e),o=ot(t);if(n===void 0||o===void 0)return!1;let r=I(n),s=I(o);if(s.length<r.length)return!1;for(let i=0;i<r.length;i+=1)if(r[i]!==s[i])return!1;return!0}var ja=new Map;function lx(e){let t=ja.get(e);if(t!==void 0)return t;let n=ot(e);return n!==void 0&&ja.set(e,n),n}function De(e,t){if(e.length===0)return!1;let n=ot(t);if(n===void 0)return!1;let o=I(n);return e.some(r=>{let s=lx(r);if(s===void 0)return!1;let i=I(s);return o.length>=i.length&&i.every((c,l)=>c===o[l])})}function Ya(e,t){return(Ba(t)?I(t):[...I(e),...I(t)]).includes("..")}var Ga=new Map;function ux(e){let t=Ga.get(e);return t===void 0&&(t=I(Wa(e)),Ga.set(e,t)),t}function qa(e,t){if(e.length===0)return!1;let n=I(t);if(n.includes(".."))return!1;let o=Xa==="/"&&Ba(t)?n.filter(r=>r!=="."):I(Wa(t));return e.some(r=>{let s=ux(r);return o.length>=s.length&&s.every((i,c)=>i===o[c])})}function Va(e){let t=e.map(ot).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=I(n).length;for(let s of t){let i=I(s),c=I(n),l=0;for(;l<o&&l<i.length&&i[l]===c[l];)l+=1;o=l}let r=n;for(;I(r).length>o&&va(r)!==r;)r=va(r);return r}function xx(e,t){let n=H(t);if(n===null)return[];let o=zo(n,...ls);return[...e==="claude-code"?[q(t,n)]:e==="codex"?[sa(t,n)]:e==="gemini"?[ca(t,n)]:e==="copilot-cli"?[ia(t,n)]:e==="kiro"?[aa(t,n)]:e==="opencode"?[la(t,n)]:e==="pi"?[ua(t,n)]:e==="vscode"?[zo(n,...C.vscode),da(t,n)]:[zo(n,...C[e])],o]}function Le(e,t,n,o=process.env){if(dx(n).toLowerCase()!==ge)return!1;let r=xx(e,o),s=fx(t,n);return!Ya(t,n)&&qa(r,s)||De(r,s)}import{extname as gx}from"node:path";var{closeSync:px,openSync:_x,readSync:Ex}=process.getBuiltinModule("node:fs");function mx(e){let t=null;try{t=_x(e,"r");let n=Buffer.alloc(Kn),o=Ex(t,n,0,Kn,0);return n.subarray(0,o)}catch{return null}finally{t!==null&&px(t)}}function ln(e,t){let n=js[e]??[];if(n.length===0)return!1;let o=gx(t).toLowerCase(),r=n.filter(i=>Xn[i].exts.includes(o));if(r.length===0)return!1;let s=mx(t);return s===null?!1:r.some(i=>Xn[i].sig.every(c=>c.bytes.every((l,a)=>s[c.at+a]===l)))}var{statSync:hx}=process.getBuiltinModule("node:fs"),el="Bash",$o="Read",Sx="WebFetch",bx="ctx_execute",Ox="ctx_batch",tl="shell",Tx="1",ne="-",Qo="--",Rx="=",Ax=".",za=",",Jo="p",yx=["-e","--expression"],Ja=".exe",Nx=";&|(`\n\r",Ee=Object.freeze({kind:"allow"}),pe=e=>({kind:"deny",reason:e}),_e=e=>typeof e=="string"?e:void 0,$a=e=>e!=null,V=(e,t)=>e.includes(t);function nl(e,t,n,o=e.cwd){let r=e.tool;if(r===void 0)return Ee;let s=r.canonicalName,i=r.input,c;if(n===null){if(process.env[ts]===Tx)return pe(L(At,t.toolNamePrefix));process.stderr.write(ys+`
35
- `),c=[]}else c=n;let l=Cx(s,i,e.cwd,c);return l!==null?pe(je+l):s===Sx?wx(i,t):s===el?Px(e,t,i,c,o):s===$o?Gx(e,t,i,o):Ee}function ol(e,t,n,o){let r=e==="webfetch",s=r?Es.map(c=>n.toolNamePrefix+c).join(As):n.toolNamePrefix+_s,i=JSON.stringify(r?{url:t}:{language:tl,code:t,intent:o??ps});return[jn+us[e]+ds,fs,xs+s,i].join(`
36
- `)}function Ix(e){for(let t of he){let n=_e(e[t]);if(n!==void 0&&n!=="")return n}}function rl(e){let t=Ix(e),n=Array.isArray(e[Se])?e[Se].filter(o=>typeof o=="string"&&o!==""):[];return t===void 0?n:[t,...n]}function Cx(e,t,n,o){if(o.length===0)return null;let r=s=>ke(rt(n,s),o,{tool:$o,projectDir:n});if(e===el){let s=_e(t.command);return s===void 0?null:ke(s,o)}if(e===$o){for(let s of rl(t)){let i=r(s);if(i!==null)return i}return null}if(e===bx){let s=_e(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=_e(t.code);return kx(t.language)&&c!==void 0?Qa(c,o):null}if(e===Ox&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?Qa(s,o):null;if(i!==null)return i}return null}function kx(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(Ja)&&(t=t.slice(0,t.length-Ja.length)),t===tl||V(Qr,t)}function Qa(e,t){let n=ke(e,t);if(n!==null)return n;let o=Ne(e);if(!o.ok)return il(e,t);for(let r of Xo(o.commands)){let s=sl(r,t);if(s!==null)return s}return null}function sl(e,t){return t.length===0?null:ke([e.argv0,...e.args].join(" "),t)??ke(e.raw,t)}function il(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||Nx.includes(e.charAt(r-1)))&&(o=!0),o&&(r===e.length||e.charAt(r).trim()!=="")&&(n[r]=1,o=!1);return La(e,t,n)}function Dx(e,t){return il(e,t)!==null}function Lx(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return Ns.some(n=>t===n||t.endsWith(Ax+n))}function wx(e,t){let n=_e(e.url)??"";return Lx(n)?Ee:pe(ol("webfetch",n,t))}function Px(e,t,n,o,r){let s=_e(n.command)??"",i=Ne(s);if(!i.ok)return Dx(s,o)?pe(L(yt,t.toolNamePrefix)):Za(e,s,t,r)??Ee;let c=Xo(i.commands);for(let l of c){let a=sl(l,o);if(a!==null)return pe(je+a)}if(!be(t)||Ce(e))for(let l of c){let a=Mx(l);if(a!==null)return pe(ol(a,s,t,_e(n.description)))}return Bx(e,c,t,r)??Za(e,s,t,r)??Ee}function Mx(e){let t=e.argv0.toLowerCase();return V(Is,t)&&Ux(t,e)?"curl":Fx(e.raw)?"http":V(Ls,t)?"build":null}function Ux(e,t){return t.redirectsToFile?!Hx(e,t.args):!t.endsInBoundedSink}function Hx(e,t){let n=Cs[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===Qo)break;if(V(ks,s)||s===Ds&&t[r+1]===ne)return!1;(s===n.long||s.startsWith(ne)&&!s.startsWith(Qo)&&s.includes(n.short,ne.length))&&(o=!0)}return o}function Fx(e){let t=e.toLowerCase();for(let n of Ms)if(t.includes(n))return!0;for(let n=t.indexOf(Be);n>=0;n=t.indexOf(Be,n+1)){let o=t.charAt(n+Be.length);if(o!==""&&ws.includes(o)&&t.startsWith(Ps,n+Be.length+o.length))return!0}return!1}var vx="cd";function Zo(e){try{let t=hx(e);return t.isFile()?t.size:-1}catch{return-1}}function er(e,t,n,o,r,s){let i=rt(n,o);return r<=ce||Le(e.agent,n,o)?null:pe(jx(s,i)?Ha(i,r,t.toolNamePrefix):Fa(i,r))}function jx(e,t){if(typeof e=="string")return De([e],t);if(De([e.worktree],t))return!0;try{return De([e.containmentRoot],t)}catch{return!1}}function Gx(e,t,n,o){if(!$a(n.offset)&&!$a(n.limit))for(let r of rl(n)){let s=rt(e.cwd,r),i=Zo(s);if(i>ce&&!ln(e.agent,s)){let c=er(e,t,e.cwd,r,i,o);if(c!==null)return c}}return Ee}function Bx(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&mo(n))return null;let r=e.cwd,s=null;for(let i of t){let c=i.argv0.toLowerCase();if(c===vx&&i.args.length===1&&i.insideConstruct===void 0&&(r=rt(r,i.args[0])),i.redirectsToFile||i.endsInBoundedSink||i.pipesOut===!0||i.insideConstruct!==void 0||!V(Us,c))continue;let l=Kx(c,i.args);if(l===null)continue;if(l.bounded){s=Ee;continue}let a=rt(r,l.file),d=er(e,n,r,l.file,Zo(a),o);if(d!==null)return d}return s}function Za(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&mo(n))return null;for(let r of ea(t,e.cwd)){let s=er(e,n,e.cwd,r,Zo(r),o);if(s!==null)return s}return null}var un=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function Wx(e){if(V(Wn,e))return 1;for(let t of Wn)if(t.startsWith(Qo)?e.startsWith(t+Rx):e.startsWith(t))return 0;return e.startsWith(ne)&&un(e.slice(ne.length))?0:-1}function Xx(e){if(e===Jo)return"all";if(!e.endsWith(Jo))return null;let t=e.slice(0,e.length-Jo.length),n=t.indexOf(za);return(n<0?un(t):un(t.slice(0,n))&&un(t.slice(n+za.length)))?"range":null}function Kx(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(V(Hs,e)){let l=Wx(c);if(l>=0){o=!0,i+=l;continue}}if(e===Nt&&V(Fs,c)){r=!0;continue}if(e===Nt&&V(yx,c)){s=t[i+1],i++;continue}c.startsWith(ne)&&c!==ne||n.push(c)}if(e===Nt){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:Xx(s);if(i===null)return null;o=i==="range"}return e===vs&&n.shift()!==w.identity?null:n.length===1&&n[0]!==ne?{file:n[0],bounded:o}:null}import{basename as $x,dirname as dn,join as it,resolve as ll}from"node:path";var Yx=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]),qx=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],F=(e,t)=>e>>>t|e<<32-t;function cl(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=qx.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=F(i[E-15],7)^F(i[E-15],18)^i[E-15]>>>3,S=F(i[E-2],17)^F(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+(F(f,6)^F(f,11)^F(f,25))+(f&x^~f&p)+Yx[E]+i[E]>>>0,S=(F(l,2)^F(l,13)^F(l,22))+(l&a^l&d^a&d)>>>0;g=p,p=x,x=f,f=u+h>>>0,u=d,d=a,a=l,l=h+S>>>0}s[0]=s[0]+l>>>0,s[1]=s[1]+a>>>0,s[2]=s[2]+d>>>0,s[3]=s[3]+u>>>0,s[4]=s[4]+f>>>0,s[5]=s[5]+x>>>0,s[6]=s[6]+p>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:Vx,readFileSync:zx,realpathSync:al,statSync:Jx}=process.getBuiltinModule("node:fs");function Qx(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 st(e){return e===void 0||e===""?void 0:e}function Zx(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return st(t.env.CLAUDE_PROJECT_DIR)??st(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return st(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(Tt);return n<0?void 0:st(t.argv[n+1])}case"pi:ctx.cwd":return st(t.piCwd)}}function ep(e){let t;try{t=al.native(e)}catch{throw new T("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=tp(it(t,wn));if(o!==null){let s=ul(it(o,Jr));return{commonDir:al.native(s===null?o:ll(o,s)),worktree:t,start:n}}let r=dn(t);if(r===t)return{commonDir:null,start:n};t=r}}function tp(e){let t;try{if(Jx(e).isDirectory())t=e;else{let n=ul(e);if(n===null||!n.startsWith(Mn))return null;t=ll(dn(e),n.slice(Mn.length))}}catch{return null}return Vx(it(t,$r))?t:null}function ul(e){let t;try{t=zx(e,"utf8")}catch{return null}let n=t.indexOf(`
37
- `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function np(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 op(e,t){let n=$x(t)===wn?dn(t):t,o=np(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(Pn)).map(r=>r.slice(Pn.length));return Va([dn(n),...o])}function dl(e,t){let n=Qx(e),o=Zx(n,t);if(o===void 0)throw new T("NO_PROJECT",{kind:n});let r=ep(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??=cl(i).slice(0,Vr),l},get projectDir(){return a??=it(fa(process.env),Ot,this.projectKey),a},get dbPath(){return it(this.projectDir,zr)},worktree:c,get containmentRoot(){return d??=s??op(o,i),d},agent:e,source:n}}var fn=He,rp=`
8
+ `),i=pd(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 pd(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 Ri(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function _d(e){let t=e;return(t.mode==="content"||t.mode==="count")&&typeof t.content=="string"}function yi(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 Ed(e){let t=fd(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)&&Ri(e)&&(o.shape=e),typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Ri(e)&&(ao(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,yi(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 fe(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=ld.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:dd(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=Ed(r.tool_response)),i}function gd(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:ao(n);return n!==void 0&&o!==null?o.put(n,t):e.result?.blocks===!0?[{type:"text",text:t}]:t}function W(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:gd(e,t.output)}):{stdout:"",exitCode:0}}}var md={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function hd(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 Sd(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 md[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function Ni(e){Sd(e);let t=fe(e,"claude-code",co,ud);if(t.tool!==void 0&&t.tool.name===cd&&(t.tool.canonicalName=ad),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"+hd(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function Ii(e,t,n){return W(e,t,!0)}var uo="mcp__context_mode__",Od={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"},lo="Stop",Td={stdout:"",exitCode:0};function Ci(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===lo){let t=e;return{event:lo,agent:"codex",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")}}return fe(e,"codex",uo,Od)}function ki(e,t,n){return e.event===lo?Td:W(e,t,!1)}var Wt="mcp_context-mode_",Di={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},Li={startup:"startup",resume:"resume",clear:"clear"},Ad=["SessionStart","UserPromptSubmit","PostToolUse"],yd=["UserPromptSubmit","PreToolUse"],Bt={stdout:"",exitCode:0},Nd=`the tool ran and succeeded; context-mode indexed its full output, and this is the part that answers the call:
12
+ `;function A(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var wi={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function Id(e,t){if(e.startsWith(Wt))return e.slice(Wt.length);if(Object.hasOwn(wi,e))return wi[e];if(typeof t!="object"||t===null)return e;let n=t,o=A(n,"server_name"),r=A(n,"tool_name");return typeof o!="string"||typeof r!="string"?e:"mcp:"+o+":"+r}function Cd(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=A(n,"text");if(typeof o!="string")return;t.push(o)}return t.join("")}function kd(e){let t=typeof e=="object"&&e!==null?e:void 0,n=t===void 0?void 0:A(t,"llmContent"),o=e===void 0?"":typeof e=="string"?e:typeof n=="string"?n:Cd(n)??JSON.stringify(e),r=t===void 0?void 0:A(t,"error"),s={isError:r!=null,bytes:Buffer.byteLength(o),text:o};return Dd(n)&&(s.keep=!0),s}function Dd(e){return(Array.isArray(e)?e:[e]).some(n=>typeof n=="object"&&n!==null&&(Object.hasOwn(n,"inlineData")||Object.hasOwn(n,"fileData")))}var Ld=["https://","http://"],wd=`.,;:!?)]}>'"`,Pd=`
13
+ \r\f\v`;function Md(e){let t=[],n="";for(let o of e)Pd.includes(o)?(n!==""&&t.push(n),n=""):n+=o;return n!==""&&t.push(n),t}function Ud(e){if(typeof e=="string")for(let t of Md(e)){let n=t.toLowerCase(),o=Ld.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&&wd.includes(r[r.length-1]);)r=r.slice(0,-1);return r}}function Hd(e,t){if(e==="web_fetch"&&A(t,"url")===void 0){let n=Ud(A(t,"prompt"));return n===void 0?t:{...t,url:n}}if(e==="read_many_files"&&A(t,"file_path")===void 0){let n=A(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 Pi(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=A(t,"hook_event_name"),o=typeof n=="string"&&Object.hasOwn(Di,n)?Di[n]:void 0;if(o===void 0)throw new Error("gemini: unknown hook event "+String(n));let r={event:o,agent:"gemini",sessionId:String(A(t,"session_id")??""),cwd:String(A(t,"cwd")??"")},s=A(t,"source");o==="SessionStart"&&typeof s=="string"&&Object.hasOwn(Li,s)&&(r.source=Li[s]);let i=A(t,"prompt");if(o==="UserPromptSubmit"&&typeof i=="string"&&(r.prompt=i),o==="PreToolUse"||o==="PostToolUse"){let c=String(A(t,"tool_name")??""),a=A(t,"tool_input");r.tool={name:c,canonicalName:Id(c,A(t,"mcp_context")),input:Hd(c,typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{})}}return o==="PostToolUse"&&(r.result=kd(A(t,"tool_response"))),r}function Mi(e,t,n){switch(t.kind){case"allow":return Bt;case"hint":return Ad.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:Bt;case"deny":return yd.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
14
+ `+t.reason}),exitCode:0}:Bt;case"replace":return e.event!=="PostToolUse"?Bt:{stdout:JSON.stringify({decision:"deny",reason:Nd+t.output}),exitCode:0}}}var fo="mcp__context-mode__",vd={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Ui={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},jd="PostToolUseFailure";function Hi(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===jd,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=fe(n,"qwen",fo,vd);if(o.tool!==void 0&&Object.hasOwn(Ui,o.tool.name)&&(o.tool.canonicalName=Ui[o.tool.name]),t){let r=e.error,s=typeof r=="string"?r:r===void 0?"":JSON.stringify(r);o.result={isError:!0,bytes:Buffer.byteLength(s),text:s}}return o}function Fi(e,t,n){return W(e,t,!1)}var Kt="context-mode-",Bd={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}},vi={startup:"startup",resume:"resume",new:"startup"},Wd={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"}},Bi="success";function Yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var xo=Object.freeze(["bash","powershell"]),ji=Object.fromEntries(xo.map(e=>[e,"Bash"]));function Xd(e){return e.startsWith(Kt)?e.slice(Kt.length):Object.hasOwn(ji,e)?ji[e]:e}var Gi=e=>typeof e=="number"&&Number.isFinite(e);function Kd(e,t){let n=t.view_range;if(e!=="view"||!Array.isArray(n)||!Gi(n[0]))return t;let o={...t,offset:n[0]};return Gi(n[1])&&n[1]>=n[0]&&(o.limit=n[1]-n[0]+1),o}function Yd(e){if(Yt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Yt(t)?t:{}}catch{return{}}}var qd={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function zd(e,t,n){let o=qd[t],r=Yt(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==Bi,bytes:Buffer.byteLength(s),text:s}}var Vd=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function Jd(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:Vd.find(([t])=>Object.hasOwn(e,t))?.[1]}function Wi(e){if(!Yt(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=Jd(e),n=typeof t=="string"?Bd[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Wd[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"&&vi[e.source]!==void 0&&(s.source=vi[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:Xd(i),input:Kd(i,Yd(e[o.args]))};s.tool=c}return r==="PostToolUse"&&(s.result=zd(e[o.result],n.casing,n.failure)),s}var Xt={stdout:"",exitCode:0};function Xi(e,t,n){switch(t.kind){case"allow":return Xt;case"hint":return e.event==="PostToolUse"?Xt:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?Xt:{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"?Xt:{stdout:JSON.stringify({modifiedResult:{resultType:Bi,textResultForLlm:t.output}}),exitCode:0}}}var qt="mcp_context-mode_",Ji=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],Ki="mcp_",Yi="_",Qd="new",po=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),Vt=Object.freeze(["read_file","view"]),_o=Object.freeze(["fetch_webpage","web_fetch"]),qi=Object.fromEntries([...po.map(e=>[e,"Bash"]),...Vt.map(e=>[e,"Read"]),..._o.map(e=>[e,"WebFetch"])]);function $i(e){if(e.startsWith(qt))return e.slice(qt.length);if(Object.hasOwn(qi,e))return qi[e];if(!e.startsWith(Ki))return e;let t=e.slice(Ki.length),n=t.indexOf(Yi);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+Yi.length)}var Qe=e=>typeof e=="number"&&Number.isFinite(e);function Qi(e,t,n){if(t==="Read"&&Vt.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),Qe(n.startLine)&&(o.offset=n.startLine),Qe(n.startLine)&&Qe(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&Qe(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];Qe(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 Zd(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 ef={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},tf=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],zi={new:"startup",startup:"startup",resume:"resume"},nf="success";function zt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function of(e){if(zt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return zt(t)?t:{}}catch{return{}}}function rf(e){let t=zt(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==nf,bytes:Buffer.byteLength(n),text:n}}function Vi(e,t){let n=typeof t=="string"?ef[t]??Ji.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"&&zi[e.source]!==void 0&&(o.source=zi[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=$i(r);o.tool={name:r,canonicalName:s,input:Qi(r,s,of(e.toolArgs))}}return n==="PostToolUse"&&(o.result=rf(e.toolResult)),o}function Zi(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 Vi(t,t.hookEventName);if(t.hook_event_name===void 0){let r=tf.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return Vi(t,r)}let n=Ji.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===Qd&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=zt(t.tool_input)?t.tool_input:{},i=$i(r);o.tool={name:r,canonicalName:i,input:Qi(r,i,s)}}return n==="PostToolUse"&&(o.result=Zd(t.tool_response)),o}function ec(e,t,n){return W(e,t,!1)}var Jt="mcp_context_mode_",tc="mcp_context-mode_",nc={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},cf="prompt",af="USER_PROMPT",oc="mcp_",Eo=Object.freeze(["execute_bash","execute_pwsh","shell"]),rc=Object.fromEntries(Eo.map(e=>[e,"Bash"])),sc="_",ic={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function lf(e){if(e.startsWith(Jt))return e.slice(Jt.length);if(e.startsWith(tc))return e.slice(tc.length);if(Object.hasOwn(rc,e))return rc[e];if(!e.startsWith(oc))return e;let t=e.slice(oc.length),n=t.indexOf(sc);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+sc.length)}function uf(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function cc(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(nc,n)?nc[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"&&ic[t.source]!==void 0&&(r.source=ic[t.source]),o==="UserPromptSubmit"){let s=t[cf],i=typeof s=="string"?s:process.env[af];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:lf(s),input:i}}return o==="PostToolUse"&&(r.result=uf(t.tool_response)),r}function ac(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 go="mcp__context-mode__",lc="mcp__plugin_context-mode_context-mode__",ff={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},xf={hook_event_name:"hookEventName",session_id:"sessionId"},pf="PostToolUseFailure";function uc(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(xf))t[i]===void 0&&(t[i]=t[c]);let n=t.hook_event_name===pf;n&&(t.hook_event_name="PostToolUse");let r=(typeof t.tool_name=="string"?t.tool_name:"").startsWith(lc)?lc:go,s=fe(t,"zcode",r,ff);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 dc(e,t,n){return W(e,t,!1)}var pc="",fc={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},xc={bash:"Bash",read:"Read",edit:"Edit",write:"Write"};function Ef(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function gf(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),e.keep===!0&&(n.keep=!0),n}function _c(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(fc,n)?fc[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(xc,s)?xc[s]:s,input:Ef(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=gf(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function mf(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 Ec(e,t,n){let o=mf(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:hi,content:o.stdout,timestamp:Date.now()}}function gc(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var bc="",mc=Z+"_",hc={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},mo="bash",ho="read",Sf=Object.freeze([mo,"shell"]),Sc={webfetch:"WebFetch",[ho]:"Read",...Object.fromEntries(Sf.map(e=>[e,"Bash"]))};function So(e){return e.startsWith(mc)?e.slice(mc.length):Object.prototype.hasOwnProperty.call(Sc,e)?Sc[e]:e}function bf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Of(e){let t=e.output===void 0?"":typeof e.output=="string"?e.output:JSON.stringify(e.output),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function Oc(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(hc,n)?hc[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(typeof t.agentID=="string"&&t.agentID!==""&&(r.agentId=t.agentID,r.agentType=t.agentID),Array.isArray(t.agentTools)&&(r.agentTools=t.agentTools.filter(s=>typeof s=="string")),o==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool??"");r.tool={name:s,canonicalName:So(s),input:bf(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=Of(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Tc(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:e.event==="PostToolUse"?t.output:"",exitCode:0}}}var Ze={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},Rc={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},Rf={...Rc,shell:[...Ai]},Af=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:co,nativeTools:Rf,execReadOnlyHint:!1,eventMap:Ze,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"skills"},decode:Ni,encode:Ii},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:uo,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:Ze,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:Ci,encode:ki},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Wt,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:G,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:Pi,encode:Mi},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:fo,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:Ze,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:Hi,encode:Fi},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:Kt,nativeTools:{shell:[...xo]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:Wi,encode:Xi},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:qt,nativeTools:{shell:[...po],read:[...Vt],webfetch:[..._o]},execReadOnlyHint:!1,eventMap:{...Ze,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:Zi,encode:ec},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:Jt,nativeTools:{shell:[...Eo]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:G,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:cc,encode:ac},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:go,nativeTools:Rc,execReadOnlyHint:!1,eventMap:Ze,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:G,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:uc,encode:dc},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:pc,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:Hn,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:_c,encode:Ec,checkPermission:gc},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:bc,nativeTools:{shell:[mo],read:[ho]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:Hn,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:Oc,encode:Tc,toCanonicalTool:So}]),yf=new Map(Af.map(e=>[e.id,e])),Nf=new Set(["claude-code","gemini","copilot-cli","pi","opencode"]);function Ae(e){return Nf.has(e.id)}var If=new Set(["claude-code","copilot-cli","pi"]);function bo(e){return If.has(e.id)&&Ae(e)}var Cf=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function $t(e){return Cf.has(e.id)}function te(e){return yf.get(e)}import{resolve as dt}from"node:path";var kf=["&&","||",";;","|&",";","|","&","(",")"],Df=["&>>","&>"],Lf=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],wf="&",Pf="<<",Ac="<<-",Mf=";",yc=`\r
19
+ `,Nc=`\\
20
+ `,Ic=`\\\r
21
+ `,Uf="$(",Dc="${",Lc="$'",et="((",Cc="))",ye="[[",Qt="]]",Oo="<(",wc=">(",M=2,Pc=`
22
+ \r;&|()<>`,Hf=`
23
+ \r`,Ff='$`"\\\n',vf="case",jf="esac";function Ne(e,t){e.end==="complete"&&(e.end=t)}function To(e){return e!==""&&e>="0"&&e<="9"}function kc(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function Mc(e){return e===""||Pc.includes(e)}function Ro(e){return e!==""&&Hf.includes(e)}function X(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function Zt(e,t){let n=e.s.indexOf("'",t+1);return n<0?(Ne(e,"unterminated-quote"),e.n):n+1}function Uc(e,t){let n=t+Lc.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=M;continue}if(o==="'")return n+1;n++}return Ne(e,"unterminated-quote"),e.n}function Ao(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+=M;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=tt(e,o,n);continue}if(r==="$"&&s==="{"){o=yo(e,o,n);continue}if(r==="`"){o=Ie(e,o);continue}o++}return Ne(e,"unterminated-quote"),e.n}function Ie(e,t){let n=t+1;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=M;continue}if(o==="`")return n+1;n++}return e.n}function yo(e,t,n){let o=t+Dc.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=M;continue}if(s==="'"){o=Zt(e,o);continue}if(s==='"'){o=Ao(e,o,n);continue}if(s==="$"&&i==="("){o=tt(e,o,n);continue}if(s==="`"){o=Ie(e,o);continue}if(s==="{"&&r++,s==="}"){if(r===0)return o+1;r--}o++}return e.n}function No(e,t){let n=0,o=t+et.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(Cc,o)?o+Cc.length:-1;n--}o++}return-1}function tt(e,t,n){let o=t+Uf.length-1;if(e.s.startsWith(et,o)){let r=No(e.s,o);if(r>0)return r}return en(e,o+1,!0,n+1,null,null)}function Gf(e,t,n){let o=t+ye.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=M;continue}if(s==="'"){o=Zt(e,o);continue}if(s==='"'){o=Ao(e,o,n);continue}if(s==="$"&&i==="("){o=tt(e,o,n);continue}if(s==="$"&&i==="{"){o=yo(e,o,n);continue}if(s==="`"){o=Ie(e,o);continue}let c=Ro(e.s.charAt(o-1));if(c&&e.s.startsWith(Qt,o)&&Mc(e.s.charAt(o+Qt.length))){if(r===0)return o+Qt.length;r--,o+=Qt.length;continue}if(c&&e.s.startsWith(ye,o)&&Ro(e.s.charAt(o+ye.length))){r++,o+=ye.length;continue}o++}return-1}function Bf(e,t){let n=t;for(;To(e.charAt(n));)n++;if(n===t){for(let o of Df)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of Lf){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(wf))if(e.charAt(r)==="-")r++;else for(;To(e.charAt(r));)r++;return{end:r,op:o}}return null}function Wf(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(Pc.includes(r))break;if(r==="\\"){o+=M;continue}if(r==="'"){o=Zt(e,o);continue}if(r==='"'){o=Ao(e,o,n);continue}if(r==="$"&&s==="'"){o=Uc(e,o);continue}if(r==="$"&&s==="("){o=tt(e,o,n);continue}if(r==="$"&&s==="{"){o=yo(e,o,n);continue}if(r==="`"){o=Ie(e,o);continue}o++}return Math.min(o,e.n)}function Xf(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(`
24
+ `,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),X(o,"unhandled",e.s.slice(c,s),c,s),!a)return Ne(e,"unterminated-heredoc"),e.n}return n.length=0,s}function en(e,t,n,o,r,s){if(o>B)return Ne(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(Nc,c)){c+=Nc.length;continue}if(i.startsWith(Ic,c)){c+=Ic.length;continue}if(f===`
25
+ `||f==="\r"){let S=c;c+=i.startsWith(yc,c)?yc.length:1,X(r,"op",Mf,S,c),u=null,d.length>0&&(c=Xf(e,c,d,r,s));continue}if(f==="#"){for(;c<e.n&&i.charAt(c)!==`
26
+ `&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(Oo,c)||i.startsWith(wc,c)){let S=en(e,c+Oo.length,!0,o+1,null,null);X(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}let p=Bf(i,c);if(p!==null){X(r,"io",i.slice(c,p.end),c,p.end),u=p.op===Pf||p.op===Ac?p.op===Ac:null,c=p.end;continue}if(i.startsWith(ye,c)&&Ro(i.charAt(c+ye.length))){let S=Gf(e,c,o);if(S>0){X(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}if(i.startsWith(et,c)){let S=No(i,c);if(S>0){X(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let g=kf.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}X(r,"op",g,c,c+g.length),c+=g.length,u=null;continue}if(f==="$"&&x==="("||f==="`"){let S=f==="`"?Ie(e,c):tt(e,c,o);if(Mc(i.charAt(S))){X(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let E=c;c=Wf(e,c,o);let h=i.slice(E,c);X(r,"word",h,E,c),u!==null&&(d.push({tag:Ce(h),strip:u}),u=null),n&&h===vf&&l++,n&&h===jf&&l>0&&l--}return d.length>0&&Ne(e,"unterminated-heredoc"),e.n}function Hc(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return en(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function Ce(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=M;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+Lc.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=M;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!==""&&Ff.includes(i)){t+=i,s+=M;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function tn(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+=M;continue}if(!o&&s==="'"){r=Zt(t,r);continue}if(!o&&s==="$"&&i==="'"){r=Uc(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Dc.length;continue}let c=e.startsWith(Oo,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(wc,r))){let a=r+1;if(s==="$"&&e.startsWith(et,a)&&No(e,a)>0){r=a+et.length;continue}let l=en(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=Ie(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 nn(e){let t=e.charAt(0);if(!(kc(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(!(kc(o)||To(o)||o==="_"))return!1}return!1}var Gc=[";","&","&&","||"],Bc=["|","|&"],nt="(",ot=")",Wc=";;",ko=["(",")"],Kf="!";function U(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"}),Xc=[],Yf="[[",qf="((",Kc=[">",">>",">|","&>","&>>",">&"],zf=[...Kc,"<","<>","<<<","<<","<<-"],Vf=["","1"],Yc=["-","/dev/stdout","/dev/stderr"],rn="-",rt="--",st="=",Jf="/",$f=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),on=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),Io="-c",Co="--bytes",Qf="c",Zf="--count",xe=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],ne=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,D=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,Do=e=>e!==""&&e>="0"&&e<="9",e0=e=>Do(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function Lo(e){let t=e.lastIndexOf(Jf);return t>=0&&t<e.length-1?e.slice(t+1):e}function wo(e,t){let n=$f[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===rt)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+st))s=r.slice(n.long.length+st.length);else if(r.startsWith(rn)&&!r.startsWith(rt)){let i=r.indexOf(n.short,rn.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&&!Yc.includes(s))return!0}return!1}function t0(e){if(e==="")return!1;for(let t of e)if(!Do(t))return!1;return!0}function n0(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===Io||n===Co?o=e[t+1]:n.startsWith(Co+st)?o=n.slice(Co.length+st.length):n.startsWith(Io)&&!n.startsWith(rt)&&(o=n.slice(Io.length)),o!==void 0)return t0(o)&&Number(o)<=le}return!1}function o0(e){for(let t of e){if(t===rt)return!1;if(t===Zf||t.startsWith(rn)&&!t.startsWith(rt)&&t.includes(Qf))return!0}return!1}function Fc(e){if(!e.startsWith(w.fieldSep))return!1;for(let t of e.slice(w.fieldSep.length).split(w.fieldSep)){if(t==="")return!1;for(let n of t)if(!e0(n))return!1}return!0}function r0(e){let t=e.trim();if(t===w.identity||t===w.length)return!0;let n=t.indexOf(w.pipeLength.charAt(0));if(n<0)return Fc(t);let o=t.slice(0,n).trim(),r=w.pipeLength.slice(1).trim();return(o===w.identity||Fc(o))&&t.slice(n+1).trim()===r}function s0(e){let t=e.argv0.toLowerCase();if(t===on.wc)return!0;if(t===on.head)return n0(e.args);if(t===on.grep)return o0(e.args);if(t===on.jq){let n=e.args.filter(o=>!o.startsWith(rn));return n.length===1&&r0(n[0])}return!1}function Po(e){return tn(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function qc(e,t,n){return n<=t?[]:Po(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function zc(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function i0(e){let t=0;for(;Do(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Vc(e){let t=i0(e.toks[e.i].text);if(e.i++,!zf.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,Kc.includes(t.op)&&Vf.includes(t.fd)&&!Yc.includes(Ce(n.text)))}function Jc(e){let t=!1;for(;O(e)?.kind==="io";)t=Vc(e)||t;return t}function $c(e){for(;O(e)?.kind==="op"&&Gc.includes(O(e)?.text??"");)e.i++}function ke(e,t){if(e.depth++,e.depth>B)return e.err="nesting-too-deep",xe();let n=t();if(e.depth--,Jc(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function Qc(e){if($c(e),!D(O(e),b.do))return[];e.i++;let t=K(e,[b.done]);return D(O(e),b.done)&&e.i++,t}function c0(e){e.i++;let t=K(e,[b.then]);for(;e.err===null;){let n=O(e);if(D(n,b.then)||D(n,b.else)){e.i++,U(t,K(e,[b.elif,b.else,b.fi]));continue}if(D(n,b.elif)){e.i++,U(t,K(e,[b.then]));continue}D(n,b.fi)&&e.i++;break}return t}function a0(e){e.i++;let t=K(e,[b.do]);return U(t,Qc(e)),t}function l0(e){e.i++;let t=[],n=O(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,D(O(e),b.in)){e.i++;let o=e.i;for(;(O(e)?.kind==="word"||O(e)?.kind==="unhandled")&&!D(O(e),b.do);)e.i++;U(t,qc(e,o,e.i))}return U(t,Qc(e)),t}function u0(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,U(t,qc(e,e.i-1,e.i))),D(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"&&(Gc.includes(o.text)||o.text===Wc)){e.i++;continue}if(D(o,b.esac)){e.i++;break}for(ne(o,nt)&&e.i++;e.i<e.toks.length&&!ne(O(e),ot);){let s=e.toks[e.i];if(s.kind==="op"&&!Bc.includes(s.text))break;e.i++}if(!ne(O(e),ot))break;e.i++;let r=K(e,[b.esac]);zc(r,b.case),U(t,r)}return t}function vc(e,t){$c(e);let n=Zc(e);return zc(n.cmds,t),{cmds:n.cmds,simple:null}}function jc(e,t){return ko.every((n,o)=>ne(e.toks[t+o],n))}function d0(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=Vc(e)||o;continue}if(n.length===0&&l.kind==="word"&&nn(l.text)){e.i++;let u=O(e);if(l.text.endsWith(st)&&u!==void 0&&ne(u,nt)&&u.start===l.end){let d=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,ne(f,nt)&&d++,ne(f,ot)&&--d===0)break}}continue}n.push(l),e.i++}if(e.i===t)return xe();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:Po(r),simple:null};let s=l=>l.kind==="word"?Ce(l.text):l.text,i=Lo(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||wo(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function Zc(e){let t=O(e);if(t===void 0)return xe();if(t.kind==="op")return t.text!==nt?xe():ke(e,()=>{e.i++;let n=K(e,Xc);return ne(O(e),ot)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(Yf)||t.text.startsWith(qf)))return e.i++,Jc(e),{cmds:Po(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return ke(e,()=>{e.i++;let n=K(e,[b.groupEnd]);return D(O(e),b.groupEnd)&&e.i++,n});case b.if:return ke(e,()=>c0(e));case b.while:case b.until:return ke(e,()=>a0(e));case b.for:return ke(e,()=>l0(e));case b.case:return ke(e,()=>u0(e));case b.coproc:return e.err="coproc",xe();case b.select:return e.err="select",xe();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=Ce(n.text),e.i++),jc(e,e.i)&&(e.i+=ko.length),vc(e,o)}default:if(jc(e,e.i+1))return e.i+=ko.length+1,vc(e,Ce(t.text))}return d0(e)}function f0(e){D(O(e),Kf)&&e.i++;let t=[],n=xe();for(;e.err===null;){n=Zc(e),U(t,n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&Bc.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&s0(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function K(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===ot||o.text===Wc)return n;if(o.text!==nt){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;U(n,f0(e)),e.i===r&&e.err===null&&e.i++}return n}function De(e){let t=Hc(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;)U(o,K(n,Xc)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as ea}from"node:path";var cn="'",Le='"',an="`",x0=" \r",ct="([{",Fo=")]}",Mo=` \r
27
+ |;>`,oa="*",ta="1",Uo="::",sn=Uo.length,p0=sn;function ln(e,t){let n=e.charAt(t);for(let o=t+1;o<e.length;o++){let r=e.charAt(o);if(n===Le&&r===an){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function _0(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===Le&&r===an&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function it(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===cn||r===Le){let s=ln(e,o);if(s<0)return-1;o=s;continue}if(r===an){o++;continue}if(ct.includes(r))n++;else if(Fo.includes(r)&&--n===0)return o}return-1}function E0(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===cn||r===Le){let s=ln(e,o);if(s<0)return e.length;o=s;continue}if(ct.includes(r))n++;else if(Fo.includes(r))n--;else if(n<=0&&Mo.includes(r))return o}return e.length}function g0(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===cn||s===Le){let i=ln(e,r);if(i<0)break;r=i;continue}ct.includes(s)?n++:Fo.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var m0=e=>e!==""&&(e===oa||[...e].every(t=>t>="0"&&t<="9")),na=()=>({words:[],toFile:!1,chained:!1});function ra(e){let t=[],n=[],o=na(),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=na()},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===cn||p===Le){let E=ln(e,x);f(_0(e.slice(x+1,E<0?a:E),p),!0),x=E<0?a:E+1}else if(p===an)g!==`
28
+ `&&g!==""&&f(g,!1),x+=sn;else if(p===`
29
+ `)d(),x++;else if(x0.includes(p))l(),x++;else if(p===";")d(),x++;else if(p==="|")g==="|"?(d(),x+=sn):(u(),x++);else if(p==="&")g==="&"?(d(),x+=sn):((s||o.words.length>0)&&f(p,!1),x++);else if(p==="#"&&!s)for(;x<a&&e.charAt(x)!==`
30
+ `;)x++;else if(p===">"){let E=ta;s&&i&&m0(r)?(E=r,r="",s=!1):s&&l();let h=x+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<a&&!Mo.includes(e.charAt(h));)h++;else c=E===ta||E===oa?"file":"skip";x=h}else if(p==="("&&s&&i&&r.includes(Uo)){let E=it(e,x),h=e.slice(x+1,E<0?a:E);l();for(let S of h.trim()===""?[]:g0(h)){let _=ra(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}x=E<0?a:E+1,x<a&&!Mo.includes(e.charAt(x))&&(o.chained=!0,x=E0(e,x))}else if(p==="["&&!s&&e.startsWith(Uo,it(e,x)+1)&&it(e,x)>=0){let E=it(e,x);f(e.slice(x,E+1),!1),x=E+1}else if(ct.includes(p)&&(p!=="["||!s)||(p==="$"||p==="@")&&ct.includes(g)&&g!=="["){let E=p==="$"||p==="@"?x+1:x,h=it(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 h0=["get-content","gc","cat","type"],S0=["[io.file]::","[system.io.file]::"],b0=["readalltext","readalllines","readallbytes","readlines"],vo=["path","literalpath"],sa=["totalcount","head","first","tail","last"],ia=[...vo,...sa,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],O0=["raw","wait","force","asbytestream"],T0=[...ia,...O0],R0=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],A0=["cd","chdir","sl","set-location","pushd","push-location"],y0=["powershell","powershell.exe","pwsh","pwsh.exe"],N0=["cmd","cmd.exe"],I0=["/c","/k","/r"],C0="command",pe="-";function Ho(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function jo(e,t){let n=e.slice(pe.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 k0(e){if(e.length===0)return null;let t=Ho(e[0]);if(!h0.includes(t)){let r=e[0].toLowerCase(),s=S0.find(i=>r.startsWith(i));return s===void 0||!b0.includes(r.slice(s.length))||e.length<p0?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(pe)||s.length===pe.length){n.push(s);continue}let i=jo(s,T0);if(i.full===void 0||!ia.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;vo.includes(i.full)&&n.push(c),sa.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function D0(e,t){if(y0.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(pe)||o.length===pe.length)continue;let r=jo(o,[C0]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(N0.includes(e)){for(let n=1;n<t.length;n++)if(I0.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function L0(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(pe)||n.length===pe.length)return n;let o=jo(n,vo);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function ca(e,t,n,o){let r=t;for(let s of ra(e)){let i=s[0];if(i.words.length===0)continue;let c=Ho(i.words[0]);if(s.length===1&&A0.includes(c)){let d=L0(i.words);d!==null&&(r=ea(r,d));continue}let a=n<B?D0(c,i.words):null;if(a!==null){ca(a,r,n+1,o);continue}if(i.toFile||i.chained)continue;let l=k0(i.words);if(l===null||l.bounded)continue;let u=!0;for(let d=1;d<s.length;d++)if(s[d].toFile||!R0.includes(Ho(s[d].words[0]??""))){u=!1;break}u&&o.push(ea(r,l.file))}}function aa(e,t){let n=[];return ca(e,t,0,n),n}import{join as we}from"node:path";var la=`\r
31
+ `,w0=`
32
+ `;function un(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(la)<0?t:t.split(la).join(w0)}import{basename as H0,dirname as F0,join as Y,posix as da,resolve as v0,win32 as fa}from"node:path";var P0=Object.freeze({NODE_TOO_OLD:"Context Mode needs Node 24.15.0 or newer; you have <v>. Fix: nvm install 24, or install it from https://nodejs.org.",NO_SQLITE:"node:sqlite failed to load. Fix: run ctx_doctor.",DB_GONE:"context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",NO_PROJECT:"Project source <kind> is missing. Fix: run ctx_doctor.",UNKNOWN_FIELD:'Unknown field "<f>". Fix: use "queries".',TIMEOUT:"Timed out after <ms> ms. Fix: pass background: true.",NO_GIT_BASH:"Git Bash not found. Fix: install Git for Windows.",NO_RUNTIME:"No <lang> runtime on PATH. Fix: install it or pick another language.",FETCH_FAILED:"Fetch failed: <code>. Fix: check the URL or proxy.",SSRF:"Blocked private address <host>. Fix: use a public URL.",OUTSIDE_ROOT:"Path <p> is outside the project. Fix: use a path inside <root>.",INVALID_ARGS:"Invalid argument <field>. Fix: <action>.",ONE_OF_INPUT:"Pass exactly one of <names>. Fix: drop the extra field.",SPAWN_FAILED:"Failed to start the process: <detail>. Fix: check the command and PATH.",DB_CORRUPT:"context.db failed integrity_check. Fix: run ctx_doctor.",SCHEMA_STALE:"context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.",NO_GIT_DIR:"No git repository at <path>. Fix: run context-mode inside a git repository.",NO_HOME:"Env var <name> is not set. Fix: set <name> to your home directory.",PLUGIN_ROOT_MISSING:"Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.",BUNDLE_HASH_MISMATCH:"Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.",CONFIG_PARSE_FAILED:"<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade."});function M0(e,t){let n=P0[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 R=class extends Error{code;vars;constructor(t,n){super(M0(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{existsSync:Em,mkdirSync:U0,readFileSync:gm,readdirSync:mm,realpathSync:ua}=process.getBuiltinModule("node:fs");function H(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 xa(e,t){let n=e[xi];return n!==void 0&&n!==""?n:Y(t,...k.codex)}function pa(e,t){let n=e[pi];return n!==void 0&&n!==""?n:Y(t,...k["copilot-cli"])}function _a(e,t){let n=e[_i];return Y(n!==void 0&&n!==""?n:t,...k.gemini)}function Ea(e,t,n=process.platform){let o=n==="win32"?fa:da,r=o.join(t,...k.kiro),s=e[Ei]?.trim();if(s===void 0||s===""||!o.isAbsolute(s)||n==="win32"&&o.parse(s).root.length<2)return r;let i=o.resolve(s),c=n===process.platform?j0:u=>u,a=c(i);if(o.parse(a).root===a)return r;let l=o.relative(a,c(o.resolve(t)));return!o.isAbsolute(l)&&l.split(o.sep)[0]!==".."?r:i}function j0(e){let t=[];for(let n=e;;)try{return Y(ua.native(n),...t.reverse())}catch{let o=F0(n);if(o===n)return e;t.push(H0(n)),n=o}}function q(e,t){let n=e[vt];return n!==void 0&&n!==""?n:Y(t,...k["claude-code"])}function ga(e,t){let n=e[gi];if(n!==void 0&&n!=="")return n;let o=e[Gt];return o!==void 0&&o!==""?Y(o,k.opencode[k.opencode.length-1]):Y(t,...k.opencode)}function ma(e,t){let n=e[Si];return n!==void 0&&n!==""?n:Y(t,...k.pi,mi)}function ha(e,t,n=process.platform){let o=s=>s!==void 0&&s!=="",r=n==="win32"?fa:da;return n==="win32"?r.join(o(e[io])?e[io]:r.join(t,"AppData","Roaming"),...jt):n==="darwin"?r.join(t,"Library","Application Support",...jt):r.join(o(e[Gt])?e[Gt]:r.join(t,".config"),...jt)}function G0(e,t=process.platform){let n=H(e,t);if(n!==null)return n;throw new R("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function dn(e,t){let n=e[Xe];return n!==void 0&&n!==""?v0(n):Y(t,cs.slice(1))}function Sa(e){let t=e[Xe],n=dn(e,t!==void 0&&t!==""?"":G0(e));return U0(n,{recursive:!0}),ua.native(n)}var{readFileSync:ya,readdirSync:B0}=process.getBuiltinModule("node:fs"),ba=Object.freeze(["Agent","Artifact","ArtifactComments","ArtifactData","ArtifactCheck","ExitPlanMode","Edit","Write","NotebookEdit"]),Oa=Object.freeze({"general-purpose":{tools:null,disallowed:[]},fork:{tools:null,disallowed:[]},Explore:{tools:null,disallowed:[...ba]},Plan:{tools:null,disallowed:[...ba]}}),W0="claude-code";function Pe(e){return e.agentId!==void 0&&e.agentId!==""}function Bo(e,t){if(t===null)return"C";let n=te(e.agent),o=new Set(t);for(let r of Tt)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function Wo(e,t){if(!Pe(e))return null;let n=te(e.agent);if(t.manifestTools!==void 0)return Aa(t.manifestTools.map(c=>Go(n,c)));let o=e.agentType??"",r=X0(o,t)??K0(e.agent,o);if(r===null)return null;let s=(r.tools??Q0(n)).map(c=>Go(n,c)),i=r.disallowed.map(c=>Go(n,c));return Aa(s.filter(c=>!i.some(a=>ex(a,c))))}function X0(e,t){if(!Y0(e))return null;let n=q0(t.env);if(e.indexOf(Oe)>=0){if(n!==null){let s=z0(q(t.env,n),e);if(s!==null)return s}}else{let s=fn(we(t.projectDir,ls,Ke,e+de));if(s!==null)return s;if(n!==null){let i=fn(we(q(t.env,n),Ke,e+de));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 K0(e,t){if(e!==W0||!Object.prototype.hasOwnProperty.call(Oa,t))return null;let n=Oa[t];return{tools:n.tools,disallowed:[...n.disallowed]}}function Y0(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(Oe))if(t===""||t==="."||t==="..")return!1;return!0}function q0(e){return H(e)}function z0(e,t){let n=t.indexOf(Oe),o=t.slice(0,n),r=t.slice(n+Oe.length);return r.indexOf(Oe)>=0?null:V0(e,o,r)??J0(e,o,r)}function V0(e,t,n){let o;try{o=JSON.parse(un(ya(we(e,Ct,ds),"utf8")))}catch{return null}let r=o?.plugins;if(r===null||typeof r!="object")return null;for(let s of Object.keys(r)){let i=s.indexOf(fs);if((i<0?s:s.slice(0,i))!==t)continue;let c=r[s];if(Array.isArray(c))for(let a of c){let l=a?.installPath;if(typeof l!="string"||l==="")continue;let u=fn(we(l,Ke,n+de));if(u!==null)return u}}return null}function J0(e,t,n){let o=we(e,Ct,us),r;try{r=B0(o).sort()}catch{return null}for(let s of r){if(s.startsWith("."))continue;let i=fn(we(o,s,t,Ke,n+de));if(i!==null)return i}return null}function fn(e){let t;try{t=ya(e,"utf8")}catch{return null}return $0(t)}function $0(e){let t=e.split(`
33
+ `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Gn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Gn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=Ta(o,xs),s=Ta(o,ps);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function Ta(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(Ra(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>Ra(s.trim())).filter(s=>s!=="")}return null}function Ra(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function Q0(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...Tt.map(n=>e.toolNamePrefix+n)]}function Go(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(_s)?Z0(o):o}function Z0(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||Es.indexOf(n)>=0;t+=o?n:"_"}return t}function ex(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(Wn)<0)return t.startsWith(e+Wn)}return!1}function Aa(e){return[...new Set(e.filter(t=>t!==""))]}var _e="",Na=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:_e},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:_e},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:_e},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:_e},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:_e},command:{valueShorts:_e,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:_e}}),tx=["bash","sh","zsh"],nx="c",ox=" -c",rx=["-o","+o","-O","+O"],xn="-",sx="+",Xo="--",ix="smhd",cx=".",Ia=e=>e!==""&&e>="0"&&e<="9";function ax(e){if(e===""||!Ia(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(Ia(n)||n===cx))return t===e.length-1&&ix.includes(n)}return!0}function lx(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===Xo){n++;break}if(e.assignments&&nn(o)){n++;continue}if(o.startsWith(Xo)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(xn)&&o.length>xn.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=xn.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||!ax(t[n]))return null;n++}return n<t.length?t.slice(n):null}function ux(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(Xo)){if(o.startsWith(xn)||o.startsWith(sx)){o.includes(nx)&&(t=!0),rx.includes(o)&&n++;continue}return t?o:null}}return null}function Ca(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function Ko(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let a=s.toLowerCase();if(tx.includes(a)){let d=ux(i),f=d!==null&&n<B?De(d):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=Ca(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,Ko(p,[...r,a+ox],n+1,o)}return}let l=Object.hasOwn(Na,a)?Na[a]:void 0,u=l===void 0?null:lx(l,i);if(u===null)break;r.push(a),s=Lo(u[0]),i=u.slice(1),c=c||wo(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=B))for(let a of tn(e.raw)){let l=De(a.body);if(l.ok)for(let u of l.commands)Ko(Ca(u,e),[...t,a.wrapper],n+1,o)}}function Yo(e){let t=[];for(let n of e)Ko(n,[],0,t);return t}import{isAbsolute as fx,join as qo,relative as xx,sep as zo}from"node:path";var{readFileSync:dx}=process.getBuiltinModule("node:fs"),ka=".claude",px="settings.local.json",Da="settings.json",Fa="Bash",_x="Read",La=":*",wa="//",Pa="~/",Ma="./",Ua="..",Ex=`
34
+ \r`,gx=Object.freeze({tool:Fa});function mx(e,t){if(t!=="claude-code")return[];let n=H(process.env),o=process.env[vt],r=o!==void 0&&o!==""?o:n===null?null:q(process.env,n),s=[qo(e,ka,px),qo(e,ka,Da)];return r===null?s:[...s,qo(r,Da)]}function Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hx(e){let t;try{t=un(dx(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Ha(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Ha(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 va(e,t){let n=[];for(let o of mx(e,t)){let r=hx(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function Vo(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 Jo(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 a=e[c];s===o&&(s=Uint8Array.from(o));let l=0;for(let d=r;d>=0;d--){let f=d<r,x=f?t[d]:"";switch(a.t){case"lit":i[d]=f&&x===a.c?s[d+1]:0;break;case"any1":i[d]=f&&!(n&&x==="/")?s[d+1]:0;break;case"star":i[d]=s[d]||(f&&!(n&&x==="/")?i[d+1]:0);break;case"globstar":i[d]=s[d]||(f?i[d+1]:0);break;case"globstarDir":f&&x==="/"&&s[d+1]&&(l=1),i[d]=s[d]||l;break}}let u=i;i=s,s=u}return s}function at(e,t,n){let o=Vo(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,Jo(o,t,n,s)[0]===1}function ja(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 Ga(e,t){let n=t.length,o=new Uint8Array(n+1);if(o[n]=1,!e.endsWith(La))return Jo(Vo(e,!1),t,!1,o);for(let r=0;r<n;r++)Ex.includes(t[r])&&(o[r]=1);return Jo(Vo(e.slice(0,e.length-La.length),!1),t,!1,o)}function Sx(e,t){return Ga(e,t)[0]===1}function Ba(e,t,n){for(let o of t){let r=ja(o);if(r===null||r.tool!==Fa)continue;let s=Ga(r.glob,e);for(let i=0;i<=e.length;i++)if(n[i]===1&&s[i]===1)return o}return null}var bx=/^[A-Za-z]:(?=\/)/;function lt(e){return zo==="/"?e:e.split(zo).join("/")}function Ox(e,t,n){if(e.startsWith(Ma)){if(n===void 0)return!1;let r=xx(n,t);return r===""||r===Ua||r.startsWith(Ua+zo)||fx(r)?!1:at(e.slice(Ma.length),lt(r),!0)}let o=lt(t);if(e.startsWith(wa)){let r=lt(e.slice(wa.length-1));return at(r,o,!0)||at(r,o.replace(bx,""),!0)}if(e.startsWith(Pa)){let r=H(process.env);return r!==null&&at(lt(r)+e.slice(Pa.length-1),o,!0)}return at(lt(e),o,!0)}function Me(e,t,n=gx){for(let o of t){let r=ja(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===_x?Ox(r.glob,e,n.projectDir):Sx(r.glob,e))return o}return null}var Fm=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),Wa='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.',Xa=`context-mode: {size}-byte file, over the one-read limit. Read "{path}" in parts with offset and limit, or sed -n '1,200p'.`;var Ka="{size}",Ya="{path}";function qa(e,t,n=""){return L(Wa,n).split(Ka).join(String(t)).split(Ya).join(e)}function za(e,t){return Xa.split(Ka).join(String(t)).split(Ya).join(e)}import{extname as yx,join as $o,resolve as Nx}from"node:path";import{dirname as Va,isAbsolute as Qa,join as Km,relative as Ym,resolve as Za,sep as el}from"node:path";var{lstatSync:Wm,realpathSync:Tx}=process.getBuiltinModule("node:fs");function ut(e){try{return Tx.native(e)}catch{return}}function I(e){return e.split(el).filter(t=>t!=="")}function tl(e,t){let n=ut(e),o=ut(t);if(n===void 0||o===void 0)return!1;let r=I(n),s=I(o);if(s.length<r.length)return!1;for(let i=0;i<r.length;i+=1)if(r[i]!==s[i])return!1;return!0}var Ja=new Map;function Rx(e){let t=Ja.get(e);if(t!==void 0)return t;let n=ut(e);return n!==void 0&&Ja.set(e,n),n}function Ue(e,t){if(e.length===0)return!1;let n=ut(t);if(n===void 0)return!1;let o=I(n);return e.some(r=>{let s=Rx(r);if(s===void 0)return!1;let i=I(s);return o.length>=i.length&&i.every((c,a)=>c===o[a])})}function nl(e,t){return(Qa(t)?I(t):[...I(e),...I(t)]).includes("..")}var $a=new Map;function Ax(e){let t=$a.get(e);return t===void 0&&(t=I(Za(e)),$a.set(e,t)),t}function ol(e,t){if(e.length===0)return!1;let n=I(t);if(n.includes(".."))return!1;let o=el==="/"&&Qa(t)?n.filter(r=>r!=="."):I(Za(t));return e.some(r=>{let s=Ax(r);return o.length>=s.length&&s.every((i,c)=>i===o[c])})}function rl(e){let t=e.map(ut).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=I(n).length;for(let s of t){let i=I(s),c=I(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;I(r).length>o&&Va(r)!==r;)r=Va(r);return r}function Ix(e,t){let n=H(t);if(n===null)return[];let o=$o(n,...gs);return[...e==="claude-code"?[q(t,n)]:e==="codex"?[xa(t,n)]:e==="gemini"?[_a(t,n)]:e==="copilot-cli"?[pa(t,n)]:e==="kiro"?[Ea(t,n)]:e==="opencode"?[ga(t,n)]:e==="pi"?[ma(t,n)]:e==="vscode"?[$o(n,...k.vscode),ha(t,n)]:[$o(n,...k[e])],o]}function He(e,t,n,o=process.env){if(yx(n).toLowerCase()!==de)return!1;let r=Ix(e,o),s=Nx(t,n);return!nl(t,n)&&ol(r,s)||Ue(r,s)}import{extname as Lx}from"node:path";var{closeSync:Cx,openSync:kx,readSync:Dx}=process.getBuiltinModule("node:fs");function wx(e){let t=null;try{t=kx(e,"r");let n=Buffer.alloc(Vn),o=Dx(t,n,0,Vn,0);return n.subarray(0,o)}catch{return null}finally{t!==null&&Cx(t)}}function pn(e,t){let n=zs[e]??[];if(n.length===0)return!1;let o=Lx(t).toLowerCase(),r=n.filter(i=>zn[i].exts.includes(o));if(r.length===0)return!1;let s=wx(t);return s===null?!1:r.some(i=>zn[i].sig.every(c=>c.bytes.every((a,l)=>s[c.at+l]===a)))}var{statSync:Px}=process.getBuiltinModule("node:fs"),ul="Bash",Zo="Read",Mx="WebFetch",Ux="ctx_execute",Hx="ctx_batch",dl="shell",Fx="1",oe="-",er="--",vx="=",jx=".",sl=",",Qo="p",Gx=["-e","--expression"],il=".exe",Bx=";&|(`\n\r",me=Object.freeze({kind:"allow"}),Ee=e=>({kind:"deny",reason:e}),ge=e=>typeof e=="string"?e:void 0,cl=e=>e!=null,z=(e,t)=>e.includes(t);function fl(e,t,n,o=e.cwd){let r=e.tool;if(r===void 0)return me;let s=r.canonicalName,i=r.input,c;if(n===null){if(process.env[as]===Fx)return Ee(L(kt,t.toolNamePrefix));process.stderr.write(Ps+`
35
+ `),c=[]}else c=n;let a=Xx(s,i,e.cwd,c);return a!==null?Ee(Ye+a):s===Mx?zx(i,t):s===ul?Vx(e,t,i,c,o):s===Zo?np(e,t,i,o):me}function xl(e,t,n,o){let r=e==="webfetch",s=r?Rs.map(c=>n.toolNamePrefix+c).join(ws):n.toolNamePrefix+Ts,i=JSON.stringify(r?{url:t}:{language:dl,code:t,intent:o??Os});return[Xn+ms[e]+hs,Ss,bs+s,i].join(`
36
+ `)}function Wx(e){for(let t of Te){let n=ge(e[t]);if(n!==void 0&&n!=="")return n}}function pl(e){let t=Wx(e),n=Array.isArray(e[Re])?e[Re].filter(o=>typeof o=="string"&&o!==""):[];return t===void 0?n:[t,...n]}function Xx(e,t,n,o){if(o.length===0)return null;let r=s=>Me(dt(n,s),o,{tool:Zo,projectDir:n});if(e===ul){let s=ge(t.command);return s===void 0?null:Me(s,o)}if(e===Zo){for(let s of pl(t)){let i=r(s);if(i!==null)return i}return null}if(e===Ux){let s=ge(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=ge(t.code);return Kx(t.language)&&c!==void 0?al(c,o):null}if(e===Hx&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?al(s,o):null;if(i!==null)return i}return null}function Kx(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(il)&&(t=t.slice(0,t.length-il.length)),t===dl||z(os,t)}function al(e,t){let n=Me(e,t);if(n!==null)return n;let o=De(e);if(!o.ok)return El(e,t);for(let r of Yo(o.commands)){let s=_l(r,t);if(s!==null)return s}return null}function _l(e,t){return t.length===0?null:Me([e.argv0,...e.args].join(" "),t)??Me(e.raw,t)}function El(e,t){if(t.length===0)return null;let n=new Uint8Array(e.length+1),o=!1;for(let r=0;r<=e.length;r++)(r===0||Bx.includes(e.charAt(r-1)))&&(o=!0),o&&(r===e.length||e.charAt(r).trim()!=="")&&(n[r]=1,o=!1);return Ba(e,t,n)}function Yx(e,t){return El(e,t)!==null}function qx(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return Ms.some(n=>t===n||t.endsWith(jx+n))}function zx(e,t){let n=ge(e.url)??"";return qx(n)?me:Ee(xl("webfetch",n,t))}function Vx(e,t,n,o,r){let s=ge(n.command)??"",i=De(s);if(!i.ok)return Yx(s,o)?Ee(L(Dt,t.toolNamePrefix)):ll(e,s,t,r)??me;let c=Yo(i.commands);for(let a of c){let l=_l(a,o);if(l!==null)return Ee(Ye+l)}if(!Ae(t)||Pe(e))for(let a of c){let l=Jx(a);if(l!==null)return Ee(xl(l,s,t,ge(n.description)))}return op(e,c,t,r)??ll(e,s,t,r)??me}function Jx(e){let t=e.argv0.toLowerCase();return z(Us,t)&&$x(t,e)?"curl":Zx(e.raw)?"http":z(js,t)?"build":null}function $x(e,t){return t.redirectsToFile?!Qx(e,t.args):!t.endsInBoundedSink}function Qx(e,t){let n=Hs[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===er)break;if(z(Fs,s)||s===vs&&t[r+1]===oe)return!1;(s===n.long||s.startsWith(oe)&&!s.startsWith(er)&&s.includes(n.short,oe.length))&&(o=!0)}return o}function Zx(e){let t=e.toLowerCase();for(let n of Ws)if(t.includes(n))return!0;for(let n=t.indexOf(ze);n>=0;n=t.indexOf(ze,n+1)){let o=t.charAt(n+ze.length);if(o!==""&&Gs.includes(o)&&t.startsWith(Bs,n+ze.length+o.length))return!0}return!1}var ep="cd";function tr(e){try{let t=Px(e);return t.isFile()?t.size:-1}catch{return-1}}function nr(e,t,n,o,r,s){let i=dt(n,o);return r<=le||He(e.agent,n,o)?null:Ee(tp(s,i)?qa(i,r,t.toolNamePrefix):za(i,r))}function tp(e,t){if(typeof e=="string")return Ue([e],t);if(Ue([e.worktree],t))return!0;try{return Ue([e.containmentRoot],t)}catch{return!1}}function np(e,t,n,o){if(!cl(n.offset)&&!cl(n.limit))for(let r of pl(n)){let s=dt(e.cwd,r),i=tr(s);if(i>le&&!pn(e.agent,s)){let c=nr(e,t,e.cwd,r,i,o);if(c!==null)return c}}return me}function op(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&bo(n))return null;let r=e.cwd,s=null;for(let i of t){let c=i.argv0.toLowerCase();if(c===ep&&i.args.length===1&&i.insideConstruct===void 0&&(r=dt(r,i.args[0])),i.redirectsToFile||i.endsInBoundedSink||i.pipesOut===!0||i.insideConstruct!==void 0||!z(Xs,c))continue;let a=ip(c,i.args);if(a===null)continue;if(a.bounded){s=me;continue}let l=dt(r,a.file),u=nr(e,n,r,a.file,tr(l),o);if(u!==null)return u}return s}function ll(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&bo(n))return null;for(let r of aa(t,e.cwd)){let s=nr(e,n,e.cwd,r,tr(r),o);if(s!==null)return s}return null}var _n=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function rp(e){if(z(qn,e))return 1;for(let t of qn)if(t.startsWith(er)?e.startsWith(t+vx):e.startsWith(t))return 0;return e.startsWith(oe)&&_n(e.slice(oe.length))?0:-1}function sp(e){if(e===Qo)return"all";if(!e.endsWith(Qo))return null;let t=e.slice(0,e.length-Qo.length),n=t.indexOf(sl);return(n<0?_n(t):_n(t.slice(0,n))&&_n(t.slice(n+sl.length)))?"range":null}function ip(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(z(Ks,e)){let a=rp(c);if(a>=0){o=!0,i+=a;continue}}if(e===Lt&&z(Ys,c)){r=!0;continue}if(e===Lt&&z(Gx,c)){s=t[i+1],i++;continue}c.startsWith(oe)&&c!==oe||n.push(c)}if(e===Lt){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:sp(s);if(i===null)return null;o=i==="range"}return e===qs&&n.shift()!==w.identity?null:n.length===1&&n[0]!==oe?{file:n[0],bounded:o}:null}import{basename as fp,dirname as En,join as xt,resolve as hl}from"node:path";var cp=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]),ap=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],F=(e,t)=>e>>>t|e<<32-t;function gl(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=ap.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=F(i[E-15],7)^F(i[E-15],18)^i[E-15]>>>3,S=F(i[E-2],17)^F(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+(F(f,6)^F(f,11)^F(f,25))+(f&x^~f&p)+cp[E]+i[E]>>>0,S=(F(a,2)^F(a,13)^F(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:lp,readFileSync:up,realpathSync:ml,statSync:dp}=process.getBuiltinModule("node:fs");function xp(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 ft(e){return e===void 0||e===""?void 0:e}function pp(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return ft(t.env.CLAUDE_PROJECT_DIR)??ft(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return ft(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(It);return n<0?void 0:ft(t.argv[n+1])}case"pi:ctx.cwd":return ft(t.piCwd)}}function _p(e){let t;try{t=ml.native(e)}catch{throw new R("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=Ep(xt(t,Fn));if(o!==null){let s=Sl(xt(o,ts));return{commonDir:ml.native(s===null?o:hl(o,s)),worktree:t,start:n}}let r=En(t);if(r===t)return{commonDir:null,start:n};t=r}}function Ep(e){let t;try{if(dp(e).isDirectory())t=e;else{let n=Sl(e);if(n===null||!n.startsWith(jn))return null;t=hl(En(e),n.slice(jn.length))}}catch{return null}return lp(xt(t,ns))?t:null}function Sl(e){let t;try{t=up(e,"utf8")}catch{return null}let n=t.indexOf(`
37
+ `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function gp(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 R("NO_GIT_DIR",{path:e});return o.stdout.split(`
38
+ `).filter(r=>r!=="")}function mp(e,t){let n=fp(t)===Fn?En(t):t,o=gp(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(vn)).map(r=>r.slice(vn.length));return rl([En(n),...o])}function bl(e,t){let n=xp(e),o=pp(n,t);if(o===void 0)throw new R("NO_PROJECT",{kind:n});let r=_p(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??=gl(i).slice(0,Zr),a},get projectDir(){return l??=xt(Sa(process.env),Nt,this.projectKey),l},get dbPath(){return xt(this.projectDir,es)},worktree:c,get containmentRoot(){return u??=s??mp(o,i),u},agent:e,source:n}}var gn=Be,hp=`
39
39
  PRAGMA busy_timeout = ${ee};
40
40
  PRAGMA journal_mode = WAL;
41
- `,xn="tokenize = 'porter unicode61 remove_diacritics 2'",sp="tokenize = 'unicode61 remove_diacritics 2'",ip=`
41
+ `,mn="tokenize = 'porter unicode61 remove_diacritics 2'",Sp="tokenize = 'unicode61 remove_diacritics 2'",bp=`
42
42
  CREATE TABLE IF NOT EXISTS events (
43
43
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
44
44
  session_id TEXT NOT NULL,
@@ -83,16 +83,16 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
83
83
  agent UNINDEXED,
84
84
  ord UNINDEXED,
85
85
  body,
86
- ${sp}
86
+ ${Sp}
87
87
  );
88
88
 
89
89
  CREATE TABLE IF NOT EXISTS meta (
90
90
  key TEXT PRIMARY KEY,
91
91
  value TEXT NOT NULL
92
92
  );
93
- `,cp=`
93
+ `,Op=`
94
94
  CREATE UNIQUE INDEX IF NOT EXISTS idx_events_cost_session_turn ON events(session_id, turn) WHERE kind = 'cost';
95
- `,ap=`
95
+ `,Tp=`
96
96
  CREATE VIRTUAL TABLE chunks_v3 USING fts5(
97
97
  source_id UNINDEXED,
98
98
  session_id UNINDEXED,
@@ -101,13 +101,13 @@ CREATE VIRTUAL TABLE chunks_v3 USING fts5(
101
101
  ord UNINDEXED,
102
102
  body,
103
103
  title,
104
- ${xn}
104
+ ${mn}
105
105
  );
106
106
  INSERT INTO chunks_v3(rowid, source_id, session_id, worktree, agent, ord, body, title)
107
107
  SELECT rowid, source_id, session_id, worktree, agent, ord, body, '' FROM chunks;
108
108
  DROP TABLE chunks;
109
109
  ALTER TABLE chunks_v3 RENAME TO chunks;
110
- `,lp=`
110
+ `,Rp=`
111
111
  CREATE VIRTUAL TABLE chunks_tri USING fts5(
112
112
  body,
113
113
  title,
@@ -116,24 +116,24 @@ CREATE VIRTUAL TABLE chunks_tri USING fts5(
116
116
  );
117
117
  INSERT INTO chunks_tri(rowid, body, title) SELECT rowid, body, title FROM chunks;
118
118
  CREATE VIRTUAL TABLE chunks_vocab USING fts5vocab(chunks, 'row');
119
- `,up=`
119
+ `,Ap=`
120
120
  CREATE VIRTUAL TABLE line_units USING fts5(
121
121
  body,
122
122
  source_id UNINDEXED,
123
123
  session_id UNINDEXED,
124
124
  ord UNINDEXED,
125
- ${xn}
125
+ ${mn}
126
126
  );
127
- `,dp=`
127
+ `,yp=`
128
128
  UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
129
- `,fp=[{version:1,sql:ip},{version:2,sql:cp},{version:3,sql:ap},{version:4,sql:lp},{version:5,sql:up},{version:6,sql:dp}];function tr(e,t){if(t!==fn){if(t>fn)throw new T("SCHEMA_STALE",{found:t,want:fn});e.exec(rp),e.exec("BEGIN IMMEDIATE");try{for(let n of fp)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${fn}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}function fl(e,t,n={}){if(("bun"in n?n.bun:process.versions.bun)===void 0)return new e.DatabaseSync(t,{timeout:ee,readOnly:!0});let r=new e.DatabaseSync(t,{timeout:ee});return n.queryOnly!==!1&&r.exec("PRAGMA query_only = ON"),r}var{existsSync:ct,linkSync:xp,mkdirSync:pp,rmSync:_p}=process.getBuiltinModule("node:fs");function xl(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function Ep(e,t){let n=xl(e),o=xl(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 gp(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&Kr;return n===Yr||n===qr}async function mp(){try{return await import("node:sqlite")}catch{throw new T("NO_SQLITE")}}function nr(e){return e.prepare("PRAGMA user_version").get().user_version}function hp(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+Xr;try{let r=new e.DatabaseSync(o,{timeout:ee});try{tr(r,nr(r))}finally{r.close()}try{xp(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",St,bt])_p(o+r,{force:!0})}}function pl(e,t){let n=null;try{return ct(t)||hp(e,t),n=new e.DatabaseSync(t,{timeout:ee}),tr(n,nr(n)),n}catch(o){throw n&&n.close(),o}}function Sp(e,t){let n=fl(e,t);try{let o=nr(n);if(o!==He)throw new T("SCHEMA_STALE",{found:o,want:He});return n}catch(o){throw n.close(),o}}async function N(e,t){if(Ep(process.version,Fe))throw new T("NODE_TOO_OLD",{v:process.version});let n=await mp();pp(e.projectDir,{recursive:!0});let o=e.dbPath;if((ct(o+St)||ct(o+bt))&&!ct(o))throw new T("DB_GONE");try{let s;return t?.readOnly===!0?(ct(o)||pl(n,o).close(),s=Sp(n,o)):s=pl(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw gp(s)?new T("DB_CORRUPT"):s}}function v(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 _l(e,t){return e.raw.isTransaction?t(e):v(e,t)}function oe(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function z(e,t,n){_l(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function pn(e,t){return _l(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var El="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",bp="INSERT INTO "+El,Op="INSERT OR IGNORE INTO "+El,Tp="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function _n(e,t){return v(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?Op:bp).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(Tp).get(t.session_id,t.turn).seq})}function gl(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 or(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 ml(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 hl(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 Sl(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function bl(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var rr=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 Rp(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=rr.length/2-1;for(;t<=n;){let o=t+n>>1,r=rr[2*o],s=rr[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function Ap(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 we(e){return Ap(e,t=>!Rp(t))}var yp=`
129
+ `,Np=[{version:1,sql:bp},{version:2,sql:Op},{version:3,sql:Tp},{version:4,sql:Rp},{version:5,sql:Ap},{version:6,sql:yp}];function or(e,t){if(t!==gn){if(t>gn)throw new R("SCHEMA_STALE",{found:t,want:gn});e.exec(hp),e.exec("BEGIN IMMEDIATE");try{for(let n of Np)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${gn}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}function Ol(e,t,n={}){if(("bun"in n?n.bun:process.versions.bun)===void 0)return new e.DatabaseSync(t,{timeout:ee,readOnly:!0});let r=new e.DatabaseSync(t,{timeout:ee});return n.queryOnly!==!1&&r.exec("PRAGMA query_only = ON"),r}var{existsSync:pt,linkSync:Ip,mkdirSync:Cp,rmSync:kp}=process.getBuiltinModule("node:fs");function Tl(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function Dp(e,t){let n=Tl(e),o=Tl(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 Lp(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&Jr;return n===$r||n===Qr}async function wp(){try{return await import("node:sqlite")}catch{throw new R("NO_SQLITE")}}function rr(e){return e.prepare("PRAGMA user_version").get().user_version}function Pp(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+Vr;try{let r=new e.DatabaseSync(o,{timeout:ee});try{or(r,rr(r))}finally{r.close()}try{Ip(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",At,yt])kp(o+r,{force:!0})}}function Rl(e,t){let n=null;try{return pt(t)||Pp(e,t),n=new e.DatabaseSync(t,{timeout:ee}),or(n,rr(n)),n}catch(o){throw n&&n.close(),o}}function Mp(e,t){let n=Ol(e,t);try{let o=rr(n);if(o!==Be)throw new R("SCHEMA_STALE",{found:o,want:Be});return n}catch(o){throw n.close(),o}}async function N(e,t){if(Dp(process.version,We))throw new R("NODE_TOO_OLD",{v:process.version});let n=await wp();Cp(e.projectDir,{recursive:!0});let o=e.dbPath;if((pt(o+At)||pt(o+yt))&&!pt(o))throw new R("DB_GONE");try{let s;return t?.readOnly===!0?(pt(o)||Rl(n,o).close(),s=Mp(n,o)):s=Rl(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw Lp(s)?new R("DB_CORRUPT"):s}}function v(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 Al(e,t){return e.raw.isTransaction?t(e):v(e,t)}function re(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function V(e,t,n){Al(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function hn(e,t){return Al(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var yl="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",Up="INSERT INTO "+yl,Hp="INSERT OR IGNORE INTO "+yl,Fp="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function Sn(e,t){return v(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?Hp:Up).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(Fp).get(t.session_id,t.turn).seq})}function Nl(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 sr(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 Il(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 Cl(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 kl(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function Dl(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var ir=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 vp(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=ir.length/2-1;for(;t<=n;){let o=t+n>>1,r=ir[2*o],s=ir[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function jp(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 Fe(e){return jp(e,t=>!vp(t))}var Gp=`
130
130
  INSERT INTO sources(session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts)
131
131
  VALUES (:session_id, :worktree, :agent, :kind, :label, :bytes_total, :chunk_count, :created_ts, :created_at, :created_ts)
132
- RETURNING id`,Np=`
133
- INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,Tl=1,Ol=" (raw)",Rl=`AND (:source IS NOT NULL OR substr(s.label, -${Ol.length}) <> '${Ol}')`,Al=`
132
+ RETURNING id`,Bp=`
133
+ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,wl=1,Ll=" (raw)",Pl=`AND (:source IS NOT NULL OR substr(s.label, -${Ll.length}) <> '${Ll}')`,Ml=`
134
134
  SELECT chunks.rowid AS rid, chunks.source_id AS source_id, chunks.session_id AS session_id,
135
135
  chunks.worktree AS worktree, chunks.ord AS ord, s.created_ts AS created_ts,
136
- bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${Tl}) AS bm,
136
+ bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${wl}) AS bm,
137
137
  (chunks.rowid IN (SELECT rowid FROM chunks WHERE chunks MATCH :all)) AS full
138
138
  FROM chunks JOIN sources s ON s.id = chunks.source_id
139
139
  WHERE chunks MATCH :match
@@ -141,9 +141,9 @@ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VAL
141
141
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
142
142
  AND (:source IS NULL OR s.label = :source)
143
143
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
144
- ${Rl}`,yl=`
145
- ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,vh=`
146
- WITH m AS (${Al}
144
+ ${Pl}`,Ul=`
145
+ ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,eS=`
146
+ WITH m AS (${Ml}
147
147
  ), r AS (
148
148
  SELECT *,
149
149
  ROW_NUMBER() OVER (ORDER BY full DESC, bm ASC, source_id DESC, ord ASC) AS rank_a,
@@ -151,11 +151,11 @@ WITH m AS (${Al}
151
151
  FROM m
152
152
  )
153
153
  SELECT rid, source_id, session_id, worktree, ord, full, 1.0 / (:k + rank_a) + 1.0 / (:k + rank_b) AS score
154
- FROM r${yl}`,jh=`
155
- WITH m AS (${Al}
154
+ FROM r${Ul}`,tS=`
155
+ WITH m AS (${Ml}
156
156
  )
157
157
  SELECT rid, source_id, session_id, worktree, ord, full, -bm AS score
158
- FROM m${yl}`;var Gh=`
158
+ FROM m${Ul}`;var nS=`
159
159
  SELECT t.rowid AS rid, c.source_id AS source_id, c.session_id AS session_id, c.worktree AS worktree, c.ord AS ord
160
160
  FROM chunks_tri t JOIN chunks c ON c.rowid = t.rowid JOIN sources s ON s.id = c.source_id
161
161
  WHERE chunks_tri MATCH :match
@@ -163,63 +163,63 @@ WHERE chunks_tri MATCH :match
163
163
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
164
164
  AND (:source IS NULL OR s.label = :source)
165
165
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
166
- ${Rl}
167
- ORDER BY bm25(chunks_tri, 1.0, ${Tl}) ASC, c.source_id DESC, c.ord ASC`;var Ip="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",Cp="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function Nl(e,t,n){let o=sr(e,t,n);return Cl(e,o,t,n),o}function sr(e,t,n){let o=0;for(let r of n)o+=r.bytes;return v(e,r=>{let s=r.raw.prepare(yp).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 Il(e,t,n,o,r){try{Cl(e,t,n,o),cr(e,t,n.sessionId,r)}catch(s){throw v(e,i=>{kp(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function Cl(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>yn&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)v(e,l=>{let a=l.raw.prepare(Np),d=l.raw.prepare(Ip);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 kp(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(Cp+" 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 ir(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 Dp(e){return[...new Set(ir(e).split(" ").filter(n=>n!==""))].join(" OR ")}var kl=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 Lp(e){let t=[...new Set(ir(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!kl.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var En=`
166
+ ${Pl}
167
+ ORDER BY bm25(chunks_tri, 1.0, ${wl}) ASC, c.source_id DESC, c.ord ASC`;var Wp="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",Xp="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function Hl(e,t,n){let o=cr(e,t,n);return vl(e,o,t,n),o}function cr(e,t,n){let o=0;for(let r of n)o+=r.bytes;return v(e,r=>{let s=r.raw.prepare(Gp).get({session_id:t.sessionId,worktree:t.worktree,agent:t.agent,kind:t.kind,label:t.label,bytes_total:o,chunk_count:n.length,created_ts:t.createdAt,created_at:new Date(t.createdAt).toISOString()});return Number(s.id)})}function Fl(e,t,n,o,r){try{vl(e,t,n,o),lr(e,t,n.sessionId,r)}catch(s){throw v(e,i=>{Kp(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function vl(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>Ln&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)v(e,a=>{let l=a.raw.prepare(Bp),u=a.raw.prepare(Wp);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 Kp(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(Xp+" 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 ar(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 Yp(e){return[...new Set(ar(e).split(" ").filter(n=>n!==""))].join(" OR ")}var jl=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 qp(e){let t=[...new Set(ar(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!jl.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var bn=`
168
168
  AND (:scope <> 'session' OR session_id = :session_id)
169
- AND (:scope <> 'worktree' OR worktree = :worktree)`,Bh=`
169
+ AND (:scope <> 'worktree' OR worktree = :worktree)`,oS=`
170
170
  WITH e AS (
171
171
  SELECT seq, kind, key, path, body, created_at FROM events
172
- WHERE created_at > :after${En}
172
+ WHERE created_at > :after${bn}
173
173
  AND (:source IS NULL OR kind = :source)
174
174
  )
175
175
  SELECT seq, kind, key, path, body, created_at FROM e
176
176
  WHERE created_at <= IFNULL((SELECT created_at FROM e ORDER BY created_at, seq LIMIT 1 OFFSET :off), created_at)
177
- ORDER BY created_at ASC, seq ASC`,Wh=`
177
+ ORDER BY created_at ASC, seq ASC`,rS=`
178
178
  WITH s AS (
179
179
  SELECT id, label, created_ts FROM sources
180
- WHERE created_ts > :after${En}
180
+ WHERE created_ts > :after${bn}
181
181
  AND (:source IS NULL OR label = :source)
182
182
  AND label <> :reserved
183
183
  )
184
184
  SELECT id, label, created_ts FROM s
185
185
  WHERE created_ts <= IFNULL((SELECT created_ts FROM s ORDER BY created_ts, id LIMIT 1 OFFSET :off), created_ts)
186
- ORDER BY created_ts ASC, id ASC`;var Xh=`
187
- SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${En} AND (:source IS NULL OR kind = :source))
188
- OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${En} AND (:source IS NULL OR label = :source)
189
- AND label <> :reserved) AS more`;var wp=`CREATE VIRTUAL TABLE r USING fts5(body, ${xn}, content='')`,Pp="INSERT INTO r(rowid, body) VALUES (?, ?)",Mp="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function J(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?Dp(t):ir(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(wp);let c=i.prepare(Pp);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(Mp).all(r))o[Number(l.id)-1]=-l.bm;return o}finally{i.close()}}var Up="s";function Dl(e){return Up+e.toString(36)}function cr(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<=yn);)i+=o[s].body.length,s++;let c=r;v(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 Ll(e){let t=new Set,n=new Set,o=s=>{n.size<kt&&n.add(s),kl.has(s.toLowerCase())||t.add(s)},r="";for(let s of e){if(t.size>=kt)break;s.trim()===""||s==="\0"?(r!==""&&o(r),r=""):r+=s}return r!==""&&t.size<kt&&o(r),[...t.size>0?t:n].join(" ")}function wl(e,t,n,o){let r=Lp(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 Hp(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function ar(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=Hp(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>Xe||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 lr(e){let t=e.indexOf(`
192
- `);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function Pe(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 at(e){return e.length>In?e.slice(e.length-In):e}function Fp(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function Pl(e,t){if(!t)return Fp();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:Pe("last_request",r,"now: "+lr(r.body),1,null),i=o.slice(0,o.length-1).map(_=>Pe("earlier_requests",_,"asked #"+_.seq+": "+lr(_.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(Pe("open_errors",m.row,"error #"+m.row.seq+" "+(m.row.tool??"")+": "+_,m.count,_));a.sort((_,m)=>_.seq-m.seq);let d=new Map;for(let _ of n)_.kind!=="edit"||_.path===null||d.set(_.path,{row:_,count:(d.get(_.path)?.count??0)+1});let u=[];for(let[_,m]of d){let y=Pe("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);u.push({...y,editCount:m.count})}u.sort((_,m)=>_.seq-m.seq);let f=new Map;for(let _ of n){if(_.kind!=="decision"||_.body==="")continue;let m=_.key??_.body;f.set(m,{row:_,count:(f.get(m)?.count??0)+1})}let x=[];for(let[_,m]of f)x.push(Pe("decisions",m.row,"decided #"+m.row.seq+": "+lr(m.row.body),m.count,_));x.sort((_,m)=>_.seq-m.seq);let p=n.filter(_=>_.kind==="index").map(_=>Pe("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:at(a),changedFiles:at(u),decisions:at(x),earlierRequests:at(i),indexedSources:at(p)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=Cn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-Cn));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 vp(e){if(!Object.hasOwn(kn,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=Dn[Math.min(t,Dn.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(kn[e.section]*n*o/ei)}function jp(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 Ml(e,t){return e.map(n=>({...n,score:vp({section:jp(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function Fl(e){return e.sourceId+":"+e.ord}function mn(e){return"@"+e.label+" line "+(e.ord+1)+`:
193
- `+e.body}function Gp(e){return new Set(we(e.toLowerCase()))}function Bp(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 dr(e,t,n){let o=e.filter(a=>!t.has(Fl(a))&&a.score>=Jn);if(o.length===0)return[];let r=Math.max(...o.map(a=>a.score)),s=o.map(a=>Gp(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,Bp(s[f],s[g]));let p=Gr*(o[f].score/r)-Br*x;p>d&&(d=p,a=f)}c.delete(a);let u=gn(mn(o[a]))+1;l+u>n||(l+=u,i.push(a))}return i.map(a=>o[a])}var Ul={text:"",seqs:[]};function gn(e){return Buffer.byteLength(e,"utf8")}function ur(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
194
- `)}function Hl(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+ur(e)}function vl(e,t,n,o=[],r=new Set){if(t.trim()==="")return Ul;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&ur(f)!==""),i=s.length===0?[]:J(s.map(ur),t,"any"),c=s.map((f,x)=>({r:f,score:i[x]})).filter(f=>f.score>=Jn).sort((f,x)=>x.score-f.score||x.r.seq-f.r.seq),l=gn(Qn)+1+gn(Zn),a=[];for(let{r:f}of c){let x=gn(Hl(f))+1;l+x>Xe||(l+=x,a.push(f))}let d=dr(o,r,Xe-l);if(a.length===0&&d.length===0)return Ul;a.sort((f,x)=>f.seq-x.seq);let u=[...a.map(Hl),...d.map(mn)];return{text:[Qn,...u,Zn].join(`
195
- `),seqs:a.map(f=>f.seq),...d.length>0?{units:d.map(Fl)}:{}}}function re(e){return Buffer.byteLength(e,"utf8")}function fr(e,t){return e.bytes>Dr?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function xr(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function jl(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=Pl(e,s),l=`<context_mode_state session="${s}" upto="${i}">`,a=re(xr([],o)),d=kr-(re(l)+1+a+1+re(An)),u=0,f=c.lastRequest===null?null:fr(c.lastRequest,o);f!==null&&(u+=re(f)+1);let x=Ml([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),p=new Map,g=[],E=[];for(;x.length>0;){let m=0,y=-1/0;for(let _t=0;_t<x.length;_t++){let Et=x[_t],Rn=Et.score*jr**(p.get(Et.section)??0)/Et.bytes;(Rn>y||Rn===y&&Et.seq>x[m].seq)&&(m=_t,y=Rn)}let D=x.splice(m,1)[0],pt=re(fr(D,o))+1;u+pt<=d?(u+=pt,g.push(D),p.set(D.section,(p.get(D.section)??0)+1)):E.push(D)}let h=[l];f!==null&&h.push(f);for(let m of["open_errors","changed_files","decisions","earlier_requests","indexed_sources"])for(let y of g.filter(D=>D.section===m).sort((D,pt)=>D.seq-pt.seq))h.push(fr(y,o));if(n!==void 0){for(let m of n.sources){let y=re(m)+1;u+y>d||(u+=y,h.push(m))}for(let m of dr(n.units,new Set,d-u)){let y=mn(m);u+=re(y)+1,h.push(y)}}let S=[],_=new Set;for(let m of E.sort((y,D)=>y.seq-D.seq))if(!(m.query===null||_.has(m.query))){if(re(xr([...S,m.query],o))-a>d-u)break;S.push(m.query),_.add(m.query)}return h.push(xr(S,o),An),h.join(`
196
- `)}var Wp=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Xp=new Set(["script","style"]),Kp=new TextEncoder;function hn(e,t,n=ae){let o=Vp(e);if(o.length===0)return[];let r=Math.max(4,Math.min(ae,Math.floor(n)));if(t==="md")return Yp(o,r,r<ae);let s=t==="html"?Qp(o):pr(o,!1);return _r(o,s,t!=="text",r,r<ae)}function Yp(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 _r(e,i,!0,t,n))c(a.text,a.bytes);i=[]}};for(let a of pr(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&&se(e.slice(a.start,a.end))>t){let d=qp(e,a,a.fence,t);if(d!==void 0){l();for(let u of d)c(u,se(u));continue}}i.push(a)}return l(),o}function qp(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-se(r)-se(s)-2;if(!(l<16||c.length===0))return _r(c,pr(c,!1),!0,l,!0).map(a=>r+`
197
- `+a.text+`
198
- `+s)}function Vp(e){let t=e.split(`\r
186
+ ORDER BY created_ts ASC, id ASC`;var sS=`
187
+ SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${bn} AND (:source IS NULL OR kind = :source))
188
+ OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${bn} AND (:source IS NULL OR label = :source)
189
+ AND label <> :reserved) AS more`;var zp=`CREATE VIRTUAL TABLE r USING fts5(body, ${mn}, content='')`,Vp="INSERT INTO r(rowid, body) VALUES (?, ?)",Jp="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function J(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?Yp(t):ar(t);if(r===""||e.length===0)return o;let s=process.getBuiltinModule("node:sqlite");if(s===void 0)throw new R("NO_SQLITE");let i=new s.DatabaseSync(":memory:");try{i.exec(zp);let c=i.prepare(Vp);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(Jp).all(r))o[Number(a.id)-1]=-a.bm;return o}finally{i.close()}}var $p="s";function Gl(e){return $p+e.toString(36)}function lr(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<=Ln);)i+=o[s].body.length,s++;let c=r;v(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 Bl(e){let t=new Set,n=new Set,o=s=>{n.size<Mt&&n.add(s),jl.has(s.toLowerCase())||t.add(s)},r="";for(let s of e){if(t.size>=Mt)break;s.trim()===""||s==="\0"?(r!==""&&o(r),r=""):r+=s}return r!==""&&t.size<Mt&&o(r),[...t.size>0?t:n].join(" ")}function Wl(e,t,n,o){let r=qp(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 Qp(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function ur(e){let t=e.split(`
190
+ `),n=[],o=[],r=ei*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=Qp(i);if(c===i.length)continue;for(;n.length>0&&n[n.length-1].indent>=c;)n.pop();let a=Buffer.byteLength(i,"utf8"),l=a,u=n.length;for(;u>0;){let d=n[u-1].bytes+1;if(l+d>Je||l-a+d>r)break;l+=d,u--}r-=l-a,o.push({ord:s,body:[...n.slice(u).map(d=>d.line),i].join(`
191
+ `)}),n.push({indent:c,line:i,bytes:a})}return o}function dr(e){let t=e.indexOf(`
192
+ `);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function ve(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 _t(e){return e.length>wn?e.slice(e.length-wn):e}function Zp(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function Xl(e,t){if(!t)return Zp();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:ve("last_request",r,"now: "+dr(r.body),1,null),i=o.slice(0,o.length-1).map(_=>ve("earlier_requests",_,"asked #"+_.seq+": "+dr(_.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(ve("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 T=ve("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);d.push({...T,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(ve("decisions",m.row,"decided #"+m.row.seq+": "+dr(m.row.body),m.count,_));x.sort((_,m)=>_.seq-m.seq);let p=n.filter(_=>_.kind==="index").map(_=>ve("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:_t(l),changedFiles:_t(d),decisions:_t(x),earlierRequests:_t(i),indexedSources:_t(p)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=Pn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-Pn));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 e_(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=Un[Math.min(t,Un.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/ai)}function t_(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 Kl(e,t){return e.map(n=>({...n,score:e_({section:t_(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function zl(e){return e.sourceId+":"+e.ord}function Tn(e){return"@"+e.label+" line "+(e.ord+1)+`:
193
+ `+e.body}function n_(e){return new Set(Fe(e.toLowerCase()))}function o_(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 xr(e,t,n){let o=e.filter(l=>!t.has(zl(l))&&l.score>=eo);if(o.length===0)return[];let r=Math.max(...o.map(l=>l.score)),s=o.map(l=>n_(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,o_(s[f],s[g]));let p=Yr*(o[f].score/r)-qr*x;p>u&&(u=p,l=f)}c.delete(l);let d=On(Tn(o[l]))+1;a+d>n||(a+=d,i.push(l))}return i.map(l=>o[l])}var Yl={text:"",seqs:[]};function On(e){return Buffer.byteLength(e,"utf8")}function fr(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
194
+ `)}function ql(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+fr(e)}function Vl(e,t,n,o=[],r=new Set){if(t.trim()==="")return Yl;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&fr(f)!==""),i=s.length===0?[]:J(s.map(fr),t,"any"),c=s.map((f,x)=>({r:f,score:i[x]})).filter(f=>f.score>=eo).sort((f,x)=>x.score-f.score||x.r.seq-f.r.seq),a=On(no)+1+On(oo),l=[];for(let{r:f}of c){let x=On(ql(f))+1;a+x>Je||(a+=x,l.push(f))}let u=xr(o,r,Je-a);if(l.length===0&&u.length===0)return Yl;l.sort((f,x)=>f.seq-x.seq);let d=[...l.map(ql),...u.map(Tn)];return{text:[no,...d,oo].join(`
195
+ `),seqs:l.map(f=>f.seq),...u.length>0?{units:u.map(zl)}:{}}}function se(e){return Buffer.byteLength(e,"utf8")}function pr(e,t){return e.bytes>Pr?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function _r(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function Jl(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=Xl(e,s),a=`<context_mode_state session="${s}" upto="${i}">`,l=se(_r([],o)),u=wr-(se(a)+1+l+1+se(Dn)),d=0,f=c.lastRequest===null?null:pr(c.lastRequest,o);f!==null&&(d+=se(f)+1);let x=Kl([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),p=new Map,g=[],E=[];for(;x.length>0;){let m=0,T=-1/0;for(let Se=0;Se<x.length;Se++){let be=x[Se],Cn=be.score*Kr**(p.get(be.section)??0)/be.bytes;(Cn>T||Cn===T&&be.seq>x[m].seq)&&(m=Se,T=Cn)}let C=x.splice(m,1)[0],ae=se(pr(C,o))+1;d+ae<=u?(d+=ae,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 T of g.filter(C=>C.section===m).sort((C,ae)=>C.seq-ae.seq))h.push(pr(T,o));if(n!==void 0){for(let m of n.sources){let T=se(m)+1;d+T>u||(d+=T,h.push(m))}for(let m of xr(n.units,new Set,u-d)){let T=Tn(m);d+=se(T)+1,h.push(T)}}let S=[],_=new Set;for(let m of E.sort((T,C)=>T.seq-C.seq))if(!(m.query===null||_.has(m.query))){if(se(_r([...S,m.query],o))-l>u-d)break;S.push(m.query),_.add(m.query)}return h.push(_r(S,o),Dn),h.join(`
196
+ `)}var r_=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),s_=new Set(["script","style"]),i_=new TextEncoder;function Rn(e,t,n=ue){let o=l_(e);if(o.length===0)return[];let r=Math.max(4,Math.min(ue,Math.floor(n)));if(t==="md")return c_(o,r,r<ue);let s=t==="html"?x_(o):Er(o,!1);return gr(o,s,t!=="text",r,r<ue)}function c_(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 gr(e,i,!0,t,n))c(l.text,l.bytes);i=[]}};for(let l of Er(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&&ie(e.slice(l.start,l.end))>t){let u=a_(e,l,l.fence,t);if(u!==void 0){a();for(let d of u)c(d,ie(d));continue}}i.push(l)}return a(),o}function a_(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-ie(r)-ie(s)-2;if(!(a<16||c.length===0))return gr(c,Er(c,!1),!0,a,!0).map(l=>r+`
197
+ `+l.text+`
198
+ `+s)}function l_(e){let t=e.split(`\r
199
199
  `).join(`
200
- `);return t.startsWith("\uFEFF")?t.slice(1):t}function pr(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),$p(p,i)&&(i="",t&&l!==void 0&&(l.closeStart=u,a()));else if(p.length===0)a();else{let g=t?Jp(p):"",E=t&&g===""?zp(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 zp(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 Jp(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 $p(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 Qp(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{Bl(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=Zp(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||Wp.has(c.name))){if(Xp.has(c.name)){s=e_(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return Bl(t,e,r,e.length),t}function Xl(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function Kl(e){return Xl(e)||e>="0"&&e<="9"||e==="-"||e===":"}function Zp(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!Xl(e[n]))return;let r=n;for(;n<e.length&&Kl(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 e_(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||!Kl(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function Gl(e){return e===" "||e===`
202
- `||e===" "||e==="\f"||e==="\r"}function Bl(e,t,n,o){let r=n,s=o;for(;r<s&&Gl(t[r]);)r+=1;for(;s>r&&Gl(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function se(e){return Buffer.byteLength(e,"utf8")}function Wl(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=Kp.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function _r(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=se(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=se(e.slice(u.start,u.end));for(;x>o;){let p=Wl(e,f,u.end,i),g=r?e.lastIndexOf(`
203
- `,p.end-1):-1;if(g>f){let E=se(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=se(e.slice(f,h));if(S<=ae){d(f,h,S),f=h,x-=S;continue}c??=new Uint8Array(ae);let _=Wl(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 t_=`
205
- `,n_=1;function Yl(e,t,n,o,r){return o_(e,t,n,o,r)}function o_(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?J(s,t):J(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?n_: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(t_),more:d?Er(t,o):null}}function Er(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>no?"...":JSON.stringify(e))+"]"+n+"})"}var ql=20,j=2,Vl=9,zl=8,r_=.9,s_=.5,i_=64,c_=2,a_=4,gr=`
206
- `,l_="(absent)",$=e=>Buffer.byteLength(e,"utf8");function Jl(e,t,n){let o=f_(e,t)??__(e,t)??m_(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):J(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?$(gr):0,u=o.units[a].render(n-c-d);u===null||c+d+$(u)>n||(i.push({pos:o.units[a].pos,text:u}),c+=d+$(u))}if(i.length===0)return null;i.sort((a,d)=>a.pos-d.pos);let l=i.map(a=>a.text);return c+$(gr)+$(o.header)<=n&&l.unshift(o.header),l.join(gr)}function u_(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
207
- `&&n!=="\r"&&n!==" ")return n}return""}function d_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $l(e,t,n){if(n.size<2||n.size>zl)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=j+1)return o[0][1]<r_*e||e-o[0][1]>j?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>j),s=o.filter(([,i])=>i<=j);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function Ql(e){if(u_(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<ql||!t.every(d_))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 Zl=(e,t)=>e+" objects {"+t.join(",")+"}";function f_(e,t){let n=Ql(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?l_:JSON.stringify(p);u.set(g,(u.get(g)??0)+1);let E=d.get(g)??[];if(E.length<=j&&E.push(x),d.set(g,E),u.size>zl)break}if(f)for(let x of $l(o.length,d,u))s.set(x,[...s.get(x)??[],a])}if(s.size===0||s.size>Vl)return null;let i=J(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=>eu(a,o[a],d,c,u)}));return{header:Zl(o.length,r)+", "+s.size+" rare:",units:l}}function eu(e,t,n,o,r){let s="["+e+"] ",i=x_(t,n,o,r-$(s));return i===null?null:s+i}function x_(e,t,n,o){let r=JSON.stringify(e);if($(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=$(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 p_(e,t){let n=J(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function __(e,t){let n=Ql(e);if(n===null)return null;let{objs:o,keys:r}=n,s=p_(r,t),i=new Map,c=0;for(let a of r){if(!s.has(a)||c>=c_||!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=>eu(a,o[a],[d],s,u)}));return{header:Zl(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:l,direct:!0}}function E_(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function g_(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 m_(e){let t=e.split(`
208
- `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<ql)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=>E_(p)?"<*>":p),u=d.length+" "+(d[0]??""),f=n.get(u)??[],x;for(let p of f)if(g_(p.tpl,d)>=s_){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>i_)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<=j&&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<=j&&E.push(l),g.counts.set(a[p],E),g.totals.size>j+1&&(x.pos[p]=null)}}let r=o.filter(l=>l.count>j);if(r.length===0||r.length>a_||r.some(l=>l.tpl.every(a=>a==="<*>")))return null;let s=new Set(o.filter(l=>l.count<=j).flatMap(l=>l.lines));for(let l of r)for(let a of l.pos)if(a!==null)for(let d of $l(l.count,a.counts,a.totals))s.add(d);if(s.size===0||s.size>Vl)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=>$(a)<=d?a:null}});return{header:i,units:c}}function h_(e,t,n,o,r,s,i,c=hn(s,i)){return{sourceId:Nl(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 mr(e,t,n,o,r,s,i){return h_(e,t,n,"content",o,r,s,i)}async function S_(e,t){try{let n=await N(e);_n(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
209
- `)}}function Sn(e,t,n){S_(e,n)}function tu(e,t,n){let o=new Set(we(t.toLowerCase()));for(let i of we(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of we(n.toLowerCase()))o.has(i)&&r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((i,c)=>i[1]-c[1]||(i[0]<c[0]?-1:i[0]>c[0]?1:0)).slice(0,vr).map(i=>i[0]).join(" ")}function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function b_(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(ni):""}function O_(e){return Array.isArray(e)?e.filter(lt).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):lt(e)?Object.entries(e):[]}function ou(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!lt(t))return[];let n=[];for(let[o,r]of O_(t[ti])){let s=b_(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function ru(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!lt(o)||!Array.isArray(o.options)))for(let r of o.options)lt(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function nu(e){return e.trim().toLowerCase()}function su(e,t,n){let o=nu(e);if(o==="")return null;let r=t.find(s=>nu(s)===o);return r===void 0?null:{key:wt,body:"A: "+r+`
210
- ref: #`+n}}function T_(e,t){return"hint:"+e+":"+t}function R_(e,t){return oe(e,t)!==null?!1:(z(e,t,"1"),!0)}function A_(e,t,n){let o=oe(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return z(e,t,String(r)),(r-1)%n===0}function bn(e,t,n,o){if(t==="")return!1;let r=T_(t,n),s=i=>o===void 0?R_(i,r):A_(i,r,o);return e.raw.isTransaction?s(e):v(e,s)}import{join as Sr,resolve as iu}from"node:path";var hr=process.getBuiltinModule("node:fs");function br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function On(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function y_(e){for(let t of hs){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(br(n))return n}return{}}function N_(e){return e.HOME??e.USERPROFILE??""}function I_(e){let t=e[ve];if(t!==void 0&&t!=="")return Sr(sn(e,""),Gn);let n=N_(e);return n===""?"":Sr(sn(e,n),Gn)}function au(e){let t=br(e)?e.code:void 0;return typeof t=="string"&&t!==""?t:e instanceof Error?e.name:"Error"}function Me(e,t,n,o){try{let r=I_(e);if(r==="")return;hr.mkdirSync(Sr(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:au(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});hr.appendFileSync(r,s+`
200
+ `);return t.startsWith("\uFEFF")?t.slice(1):t}function Er(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(`
201
+ `,d),x=f<0?e.length:f,p=e.slice(d,x);if(i!=="")u(d,x,!1),f_(p,i)&&(i="",t&&a!==void 0&&(a.closeStart=d,l()));else if(p.length===0)l();else{let g=t?d_(p):"",E=t&&g===""?u_(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 u_(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 d_(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 f_(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 x_(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{Ql(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=p_(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||r_.has(c.name))){if(s_.has(c.name)){s=__(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return Ql(t,e,r,e.length),t}function eu(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function tu(e){return eu(e)||e>="0"&&e<="9"||e==="-"||e===":"}function p_(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!eu(e[n]))return;let r=n;for(;n<e.length&&tu(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 __(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||!tu(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function $l(e){return e===" "||e===`
202
+ `||e===" "||e==="\f"||e==="\r"}function Ql(e,t,n,o){let r=n,s=o;for(;r<s&&$l(t[r]);)r+=1;for(;s>r&&$l(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function ie(e){return Buffer.byteLength(e,"utf8")}function Zl(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=i_.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function gr(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=ie(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=ie(e.slice(d.start,d.end));for(;x>o;){let p=Zl(e,f,d.end,i),g=r?e.lastIndexOf(`
203
+ `,p.end-1):-1;if(g>f){let E=ie(e.slice(f,g+1));u(f,g+1,E),f=g+1,x-=E;continue}if(r){let E=e.indexOf(`
204
+ `,f),h=E<0||E>=d.end?d.end:E+1,S=ie(e.slice(f,h));if(S<=ue){u(f,h,S),f=h,x-=S;continue}c??=new Uint8Array(ue);let _=Zl(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 E_=`
205
+ `,g_=1;function nu(e,t,n,o,r){return m_(e,t,n,o,r)}function m_(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?J(s,t):J(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?g_: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(E_),more:u?mr(t,o):null}}function mr(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>$e?"...":JSON.stringify(e))+"]"+n+"})"}var ou=20,j=2,ru=9,su=8,h_=.9,S_=.5,b_=64,O_=2,T_=4,hr=`
206
+ `,R_="(absent)",$=e=>Buffer.byteLength(e,"utf8");function iu(e,t,n){let o=N_(e,t)??k_(e,t)??w_(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):J(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?$(hr):0,d=o.units[l].render(n-c-u);d===null||c+u+$(d)>n||(i.push({pos:o.units[l].pos,text:d}),c+=u+$(d))}if(i.length===0)return null;i.sort((l,u)=>l.pos-u.pos);let a=i.map(l=>l.text);return c+$(hr)+$(o.header)<=n&&a.unshift(o.header),a.join(hr)}function A_(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
207
+ `&&n!=="\r"&&n!==" ")return n}return""}function y_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cu(e,t,n){if(n.size<2||n.size>su)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=j+1)return o[0][1]<h_*e||e-o[0][1]>j?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>j),s=o.filter(([,i])=>i<=j);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function au(e){if(A_(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<ou||!t.every(y_))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 lu=(e,t)=>e+" objects {"+t.join(",")+"}";function N_(e,t){let n=au(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?R_:JSON.stringify(p);d.set(g,(d.get(g)??0)+1);let E=u.get(g)??[];if(E.length<=j&&E.push(x),u.set(g,E),d.size>su)break}if(f)for(let x of cu(o.length,u,d))s.set(x,[...s.get(x)??[],l])}if(s.size===0||s.size>ru)return null;let i=J(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=>uu(l,o[l],u,c,d)}));return{header:lu(o.length,r)+", "+s.size+" rare:",units:a}}function uu(e,t,n,o,r){let s="["+e+"] ",i=I_(t,n,o,r-$(s));return i===null?null:s+i}function I_(e,t,n,o){let r=JSON.stringify(e);if($(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=$(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 C_(e,t){let n=J(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function k_(e,t){let n=au(e);if(n===null)return null;let{objs:o,keys:r}=n,s=C_(r,t),i=new Map,c=0;for(let l of r){if(!s.has(l)||c>=O_||!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=>uu(l,o[l],[u],s,d)}));return{header:lu(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:a,direct:!0}}function D_(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function L_(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 w_(e){let t=e.split(`
208
+ `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<ou)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=>D_(p)?"<*>":p),d=u.length+" "+(u[0]??""),f=n.get(d)??[],x;for(let p of f)if(L_(p.tpl,u)>=S_){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>b_)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<=j&&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<=j&&E.push(a),g.counts.set(l[p],E),g.totals.size>j+1&&(x.pos[p]=null)}}let r=o.filter(a=>a.count>j);if(r.length===0||r.length>T_||r.some(a=>a.tpl.every(l=>l==="<*>")))return null;let s=new Set(o.filter(a=>a.count<=j).flatMap(a=>a.lines));for(let a of r)for(let l of a.pos)if(l!==null)for(let u of cu(a.count,l.counts,l.totals))s.add(u);if(s.size===0||s.size>ru)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=>$(l)<=u?l:null}});return{header:i,units:c}}function P_(e,t,n,o,r,s,i,c=Rn(s,i)){return{sourceId:Hl(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 Sr(e,t,n,o,r,s,i){return P_(e,t,n,"content",o,r,s,i)}async function M_(e,t){try{let n=await N(e);Sn(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
209
+ `)}}function An(e,t,n){M_(e,n)}function du(e,t,n){let o=new Set(Fe(t.toLowerCase()));for(let i of Fe(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of Fe(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,Xr).map(i=>i[0]).join(" ")}function Et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function U_(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(ui):""}function H_(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 xu(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!Et(t))return[];let n=[];for(let[o,r]of H_(t[li])){let s=U_(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function pu(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 fu(e){return e.trim().toLowerCase()}function _u(e,t,n){let o=fu(e);if(o==="")return null;let r=t.find(s=>fu(s)===o);return r===void 0?null:{key:Ft,body:"A: "+r+`
210
+ ref: #`+n}}function F_(e,t){return"hint:"+e+":"+t}function v_(e,t){return re(e,t)!==null?!1:(V(e,t,"1"),!0)}function j_(e,t,n){let o=re(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return V(e,t,String(r)),(r-1)%n===0}function yn(e,t,n,o){if(t==="")return!1;let r=F_(t,n),s=i=>o===void 0?v_(i,r):j_(i,r,o);return e.raw.isTransaction?s(e):v(e,s)}import{join as Or,resolve as Eu}from"node:path";var br=process.getBuiltinModule("node:fs");function Tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function G_(e){for(let t of Ns){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(Tr(n))return n}return{}}function B_(e){return e.HOME??e.USERPROFILE??""}function W_(e){let t=e[Xe];if(t!==void 0&&t!=="")return Or(dn(e,""),Kn);let n=B_(e);return n===""?"":Or(dn(e,n),Kn)}function mu(e){let t=Tr(e)?e.code:void 0;return typeof t=="string"&&t!==""?t:e instanceof Error?e.name:"Error"}function je(e,t,n,o){try{let r=W_(e);if(r==="")return;br.mkdirSync(Or(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:mu(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});br.appendFileSync(r,s+`
211
211
  `)}catch{process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
212
- `)}}var cu=!1;function ut(e,t){if(!(cu||e[Os]!==t))throw cu=!0,new Error("injected fault at "+t)}function lu(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=Fe.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 ie(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function C_(e,t){let n=t.toLowerCase();return ie(e.nativeTools.shell,n)||ie(Ge.shell,n)?"shell":ie(e.nativeTools.read,n)||ie(Ge.read,n)?"read":ie(e.nativeTools.grep,n)||ie(Ge.grep,n)?"grep":ie(e.nativeTools.webfetch,n)||ie(Ge.fetch,n)?"fetch":null}function k_(e,t){let n=t.toLowerCase();return bs.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function D_(e){try{let t=hr.statSync(e);return t.isFile()&&t.size>ce}catch{return!1}}function L_(e,t,n){if((t.offset??null)!==null||(t.limit??null)!==null)return!1;let o=Array.isArray(t[Se])?t[Se].filter(r=>typeof r=="string"):[];return[On(t,he),...o].some(r=>r!==""&&D_(iu(n,r))&&!ln(e,iu(n,r))&&!Le(e,n,r))}function dt(e,t,n,o=""){let r=ue(e),s=()=>r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"});try{if(!br(t)||!k_(r,On(t,ms)))return s();let i=On(t,gs);if(i===""||i.includes(It))return s();let c=C_(r,i);if(c===null)return s();let l=On(t,Ss)||o;if(c==="read"&&!L_(e,y_(t),l))return s();let a=c==="read"?Bn.read:Bn[c],d=L(a,r.toolNamePrefix)+`
213
- `+Ts(au(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:w_,writeSync:P_}=process.getBuiltinModule("node:fs"),uu=65536;function M_(e){let t=Buffer.allocUnsafe(uu);return new Promise(n=>{let o=()=>{w_(0,t,0,uu,null,(r,s)=>{if(r)return n(r.code==="EOF");if(s===0)return n(!0);e.push(Buffer.from(t.subarray(0,s))),o()})};o()})}async function Or(){let e=[];if(!await M_(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function Tr(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=P_(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{lstatSync:U_,readFileSync:H_}=process.getBuiltinModule("node:fs"),A={kind:"allow"},G_={stdout:"",exitCode:0},B_=48;function W_(e){return Ue.includes(e)}function ft(e){return e instanceof Error?e.message:String(e)}function xt(e){return typeof e=="string"?e:""}async function pu(e,t,n){if(!W_(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
214
- `),G_;let o=ue(e),r=(a,d,u)=>(Me(n,e,a,d),process.stderr.write(u??"hooks: "+a+" failed: "+ft(d)+`
215
- `),dt(e,t,d));if(lu(process.version))return r("node",new T("NODE_TOO_OLD",{v:process.version}));let s;try{ut(n,"decode"),s=o.decode(t)}catch(a){return r("decode",a)}if(s.event==="Stop")return o.encode(s,A);let i;try{ut(n,"project");let a=e==="vscode"?[Tt,s.cwd]:process.argv;i=dl(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")+" "+ft(a)+`
216
- `)}let c,l={};try{ut(n,"policy"),c=await X_(s,o,i,n,l)}catch(a){return r("store",a)}try{ut(n,"encode");let a=o.encode(s,c);return l.run?.(!0),a}catch(a){return l.run?.(!1),r("encode",a)}}function X_(e,t,n,o,r){switch(e.event){case"SessionStart":return K_(e,t,n);case"UserPromptSubmit":return Y_(e,t,n);case"PreToolUse":return eE(e,t,n,o);case"PostToolUse":return sE(e,t,n,o,r);case"PreCompact":return _E(e,t,n);case"Usage":return EE(e,n)}return Promise.resolve(A)}function _u(e,t){return e.split(Rs).join(t.toolNamePrefix)}function Ar(e,t,n){return n.compactSummary==="host"?L(Wr,n.toolNamePrefix):jl(or(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function K_(e,t,n){if(e.source==="compact"&&Yt(t)&&Eu(await N(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await N(n);return bn(r,e.sessionId,qn)?{kind:"hint",text:Ar(r,e,t),onceKey:qn}:A}let o=await N(n);return t.compactDelivery==="opencode-cache"&&pn(o,Ct+e.sessionId)!==null?{kind:"hint",text:Ar(o,e,t),onceKey:Vn}:bn(o,e.sessionId,We)?{kind:"hint",text:_u(eo,t),onceKey:We}:A}async function Y_(e,t,n){let o=e.prompt??"",r=await q_(e,t,n);if(Sn(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}),Q_(e,n,o),t.compactDelivery==="pending-flag"){let s=await N(n);if(pn(s,Ct+e.sessionId)!==null)return{kind:"hint",text:Ar(s,e,t),onceKey:Vn}}return r!==null?r:J_(e,t,n,o)}async function q_(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await N(n);return bl(o,e.sessionId)||!bn(o,e.sessionId,We)||!Sl(o,n.worktree,e.agent)?null:{kind:"hint",text:_u(eo,t),onceKey:We}}function Eu(e,t){t!==""&&z(e,$n+t,zn)}function V_(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function z_(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}async function J_(e,t,n,o){if(!Yt(t)||e.sessionId==="")return A;let r=await N(n);if(oe(r,$n+e.sessionId)===null)return A;let s=Vs+e.sessionId,i=V_(oe(r,s)),c=Ks+e.sessionId,l=z_(oe(r,c)),a=wl(r,e.sessionId,Ll(o),qs),d=vl(hl(r,e.sessionId,n.worktree,Xs),o,new Set(i),a,new Set(l));return d.text===""?A:(d.seqs.length>0&&z(r,s,JSON.stringify([...i,...d.seqs])),d.units!==void 0&&z(r,c,JSON.stringify([...l,...d.units])),{kind:"hint",text:d.text,onceKey:zs})}function gu(e){return Lt+":"+wt+":"+e}function $_(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 Q_(e,t,n){if(e.sessionId==="")return;let o=gu(e.sessionId);N(t).then(r=>{if(oe(r,o)===null)return;let s=pn(r,o),i=s===null?null:$_(s);if(i===null)return;let c=su(n,i.labels,i.seq);c!==null&&mu(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+ft(r)+`
217
- `)})}function mu(e,t,n,o){for(let r of o)_n(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:to,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}),mr(e,n,t.sessionId,Lt,r.body,"text")}function Z_(e,t,n,o){let r=ou(o),s=r.length===0?ru(n.input):[];r.length===0&&s.length===0||N(t).then(i=>{if(r.length>0)return mu(i,e,t,r);let c=or(i,e.sessionId,"prompt"),l=c[c.length-1];l===void 0||e.sessionId===""||z(i,gu(e.sessionId),JSON.stringify({seq:l.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+ft(i)+`
218
- `)})}function hu(e,t,n){let o={projectDir:t.worktree,env:n};return e.agentTools!==void 0&&(o.manifestTools=e.agentTools),o}async function eE(e,t,n,o){let r=Ca(n.worktree,e.agent),s=nl(e,t,r,n),i=s;if(s.kind==="deny"&&Ce(e)&&!Su(s.reason,t)){let c=Go(e,hu(e,n,o)),l=jo(e,c),a=e.tool,d=c!==null||(e.agentType??"")!==""&&be(t);l==="B"&&a!==void 0&&Nr(a,t)?i=tE(e,t,s,r):l!=="A"&&d&&(i=A)}return i}function Nr(e,t){return e.canonicalName===Gs||t.nativeTools.shell.includes(e.name)}function Su(e,t){return e.startsWith(je)||e===L(At,t.toolNamePrefix)||e===L(yt,t.toolNamePrefix)}function Rr(e){return Buffer.from(e,"utf8").toString("base64url")}function tE(e,t,n,o){let r=e.tool;if(r===void 0||!Nr(r,t)||Su(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+xu(F_(process.argv[1]??""),$s)+'"',c=[Qs,i,Rr(s),Rr(JSON.stringify(o??[])),Rr(xt(r.input.description))].join(" ");return{kind:"deny",reason:Zs,rewritten:c}}function nE(e,t,n){return n?"toolerr":Bs.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":Nr(e,t)?"cmd":null}function yr(e){if(Array.isArray(e))return"["+e.map(yr).join(",")+"]";if(typeof e=="object"&&e!==null){let t=e;return"{"+Object.keys(t).filter(o=>t[o]!==void 0).sort().map(o=>JSON.stringify(o)+":"+yr(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function oE(e){let t=e.indexOf(`
219
- `),n=t<0?e:e.slice(0,t);if(!n.startsWith(Yn))return null;let o=0,r=0;for(let s of n.slice(Yn.length)){let i=s.charCodeAt(0)-B_;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function rE(e){for(let t of Ws)if(typeof e[t]=="string")return e[t];return null}async function sE(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(It))return A;let i=e.result??{isError:!1,bytes:0},c=dE(i,e.sessionId,o);i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(c)),s.canonicalName===to&&Z_(e,n,s,c);let l=nE(s,t,i.isError),a=f=>{if(l===null)return;let x=l==="cmd"?gl(s.canonicalName,xt(s.input.command)):l==="toolerr"?s.canonicalName+":"+yr(s.input):null;Sn(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:l,tool:s.canonicalName,key:x,path:rE(s.input),ok:i.isError?0:1,exit_code:oE(c),bytes:i.bytes,body:c,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:f})},d;try{d=await cE(e,t,n,o,s,i,c)}catch(f){throw a(i.bytes),f}let u=d;return r.run=f=>a(f&&u.kind==="replace"?Buffer.byteLength(u.output):i.bytes),d}function iE(e,t,n){if(!Nn.includes(t.canonicalName))return!1;let o=he.map(r=>t.input[r]).find(r=>typeof r=="string"&&r!=="");return o!==void 0&&Le(e.agent,e.cwd,o,n)}async function cE(e,t,n,o,r,s,i){if(s.bytes<=wr||aE(r)||iE(e,r,o)||s.keep===!0||!be(t))return A;let c;if(Ce(e)){if(jo(e,Go(e,hu(e,n,o)))==="A")return A;c=Js+r.canonicalName+":"+String(e.turn??0)}else c=xE(r,e);let l=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url].map(xt).find(_=>_.trim()!=="")??"",a=hn(i,"text",Hr),d=await N(n),u;s.bytes<=Lr?(u=mr(d,n,e.sessionId,c,i,"text",a).sourceId,cr(d,u,e.sessionId,ar(i))):(u=sr(d,bu(n,e.sessionId,c),a),pE(n,e.sessionId,u,c,i,a));let f=Dl(u),x=await fE(n,e.sessionId),p=x.trim()===""?void 0:l+" "+x,g=Fr(l,f,s.bytes,t.toolNamePrefix,tu(l,x,i)),E=lE(g,Er(l,c)),h=Jl(i,p??l,Ur);if(h!==null)return{kind:"replace",output:fu(h,g)};let S=Yl(a,l,E,c,p);return{kind:"replace",output:S.more!==null?fu(S.text,g):S.text}}function aE(e){return Nn.includes(e.canonicalName)&&Pr.some(t=>e.input[t]!==void 0&&e.input[t]!==null)}function fu(e,t){return e===""?t:e+`
220
- `+t}function lE(e,t){return Math.max(0,Mr+Buffer.byteLength(`
221
- `+t)-1-Buffer.byteLength(e))}function uE(e,t,n){if(t===""||t.includes(du)||t.includes("/"))return!1;let o=xu(q(n,H(n)??""),Ot),r=v_(o,j_(e)).split(du);if(r.length!==4||r.includes("..")||r.includes("")||r[1]!==t||r[2]!==oi)return!1;let s=U_(e);return s.isFile()&&s.size<=ri&&Ka(o,e)}function dE(e,t,n){let o=e.text??"";if(e.persistedPath===void 0)return o;try{return uE(e.persistedPath,t,n)?H_(e.persistedPath,"utf8"):(Me(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 fE(e,t){try{return ml(await N(e),t)}catch{return""}}function xE(e,t){let n=xt(e.input.command)??xt(e.input.file_path)??"",o=n.indexOf(`
222
- `);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,Zr)+"#"+(e.callId??String(t.turn??0))}function pE(e,t,n,o,r,s){N(e).then(i=>{Il(i,n,bu(e,t,o),s,ar(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+ft(i)+`
223
- `)})}function bu(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function _E(e,t,n){let o=await N(n);return z(o,Ct+e.sessionId,zn),Yt(t)&&Eu(o,e.sessionId),A}function EE(e,t){return Sn(t,e.sessionId,{session_id:e.sessionId,worktree:t.worktree,agent:e.agent,kind:"cost",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:0,body:"",turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),Promise.resolve(A)}var Tu={stdout:"",exitCode:0};function gE(e){return Ue.includes(e)}function Tn(e){process.exitCode=e.exitCode,e.stdout!==""&&Tr(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
224
- `)}function Ou(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
225
- `);try{return Me(r,e,n,o),dt(e,t,o)}catch{return Tu}}async function mE(e,t){let n=e.indexOf(Dt),o=n>=0?e[n+1]??"":"";if(!gE(o))return console.error("hooks: unknown "+Dt+" "+JSON.stringify(o)+". Fix: pass "+Dt+" with one of "+Ue.join(", ")+"."),Tn(Tu);let r;try{r=JSON.parse(await Or())}catch(s){return Tn(Ou(o,void 0,"stdin",s,t))}try{return Tn(await pu(o,r,t))}catch(s){return Tn(Ou(o,r,"load",s,t))}}mE(process.argv.slice(2),process.env);export{mE as main};
212
+ `)}}var gu=!1;function gt(e,t){if(!(gu||e[ks]!==t))throw gu=!0,new Error("injected fault at "+t)}function hu(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=We.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 ce(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function X_(e,t){let n=t.toLowerCase();return ce(e.nativeTools.shell,n)||ce(qe.shell,n)?"shell":ce(e.nativeTools.read,n)||ce(qe.read,n)?"read":ce(e.nativeTools.grep,n)||ce(qe.grep,n)?"grep":ce(e.nativeTools.webfetch,n)||ce(qe.fetch,n)?"fetch":null}function K_(e,t){let n=t.toLowerCase();return Cs.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function Y_(e){try{let t=br.statSync(e);return t.isFile()&&t.size>le}catch{return!1}}function q_(e,t,n){if((t.offset??null)!==null||(t.limit??null)!==null)return!1;let o=Array.isArray(t[Re])?t[Re].filter(r=>typeof r=="string"):[];return[Nn(t,Te),...o].some(r=>r!==""&&Y_(Eu(n,r))&&!pn(e,Eu(n,r))&&!He(e,n,r))}function he(e){try{return te(e).encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"})}catch{return{stdout:"",exitCode:0}}}function mt(e,t,n,o=""){let r=te(e);try{if(!Tr(t)||!K_(r,Nn(t,ys)))return he(e);let s=Nn(t,As);if(s===""||s.includes(wt))return he(e);let i=X_(r,s);if(i===null)return he(e);let c=Nn(t,Is)||o;if(i==="read"&&!q_(e,G_(t),c))return he(e);let a=i==="read"?Yn.read:Yn[i],l=L(a,r.toolNamePrefix)+`
213
+ `+Ds(mu(n),r.toolNamePrefix);return r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:c,turn:0},{kind:"deny",reason:l})}catch{return{stdout:"",exitCode:0}}}var{read:z_,writeSync:V_}=process.getBuiltinModule("node:fs"),Su=65536;function J_(e){let t=Buffer.allocUnsafe(Su);return new Promise(n=>{let o=()=>{z_(0,t,0,Su,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 Rr(){let e=[];if(!await J_(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function Ar(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=V_(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{lstatSync:$_,readFileSync:Q_}=process.getBuiltinModule("node:fs"),y={kind:"allow"},tE={stdout:"",exitCode:0},nE=48;function oE(e){return Ge.includes(e)}function ht(e){return e instanceof Error?e.message:String(e)}function St(e){return typeof e=="string"?e:""}async function Ru(e,t,n){if(!oE(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
214
+ `),tE;let o=te(e),r=(u,d,f)=>{je(n,e,u,d),process.stderr.write(f??"hooks: "+u+" failed: "+ht(d)+`
215
+ `)},s=(u,d,f)=>(r(u,d,f),mt(e,t,d));if(hu(process.version)){let u=new R("NODE_TOO_OLD",{v:process.version});return o.installMode==="in-process"?s("node",u):(r("node",u),he(e))}let i;try{gt(n,"decode"),i=o.decode(t)}catch(u){return s("decode",u)}if(i.event==="Stop")return o.encode(i,y);let c;try{gt(n,"project");let u=e==="vscode"?[It,i.cwd]:process.argv;c=bl(e,{env:n,argv:u,cwd:i.cwd,piCwd:e==="pi"?i.cwd:void 0})}catch(u){return s("project",u,"hooks: no project: "+String(u.code??"ERROR")+" "+ht(u)+`
216
+ `)}let a,l={};try{gt(n,"policy"),a=await rE(i,o,c,n,l)}catch(u){return s("store",u)}try{gt(n,"encode");let u=o.encode(i,a);return l.run?.(!0),u}catch(u){return l.run?.(!1),s("encode",u)}}function rE(e,t,n,o,r){switch(e.event){case"SessionStart":return sE(e,t,n);case"UserPromptSubmit":return iE(e,t,n);case"PreToolUse":return pE(e,t,n,o);case"PostToolUse":return hE(e,t,n,o,r);case"PreCompact":return kE(e,t,n);case"Usage":return DE(e,n)}return Promise.resolve(y)}function Au(e,t){return e.split(Ls).join(t.toolNamePrefix)}function Nr(e,t,n){return n.compactSummary==="host"?L(zr,n.toolNamePrefix):Jl(sr(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function sE(e,t,n){if(e.source==="compact"&&$t(t)&&yu(await N(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await N(n);return yn(r,e.sessionId,$n)?{kind:"hint",text:Nr(r,e,t),onceKey:$n}:y}let o=await N(n);return t.compactDelivery==="opencode-cache"&&hn(o,Pt+e.sessionId)!==null?{kind:"hint",text:Nr(o,e,t),onceKey:Qn}:yn(o,e.sessionId,Ve)?{kind:"hint",text:Au(ro,t),onceKey:Ve}:y}async function iE(e,t,n){let o=e.prompt??"",r=await cE(e,t,n);if(An(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}),fE(e,n,o),t.compactDelivery==="pending-flag"){let s=await N(n);if(hn(s,Pt+e.sessionId)!==null)return{kind:"hint",text:Nr(s,e,t),onceKey:Qn}}return r!==null?r:uE(e,t,n,o)}async function cE(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await N(n);return Dl(o,e.sessionId)||!yn(o,e.sessionId,Ve)||!kl(o,n.worktree,e.agent)?null:{kind:"hint",text:Au(ro,t),onceKey:Ve}}function yu(e,t){t!==""&&V(e,to+t,Zn)}function aE(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function lE(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 uE(e,t,n,o){if(!$t(t)||e.sessionId==="")return y;let r=await N(n);if(re(r,to+e.sessionId)===null)return y;let s=ni+e.sessionId,i=aE(re(r,s)),c=Zs+e.sessionId,a=lE(re(r,c)),l=Wl(r,e.sessionId,Bl(o),ti),u=Vl(Cl(r,e.sessionId,n.worktree,Qs),o,new Set(i),l,new Set(a));return u.text===""?y:(u.seqs.length>0&&V(r,s,JSON.stringify([...i,...u.seqs])),u.units!==void 0&&V(r,c,JSON.stringify([...a,...u.units])),{kind:"hint",text:u.text,onceKey:oi})}function Nu(e){return Ht+":"+Ft+":"+e}function dE(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 fE(e,t,n){if(e.sessionId==="")return;let o=Nu(e.sessionId);N(t).then(r=>{if(re(r,o)===null)return;let s=hn(r,o),i=s===null?null:dE(s);if(i===null)return;let c=_u(n,i.labels,i.seq);c!==null&&Iu(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+ht(r)+`
217
+ `)})}function Iu(e,t,n,o){for(let r of o)Sn(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:so,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}),Sr(e,n,t.sessionId,Ht,r.body,"text")}function xE(e,t,n,o){let r=xu(o),s=r.length===0?pu(n.input):[];r.length===0&&s.length===0||N(t).then(i=>{if(r.length>0)return Iu(i,e,t,r);let c=sr(i,e.sessionId,"prompt"),a=c[c.length-1];a===void 0||e.sessionId===""||V(i,Nu(e.sessionId),JSON.stringify({seq:a.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+ht(i)+`
218
+ `)})}function Cu(e,t,n){let o={projectDir:t.worktree,env:n};return e.agentTools!==void 0&&(o.manifestTools=e.agentTools),o}async function pE(e,t,n,o){let r=va(n.worktree,e.agent),s=fl(e,t,r,n),i=s;if(s.kind==="deny"&&Pe(e)&&!ku(s.reason,t)){let c=Wo(e,Cu(e,n,o)),a=Bo(e,c),l=e.tool,u=c!==null||(e.agentType??"")!==""&&Ae(t);a==="B"&&l!==void 0&&kr(l,t)?i=_E(e,t,s,r):a!=="A"&&u&&(i=y)}return i}function kr(e,t){return e.canonicalName===Vs||t.nativeTools.shell.includes(e.name)}function ku(e,t){return e.startsWith(Ye)||e===L(kt,t.toolNamePrefix)||e===L(Dt,t.toolNamePrefix)}function yr(e){return Buffer.from(e,"utf8").toString("base64url")}function _E(e,t,n,o){let r=e.tool;if(r===void 0||!kr(r,t)||ku(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+Cr(Tu(process.argv[1]??""),si)+'"',c=[ii,i,yr(s),yr(JSON.stringify(o??[])),yr(St(r.input.description))].join(" ");return{kind:"deny",reason:ci,rewritten:c}}function EE(e,t,n){return n?"toolerr":Js.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":kr(e,t)?"cmd":null}function Ir(e){if(Array.isArray(e))return"["+e.map(Ir).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)+":"+Ir(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function gE(e){let t=e.indexOf(`
219
+ `),n=t<0?e:e.slice(0,t);if(!n.startsWith(Jn))return null;let o=0,r=0;for(let s of n.slice(Jn.length)){let i=s.charCodeAt(0)-nE;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function mE(e){for(let t of $s)if(typeof e[t]=="string")return e[t];return null}async function hE(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(wt))return y;let i=e.result??{isError:!1,bytes:0},c=yE(i,e.sessionId,o);i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(c)),s.canonicalName===so&&xE(e,n,s,c);let a=EE(s,t,i.isError),l=f=>{if(a===null)return;let x=a==="cmd"?Nl(s.canonicalName,St(s.input.command)):a==="toolerr"?s.canonicalName+":"+Ir(s.input):null;An(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:a,tool:s.canonicalName,key:x,path:mE(s.input),ok:i.isError?0:1,exit_code:gE(c),bytes:i.bytes,body:c,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:f})},u;try{u=await bE(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}function SE(e,t,n){if(!Rt.includes(t.canonicalName))return!1;let o=Te.map(r=>t.input[r]).find(r=>typeof r=="string"&&r!=="");return o!==void 0&&He(e.agent,e.cwd,o,n)}async function bE(e,t,n,o,r,s,i){if(s.bytes<=Ur||TE(r)||SE(e,r,o)||s.keep===!0||!Ae(t))return y;let c,a={ctx:!0,shell:!0,read:!1};if(Pe(e)){let T=Wo(e,Cu(e,n,o)),C=Bo(e,T),ae=Se=>T!==null&&Se.some(be=>T.includes(be));a={ctx:C==="A",shell:ae(t.nativeTools.shell),read:Rt.includes(r.canonicalName)&&ae(t.nativeTools.read??[])},c=ri+r.canonicalName+":"+(r.callId??String(e.turn??0))}else c=IE(r,e);let l=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url,r.name].map(St).find(T=>T.trim()!=="")??r.canonicalName,u=Rn(i,"text",jr),d=await N(n),f;s.bytes<=Mr?(f=Sr(d,n,e.sessionId,c,i,"text",u).sourceId,lr(d,f,e.sessionId,ur(i))):(f=cr(d,Du(n,e.sessionId,c),u),CE(n,e.sessionId,f,c,i,u));let x=Gl(f),p=await NE(n,e.sessionId),g=p.trim()===""?void 0:l+" "+p,E=a.ctx?Gr(l,x,s.bytes,t.toolNamePrefix,du(l,p,i)):Br(x,s.bytes,a.read),h=RE(E,mr(l,c)),S=E+(a.shell&&e.agent===is?OE(x,l,n):""),_=iu(i,g??l,vr);if(_!==null)return{kind:"replace",output:Ou(_,S)};let m=nu(u,l,h,c,g);return{kind:"replace",output:m.more!==null?Ou(m.text,S):m.text}}function OE(e,t,n){let o=Buffer.byteLength(t,"utf8")>$e?"":t;return Wr(Cr(Tu(process.argv[1]??""),ss),e,o,n.worktree)}function TE(e){return Rt.includes(e.canonicalName)&&Hr.some(t=>e.input[t]!==void 0&&e.input[t]!==null)}function Ou(e,t){return e===""?t:e+`
220
+ `+t}function RE(e,t){return Math.max(0,Fr+Buffer.byteLength(`
221
+ `+t)-1-Buffer.byteLength(e))}function AE(e,t,n){if(t===""||t.includes(bu)||t.includes("/"))return!1;let o=Cr(q(n,H(n)??""),Nt),r=Z_(o,eE(e)).split(bu);if(r.length!==4||r.includes("..")||r.includes("")||r[1]!==t||r[2]!==di)return!1;let s=$_(e);return s.isFile()&&s.size<=fi&&tl(o,e)}function yE(e,t,n){let o=e.text??"";if(e.persistedPath===void 0)return o;try{return AE(e.persistedPath,t,n)?Q_(e.persistedPath,"utf8"):(je(n,"claude-code","persisted-output",new Error("persisted output path is outside this session's tool-results dir or too large; kept the head")),o)}catch{return o}}async function NE(e,t){try{return Il(await N(e),t)}catch{return""}}function IE(e,t){let n=St(e.input.command)??St(e.input.file_path)??"",o=n.indexOf(`
222
+ `);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,rs)+"#"+(e.callId??String(t.turn??0))}function CE(e,t,n,o,r,s){N(e).then(i=>{Fl(i,n,Du(e,t,o),s,ur(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+ht(i)+`
223
+ `)})}function Du(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function kE(e,t,n){let o=await N(n);return V(o,Pt+e.sessionId,Zn),$t(t)&&yu(o,e.sessionId),y}function DE(e,t){return An(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 wu={stdout:"",exitCode:0};function LE(e){return Ge.includes(e)}function In(e){process.exitCode=e.exitCode,e.stdout!==""&&Ar(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
224
+ `)}function Lu(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
225
+ `);try{return je(r,e,n,o),mt(e,t,o)}catch{return wu}}async function wE(e,t){let n=e.indexOf(Ut),o=n>=0?e[n+1]??"":"";if(!LE(o))return console.error("hooks: unknown "+Ut+" "+JSON.stringify(o)+". Fix: pass "+Ut+" with one of "+Ge.join(", ")+"."),In(wu);let r;try{r=JSON.parse(await Rr())}catch(s){return In(Lu(o,void 0,"stdin",s,t))}try{return In(await Ru(o,r,t))}catch(s){return In(Lu(o,r,"load",s,t))}}wE(process.argv.slice(2),process.env);export{wE as main};