context-mode 2.2.2 → 2.2.3

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 ze=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode","omp"];var re="context-mode",Lt=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function P(e,t){if(t==="")return e;let n=e;for(let o of Lt)n=n.split(o).join(t+o);return n}var xe=16384;var qr=2048;var zr=640,Bn="</context_mode_state>",Wn=1048576,Vr=65536,Kr=4096,hd="CTX_REPLACE_TRIGGER_BYTES";function Sd(e){if(e===void 0||e.trim()==="")return Kr;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Kr}var Jr=Sd(process.env[hd]),Je=Object.freeze(["Read","view"]),$r=Object.freeze(["offset","limit","view_range"]),Qr=Object.freeze(["Skill"]),Zr=96,es=256,Xn=48;function ts(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 ns(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 os(e,t,n,o){return" Or run: node "+Gn(e)+" "+t+" "+Gn(n)+" "+Gn(o)}function rs(e){return" The whole output is also in "+JSON.stringify(e)+"; Read it with offset and limit."}function Gn(e){return"'"+e.split("'").join("'\\''")+"'"}var ss=3,W=4096;var Kn=85,Yn=340,qn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var is=.7,cs=.7,as=.3,zn=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]),ls='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var bd=6e5;var H=5e3,us=250,ds="pending",fs=3e4,ps=1e3,wt="-wal",Pt="-shm",xs=".tmp",_s=["EACCES","EPERM","ENOSYS","ENOTSUP","EOPNOTSUPP"],Es=".publish",gs=["EEXIST","EPERM"],ms=5,Mt=255,hs=11,Ss=26;var X=5e3;var Ut=0;var bs=16,$e=6;var Ht="projects",Os="context.db";var Vn=".git",Jn="worktree ",$n="gitdir: ",Ts="commondir",Rs="HEAD",Ft="--workspace-folder",vg=Object.freeze(["shell","powershell","javascript","typescript","python"]),As=Object.freeze(["sh","bash","zsh","dash","ksh","fish"]);var Ns=80;var jg=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var ys="search.mjs",Is="claude-code";var Gg=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),Bg=Object.freeze({zcode:"session_id"}),Qe="24.15.0",Cs="~/.context-mode",Ze="CONTEXT_MODE_DATA_DIR";var Ds="CONTEXT_MODE_REQUIRE_SECURITY",ks=".claude",et="agents",_e=".md",Ls="synced",vt="plugins",ws="installed_plugins.json",Ie=":",Ps="@";var Wg=Object.freeze(["local","project"]),Xg=Object.freeze({local:0,project:1,user:2,managed:2}),Qn="---",Ms="tools",Us="disallowedTools",se="mcp__",Hs="toolu_plugin_",Ce="__",Fs="mcp_",vs="_-.:",Yr=10;function Od(e){if(e===void 0||e.trim()==="")return Yr;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Yr}var Kg=Od(process.env.CTX_MCP_HINT_EVERY);var K=32;var js=Object.freeze([".agents","skills"]),Zn="context-mode: ",Gs=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),Bs=" sends its body into the conversation.",Ws="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",Xs="Tool: ",Ks="state what you need",Ys="ctx_execute",qs=Object.freeze(["ctx_index","ctx_search"]),tt="Blocked by security policy: matches deny pattern ",jt="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",Gt="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",eo="hook-errors.log";var zs=Object.freeze(["tool_name","toolName","tool"]),Vs=Object.freeze(["hook_event_name","hookEventName","type"]),Js=Object.freeze(["tool_input","toolArgs","input","args"]),$s=Object.freeze(["cwd","directory"]),Qs=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),Zs="CM_HOOK_FAULT",Yg=Object.freeze(["decode","project","policy","store","encode"]),nt=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 ei(e,t){return`${Zn}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var to=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 qg=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),zg=Object.freeze(["status"]),Vg=Object.freeze(["--version","-v"]),Jg=Object.freeze(["cp","mv","rm"]),$g=Object.freeze(["-v","--verbose"]),M=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),ti="{prefix}",ni=", then ",oi="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",ri=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),si=Object.freeze(["curl","wget"]),ii=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),ci=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),ai="-D",li=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),ot="fetch(",ui="'\"`",di="http",fi=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),pi=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),xi=Object.freeze(["head","tail"]),no=Object.freeze(["-n","-c","--lines","--bytes"]),Bt="sed",_i=Object.freeze(["-n","--quiet","--silent"]),Ei="jq",Ee=Object.freeze(["file_path","absolute_path","path","filePath"]),De="filePaths",oo=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]}]}}),ro=12,Ve=Object.freeze(["png","jpeg","gif","webp"]),kt=Object.freeze([...Ve,"pdf"]),gi=Object.freeze({"claude-code":kt,gemini:kt,qwen:kt,opencode:kt,pi:Ve,omp:Ve,vscode:Ve,zcode:Ve,"copilot-cli":[],codex:[],kiro:[]}),Wt="ctx_",mi="Bash",hi=Object.freeze(["Write","Edit"]),Si=Object.freeze(["file_path","path"]),so="Exit code ",rt="resume-hint",bi="compact-state",io="pending-compact",Xt="pending_compact:",Oi="1",st=2048,co=5,Ti=340,ao="compacted:",Ri="recall_units_seen:",Ai=8,Kt=64,Ni=64,yi="recall_seen:",lo="<context_mode_recall>",uo="</context_mode_recall>",Ii="recall",fo="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",Ci="subagent:",Di="run.mjs",ki="node",Li=`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.`,Yt="--agent",wi=1e3;var Pi=5;var Qg=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var Zg=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."]),em=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),tm=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 nm=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),om=Object.freeze(["ctx_index","ctx_search"]);var rm=Object.freeze(["session","source","project"]);var qt="decision";var po="AskUserQuestion",Mi="answers",zt="option",Ui=" | ",Td="https://github.com/mksglu/context-mode.git";var sm=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),im=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 it=256;var Rd="ctx_doctor:report";var cm=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(Rd)}})`;var am=Object.freeze(["--tags","--refs"]),Ad="v*";var lm=`git ls-remote --tags --refs ${Td} "${Ad}"`;var um=`nvm install ${Qe.split(".")[0]}, or install it from https://nodejs.org`;var dm=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"],omp:[".omp"]});var fm=Object.freeze(["upgrade","uninstall"]);var pm=Object.freeze(["clone","--depth","1","--branch"]),xm=Object.freeze(["rev-parse","HEAD"]);var _m=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),Em=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var gm=Object.freeze(["shell","bash","sh"]),mm=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var Hi="tool-results",Fi=16*1024*1024;var hm=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 pe=e=>Object.freeze(e),Sm=Object.freeze([pe({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"}),pe({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"}),pe({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)"}),pe({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"}),pe({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"}),pe({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"}),pe({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 bm=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,omp:null}),Om=Object.freeze(["PreToolUse","PostToolUse"]);var Tm=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var Rm=Object.freeze(["features","hooks"]);var Am=Object.freeze(["",wt,Pt]);var Nd=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",omp:"omp plugin upgrade context-mode",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 Nm=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 ym=Object.freeze(["hooks","codex"]),Im=Object.freeze(["pretooluse.mjs","posttooluse.mjs","sessionstart.mjs","precompact.mjs","userpromptsubmit.mjs","stop.mjs"]);var Cm=Object.freeze([".mjs",".sh"]);var yd="npm:context-mode";var Vt="CLAUDE_CONFIG_DIR";var vi="CODEX_HOME",ji="COPILOT_HOME",Gi="GEMINI_CLI_HOME",Bi="KIRO_HOME",Wi="OPENCODE_CONFIG_DIR",xo="APPDATA",Jt=Object.freeze(["Code","User"]),$t="XDG_CONFIG_HOME";var Id="mcp.json",Dm=Object.freeze(["agents","default.json"]);var km=Object.freeze(["steering","KIRO.md"]),Xi="agent",Lm=Object.freeze(["opencode.jsonc","opencode.json"]);var Cd=`${re}@`,Dd="@",wm=`${Cd}latest`,Pm=`${yd}${Dd}latest`;var Mm=Object.freeze(["content","platform.json"]);var Ki="custom",Yi="PI_CODING_AGENT_DIR";var kd=Object.freeze(["/","\\"]),Ld="${/}",Um=Object.freeze([...kd,Ld]),U=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"}),Hm=Object.freeze([U.statusLine,U.vscodeMcp,U.dataDirShared,U.tmpFile,U.kiroSteering,U.piGit,U.opencodeGit,U.projectLink]),Fm=Object.freeze([U.dataDir,U.dataRoot]);var vm=re+"_";var jm=Object.freeze(["opencode","plugin.js"]);var wd=Object.freeze(["features","mcp"]),Pd="omit_tools_from",Md=Object.freeze(["deferred"]),Ud="default_tools_approval_mode",Hd="approve",Gm=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",re],fields:{[Pd]:Md,[Ud]:Hd}},vscode:{file:[Id],key:["servers",re]},kiro:{file:[".kiro","settings","mcp.json"],key:["mcpServers",re]},zcode:{file:[".zcode","cli","config.json"],key:["mcp","servers",re],fields:{type:"stdio",enabled:!0,timeoutMs:bd},also:[[wd,!0]]}});var Bm=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),Fd="Environment: ";var vd="Docs: ";var jd="Report file: ",Gd="File it: ",Bd="Or open: ",Wd="Rules: ",Xd=" --",Wm=Object.freeze([Fd,vd,jd,Gd,Xd.trim(),Bd,Wd]),qi="mksglu/context-mode",Kd="agent-report.yml",Xm=`https://github.com/${qi}/blob/main/.github/AGENT_ISSUE.md`,Km=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 Ym=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var qm=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"]),zm=Object.freeze(["node","git","sh"]),Vm=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var Jm=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"],omp:["omp plugin install 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"]}),$m=`https://github.com/${qi}/issues/new?template=${Kd}`;import{dirname as rd,join as Wr,relative as JE,resolve as sd,sep as td}from"node:path";var _o="mcp__plugin_context-mode_context-mode__",$i=Object.freeze(["Bash","PowerShell"]),Yd="PowerShell",qd="Bash",zd=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],Vd="PostToolUseFailure",zi="mcp__",Vi="__",Jd={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function $d(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(zi))return e;let n=e.slice(zi.length),o=n.indexOf(Vi);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+Vi.length)}function Qd(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return Qi(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=Eo(e);if(t!==null)return t.text}return JSON.stringify(e)}function Eo(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:Zd(n.file,o)})}:tf(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 Qe=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode","omp"];var ce="context-mode",Mt=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function U(e,t){if(t==="")return e;let n=e;for(let o of Mt)n=n.split(o).join(t+o);return n}var Y=16384;var os=2048;var rs=640,Vn="</context_mode_state>",Jn=1048576,ss=65536,is=4096;var ge=Object.freeze(["Read","view"]),cs=Object.freeze(["offset","limit","view_range"]),as=Object.freeze(["Skill"]),ls=96,us=256,zn=48;function ds(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 fs(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 ps(e,t,n,o){return" Or run: node "+qn(e)+" "+t+" "+qn(n)+" "+qn(o)}function xs(e){return" The whole output is also in "+JSON.stringify(e)+"; Read it with offset and limit."}function qn(e){return"'"+e.split("'").join("'\\''")+"'"}var _s=3,q=4096;var $n=85,Qn=340,Zn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var Es=.7,gs=.7,ms=.3,eo=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]),hs='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var vd=6e5;var v=5e3,et=250,Ss="pending",Os=3e4,bs=1e3,Ut="-wal",Ht="-shm",Ts=".tmp",Rs=["EACCES","EPERM","ENOSYS","ENOTSUP","EOPNOTSUPP"],As=".publish",Ns=["EEXIST","EPERM"],ys=5,Ft=255,Is=11,Cs=26;var V=5e3;var vt=0;var Ds=16,tt=7;var jt="projects",ks="context.db";var to=".git",no="worktree ",oo="gitdir: ",Ls="commondir",Ps="HEAD",Gt="--workspace-folder",em=Object.freeze(["shell","powershell","javascript","typescript","python"]),ws=Object.freeze(["sh","bash","zsh","dash","ksh","fish"]);var Ms=80;var tm=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var Us="search.mjs",Hs="claude-code";var nm=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),om=Object.freeze({zcode:"session_id"}),nt="24.15.0",Fs="~/.context-mode",ot="CONTEXT_MODE_DATA_DIR";var vs="CONTEXT_MODE_REQUIRE_SECURITY",js=".claude",rt="agents",me=".md",Gs="synced",Bt="plugins",Bs="installed_plugins.json",De=":",Ws="@";var rm=Object.freeze(["local","project"]),sm=Object.freeze({local:0,project:1,user:2,managed:2}),ro="---",Xs="tools",Ks="disallowedTools",j="mcp__",Ys="toolu_plugin_",ke="__",qs="mcp_",Vs="_-.:",ns=10;function jd(e){if(e===void 0||e.trim()==="")return ns;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:ns}var im=jd(process.env.CTX_MCP_HINT_EVERY);var J=32;var Js=Object.freeze([".agents","skills"]),so="context-mode: ",zs=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),$s=" sends its body into the conversation.",Qs="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",Zs="Tool: ",ei="state what you need",ti="ctx_execute",ni=Object.freeze(["ctx_index","ctx_search"]),st="Blocked by security policy: matches deny pattern ",Wt="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",Xt="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",io="hook-errors.log";var oi=Object.freeze(["tool_name","toolName","tool"]),ri=Object.freeze(["hook_event_name","hookEventName","type"]),si=Object.freeze(["tool_input","toolArgs","input","args"]),ii=Object.freeze(["cwd","directory"]),ci=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),ai="CM_HOOK_FAULT",cm=Object.freeze(["decode","project","policy","store","encode"]),it=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 li(e,t){return`${so}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var co=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 am=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),lm=Object.freeze(["status"]),um=Object.freeze(["--version","-v"]),dm=Object.freeze(["cp","mv","rm"]),fm=Object.freeze(["-v","--verbose"]),H=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),ui="{prefix}",di=", then ",fi="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",pi=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),xi=Object.freeze(["curl","wget"]),_i=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),Ei=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),gi="-D",mi=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),ct="fetch(",hi="'\"`",Si="http",Oi=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),bi=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),Ti=Object.freeze(["head","tail"]),ao=Object.freeze(["-n","-c","--lines","--bytes"]),Kt="sed",Ri=Object.freeze(["-n","--quiet","--silent"]),Ai="jq",ae=Object.freeze(["file_path","absolute_path","path","filePath"]),Le="filePaths",lo=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]}]}}),uo=12,Ze=Object.freeze(["png","jpeg","gif","webp"]),wt=Object.freeze([...Ze,"pdf"]),Ni=Object.freeze({"claude-code":wt,gemini:wt,qwen:wt,opencode:wt,pi:Ze,omp:Ze,vscode:Ze,zcode:Ze,"copilot-cli":[],codex:[],kiro:[]}),Yt="ctx_",yi="Bash",Ii=Object.freeze(["Write","Edit"]),Ci=Object.freeze(["file_path","path"]),fo="Exit code ",at="resume-hint",Di="compact-state",po="pending-compact",qt="pending_compact:",ki="1",lt=2048,xo=5,Li=340,_o="compacted:",Eo="bet:",Vt="lostbet:",Pi="recall_units_seen:",wi=8,Jt=64,Mi=64,Ui="recall_seen:",go="<context_mode_recall>",mo="</context_mode_recall>",Hi="recall",ho="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",zt="subagent:",Fi="run.mjs",vi="node",ji=`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.`,$t="--agent",Gi=1e3;var Bi=5;var pm=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var xm=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."]),_m=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),Em=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 gm=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),mm=Object.freeze(["ctx_index","ctx_search"]);var hm=Object.freeze(["session","source","project"]);var Qt="decision";var So="AskUserQuestion",Wi="answers",Zt="option",Xi=" | ",Gd="https://github.com/mksglu/context-mode.git";var Sm=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),Om=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 ut=256;var Bd="ctx_doctor:report";var bm=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(Bd)}})`;var Tm=Object.freeze(["--tags","--refs"]),Wd="v*";var Rm=`git ls-remote --tags --refs ${Gd} "${Wd}"`;var Am=`nvm install ${nt.split(".")[0]}, or install it from https://nodejs.org`;var Nm=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"],omp:[".omp"]});var ym=Object.freeze(["upgrade","uninstall"]);var Im=Object.freeze(["clone","--depth","1","--branch"]),Cm=Object.freeze(["rev-parse","HEAD"]);var Dm=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),km=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var Lm=Object.freeze(["shell","bash","sh"]),Pm=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var Ki="tool-results",Yi=16*1024*1024;var wm=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 Ee=e=>Object.freeze(e),Mm=Object.freeze([Ee({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"}),Ee({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"}),Ee({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)"}),Ee({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"}),Ee({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"}),Ee({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"}),Ee({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 Um=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,omp:null}),Hm=Object.freeze(["PreToolUse","PostToolUse"]);var Fm=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var vm=Object.freeze(["features","hooks"]);var jm=Object.freeze(["",Ut,Ht]);var Xd=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",omp:"omp plugin upgrade context-mode",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 Gm=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 Bm=Object.freeze(["hooks","codex"]),Wm=Object.freeze(["pretooluse.mjs","posttooluse.mjs","sessionstart.mjs","precompact.mjs","userpromptsubmit.mjs","stop.mjs"]);var Xm=Object.freeze([".mjs",".sh"]);var Kd="npm:context-mode";var en="CLAUDE_CONFIG_DIR";var qi="CODEX_HOME",Vi="COPILOT_HOME",Ji="GEMINI_CLI_HOME",zi="KIRO_HOME",$i="OPENCODE_CONFIG_DIR",Oo="APPDATA",tn=Object.freeze(["Code","User"]),nn="XDG_CONFIG_HOME";var Yd="mcp.json",Km=Object.freeze(["agents","default.json"]);var Ym=Object.freeze(["steering","KIRO.md"]),Qi="agent",qm=Object.freeze(["opencode.jsonc","opencode.json"]);var qd=`${ce}@`,Vd="@",Vm=`${qd}latest`,Jm=`${Kd}${Vd}latest`;var zm=Object.freeze(["content","platform.json"]);var Zi="custom",ec="PI_CODING_AGENT_DIR";var Jd=Object.freeze(["/","\\"]),zd="${/}",$m=Object.freeze([...Jd,zd]),F=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"}),Qm=Object.freeze([F.statusLine,F.vscodeMcp,F.dataDirShared,F.tmpFile,F.kiroSteering,F.piGit,F.opencodeGit,F.projectLink]),Zm=Object.freeze([F.dataDir,F.dataRoot]);var eh=ce+"_";var th=Object.freeze(["opencode","plugin.js"]);var $d=Object.freeze(["features","mcp"]),Qd="omit_tools_from",Zd=Object.freeze(["deferred"]),ef="default_tools_approval_mode",tf="approve",nh=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",ce],fields:{[Qd]:Zd,[ef]:tf}},vscode:{file:[Yd],key:["servers",ce]},kiro:{file:[".kiro","settings","mcp.json"],key:["mcpServers",ce]},zcode:{file:[".zcode","cli","config.json"],key:["mcp","servers",ce],fields:{type:"stdio",enabled:!0,timeoutMs:vd},also:[[$d,!0]]}});var oh=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),nf="Environment: ";var of="Docs: ";var rf="Report file: ",sf="File it: ",cf="Or open: ",af="Rules: ",lf=" --",rh=Object.freeze([nf,of,rf,sf,lf.trim(),cf,af]),tc="mksglu/context-mode",uf="agent-report.yml",sh=`https://github.com/${tc}/blob/main/.github/AGENT_ISSUE.md`,ih=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 ch=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var ah=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"]),lh=Object.freeze(["node","git","sh"]),uh=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var dh=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"],omp:["omp plugin install 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"]}),fh=`https://github.com/${tc}/issues/new?template=${uf}`;import{dirname as bd,join as Zr,relative as pg,resolve as es,sep as hd}from"node:path";var bo="mcp__plugin_context-mode_context-mode__",sc=Object.freeze(["Bash","PowerShell"]),df="PowerShell",ff="Bash",pf=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],xf="PostToolUseFailure",nc="mcp__",oc="__",_f={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function Ef(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(nc))return e;let n=e.slice(nc.length),o=n.indexOf(oc);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+oc.length)}function gf(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return ic(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=To(e);if(t!==null)return t.text}return JSON.stringify(e)}function To(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:mf(n.file,o)})}:Sf(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 Zd(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 mf(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=ef(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 ef(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 Ji(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function tf(e){let t=e;return(t.mode==="content"||t.mode==="count")&&typeof t.content=="string"}function Qi(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 nf(e){let t=Qd(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)&&Ji(e)&&(o.shape=e),typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Ji(e)&&(Eo(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,Qi(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 ge(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=zd.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:$d(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=nf(r.tool_response)),i}function of(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:Eo(n);return n!==void 0&&o!==null?o.put(n,t):e.result?.blocks===!0?[{type:"text",text:t}]:t}function Y(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:of(e,t.output)}):{stdout:"",exitCode:0}}}var rf={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function sf(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 cf(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 rf[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function Zi(e){cf(e);let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===Vd,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=ge(n,"claude-code",_o,Jd);if(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,keep:!0}}if(o.tool!==void 0&&o.tool.name===Yd&&(o.tool.canonicalName=qd),o.cwd===""&&(o.cwd=process.env.CLAUDE_PROJECT_DIR||process.cwd()),o.event==="PostToolUse"&&o.tool!==void 0&&o.tool.callId===void 0){let r=typeof o.tool.input.command=="string"?o.tool.input.command:JSON.stringify(o.tool.input);o.tool.callId="h"+sf(o.tool.name+"\0"+r+"\0"+String(o.turn??0))}return o}function ec(e,t,n){return Y(e,t,!0)}var mo="mcp__context_mode__",lf={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"},go="Stop",uf={stdout:"",exitCode:0};function tc(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===go){let t=e;return{event:go,agent:"codex",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")}}return ge(e,"codex",mo,lf)}function nc(e,t,n){return e.event===go?uf:Y(e,t,!1)}var Zt="mcp_context-mode_",oc={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},rc={startup:"startup",resume:"resume",clear:"clear"},ff=["SessionStart","UserPromptSubmit","PostToolUse"],pf=["UserPromptSubmit","PreToolUse"],Qt={stdout:"",exitCode:0},xf=`the tool ran and succeeded; context-mode indexed its full output, and this is the part that answers the call:
12
- `;function N(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var sc={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function _f(e,t){if(e.startsWith(Zt))return e.slice(Zt.length);if(Object.hasOwn(sc,e))return sc[e];if(typeof t!="object"||t===null)return e;let n=t,o=N(n,"server_name"),r=N(n,"tool_name");return typeof o!="string"||typeof r!="string"?e:"mcp:"+o+":"+r}function Ef(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=N(n,"text");if(typeof o!="string")return;t.push(o)}return t.join("")}function gf(e){let t=typeof e=="object"&&e!==null?e:void 0,n=t===void 0?void 0:N(t,"llmContent"),o=e===void 0?"":typeof e=="string"?e:typeof n=="string"?n:Ef(n)??JSON.stringify(e),r=t===void 0?void 0:N(t,"error"),s={isError:r!=null,bytes:Buffer.byteLength(o),text:o};return mf(n)&&(s.keep=!0),s}function mf(e){return(Array.isArray(e)?e:[e]).some(n=>typeof n=="object"&&n!==null&&(Object.hasOwn(n,"inlineData")||Object.hasOwn(n,"fileData")))}var hf=["https://","http://"],Sf=`.,;:!?)]}>'"`,bf=`
13
- \r\f\v`;function Of(e){let t=[],n="";for(let o of e)bf.includes(o)?(n!==""&&t.push(n),n=""):n+=o;return n!==""&&t.push(n),t}function Tf(e){if(typeof e=="string")for(let t of Of(e)){let n=t.toLowerCase(),o=hf.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&&Sf.includes(r[r.length-1]);)r=r.slice(0,-1);return r}}function Rf(e,t){if(e==="web_fetch"&&N(t,"url")===void 0){let n=Tf(N(t,"prompt"));return n===void 0?t:{...t,url:n}}if(e==="read_many_files"&&N(t,"file_path")===void 0){let n=N(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 ic(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=N(t,"hook_event_name"),o=typeof n=="string"&&Object.hasOwn(oc,n)?oc[n]:void 0;if(o===void 0)throw new Error("gemini: unknown hook event "+String(n));let r={event:o,agent:"gemini",sessionId:String(N(t,"session_id")??""),cwd:String(N(t,"cwd")??"")},s=N(t,"source");o==="SessionStart"&&typeof s=="string"&&Object.hasOwn(rc,s)&&(r.source=rc[s]);let i=N(t,"prompt");if(o==="UserPromptSubmit"&&typeof i=="string"&&(r.prompt=i),o==="PreToolUse"||o==="PostToolUse"){let c=String(N(t,"tool_name")??""),a=N(t,"tool_input");r.tool={name:c,canonicalName:_f(c,N(t,"mcp_context")),input:Rf(c,typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{})}}return o==="PostToolUse"&&(r.result=gf(N(t,"tool_response"))),r}function cc(e,t,n){switch(t.kind){case"allow":return Qt;case"hint":return ff.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:Qt;case"deny":return pf.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
14
- `+t.reason}),exitCode:0}:Qt;case"replace":return e.event!=="PostToolUse"?Qt:{stdout:JSON.stringify({decision:"deny",reason:xf+t.output}),exitCode:0}}}var ho="mcp__context-mode__",Nf={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},ac={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},yf="PostToolUseFailure";function lc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===yf,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=ge(n,"qwen",ho,Nf);if(o.tool!==void 0&&Object.hasOwn(ac,o.tool.name)&&(o.tool.canonicalName=ac[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 uc(e,t,n){return Y(e,t,!1)}var tn="context-mode-",Cf={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}},dc={startup:"startup",resume:"resume",new:"startup"},Df={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"}},xc="success";function nn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var So=Object.freeze(["bash","powershell"]),fc=Object.fromEntries(So.map(e=>[e,"Bash"]));function kf(e){return e.startsWith(tn)?e.slice(tn.length):Object.hasOwn(fc,e)?fc[e]:e}var pc=e=>typeof e=="number"&&Number.isFinite(e);function Lf(e,t){let n=t.view_range;if(e!=="view"||!Array.isArray(n)||!pc(n[0]))return t;let o={...t,offset:n[0]};return pc(n[1])&&n[1]>=n[0]&&(o.limit=n[1]-n[0]+1),o}function wf(e){if(nn(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return nn(t)?t:{}}catch{return{}}}var Pf={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function Mf(e,t,n){let o=Pf[t],r=nn(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==xc,bytes:Buffer.byteLength(s),text:s}}var Uf=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function Hf(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:Uf.find(([t])=>Object.hasOwn(e,t))?.[1]}function _c(e){if(!nn(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=Hf(e),n=typeof t=="string"?Cf[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Df[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"&&dc[e.source]!==void 0&&(s.source=dc[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:kf(i),input:Lf(i,wf(e[o.args]))};s.tool=c}return r==="PostToolUse"&&(s.result=Mf(e[o.result],n.casing,n.failure)),s}var en={stdout:"",exitCode:0};function Ec(e,t,n){switch(t.kind){case"allow":return en;case"hint":return e.event==="PostToolUse"?en:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?en:{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"?en:{stdout:JSON.stringify({modifiedResult:{resultType:xc,textResultForLlm:t.output}}),exitCode:0}}}var on="mcp_context-mode_",Oc=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],gc="mcp_",mc="_",vf="new",bo=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),sn=Object.freeze(["read_file","view"]),Oo=Object.freeze(["fetch_webpage","web_fetch"]),hc=Object.fromEntries([...bo.map(e=>[e,"Bash"]),...sn.map(e=>[e,"Read"]),...Oo.map(e=>[e,"WebFetch"])]);function Tc(e){if(e.startsWith(on))return e.slice(on.length);if(Object.hasOwn(hc,e))return hc[e];if(!e.startsWith(gc))return e;let t=e.slice(gc.length),n=t.indexOf(mc);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+mc.length)}var ct=e=>typeof e=="number"&&Number.isFinite(e);function Rc(e,t,n){if(t==="Read"&&sn.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),ct(n.startLine)&&(o.offset=n.startLine),ct(n.startLine)&&ct(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&ct(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];ct(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 jf(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 Gf={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},Bf=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],Sc={new:"startup",startup:"startup",resume:"resume"},Wf="success";function rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xf(e){if(rn(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return rn(t)?t:{}}catch{return{}}}function Kf(e){let t=rn(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==Wf,bytes:Buffer.byteLength(n),text:n}}function bc(e,t){let n=typeof t=="string"?Gf[t]??Oc.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"&&Sc[e.source]!==void 0&&(o.source=Sc[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=Tc(r);o.tool={name:r,canonicalName:s,input:Rc(r,s,Xf(e.toolArgs))}}return n==="PostToolUse"&&(o.result=Kf(e.toolResult)),o}function Ac(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 bc(t,t.hookEventName);if(t.hook_event_name===void 0){let r=Bf.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return bc(t,r)}let n=Oc.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===vf&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=rn(t.tool_input)?t.tool_input:{},i=Tc(r);o.tool={name:r,canonicalName:i,input:Rc(r,i,s)}}return n==="PostToolUse"&&(o.result=jf(t.tool_response)),o}function Nc(e,t,n){return Y(e,t,!1)}var cn="mcp_context_mode_",yc="mcp_context-mode_",Ic={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},qf="prompt",zf="USER_PROMPT",Cc="mcp_",To=Object.freeze(["execute_bash","execute_pwsh","shell"]),Dc=Object.fromEntries(To.map(e=>[e,"Bash"])),kc="_",Lc={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function Vf(e){if(e.startsWith(cn))return e.slice(cn.length);if(e.startsWith(yc))return e.slice(yc.length);if(Object.hasOwn(Dc,e))return Dc[e];if(!e.startsWith(Cc))return e;let t=e.slice(Cc.length),n=t.indexOf(kc);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+kc.length)}function Jf(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function wc(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(Ic,n)?Ic[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"&&Lc[t.source]!==void 0&&(r.source=Lc[t.source]),o==="UserPromptSubmit"){let s=t[qf],i=typeof s=="string"?s:process.env[zf];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:Vf(s),input:i}}return o==="PostToolUse"&&(r.result=Jf(t.tool_response)),r}function Pc(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 Ro="mcp__context-mode__",Mc="mcp__plugin_context-mode_context-mode__",Qf={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Zf={hook_event_name:"hookEventName",session_id:"sessionId"},e0="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(Zf))t[i]===void 0&&(t[i]=t[c]);let n=t.hook_event_name===e0;n&&(t.hook_event_name="PostToolUse");let r=(typeof t.tool_name=="string"?t.tool_name:"").startsWith(Mc)?Mc:Ro,s=ge(t,"zcode",r,Qf);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 Hc(e,t,n){return Y(e,t,!1)}var Ao="",Fc={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},vc={bash:"Bash",read:"Read",edit:"Edit",write:"Write"};function n0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function o0(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 jc(e){return{...No(e),agent:"omp"}}function No(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(vc,s)?vc[s]:s,input:n0(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=o0(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function r0(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 yo(e,t,n){let o=r0(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:Ki,content:o.stdout,timestamp:Date.now()}}function Io(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var Xc="",Gc=re+"_",Bc={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},Co="bash",Do="read",i0=Object.freeze([Co,"shell"]),c0="skill",Wc={webfetch:"WebFetch",[Do]:"Read",[c0]:"Skill",...Object.fromEntries(i0.map(e=>[e,"Bash"]))};function ko(e){return e.startsWith(Gc)?e.slice(Gc.length):Object.prototype.hasOwnProperty.call(Wc,e)?Wc[e]:e}function a0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function l0(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 Kc(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(Bc,n)?Bc[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:ko(s),input:a0(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=l0(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Yc(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 at={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},qc={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},d0={...qc,shell:[...$i]},f0=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:_o,nativeTools:d0,execReadOnlyHint:!1,eventMap:at,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:X,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"skills"},decode:Zi,encode:ec},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:mo,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:at,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:X,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:tc,encode:nc},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Zt,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:X,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:ic,encode:cc},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:ho,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:at,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:X,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:lc,encode:uc},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:tn,nativeTools:{shell:[...So]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:X,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:_c,encode:Ec},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:on,nativeTools:{shell:[...bo],read:[...sn],webfetch:[...Oo]},execReadOnlyHint:!1,eventMap:{...at,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:X,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:Ac,encode:Nc},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:cn,nativeTools:{shell:[...To]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:X,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:wc,encode:Pc},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:Ro,nativeTools:qc,execReadOnlyHint:!1,eventMap:at,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:X,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:Uc,encode:Hc},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:Ao,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:Ut,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:No,encode:yo,checkPermission:Io},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:Xc,nativeTools:{shell:[Co],read:[Do]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:Ut,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:Kc,encode:Yc,toCanonicalTool:ko},{id:"omp",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:Ao,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:Ut,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"omp/index.js"},skillChannel:{kind:"package",path:"skills"},decode:jc,encode:yo,checkPermission:Io}]),p0=new Map(f0.map(e=>[e.id,e])),x0=new Set(["claude-code","gemini","copilot-cli","pi","opencode","omp"]);function ke(e){return x0.has(e.id)}var _0=new Set(["claude-code","copilot-cli","pi","omp"]);function Lo(e){return _0.has(e.id)&&ke(e)}var E0=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function an(e){return E0.has(e.id)}function q(e){return p0.get(e)}import{resolve as St}from"node:path";var g0=["&&","||",";;","|&",";","|","&","(",")"],m0=["&>>","&>"],h0=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],S0="&",b0="<<",zc="<<-",O0=";",Vc=`\r
19
- `,Jc=`\\
20
- `,$c=`\\\r
21
- `,T0="$(",ea="${",ta="$'",lt="((",Qc="))",Le="[[",ln="]]",wo="<(",na=">(",F=2,oa=`
22
- \r;&|()<>`,R0=`
23
- \r`,A0='$`"\\\n',N0="case",y0="esac";function we(e,t){e.end==="complete"&&(e.end=t)}function Po(e){return e!==""&&e>="0"&&e<="9"}function Zc(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function ra(e){return e===""||oa.includes(e)}function Mo(e){return e!==""&&R0.includes(e)}function z(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function un(e,t){let n=e.s.indexOf("'",t+1);return n<0?(we(e,"unterminated-quote"),e.n):n+1}function sa(e,t){let n=t+ta.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=F;continue}if(o==="'")return n+1;n++}return we(e,"unterminated-quote"),e.n}function Uo(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+=F;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=ut(e,o,n);continue}if(r==="$"&&s==="{"){o=Ho(e,o,n);continue}if(r==="`"){o=Pe(e,o);continue}o++}return we(e,"unterminated-quote"),e.n}function Pe(e,t){let n=t+1;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=F;continue}if(o==="`")return n+1;n++}return e.n}function Ho(e,t,n){let o=t+ea.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=F;continue}if(s==="'"){o=un(e,o);continue}if(s==='"'){o=Uo(e,o,n);continue}if(s==="$"&&i==="("){o=ut(e,o,n);continue}if(s==="`"){o=Pe(e,o);continue}if(s==="{"&&r++,s==="}"){if(r===0)return o+1;r--}o++}return e.n}function Fo(e,t){let n=0,o=t+lt.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(Qc,o)?o+Qc.length:-1;n--}o++}return-1}function ut(e,t,n){let o=t+T0.length-1;if(e.s.startsWith(lt,o)){let r=Fo(e.s,o);if(r>0)return r}return dn(e,o+1,!0,n+1,null,null)}function I0(e,t,n){let o=t+Le.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=F;continue}if(s==="'"){o=un(e,o);continue}if(s==='"'){o=Uo(e,o,n);continue}if(s==="$"&&i==="("){o=ut(e,o,n);continue}if(s==="$"&&i==="{"){o=Ho(e,o,n);continue}if(s==="`"){o=Pe(e,o);continue}let c=Mo(e.s.charAt(o-1));if(c&&e.s.startsWith(ln,o)&&ra(e.s.charAt(o+ln.length))){if(r===0)return o+ln.length;r--,o+=ln.length;continue}if(c&&e.s.startsWith(Le,o)&&Mo(e.s.charAt(o+Le.length))){r++,o+=Le.length;continue}o++}return-1}function C0(e,t){let n=t;for(;Po(e.charAt(n));)n++;if(n===t){for(let o of m0)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of h0){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(S0))if(e.charAt(r)==="-")r++;else for(;Po(e.charAt(r));)r++;return{end:r,op:o}}return null}function D0(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(oa.includes(r))break;if(r==="\\"){o+=F;continue}if(r==="'"){o=un(e,o);continue}if(r==='"'){o=Uo(e,o,n);continue}if(r==="$"&&s==="'"){o=sa(e,o);continue}if(r==="$"&&s==="("){o=ut(e,o,n);continue}if(r==="$"&&s==="{"){o=Ho(e,o,n);continue}if(r==="`"){o=Pe(e,o);continue}o++}return Math.min(o,e.n)}function k0(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),z(o,"unhandled",e.s.slice(c,s),c,s),!a)return we(e,"unterminated-heredoc"),e.n}return n.length=0,s}function dn(e,t,n,o,r,s){if(o>K)return we(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),p=i.charAt(c+1);if(f===" "||f===" "){c++;continue}if(i.startsWith(Jc,c)){c+=Jc.length;continue}if(i.startsWith($c,c)){c+=$c.length;continue}if(f===`
25
- `||f==="\r"){let S=c;c+=i.startsWith(Vc,c)?Vc.length:1,z(r,"op",O0,S,c),u=null,d.length>0&&(c=k0(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(wo,c)||i.startsWith(na,c)){let S=dn(e,c+wo.length,!0,o+1,null,null);z(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}let x=C0(i,c);if(x!==null){z(r,"io",i.slice(c,x.end),c,x.end),u=x.op===b0||x.op===zc?x.op===zc:null,c=x.end;continue}if(i.startsWith(Le,c)&&Mo(i.charAt(c+Le.length))){let S=I0(e,c,o);if(S>0){z(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}if(i.startsWith(lt,c)){let S=Fo(i,c);if(S>0){z(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let g=g0.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}z(r,"op",g,c,c+g.length),c+=g.length,u=null;continue}if(f==="$"&&p==="("||f==="`"){let S=f==="`"?Pe(e,c):ut(e,c,o);if(ra(i.charAt(S))){z(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let E=c;c=D0(e,c,o);let h=i.slice(E,c);z(r,"word",h,E,c),u!==null&&(d.push({tag:Me(h),strip:u}),u=null),n&&h===N0&&l++,n&&h===y0&&l>0&&l--}return d.length>0&&we(e,"unterminated-heredoc"),e.n}function ia(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return dn(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function Me(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=F;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+ta.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=F;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!==""&&A0.includes(i)){t+=i,s+=F;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function fn(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+=F;continue}if(!o&&s==="'"){r=un(t,r);continue}if(!o&&s==="$"&&i==="'"){r=sa(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=ea.length;continue}let c=e.startsWith(wo,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(na,r))){let a=r+1;if(s==="$"&&e.startsWith(lt,a)&&Fo(e,a)>0){r=a+lt.length;continue}let l=dn(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=Pe(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 pn(e){let t=e.charAt(0);if(!(Zc(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(!(Zc(o)||Po(o)||o==="_"))return!1}return!1}var ua=[";","&","&&","||"],da=["|","|&"],dt="(",ft=")",fa=";;",Go=["(",")"],L0="!";function v(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"}),pa=[],w0="[[",P0="((",xa=[">",">>",">|","&>","&>>",">&"],M0=[...xa,"<","<>","<<<","<<","<<-"],U0=["","1"],_a=["-","/dev/stdout","/dev/stderr"],_n="-",pt="--",xt="=",H0="/",F0=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),xn=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),vo="-c",jo="--bytes",v0="c",j0="--count",me=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],ie=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,k=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,Bo=e=>e!==""&&e>="0"&&e<="9",G0=e=>Bo(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function Wo(e){let t=e.lastIndexOf(H0);return t>=0&&t<e.length-1?e.slice(t+1):e}function Xo(e,t){let n=F0[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===pt)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+xt))s=r.slice(n.long.length+xt.length);else if(r.startsWith(_n)&&!r.startsWith(pt)){let i=r.indexOf(n.short,_n.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&&!_a.includes(s))return!0}return!1}function B0(e){if(e==="")return!1;for(let t of e)if(!Bo(t))return!1;return!0}function W0(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===vo||n===jo?o=e[t+1]:n.startsWith(jo+xt)?o=n.slice(jo.length+xt.length):n.startsWith(vo)&&!n.startsWith(pt)&&(o=n.slice(vo.length)),o!==void 0)return B0(o)&&Number(o)<=xe}return!1}function X0(e){for(let t of e){if(t===pt)return!1;if(t===j0||t.startsWith(_n)&&!t.startsWith(pt)&&t.includes(v0))return!0}return!1}function ca(e){if(!e.startsWith(M.fieldSep))return!1;for(let t of e.slice(M.fieldSep.length).split(M.fieldSep)){if(t==="")return!1;for(let n of t)if(!G0(n))return!1}return!0}function K0(e){let t=e.trim();if(t===M.identity||t===M.length)return!0;let n=t.indexOf(M.pipeLength.charAt(0));if(n<0)return ca(t);let o=t.slice(0,n).trim(),r=M.pipeLength.slice(1).trim();return(o===M.identity||ca(o))&&t.slice(n+1).trim()===r}function Y0(e){let t=e.argv0.toLowerCase();if(t===xn.wc)return!0;if(t===xn.head)return W0(e.args);if(t===xn.grep)return X0(e.args);if(t===xn.jq){let n=e.args.filter(o=>!o.startsWith(_n));return n.length===1&&K0(n[0])}return!1}function Ko(e){return fn(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function Ea(e,t,n){return n<=t?[]:Ko(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function ga(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function q0(e){let t=0;for(;Bo(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function ma(e){let t=q0(e.toks[e.i].text);if(e.i++,!M0.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,xa.includes(t.op)&&U0.includes(t.fd)&&!_a.includes(Me(n.text)))}function ha(e){let t=!1;for(;O(e)?.kind==="io";)t=ma(e)||t;return t}function Sa(e){for(;O(e)?.kind==="op"&&ua.includes(O(e)?.text??"");)e.i++}function Ue(e,t){if(e.depth++,e.depth>K)return e.err="nesting-too-deep",me();let n=t();if(e.depth--,ha(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function ba(e){if(Sa(e),!k(O(e),b.do))return[];e.i++;let t=V(e,[b.done]);return k(O(e),b.done)&&e.i++,t}function z0(e){e.i++;let t=V(e,[b.then]);for(;e.err===null;){let n=O(e);if(k(n,b.then)||k(n,b.else)){e.i++,v(t,V(e,[b.elif,b.else,b.fi]));continue}if(k(n,b.elif)){e.i++,v(t,V(e,[b.then]));continue}k(n,b.fi)&&e.i++;break}return t}function V0(e){e.i++;let t=V(e,[b.do]);return v(t,ba(e)),t}function J0(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++;v(t,Ea(e,o,e.i))}return v(t,ba(e)),t}function $0(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,v(t,Ea(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"&&(ua.includes(o.text)||o.text===fa)){e.i++;continue}if(k(o,b.esac)){e.i++;break}for(ie(o,dt)&&e.i++;e.i<e.toks.length&&!ie(O(e),ft);){let s=e.toks[e.i];if(s.kind==="op"&&!da.includes(s.text))break;e.i++}if(!ie(O(e),ft))break;e.i++;let r=V(e,[b.esac]);ga(r,b.case),v(t,r)}return t}function aa(e,t){Sa(e);let n=Oa(e);return ga(n.cmds,t),{cmds:n.cmds,simple:null}}function la(e,t){return Go.every((n,o)=>ie(e.toks[t+o],n))}function Q0(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=ma(e)||o;continue}if(n.length===0&&l.kind==="word"&&pn(l.text)){e.i++;let u=O(e);if(l.text.endsWith(xt)&&u!==void 0&&ie(u,dt)&&u.start===l.end){let d=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,ie(f,dt)&&d++,ie(f,ft)&&--d===0)break}}continue}n.push(l),e.i++}if(e.i===t)return me();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:Ko(r),simple:null};let s=l=>l.kind==="word"?Me(l.text):l.text,i=Wo(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||Xo(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function Oa(e){let t=O(e);if(t===void 0)return me();if(t.kind==="op")return t.text!==dt?me():Ue(e,()=>{e.i++;let n=V(e,pa);return ie(O(e),ft)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(w0)||t.text.startsWith(P0)))return e.i++,ha(e),{cmds:Ko(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return Ue(e,()=>{e.i++;let n=V(e,[b.groupEnd]);return k(O(e),b.groupEnd)&&e.i++,n});case b.if:return Ue(e,()=>z0(e));case b.while:case b.until:return Ue(e,()=>V0(e));case b.for:return Ue(e,()=>J0(e));case b.case:return Ue(e,()=>$0(e));case b.coproc:return e.err="coproc",me();case b.select:return e.err="select",me();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=Me(n.text),e.i++),la(e,e.i)&&(e.i+=Go.length),aa(e,o)}default:if(la(e,e.i+1))return e.i+=Go.length+1,aa(e,Me(t.text))}return Q0(e)}function Z0(e){k(O(e),L0)&&e.i++;let t=[],n=me();for(;e.err===null;){n=Oa(e),v(t,n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&da.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&Y0(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function V(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===ft||o.text===fa)return n;if(o.text!==dt){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;v(n,Z0(e)),e.i===r&&e.err===null&&e.i++}return n}function He(e){let t=ia(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;)v(o,V(n,pa)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as Ta}from"node:path";var gn="'",Fe='"',mn="`",ep=" \r",Et="([{",Vo=")]}",Yo=` \r
27
- |;>`,Na="*",Ra="1",qo="::",En=qo.length,tp=En;function hn(e,t){let n=e.charAt(t);for(let o=t+1;o<e.length;o++){let r=e.charAt(o);if(n===Fe&&r===mn){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function np(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===Fe&&r===mn&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function _t(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===gn||r===Fe){let s=hn(e,o);if(s<0)return-1;o=s;continue}if(r===mn){o++;continue}if(Et.includes(r))n++;else if(Vo.includes(r)&&--n===0)return o}return-1}function op(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===gn||r===Fe){let s=hn(e,o);if(s<0)return e.length;o=s;continue}if(Et.includes(r))n++;else if(Vo.includes(r))n--;else if(n<=0&&Yo.includes(r))return o}return e.length}function rp(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===gn||s===Fe){let i=hn(e,r);if(i<0)break;r=i;continue}Et.includes(s)?n++:Vo.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var sp=e=>e!==""&&(e===Na||[...e].every(t=>t>="0"&&t<="9")),Aa=()=>({words:[],toFile:!1,chained:!1});function ya(e){let t=[],n=[],o=Aa(),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=Aa()},d=()=>{u(),n.length>0&&t.push(n),n=[]},f=(x,g)=>{r+=x,s=!0,g&&(i=!1)},p=0;for(;p<a;){let x=e.charAt(p),g=e.charAt(p+1);if(x===gn||x===Fe){let E=hn(e,p);f(np(e.slice(p+1,E<0?a:E),x),!0),p=E<0?a:E+1}else if(x===mn)g!==`
28
- `&&g!==""&&f(g,!1),p+=En;else if(x===`
29
- `)d(),p++;else if(ep.includes(x))l(),p++;else if(x===";")d(),p++;else if(x==="|")g==="|"?(d(),p+=En):(u(),p++);else if(x==="&")g==="&"?(d(),p+=En):((s||o.words.length>0)&&f(x,!1),p++);else if(x==="#"&&!s)for(;p<a&&e.charAt(p)!==`
30
- `;)p++;else if(x===">"){let E=Ra;s&&i&&sp(r)?(E=r,r="",s=!1):s&&l();let h=p+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<a&&!Yo.includes(e.charAt(h));)h++;else c=E===Ra||E===Na?"file":"skip";p=h}else if(x==="("&&s&&i&&r.includes(qo)){let E=_t(e,p),h=e.slice(p+1,E<0?a:E);l();for(let S of h.trim()===""?[]:rp(h)){let _=ya(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}p=E<0?a:E+1,p<a&&!Yo.includes(e.charAt(p))&&(o.chained=!0,p=op(e,p))}else if(x==="["&&!s&&e.startsWith(qo,_t(e,p)+1)&&_t(e,p)>=0){let E=_t(e,p);f(e.slice(p,E+1),!1),p=E+1}else if(Et.includes(x)&&(x!=="["||!s)||(x==="$"||x==="@")&&Et.includes(g)&&g!=="["){let E=x==="$"||x==="@"?p+1:p,h=_t(e,E);f(e.slice(p,h<0?a:h+1),!0),p=h<0?a:h+1}else f(x,!1),p++}return d(),t}var ip=["get-content","gc","cat","type"],cp=["[io.file]::","[system.io.file]::"],ap=["readalltext","readalllines","readallbytes","readlines"],Jo=["path","literalpath"],Ia=["totalcount","head","first","tail","last"],Ca=[...Jo,...Ia,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],lp=["raw","wait","force","asbytestream"],up=[...Ca,...lp],dp=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],fp=["cd","chdir","sl","set-location","pushd","push-location"],pp=["powershell","powershell.exe","pwsh","pwsh.exe"],xp=["cmd","cmd.exe"],_p=["/c","/k","/r"],Ep="command",he="-";function zo(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function $o(e,t){let n=e.slice(he.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 gp(e){if(e.length===0)return null;let t=zo(e[0]);if(!ip.includes(t)){let r=e[0].toLowerCase(),s=cp.find(i=>r.startsWith(i));return s===void 0||!ap.includes(r.slice(s.length))||e.length<tp?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(he)||s.length===he.length){n.push(s);continue}let i=$o(s,up);if(i.full===void 0||!Ca.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;Jo.includes(i.full)&&n.push(c),Ia.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function mp(e,t){if(pp.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(he)||o.length===he.length)continue;let r=$o(o,[Ep]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(xp.includes(e)){for(let n=1;n<t.length;n++)if(_p.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function hp(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(he)||n.length===he.length)return n;let o=$o(n,Jo);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function Da(e,t,n,o){let r=t;for(let s of ya(e)){let i=s[0];if(i.words.length===0)continue;let c=zo(i.words[0]);if(s.length===1&&fp.includes(c)){let d=hp(i.words);d!==null&&(r=Ta(r,d));continue}let a=n<K?mp(c,i.words):null;if(a!==null){Da(a,r,n+1,o);continue}if(i.toFile||i.chained)continue;let l=gp(i.words);if(l===null||l.bounded)continue;let u=!0;for(let d=1;d<s.length;d++)if(s[d].toFile||!dp.includes(zo(s[d].words[0]??""))){u=!1;break}u&&o.push(Ta(r,l.file))}}function ka(e,t){let n=[];return Da(e,t,0,n),n}import{join as ve}from"node:path";var La=`\r
31
- `,Sp=`
32
- `;function Sn(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(La)<0?t:t.split(La).join(Sp)}import{basename as Rp,dirname as Ap,join as J,posix as Pa,resolve as Np,win32 as Ma}from"node:path";var bp=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 Op(e,t){let n=bp[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(Op(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{existsSync:bh,mkdirSync:Tp,readFileSync:Oh,readdirSync:Th,realpathSync:wa}=process.getBuiltinModule("node:fs");function j(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 Ua(e,t){let n=e[vi];return n!==void 0&&n!==""?n:J(t,...C.codex)}function Ha(e,t){let n=e[ji];return n!==void 0&&n!==""?n:J(t,...C["copilot-cli"])}function Fa(e,t){let n=e[Gi];return J(n!==void 0&&n!==""?n:t,...C.gemini)}function va(e,t,n=process.platform){let o=n==="win32"?Ma:Pa,r=o.join(t,...C.kiro),s=e[Bi]?.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?yp: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 yp(e){let t=[];for(let n=e;;)try{return J(wa.native(n),...t.reverse())}catch{let o=Ap(n);if(o===n)return e;t.push(Rp(n)),n=o}}function $(e,t){let n=e[Vt];return n!==void 0&&n!==""?n:J(t,...C["claude-code"])}function ja(e,t){let n=e[Wi];if(n!==void 0&&n!=="")return n;let o=e[$t];return o!==void 0&&o!==""?J(o,C.opencode[C.opencode.length-1]):J(t,...C.opencode)}function Ga(e,t){let n=e[Yi];return n!==void 0&&n!==""?n:J(t,...C.pi,Xi)}function Ba(e,t,n=process.platform){let o=s=>s!==void 0&&s!=="",r=n==="win32"?Ma:Pa;return n==="win32"?r.join(o(e[xo])?e[xo]:r.join(t,"AppData","Roaming"),...Jt):n==="darwin"?r.join(t,"Library","Application Support",...Jt):r.join(o(e[$t])?e[$t]:r.join(t,".config"),...Jt)}function Ip(e,t=process.platform){let n=j(e,t);if(n!==null)return n;throw new T("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function bn(e,t){let n=e[Ze];return n!==void 0&&n!==""?Np(n):J(t,Cs.slice(1))}function Wa(e){let t=e[Ze],n=bn(e,t!==void 0&&t!==""?"":Ip(e));return Tp(n,{recursive:!0}),wa.native(n)}var{readFileSync:Va,readdirSync:Cp}=process.getBuiltinModule("node:fs"),Xa=Object.freeze(["Agent","Artifact","ArtifactComments","ArtifactData","ArtifactCheck","ExitPlanMode","Edit","Write","NotebookEdit"]),Ka=Object.freeze({"general-purpose":{tools:null,disallowed:[]},fork:{tools:null,disallowed:[]},claude:{tools:null,disallowed:[]},Explore:{tools:null,disallowed:[...Xa]},Plan:{tools:null,disallowed:[...Xa]},"claude-code-guide":{tools:["Glob","Grep","Read","WebFetch","WebSearch"],disallowed:[]},"statusline-setup":{tools:["Read","Edit"],disallowed:[]},"web-fetch":{tools:["WebFetch"],disallowed:[]}}),Dp="claude-code";function je(e){return e.agentId!==void 0&&e.agentId!==""}function Zo(e,t){if(t===null)return"C";let n=q(e.agent),o=new Set(t);for(let r of Lt)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function er(e,t){if(!je(e))return null;let n=q(e.agent);if(t.manifestTools!==void 0)return za(t.manifestTools.map(a=>Qo(n,a)));let o=e.agentType??"",r=kp(o,t)??Lp(e.agent,o);if(r===null)return null;let s=vp(n),i=r.tools===null?s:r.tools.map(a=>Qo(n,a)).flatMap(a=>[a,...s.filter(l=>Gp(a,l))]),c=r.disallowed.map(a=>Qo(n,a));return za(i.filter(a=>!c.some(l=>Bp(l,a))))}function kp(e,t){if(!wp(e))return null;let n=Pp(t.env);if(e.indexOf(Ie)>=0){if(n!==null){let s=Mp($(t.env,n),e);if(s!==null)return s}}else{let s=On(ve(t.projectDir,ks,et,e+_e));if(s!==null)return s;if(n!==null){let i=On(ve($(t.env,n),et,e+_e));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 Lp(e,t){if(e!==Dp||!Object.prototype.hasOwnProperty.call(Ka,t))return null;let n=Ka[t];return{tools:n.tools,disallowed:[...n.disallowed]}}function wp(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(Ie))if(t===""||t==="."||t==="..")return!1;return!0}function Pp(e){return j(e)}function Mp(e,t){let n=t.indexOf(Ie),o=t.slice(0,n),r=t.slice(n+Ie.length);return r.indexOf(Ie)>=0?null:Up(e,o,r)??Hp(e,o,r)}function Up(e,t,n){let o;try{o=JSON.parse(Sn(Va(ve(e,vt,ws),"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(Ps);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=On(ve(l,et,n+_e));if(u!==null)return u}}return null}function Hp(e,t,n){let o=ve(e,vt,Ls),r;try{r=Cp(o).sort()}catch{return null}for(let s of r){if(s.startsWith("."))continue;let i=On(ve(o,s,t,et,n+_e));if(i!==null)return i}return null}function On(e){let t;try{t=Va(e,"utf8")}catch{return null}return Fp(t)}function Fp(e){let t=e.split(`
33
- `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Qn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Qn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=Ya(o,Ms),s=Ya(o,Us);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function Ya(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(qa(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>qa(s.trim())).filter(s=>s!=="")}return null}function qa(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function vp(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...Lt.map(n=>e.toolNamePrefix+n)]}function Qo(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(Fs)?jp(o):o}function jp(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||vs.indexOf(n)>=0;t+=o?n:"_"}return t}function Gp(e,t){if(!e.startsWith(se))return!1;let n=Ce+"*",o=e.slice(se.length,e.endsWith(n)?-n.length:e.length);return o===""||o.indexOf("*")>=0||o.indexOf(Ce)>=0?!1:t.startsWith(se+o+Ce)}function Bp(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(se)){let n=e.slice(se.length);if(n!==""&&n.indexOf(Ce)<0)return t.startsWith(e+Ce)}return!1}function za(e){return[...new Set(e.filter(t=>t!==""))]}var Q="",Ja=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:Q,subcommands:[]},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:Q,subcommands:[]},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:Q,subcommands:[]},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:Q,subcommands:[]},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:Q,subcommands:[]},command:{valueShorts:Q,valueLongs:[],assignments:!1,duration:!1,refuseShorts:"vV",subcommands:[]},xargs:{valueShorts:"aEdILnPs",valueLongs:["--arg-file","--delimiter","--max-args","--max-procs","--max-chars"],assignments:!1,duration:!1,refuseShorts:Q,subcommands:[]},rtk:{valueShorts:Q,valueLongs:[],assignments:!1,duration:!1,refuseShorts:Q,subcommands:["proxy","bypass"]}}),Wp=["bash","sh","zsh"],Xp="c",Kp=" -c",Yp=["-o","+o","-O","+O"],Tn="-",qp="+",tr="--",zp="smhd",Vp=".",$a=e=>e!==""&&e>="0"&&e<="9";function Jp(e){if(e===""||!$a(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!($a(n)||n===Vp))return t===e.length-1&&zp.includes(n)}return!0}function $p(e,t){let n=0;if(e.subcommands.length>0){if(t.length===0||!e.subcommands.includes(t[0]))return null;n=1}for(;n<t.length;){let o=t[n];if(o===tr){n++;break}if(e.assignments&&pn(o)){n++;continue}if(o.startsWith(tr)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(Tn)&&o.length>Tn.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=Tn.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||!Jp(t[n]))return null;n++}return n<t.length?t.slice(n):null}function Qp(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(tr)){if(o.startsWith(Tn)||o.startsWith(qp)){o.includes(Xp)&&(t=!0),Yp.includes(o)&&n++;continue}return t?o:null}}return null}function Qa(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function nr(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let a=s.toLowerCase();if(Wp.includes(a)){let d=Qp(i),f=d!==null&&n<K?He(d):null;if(f===null||!f.ok)break;for(let p of f.commands){let x=Qa(p,e);x.redirectsToFile=p.redirectsToFile||c,x.endsInBoundedSink=p.endsInBoundedSink||e.endsInBoundedSink,nr(x,[...r,a+Kp],n+1,o)}return}let l=Object.hasOwn(Ja,a)?Ja[a]:void 0,u=l===void 0?null:$p(l,i);if(u===null)break;r.push(a),s=Wo(u[0]),i=u.slice(1),c=c||Xo(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=K))for(let a of fn(e.raw)){let l=He(a.body);if(l.ok)for(let u of l.commands)nr(Qa(u,e),[...t,a.wrapper],n+1,o)}}function or(e){let t=[];for(let n of e)nr(n,[],0,t);return t}import{isAbsolute as ex,join as rr,relative as tx,sep as sr}from"node:path";var{readFileSync:Zp}=process.getBuiltinModule("node:fs"),Za=".claude",nx="settings.local.json",el="settings.json",cl="Bash",ox="Read",tl=":*",nl="//",ol="~/",rl="./",sl="..",rx=`
34
- \r`,sx=Object.freeze({tool:cl});function ix(e,t){if(t!=="claude-code")return[];let n=j(process.env),o=process.env[Vt],r=o!==void 0&&o!==""?o:n===null?null:$(process.env,n),s=[rr(e,Za,nx),rr(e,Za,el)];return r===null?s:[...s,rr(r,el)]}function il(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cx(e){let t;try{t=Sn(Zp(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!il(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!il(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 al(e,t){let n=[];for(let o of ix(e,t)){let r=cx(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function ir(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 cr(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,p=f?t[d]:"";switch(a.t){case"lit":i[d]=f&&p===a.c?s[d+1]:0;break;case"any1":i[d]=f&&!(n&&p==="/")?s[d+1]:0;break;case"star":i[d]=s[d]||(f&&!(n&&p==="/")?i[d+1]:0);break;case"globstar":i[d]=s[d]||(f?i[d+1]:0);break;case"globstarDir":f&&p==="/"&&s[d+1]&&(l=1),i[d]=s[d]||l;break}}let u=i;i=s,s=u}return s}function gt(e,t,n){let o=ir(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,cr(o,t,n,s)[0]===1}function ll(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 ul(e,t){let n=t.length,o=new Uint8Array(n+1);if(o[n]=1,!e.endsWith(tl))return cr(ir(e,!1),t,!1,o);for(let r=0;r<n;r++)rx.includes(t[r])&&(o[r]=1);return cr(ir(e.slice(0,e.length-tl.length),!1),t,!1,o)}function ax(e,t){return ul(e,t)[0]===1}function dl(e,t,n){for(let o of t){let r=ll(o);if(r===null||r.tool!==cl)continue;let s=ul(r.glob,e);for(let i=0;i<=e.length;i++)if(n[i]===1&&s[i]===1)return o}return null}var lx=/^[A-Za-z]:(?=\/)/;function mt(e){return sr==="/"?e:e.split(sr).join("/")}function ux(e,t,n){if(e.startsWith(rl)){if(n===void 0)return!1;let r=tx(n,t);return r===""||r===sl||r.startsWith(sl+sr)||ex(r)?!1:gt(e.slice(rl.length),mt(r),!0)}let o=mt(t);if(e.startsWith(nl)){let r=mt(e.slice(nl.length-1));return gt(r,o,!0)||gt(r,o.replace(lx,""),!0)}if(e.startsWith(ol)){let r=j(process.env);return r!==null&&gt(mt(r)+e.slice(ol.length-1),o,!0)}return gt(mt(e),o,!0)}function Ge(e,t,n=sx){for(let o of t){let r=ll(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===ox?ux(r.glob,e,n.projectDir):ax(r.glob,e))return o}return null}var Wh=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.'}),fl='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.',pl=`context-mode: {size}-byte file, over the one-read limit. Read "{path}" in parts with offset and limit, or sed -n '1,200p'.`;var xl="{size}",_l="{path}";function El(e,t,n=""){return P(fl,n).split(xl).join(String(t)).split(_l).join(e)}function gl(e,t){return pl.split(xl).join(String(t)).split(_l).join(e)}import{extname as xx,join as ar,resolve as _x}from"node:path";import{dirname as ml,isAbsolute as bl,join as Jh,relative as $h,resolve as Ol,sep as Tl}from"node:path";var{lstatSync:zh,realpathSync:dx}=process.getBuiltinModule("node:fs");function ht(e){try{return dx.native(e)}catch{return}}function I(e){return e.split(Tl).filter(t=>t!=="")}function Rl(e,t){let n=ht(e),o=ht(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 hl=new Map;function fx(e){let t=hl.get(e);if(t!==void 0)return t;let n=ht(e);return n!==void 0&&hl.set(e,n),n}function Be(e,t){if(e.length===0)return!1;let n=ht(t);if(n===void 0)return!1;let o=I(n);return e.some(r=>{let s=fx(r);if(s===void 0)return!1;let i=I(s);return o.length>=i.length&&i.every((c,a)=>c===o[a])})}function Al(e,t){return(bl(t)?I(t):[...I(e),...I(t)]).includes("..")}var Sl=new Map;function px(e){let t=Sl.get(e);return t===void 0&&(t=I(Ol(e)),Sl.set(e,t)),t}function Nl(e,t){if(e.length===0)return!1;let n=I(t);if(n.includes(".."))return!1;let o=Tl==="/"&&bl(t)?n.filter(r=>r!=="."):I(Ol(t));return e.some(r=>{let s=px(r);return o.length>=s.length&&s.every((i,c)=>i===o[c])})}function yl(e){let t=e.map(ht).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&&ml(r)!==r;)r=ml(r);return r}function Ex(e,t){let n=j(t);if(n===null)return[];let o=ar(n,...js);return[...e==="claude-code"?[$(t,n)]:e==="codex"?[Ua(t,n)]:e==="gemini"?[Fa(t,n)]:e==="copilot-cli"?[Ha(t,n)]:e==="kiro"?[va(t,n)]:e==="opencode"?[ja(t,n)]:e==="pi"?[Ga(t,n)]:e==="vscode"?[ar(n,...C.vscode),Ba(t,n)]:[ar(n,...C[e])],o]}function We(e,t,n,o=process.env){if(xx(n).toLowerCase()!==_e)return!1;let r=Ex(e,o),s=_x(t,n);return!Al(t,n)&&Nl(r,s)||Be(r,s)}import{extname as Sx}from"node:path";var{closeSync:gx,openSync:mx,readSync:hx}=process.getBuiltinModule("node:fs");function bx(e){let t=null;try{t=mx(e,"r");let n=Buffer.alloc(ro),o=hx(t,n,0,ro,0);return n.subarray(0,o)}catch{return null}finally{t!==null&&gx(t)}}function Rn(e,t){let n=gi[e]??[];if(n.length===0)return!1;let o=Sx(t).toLowerCase(),r=n.filter(i=>oo[i].exts.includes(o));if(r.length===0)return!1;let s=bx(t);return s===null?!1:r.some(i=>oo[i].sig.every(c=>c.bytes.every((a,l)=>s[c.at+l]===a)))}var{statSync:Ox}=process.getBuiltinModule("node:fs"),wl="Bash",ur="Read",Tx="WebFetch",Rx="ctx_execute",Ax="ctx_batch",Pl="shell",Nx="1",ce="-",dr="--",yx="=",Ix=".",Il=",",lr="p",Cx=["-e","--expression"],Cl=".exe",Dx=";&|(`\n\r",Oe=Object.freeze({kind:"allow"}),Se=e=>({kind:"deny",reason:e}),be=e=>typeof e=="string"?e:void 0,Dl=e=>e!=null,Z=(e,t)=>e.includes(t);function Ml(e,t,n,o=e.cwd){let r=e.tool;if(r===void 0)return Oe;let s=r.canonicalName,i=r.input,c;if(n===null){if(process.env[Ds]===Nx)return Se(P(jt,t.toolNamePrefix));process.stderr.write(oi+`
35
- `),c=[]}else c=n;let a=Lx(s,i,e.cwd,c);return a!==null?Se(tt+a):s===Tx?Ux(i,t):s===wl?Hx(e,t,i,c,o):s===ur?Xx(e,t,i,o):Oe}function Ul(e,t,n,o){let r=e==="webfetch",s=r?qs.map(c=>n.toolNamePrefix+c).join(ni):n.toolNamePrefix+Ys,i=JSON.stringify(r?{url:t}:{language:Pl,code:t,intent:o??Ks});return[Zn+Gs[e]+Bs,Ws,Xs+s,i].join(`
36
- `)}function kx(e){for(let t of Ee){let n=be(e[t]);if(n!==void 0&&n!=="")return n}}function Hl(e){let t=kx(e),n=Array.isArray(e[De])?e[De].filter(o=>typeof o=="string"&&o!==""):[];return t===void 0?n:[t,...n]}function Lx(e,t,n,o){if(o.length===0)return null;let r=s=>Ge(St(n,s),o,{tool:ur,projectDir:n});if(e===wl){let s=be(t.command);return s===void 0?null:Ge(s,o)}if(e===ur){for(let s of Hl(t)){let i=r(s);if(i!==null)return i}return null}if(e===Rx){let s=be(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=be(t.code);return wx(t.language)&&c!==void 0?kl(c,o):null}if(e===Ax&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?kl(s,o):null;if(i!==null)return i}return null}function wx(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(Cl)&&(t=t.slice(0,t.length-Cl.length)),t===Pl||Z(As,t)}function kl(e,t){let n=Ge(e,t);if(n!==null)return n;let o=He(e);if(!o.ok)return vl(e,t);for(let r of or(o.commands)){let s=Fl(r,t);if(s!==null)return s}return null}function Fl(e,t){return t.length===0?null:Ge([e.argv0,...e.args].join(" "),t)??Ge(e.raw,t)}function vl(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||Dx.includes(e.charAt(r-1)))&&(o=!0),o&&(r===e.length||e.charAt(r).trim()!=="")&&(n[r]=1,o=!1);return dl(e,t,n)}function Px(e,t){return vl(e,t)!==null}function Mx(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return ri.some(n=>t===n||t.endsWith(Ix+n))}function Ux(e,t){let n=be(e.url)??"";return Mx(n)?Oe:Se(Ul("webfetch",n,t))}function Hx(e,t,n,o,r){let s=be(n.command)??"",i=He(s);if(!i.ok)return Px(s,o)?Se(P(Gt,t.toolNamePrefix)):Ll(e,s,t,r)??Oe;let c=or(i.commands);for(let a of c){let l=Fl(a,o);if(l!==null)return Se(tt+l)}if(!ke(t)||je(e))for(let a of c){let l=Fx(a);if(l!==null)return Se(Ul(l,s,t,be(n.description)))}return Kx(e,c,t,r)??Ll(e,s,t,r)??Oe}function Fx(e){let t=e.argv0.toLowerCase();return Z(si,t)&&vx(t,e)?"curl":Gx(e.raw)?"http":Z(li,t)?"build":null}function vx(e,t){return t.redirectsToFile?!jx(e,t.args):!t.endsInBoundedSink}function jx(e,t){let n=ii[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===dr)break;if(Z(ci,s)||s===ai&&t[r+1]===ce)return!1;(s===n.long||s.startsWith(ce)&&!s.startsWith(dr)&&s.includes(n.short,ce.length))&&(o=!0)}return o}function Gx(e){let t=e.toLowerCase();for(let n of fi)if(t.includes(n))return!0;for(let n=t.indexOf(ot);n>=0;n=t.indexOf(ot,n+1)){let o=t.charAt(n+ot.length);if(o!==""&&ui.includes(o)&&t.startsWith(di,n+ot.length+o.length))return!0}return!1}var Bx="cd";function fr(e){try{let t=Ox(e);return t.isFile()?t.size:-1}catch{return-1}}function pr(e,t,n,o,r,s){let i=St(n,o);return r<=xe||We(e.agent,n,o)?null:Se(Wx(s,i)?El(i,r,t.toolNamePrefix):gl(i,r))}function Wx(e,t){if(typeof e=="string")return Be([e],t);if(Be([e.worktree],t))return!0;try{return Be([e.containmentRoot],t)}catch{return!1}}function Xx(e,t,n,o){if(!Dl(n.offset)&&!Dl(n.limit))for(let r of Hl(n)){let s=St(e.cwd,r),i=fr(s);if(i>xe&&!Rn(e.agent,s)){let c=pr(e,t,e.cwd,r,i,o);if(c!==null)return c}}return Oe}function Kx(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&Lo(n))return null;let r=e.cwd,s=null;for(let i of t){let c=i.argv0.toLowerCase();if(c===Bx&&i.args.length===1&&i.insideConstruct===void 0&&(r=St(r,i.args[0])),i.redirectsToFile||i.endsInBoundedSink||i.pipesOut===!0||i.insideConstruct!==void 0||!Z(pi,c))continue;let a=zx(c,i.args);if(a===null)continue;if(a.bounded){s=Oe;continue}let l=St(r,a.file),u=pr(e,n,r,a.file,fr(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&&Lo(n))return null;for(let r of ka(t,e.cwd)){let s=pr(e,n,e.cwd,r,fr(r),o);if(s!==null)return s}return null}var An=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function Yx(e){if(Z(no,e))return 1;for(let t of no)if(t.startsWith(dr)?e.startsWith(t+yx):e.startsWith(t))return 0;return e.startsWith(ce)&&An(e.slice(ce.length))?0:-1}function qx(e){if(e===lr)return"all";if(!e.endsWith(lr))return null;let t=e.slice(0,e.length-lr.length),n=t.indexOf(Il);return(n<0?An(t):An(t.slice(0,n))&&An(t.slice(n+Il.length)))?"range":null}function zx(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(Z(xi,e)){let a=Yx(c);if(a>=0){o=!0,i+=a;continue}}if(e===Bt&&Z(_i,c)){r=!0;continue}if(e===Bt&&Z(Cx,c)){s=t[i+1],i++;continue}c.startsWith(ce)&&c!==ce||n.push(c)}if(e===Bt){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:qx(s);if(i===null)return null;o=i==="range"}return e===Ei&&n.shift()!==M.identity?null:n.length===1&&n[0]!==ce?{file:n[0],bounded:o}:null}import{basename as e_,dirname as Ot,isAbsolute as t_,join as Tt,resolve as xr}from"node:path";var Vx=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]),Jx=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],G=(e,t)=>e>>>t|e<<32-t;function jl(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=Jx.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=G(i[E-15],7)^G(i[E-15],18)^i[E-15]>>>3,S=G(i[E-2],17)^G(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,p,x,g]=s;for(let E=0;E<64;E++){let h=g+(G(f,6)^G(f,11)^G(f,25))+(f&p^~f&x)+Vx[E]+i[E]>>>0,S=(G(a,2)^G(a,13)^G(a,22))+(a&l^a&u^l&u)>>>0;g=x,x=p,p=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]+p>>>0,s[6]=s[6]+x>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:$x,readFileSync:Qx,realpathSync:Gl,statSync:Zx}=process.getBuiltinModule("node:fs");function n_(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":case"omp":return"pi:ctx.cwd"}}function bt(e){return e===void 0||e===""?void 0:e}function o_(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return bt(t.env.CLAUDE_PROJECT_DIR)??bt(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return bt(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(Ft);return n<0?void 0:bt(t.argv[n+1])}case"pi:ctx.cwd":return bt(t.piCwd)}}function r_(e){let t=s_(e),n=t;for(;;){let o=i_(Tt(t,Vn));if(o!==null){let s=Bl(Tt(o,Ts));return{commonDir:Gl.native(s===null?o:xr(o,s)),worktree:t,start:n}}let r=Ot(t);if(r===t)return{commonDir:null,start:n};t=r}}function s_(e){let t=t_(e);for(let n=t?xr(e):e;;)try{return Gl.native(n)}catch{let o=Ot(n);if(!t||o===n)throw new T("NO_GIT_DIR",{path:e});n=o}}function i_(e){let t;try{if(Zx(e).isDirectory())t=e;else{let n=Bl(e);if(n===null||!n.startsWith($n))return null;t=xr(Ot(e),n.slice($n.length))}}catch{return null}return $x(Tt(t,Rs))?t:null}function Bl(e){let t;try{t=Qx(e,"utf8")}catch{return null}let n=t.indexOf(`
37
- `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function c_(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 a_(e,t){let n=e_(t)===Vn?Ot(t):t,o=c_(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(Jn)).map(r=>r.slice(Jn.length));return yl([Ot(n),...o])}function Wl(e,t){let n=n_(e),o=o_(n,t);if(o===void 0)throw new T("NO_PROJECT",{kind:n});let r=r_(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??=jl(i).slice(0,bs),a},get projectDir(){return l??=Tt(Wa(process.env),Ht,this.projectKey),l},get dbPath(){return Tt(this.projectDir,Os)},worktree:c,get containmentRoot(){return u??=s??a_(c,i),u},agent:e,source:n}}var Nn=$e,l_=`
39
- PRAGMA busy_timeout = ${H};
8
+ `),i=hf(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 hf(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 rc(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function Sf(e){let t=e;return(t.mode==="content"||t.mode==="count")&&typeof t.content=="string"}function ic(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 Of(e){let t=gf(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)&&rc(e)&&(o.shape=e),typeof e=="object"&&e!==null&&!Array.isArray(e)&&!rc(e)&&(To(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,ic(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 he(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=pf.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:Ef(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=Of(r.tool_response)),i}function bf(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:To(n);return n!==void 0&&o!==null?o.put(n,t):e.result?.blocks===!0?[{type:"text",text:t}]:t}function z(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:bf(e,t.output)}):{stdout:"",exitCode:0}}}var Tf={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function Rf(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 Af(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 Tf[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function cc(e){Af(e);let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===xf,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=he(n,"claude-code",bo,_f);if(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,keep:!0}}if(o.tool!==void 0&&o.tool.name===df&&(o.tool.canonicalName=ff),o.cwd===""&&(o.cwd=process.env.CLAUDE_PROJECT_DIR||process.cwd()),o.event==="PostToolUse"&&o.tool!==void 0&&o.tool.callId===void 0){let r=typeof o.tool.input.command=="string"?o.tool.input.command:JSON.stringify(o.tool.input);o.tool.callId="h"+Rf(o.tool.name+"\0"+r+"\0"+String(o.turn??0))}return o}function ac(e,t,n){return z(e,t,!0)}var Ao="mcp__context_mode__",yf={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"},Ro="Stop",If={stdout:"",exitCode:0};function lc(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===Ro){let t=e;return{event:Ro,agent:"codex",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")}}return he(e,"codex",Ao,yf)}function uc(e,t,n){return e.event===Ro?If:z(e,t,!1)}var rn="mcp_context-mode_",dc={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},fc={startup:"startup",resume:"resume",clear:"clear"},Df=["SessionStart","UserPromptSubmit","PostToolUse"],kf=["UserPromptSubmit","PreToolUse"],on={stdout:"",exitCode:0},Lf=`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 pc={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function Pf(e,t){if(e.startsWith(rn))return e.slice(rn.length);if(Object.hasOwn(pc,e))return pc[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 wf(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 Mf(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:wf(n)??JSON.stringify(e),r=t===void 0?void 0:A(t,"error"),s={isError:r!=null,bytes:Buffer.byteLength(o),text:o};return Uf(n)&&(s.keep=!0),s}function Uf(e){return(Array.isArray(e)?e:[e]).some(n=>typeof n=="object"&&n!==null&&(Object.hasOwn(n,"inlineData")||Object.hasOwn(n,"fileData")))}var Hf=["https://","http://"],Ff=`.,;:!?)]}>'"`,vf=`
13
+ \r\f\v`;function jf(e){let t=[],n="";for(let o of e)vf.includes(o)?(n!==""&&t.push(n),n=""):n+=o;return n!==""&&t.push(n),t}function Gf(e){if(typeof e=="string")for(let t of jf(e)){let n=t.toLowerCase(),o=Hf.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&&Ff.includes(r[r.length-1]);)r=r.slice(0,-1);return r}}function Bf(e,t){if(e==="web_fetch"&&A(t,"url")===void 0){let n=Gf(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 xc(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(dc,n)?dc[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(fc,s)&&(r.source=fc[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:Pf(c,A(t,"mcp_context")),input:Bf(c,typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{})}}return o==="PostToolUse"&&(r.result=Mf(A(t,"tool_response"))),r}function _c(e,t,n){switch(t.kind){case"allow":return on;case"hint":return Df.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:on;case"deny":return kf.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
14
+ `+t.reason}),exitCode:0}:on;case"replace":return e.event!=="PostToolUse"?on:{stdout:JSON.stringify({decision:"deny",reason:Lf+t.output}),exitCode:0}}}var No="mcp__context-mode__",Xf={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Ec={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},Kf="PostToolUseFailure";function gc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===Kf,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=he(n,"qwen",No,Xf);if(o.tool!==void 0&&Object.hasOwn(Ec,o.tool.name)&&(o.tool.canonicalName=Ec[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 mc(e,t,n){return z(e,t,!1)}var cn="context-mode-",qf={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}},hc={startup:"startup",resume:"resume",new:"startup"},Vf={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"}},bc="success";function an(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var yo=Object.freeze(["bash","powershell"]),Sc=Object.fromEntries(yo.map(e=>[e,"Bash"]));function Jf(e){return e.startsWith(cn)?e.slice(cn.length):Object.hasOwn(Sc,e)?Sc[e]:e}var Oc=e=>typeof e=="number"&&Number.isFinite(e);function zf(e,t){let n=t.view_range;if(e!=="view"||!Array.isArray(n)||!Oc(n[0]))return t;let o={...t,offset:n[0]};return Oc(n[1])&&n[1]>=n[0]&&(o.limit=n[1]-n[0]+1),o}function $f(e){if(an(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return an(t)?t:{}}catch{return{}}}var Qf={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function Zf(e,t,n){let o=Qf[t],r=an(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==bc,bytes:Buffer.byteLength(s),text:s}}var e0=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function t0(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:e0.find(([t])=>Object.hasOwn(e,t))?.[1]}function Tc(e){if(!an(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=t0(e),n=typeof t=="string"?qf[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Vf[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"&&hc[e.source]!==void 0&&(s.source=hc[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:Jf(i),input:zf(i,$f(e[o.args]))};s.tool=c}return r==="PostToolUse"&&(s.result=Zf(e[o.result],n.casing,n.failure)),s}var sn={stdout:"",exitCode:0};function Rc(e,t,n){switch(t.kind){case"allow":return sn;case"hint":return e.event==="PostToolUse"?sn:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?sn:{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"?sn:{stdout:JSON.stringify({modifiedResult:{resultType:bc,textResultForLlm:t.output}}),exitCode:0}}}var ln="mcp_context-mode_",Dc=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],Ac="mcp_",Nc="_",o0="new",Io=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),dn=Object.freeze(["read_file","view"]),Co=Object.freeze(["fetch_webpage","web_fetch"]),yc=Object.fromEntries([...Io.map(e=>[e,"Bash"]),...dn.map(e=>[e,"Read"]),...Co.map(e=>[e,"WebFetch"])]);function kc(e){if(e.startsWith(ln))return e.slice(ln.length);if(Object.hasOwn(yc,e))return yc[e];if(!e.startsWith(Ac))return e;let t=e.slice(Ac.length),n=t.indexOf(Nc);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+Nc.length)}var dt=e=>typeof e=="number"&&Number.isFinite(e);function Lc(e,t,n){if(t==="Read"&&dn.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),dt(n.startLine)&&(o.offset=n.startLine),dt(n.startLine)&&dt(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&dt(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];dt(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 r0(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 s0={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},i0=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],Ic={new:"startup",startup:"startup",resume:"resume"},c0="success";function un(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function a0(e){if(un(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return un(t)?t:{}}catch{return{}}}function l0(e){let t=un(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==c0,bytes:Buffer.byteLength(n),text:n}}function Cc(e,t){let n=typeof t=="string"?s0[t]??Dc.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"&&Ic[e.source]!==void 0&&(o.source=Ic[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=kc(r);o.tool={name:r,canonicalName:s,input:Lc(r,s,a0(e.toolArgs))}}return n==="PostToolUse"&&(o.result=l0(e.toolResult)),o}function Pc(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 Cc(t,t.hookEventName);if(t.hook_event_name===void 0){let r=i0.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return Cc(t,r)}let n=Dc.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===o0&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=un(t.tool_input)?t.tool_input:{},i=kc(r);o.tool={name:r,canonicalName:i,input:Lc(r,i,s)}}return n==="PostToolUse"&&(o.result=r0(t.tool_response)),o}function wc(e,t,n){return z(e,t,!1)}var fn="mcp_context_mode_",Mc="mcp_context-mode_",Uc={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},d0="prompt",f0="USER_PROMPT",Hc="mcp_",Do=Object.freeze(["execute_bash","execute_pwsh","shell"]),Fc=Object.fromEntries(Do.map(e=>[e,"Bash"])),vc="_",jc={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function p0(e){if(e.startsWith(fn))return e.slice(fn.length);if(e.startsWith(Mc))return e.slice(Mc.length);if(Object.hasOwn(Fc,e))return Fc[e];if(!e.startsWith(Hc))return e;let t=e.slice(Hc.length),n=t.indexOf(vc);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+vc.length)}function x0(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function Gc(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(Uc,n)?Uc[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"&&jc[t.source]!==void 0&&(r.source=jc[t.source]),o==="UserPromptSubmit"){let s=t[d0],i=typeof s=="string"?s:process.env[f0];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:p0(s),input:i}}return o==="PostToolUse"&&(r.result=x0(t.tool_response)),r}function Bc(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 ko="mcp__context-mode__",Wc="mcp__plugin_context-mode_context-mode__",E0={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},g0={hook_event_name:"hookEventName",session_id:"sessionId"},m0="PostToolUseFailure";function Xc(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(g0))t[i]===void 0&&(t[i]=t[c]);let n=t.hook_event_name===m0;n&&(t.hook_event_name="PostToolUse");let r=(typeof t.tool_name=="string"?t.tool_name:"").startsWith(Wc)?Wc:ko,s=he(t,"zcode",r,E0);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 Kc(e,t,n){return z(e,t,!1)}var Lo="",Yc={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},qc={bash:"Bash",read:"Read",edit:"Edit",write:"Write"};function S0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function O0(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 Vc(e){return{...Po(e),agent:"omp"}}function Po(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(Yc,n)?Yc[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(qc,s)?qc[s]:s,input:S0(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=O0(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function b0(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 wo(e,t,n){let o=b0(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:Zi,content:o.stdout,timestamp:Date.now()}}function Mo(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var Qc="",Jc=ce+"_",zc={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},Uo="bash",Ho="read",R0=Object.freeze([Uo,"shell"]),A0="skill",$c={webfetch:"WebFetch",[Ho]:"Read",[A0]:"Skill",...Object.fromEntries(R0.map(e=>[e,"Bash"]))};function Fo(e){return e.startsWith(Jc)?e.slice(Jc.length):Object.prototype.hasOwnProperty.call($c,e)?$c[e]:e}function N0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function y0(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 Zc(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(zc,n)?zc[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:Fo(s),input:N0(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=y0(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function ea(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 ft={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},ta={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},C0={...ta,shell:[...sc]},D0=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:bo,nativeTools:C0,execReadOnlyHint:!1,eventMap:ft,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:V,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"skills"},decode:cc,encode:ac},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:Ao,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:ft,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:V,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:lc,encode:uc},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:rn,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:V,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:xc,encode:_c},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:No,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:ft,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:V,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:gc,encode:mc},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:cn,nativeTools:{shell:[...yo]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:V,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:Tc,encode:Rc},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:ln,nativeTools:{shell:[...Io],read:[...dn],webfetch:[...Co]},execReadOnlyHint:!1,eventMap:{...ft,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:V,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:Pc,encode:wc},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:fn,nativeTools:{shell:[...Do]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:V,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:Gc,encode:Bc},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:ko,nativeTools:ta,execReadOnlyHint:!1,eventMap:ft,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:V,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:Xc,encode:Kc},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:Lo,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:vt,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:Po,encode:wo,checkPermission:Mo},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:Qc,nativeTools:{shell:[Uo],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:vt,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:Zc,encode:ea,toCanonicalTool:Fo},{id:"omp",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:Lo,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:vt,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"omp/index.js"},skillChannel:{kind:"package",path:"skills"},decode:Vc,encode:wo,checkPermission:Mo}]),k0=new Map(D0.map(e=>[e.id,e])),L0=new Set(["claude-code","gemini","copilot-cli","pi","opencode","omp"]);function Se(e){return L0.has(e.id)}var P0=new Set(["claude-code","copilot-cli","pi","omp"]);function vo(e){return P0.has(e.id)&&Se(e)}var w0=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function pn(e){return w0.has(e.id)}function $(e){return k0.get(e)}import{resolve as Rt}from"node:path";var M0=["&&","||",";;","|&",";","|","&","(",")"],U0=["&>>","&>"],H0=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],F0="&",v0="<<",na="<<-",j0=";",oa=`\r
19
+ `,ra=`\\
20
+ `,sa=`\\\r
21
+ `,G0="$(",aa="${",la="$'",pt="((",ia="))",Pe="[[",xn="]]",jo="<(",ua=">(",G=2,da=`
22
+ \r;&|()<>`,B0=`
23
+ \r`,W0='$`"\\\n',X0="case",K0="esac";function we(e,t){e.end==="complete"&&(e.end=t)}function Go(e){return e!==""&&e>="0"&&e<="9"}function ca(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function fa(e){return e===""||da.includes(e)}function Bo(e){return e!==""&&B0.includes(e)}function Q(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function _n(e,t){let n=e.s.indexOf("'",t+1);return n<0?(we(e,"unterminated-quote"),e.n):n+1}function pa(e,t){let n=t+la.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=G;continue}if(o==="'")return n+1;n++}return we(e,"unterminated-quote"),e.n}function Wo(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+=G;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=xt(e,o,n);continue}if(r==="$"&&s==="{"){o=Xo(e,o,n);continue}if(r==="`"){o=Me(e,o);continue}o++}return we(e,"unterminated-quote"),e.n}function Me(e,t){let n=t+1;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=G;continue}if(o==="`")return n+1;n++}return e.n}function Xo(e,t,n){let o=t+aa.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=G;continue}if(s==="'"){o=_n(e,o);continue}if(s==='"'){o=Wo(e,o,n);continue}if(s==="$"&&i==="("){o=xt(e,o,n);continue}if(s==="`"){o=Me(e,o);continue}if(s==="{"&&r++,s==="}"){if(r===0)return o+1;r--}o++}return e.n}function Ko(e,t){let n=0,o=t+pt.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(ia,o)?o+ia.length:-1;n--}o++}return-1}function xt(e,t,n){let o=t+G0.length-1;if(e.s.startsWith(pt,o)){let r=Ko(e.s,o);if(r>0)return r}return En(e,o+1,!0,n+1,null,null)}function Y0(e,t,n){let o=t+Pe.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=G;continue}if(s==="'"){o=_n(e,o);continue}if(s==='"'){o=Wo(e,o,n);continue}if(s==="$"&&i==="("){o=xt(e,o,n);continue}if(s==="$"&&i==="{"){o=Xo(e,o,n);continue}if(s==="`"){o=Me(e,o);continue}let c=Bo(e.s.charAt(o-1));if(c&&e.s.startsWith(xn,o)&&fa(e.s.charAt(o+xn.length))){if(r===0)return o+xn.length;r--,o+=xn.length;continue}if(c&&e.s.startsWith(Pe,o)&&Bo(e.s.charAt(o+Pe.length))){r++,o+=Pe.length;continue}o++}return-1}function q0(e,t){let n=t;for(;Go(e.charAt(n));)n++;if(n===t){for(let o of U0)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of H0){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(F0))if(e.charAt(r)==="-")r++;else for(;Go(e.charAt(r));)r++;return{end:r,op:o}}return null}function V0(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(da.includes(r))break;if(r==="\\"){o+=G;continue}if(r==="'"){o=_n(e,o);continue}if(r==='"'){o=Wo(e,o,n);continue}if(r==="$"&&s==="'"){o=pa(e,o);continue}if(r==="$"&&s==="("){o=xt(e,o,n);continue}if(r==="$"&&s==="{"){o=Xo(e,o,n);continue}if(r==="`"){o=Me(e,o);continue}o++}return Math.min(o,e.n)}function J0(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),Q(o,"unhandled",e.s.slice(c,s),c,s),!a)return we(e,"unterminated-heredoc"),e.n}return n.length=0,s}function En(e,t,n,o,r,s){if(o>J)return we(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),p=i.charAt(c+1);if(f===" "||f===" "){c++;continue}if(i.startsWith(ra,c)){c+=ra.length;continue}if(i.startsWith(sa,c)){c+=sa.length;continue}if(f===`
25
+ `||f==="\r"){let S=c;c+=i.startsWith(oa,c)?oa.length:1,Q(r,"op",j0,S,c),u=null,d.length>0&&(c=J0(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(jo,c)||i.startsWith(ua,c)){let S=En(e,c+jo.length,!0,o+1,null,null);Q(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}let x=q0(i,c);if(x!==null){Q(r,"io",i.slice(c,x.end),c,x.end),u=x.op===v0||x.op===na?x.op===na:null,c=x.end;continue}if(i.startsWith(Pe,c)&&Bo(i.charAt(c+Pe.length))){let S=Y0(e,c,o);if(S>0){Q(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}if(i.startsWith(pt,c)){let S=Ko(i,c);if(S>0){Q(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let g=M0.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}Q(r,"op",g,c,c+g.length),c+=g.length,u=null;continue}if(f==="$"&&p==="("||f==="`"){let S=f==="`"?Me(e,c):xt(e,c,o);if(fa(i.charAt(S))){Q(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let E=c;c=V0(e,c,o);let h=i.slice(E,c);Q(r,"word",h,E,c),u!==null&&(d.push({tag:Ue(h),strip:u}),u=null),n&&h===X0&&l++,n&&h===K0&&l>0&&l--}return d.length>0&&we(e,"unterminated-heredoc"),e.n}function xa(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 Ue(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=G;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+la.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=G;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!==""&&W0.includes(i)){t+=i,s+=G;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function gn(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+=G;continue}if(!o&&s==="'"){r=_n(t,r);continue}if(!o&&s==="$"&&i==="'"){r=pa(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=aa.length;continue}let c=e.startsWith(jo,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(ua,r))){let a=r+1;if(s==="$"&&e.startsWith(pt,a)&&Ko(e,a)>0){r=a+pt.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=Me(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 mn(e){let t=e.charAt(0);if(!(ca(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(!(ca(o)||Go(o)||o==="_"))return!1}return!1}var ma=[";","&","&&","||"],ha=["|","|&"],_t="(",Et=")",Sa=";;",Vo=["(",")"],z0="!";function B(e,t){for(let n of t)e.push(n)}var O=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"}),Oa=[],$0="[[",Q0="((",ba=[">",">>",">|","&>","&>>",">&"],Z0=[...ba,"<","<>","<<<","<<","<<-"],ep=["","1"],Ta=["-","/dev/stdout","/dev/stderr"],Sn="-",gt="--",mt="=",tp="/",np=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),hn=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),Yo="-c",qo="--bytes",op="c",rp="--count",Oe=()=>({cmds:[],simple:null}),b=(e,t=0)=>e.toks[e.i+t],le=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,L=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,Jo=e=>e!==""&&e>="0"&&e<="9",sp=e=>Jo(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function zo(e){let t=e.lastIndexOf(tp);return t>=0&&t<e.length-1?e.slice(t+1):e}function $o(e,t){let n=np[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===gt)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+mt))s=r.slice(n.long.length+mt.length);else if(r.startsWith(Sn)&&!r.startsWith(gt)){let i=r.indexOf(n.short,Sn.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&&!Ta.includes(s))return!0}return!1}function ip(e){if(e==="")return!1;for(let t of e)if(!Jo(t))return!1;return!0}function cp(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===Yo||n===qo?o=e[t+1]:n.startsWith(qo+mt)?o=n.slice(qo.length+mt.length):n.startsWith(Yo)&&!n.startsWith(gt)&&(o=n.slice(Yo.length)),o!==void 0)return ip(o)&&Number(o)<=Y}return!1}function ap(e){for(let t of e){if(t===gt)return!1;if(t===rp||t.startsWith(Sn)&&!t.startsWith(gt)&&t.includes(op))return!0}return!1}function _a(e){if(!e.startsWith(H.fieldSep))return!1;for(let t of e.slice(H.fieldSep.length).split(H.fieldSep)){if(t==="")return!1;for(let n of t)if(!sp(n))return!1}return!0}function lp(e){let t=e.trim();if(t===H.identity||t===H.length)return!0;let n=t.indexOf(H.pipeLength.charAt(0));if(n<0)return _a(t);let o=t.slice(0,n).trim(),r=H.pipeLength.slice(1).trim();return(o===H.identity||_a(o))&&t.slice(n+1).trim()===r}function up(e){let t=e.argv0.toLowerCase();if(t===hn.wc)return!0;if(t===hn.head)return cp(e.args);if(t===hn.grep)return ap(e.args);if(t===hn.jq){let n=e.args.filter(o=>!o.startsWith(Sn));return n.length===1&&lp(n[0])}return!1}function Qo(e){return gn(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function Ra(e,t,n){return n<=t?[]:Qo(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function Aa(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function dp(e){let t=0;for(;Jo(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Na(e){let t=dp(e.toks[e.i].text);if(e.i++,!Z0.includes(t.op))return!1;let n=b(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,ba.includes(t.op)&&ep.includes(t.fd)&&!Ta.includes(Ue(n.text)))}function ya(e){let t=!1;for(;b(e)?.kind==="io";)t=Na(e)||t;return t}function Ia(e){for(;b(e)?.kind==="op"&&ma.includes(b(e)?.text??"");)e.i++}function He(e,t){if(e.depth++,e.depth>J)return e.err="nesting-too-deep",Oe();let n=t();if(e.depth--,ya(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function Ca(e){if(Ia(e),!L(b(e),O.do))return[];e.i++;let t=Z(e,[O.done]);return L(b(e),O.done)&&e.i++,t}function fp(e){e.i++;let t=Z(e,[O.then]);for(;e.err===null;){let n=b(e);if(L(n,O.then)||L(n,O.else)){e.i++,B(t,Z(e,[O.elif,O.else,O.fi]));continue}if(L(n,O.elif)){e.i++,B(t,Z(e,[O.then]));continue}L(n,O.fi)&&e.i++;break}return t}function pp(e){e.i++;let t=Z(e,[O.do]);return B(t,Ca(e)),t}function xp(e){e.i++;let t=[],n=b(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,L(b(e),O.in)){e.i++;let o=e.i;for(;(b(e)?.kind==="word"||b(e)?.kind==="unhandled")&&!L(b(e),O.do);)e.i++;B(t,Ra(e,o,e.i))}return B(t,Ca(e)),t}function _p(e){e.i++;let t=[],n=b(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,B(t,Ra(e,e.i-1,e.i))),L(b(e),O.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"&&(ma.includes(o.text)||o.text===Sa)){e.i++;continue}if(L(o,O.esac)){e.i++;break}for(le(o,_t)&&e.i++;e.i<e.toks.length&&!le(b(e),Et);){let s=e.toks[e.i];if(s.kind==="op"&&!ha.includes(s.text))break;e.i++}if(!le(b(e),Et))break;e.i++;let r=Z(e,[O.esac]);Aa(r,O.case),B(t,r)}return t}function Ea(e,t){Ia(e);let n=Da(e);return Aa(n.cmds,t),{cmds:n.cmds,simple:null}}function ga(e,t){return Vo.every((n,o)=>le(e.toks[t+o],n))}function Ep(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=Na(e)||o;continue}if(n.length===0&&l.kind==="word"&&mn(l.text)){e.i++;let u=b(e);if(l.text.endsWith(mt)&&u!==void 0&&le(u,_t)&&u.start===l.end){let d=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,le(f,_t)&&d++,le(f,Et)&&--d===0)break}}continue}n.push(l),e.i++}if(e.i===t)return Oe();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:Qo(r),simple:null};let s=l=>l.kind==="word"?Ue(l.text):l.text,i=zo(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||$o(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function Da(e){let t=b(e);if(t===void 0)return Oe();if(t.kind==="op")return t.text!==_t?Oe():He(e,()=>{e.i++;let n=Z(e,Oa);return le(b(e),Et)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith($0)||t.text.startsWith(Q0)))return e.i++,ya(e),{cmds:Qo(t.text),simple:null};if(t.kind==="word")switch(t.text){case O.group:return He(e,()=>{e.i++;let n=Z(e,[O.groupEnd]);return L(b(e),O.groupEnd)&&e.i++,n});case O.if:return He(e,()=>fp(e));case O.while:case O.until:return He(e,()=>pp(e));case O.for:return He(e,()=>xp(e));case O.case:return He(e,()=>_p(e));case O.coproc:return e.err="coproc",Oe();case O.select:return e.err="select",Oe();case O.function:{e.i++;let n=b(e),o="";return n?.kind==="word"&&(o=Ue(n.text),e.i++),ga(e,e.i)&&(e.i+=Vo.length),Ea(e,o)}default:if(ga(e,e.i+1))return e.i+=Vo.length+1,Ea(e,Ue(t.text))}return Ep(e)}function gp(e){L(b(e),z0)&&e.i++;let t=[],n=Oe();for(;e.err===null;){n=Da(e),B(t,n.cmds);let o=b(e);if(o!==void 0&&o.kind==="op"&&ha.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&up(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function Z(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===Et||o.text===Sa)return n;if(o.text!==_t){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;B(n,gp(e)),e.i===r&&e.err===null&&e.i++}return n}function Fe(e){let t=xa(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;)B(o,Z(n,Oa)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as ka}from"node:path";var bn="'",ve='"',Tn="`",mp=" \r",St="([{",nr=")]}",Zo=` \r
27
+ |;>`,wa="*",La="1",er="::",On=er.length,hp=On;function Rn(e,t){let n=e.charAt(t);for(let o=t+1;o<e.length;o++){let r=e.charAt(o);if(n===ve&&r===Tn){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function Sp(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===ve&&r===Tn&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function ht(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===bn||r===ve){let s=Rn(e,o);if(s<0)return-1;o=s;continue}if(r===Tn){o++;continue}if(St.includes(r))n++;else if(nr.includes(r)&&--n===0)return o}return-1}function Op(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===bn||r===ve){let s=Rn(e,o);if(s<0)return e.length;o=s;continue}if(St.includes(r))n++;else if(nr.includes(r))n--;else if(n<=0&&Zo.includes(r))return o}return e.length}function bp(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===bn||s===ve){let i=Rn(e,r);if(i<0)break;r=i;continue}St.includes(s)?n++:nr.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var Tp=e=>e!==""&&(e===wa||[...e].every(t=>t>="0"&&t<="9")),Pa=()=>({words:[],toFile:!1,chained:!1});function Ma(e){let t=[],n=[],o=Pa(),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=Pa()},d=()=>{u(),n.length>0&&t.push(n),n=[]},f=(x,g)=>{r+=x,s=!0,g&&(i=!1)},p=0;for(;p<a;){let x=e.charAt(p),g=e.charAt(p+1);if(x===bn||x===ve){let E=Rn(e,p);f(Sp(e.slice(p+1,E<0?a:E),x),!0),p=E<0?a:E+1}else if(x===Tn)g!==`
28
+ `&&g!==""&&f(g,!1),p+=On;else if(x===`
29
+ `)d(),p++;else if(mp.includes(x))l(),p++;else if(x===";")d(),p++;else if(x==="|")g==="|"?(d(),p+=On):(u(),p++);else if(x==="&")g==="&"?(d(),p+=On):((s||o.words.length>0)&&f(x,!1),p++);else if(x==="#"&&!s)for(;p<a&&e.charAt(p)!==`
30
+ `;)p++;else if(x===">"){let E=La;s&&i&&Tp(r)?(E=r,r="",s=!1):s&&l();let h=p+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<a&&!Zo.includes(e.charAt(h));)h++;else c=E===La||E===wa?"file":"skip";p=h}else if(x==="("&&s&&i&&r.includes(er)){let E=ht(e,p),h=e.slice(p+1,E<0?a:E);l();for(let S of h.trim()===""?[]:bp(h)){let _=Ma(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}p=E<0?a:E+1,p<a&&!Zo.includes(e.charAt(p))&&(o.chained=!0,p=Op(e,p))}else if(x==="["&&!s&&e.startsWith(er,ht(e,p)+1)&&ht(e,p)>=0){let E=ht(e,p);f(e.slice(p,E+1),!1),p=E+1}else if(St.includes(x)&&(x!=="["||!s)||(x==="$"||x==="@")&&St.includes(g)&&g!=="["){let E=x==="$"||x==="@"?p+1:p,h=ht(e,E);f(e.slice(p,h<0?a:h+1),!0),p=h<0?a:h+1}else f(x,!1),p++}return d(),t}var Rp=["get-content","gc","cat","type"],Ap=["[io.file]::","[system.io.file]::"],Np=["readalltext","readalllines","readallbytes","readlines"],or=["path","literalpath"],Ua=["totalcount","head","first","tail","last"],Ha=[...or,...Ua,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],yp=["raw","wait","force","asbytestream"],Ip=[...Ha,...yp],Cp=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],Dp=["cd","chdir","sl","set-location","pushd","push-location"],kp=["powershell","powershell.exe","pwsh","pwsh.exe"],Lp=["cmd","cmd.exe"],Pp=["/c","/k","/r"],wp="command",be="-";function tr(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function rr(e,t){let n=e.slice(be.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 Mp(e){if(e.length===0)return null;let t=tr(e[0]);if(!Rp.includes(t)){let r=e[0].toLowerCase(),s=Ap.find(i=>r.startsWith(i));return s===void 0||!Np.includes(r.slice(s.length))||e.length<hp?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(be)||s.length===be.length){n.push(s);continue}let i=rr(s,Ip);if(i.full===void 0||!Ha.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;or.includes(i.full)&&n.push(c),Ua.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function Up(e,t){if(kp.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(be)||o.length===be.length)continue;let r=rr(o,[wp]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(Lp.includes(e)){for(let n=1;n<t.length;n++)if(Pp.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function Hp(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(be)||n.length===be.length)return n;let o=rr(n,or);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function Fa(e,t,n,o){let r=t;for(let s of Ma(e)){let i=s[0];if(i.words.length===0)continue;let c=tr(i.words[0]);if(s.length===1&&Dp.includes(c)){let d=Hp(i.words);d!==null&&(r=ka(r,d));continue}let a=n<J?Up(c,i.words):null;if(a!==null){Fa(a,r,n+1,o);continue}if(i.toFile||i.chained)continue;let l=Mp(i.words);if(l===null||l.bounded)continue;let u=!0;for(let d=1;d<s.length;d++)if(s[d].toFile||!Cp.includes(tr(s[d].words[0]??""))){u=!1;break}u&&o.push(ka(r,l.file))}}function va(e,t){let n=[];return Fa(e,t,0,n),n}import{join as je}from"node:path";var ja=`\r
31
+ `,Fp=`
32
+ `;function An(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(ja)<0?t:t.split(ja).join(Fp)}import{basename as Bp,dirname as Wp,join as ee,posix as Ba,resolve as Xp,win32 as Wa}from"node:path";var vp=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 and the folders added to this session. Fix: use a path inside <root>, or add its folder to the session (Claude Code /add-dir, Codex --add-dir).",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 jp(e,t){let n=vp[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(jp(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{existsSync:jh,mkdirSync:Gp,readFileSync:Gh,readdirSync:Bh,realpathSync:Ga}=process.getBuiltinModule("node:fs");function W(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[qi];return n!==void 0&&n!==""?n:ee(t,...k.codex)}function Ka(e,t){let n=e[Vi];return n!==void 0&&n!==""?n:ee(t,...k["copilot-cli"])}function Ya(e,t){let n=e[Ji];return ee(n!==void 0&&n!==""?n:t,...k.gemini)}function qa(e,t,n=process.platform){let o=n==="win32"?Wa:Ba,r=o.join(t,...k.kiro),s=e[zi]?.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?Kp: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 Kp(e){let t=[];for(let n=e;;)try{return ee(Ga.native(n),...t.reverse())}catch{let o=Wp(n);if(o===n)return e;t.push(Bp(n)),n=o}}function te(e,t){let n=e[en];return n!==void 0&&n!==""?n:ee(t,...k["claude-code"])}function Va(e,t){let n=e[$i];if(n!==void 0&&n!=="")return n;let o=e[nn];return o!==void 0&&o!==""?ee(o,k.opencode[k.opencode.length-1]):ee(t,...k.opencode)}function Ja(e,t){let n=e[ec];return n!==void 0&&n!==""?n:ee(t,...k.pi,Qi)}function za(e,t,n=process.platform){let o=s=>s!==void 0&&s!=="",r=n==="win32"?Wa:Ba;return n==="win32"?r.join(o(e[Oo])?e[Oo]:r.join(t,"AppData","Roaming"),...tn):n==="darwin"?r.join(t,"Library","Application Support",...tn):r.join(o(e[nn])?e[nn]:r.join(t,".config"),...tn)}function Yp(e,t=process.platform){let n=W(e,t);if(n!==null)return n;throw new R("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function Nn(e,t){let n=e[ot];return n!==void 0&&n!==""?Xp(n):ee(t,Fs.slice(1))}function $a(e){let t=e[ot],n=Nn(e,t!==void 0&&t!==""?"":Yp(e));return Gp(n,{recursive:!0}),Ga.native(n)}var{readFileSync:ol,readdirSync:qp}=process.getBuiltinModule("node:fs"),Qa=Object.freeze(["Agent","Artifact","ArtifactComments","ArtifactData","ArtifactCheck","ExitPlanMode","Edit","Write","NotebookEdit"]),Za=Object.freeze({"general-purpose":{tools:null,disallowed:[]},fork:{tools:null,disallowed:[]},claude:{tools:null,disallowed:[]},Explore:{tools:null,disallowed:[...Qa]},Plan:{tools:null,disallowed:[...Qa]},"claude-code-guide":{tools:["Glob","Grep","Read","WebFetch","WebSearch"],disallowed:[]},"statusline-setup":{tools:["Read","Edit"],disallowed:[]},"web-fetch":{tools:["WebFetch"],disallowed:[]}}),Vp="claude-code";function Ge(e){return e.agentId!==void 0&&e.agentId!==""}function ir(e,t){if(t===null)return"C";let n=$(e.agent),o=new Set(t);for(let r of Mt)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function cr(e,t){if(!Ge(e))return null;let n=$(e.agent);if(t.manifestTools!==void 0)return nl(t.manifestTools.map(a=>sr(n,a)));let o=e.agentType??"",r=Jp(o,t)??zp(e.agent,o);if(r===null)return null;let s=ox(n),i=r.tools===null?s:r.tools.map(a=>sr(n,a)).flatMap(a=>[a,...s.filter(l=>sx(a,l))]),c=r.disallowed.map(a=>sr(n,a));return nl(i.filter(a=>!c.some(l=>ix(l,a))))}function Jp(e,t){if(!$p(e))return null;let n=Qp(t.env);if(e.indexOf(De)>=0){if(n!==null){let s=Zp(te(t.env,n),e);if(s!==null)return s}}else{let s=yn(je(t.projectDir,js,rt,e+me));if(s!==null)return s;if(n!==null){let i=yn(je(te(t.env,n),rt,e+me));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 zp(e,t){if(e!==Vp||!Object.prototype.hasOwnProperty.call(Za,t))return null;let n=Za[t];return{tools:n.tools,disallowed:[...n.disallowed]}}function $p(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(De))if(t===""||t==="."||t==="..")return!1;return!0}function Qp(e){return W(e)}function Zp(e,t){let n=t.indexOf(De),o=t.slice(0,n),r=t.slice(n+De.length);return r.indexOf(De)>=0?null:ex(e,o,r)??tx(e,o,r)}function ex(e,t,n){let o;try{o=JSON.parse(An(ol(je(e,Bt,Bs),"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(Ws);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=yn(je(l,rt,n+me));if(u!==null)return u}}return null}function tx(e,t,n){let o=je(e,Bt,Gs),r;try{r=qp(o).sort()}catch{return null}for(let s of r){if(s.startsWith("."))continue;let i=yn(je(o,s,t,rt,n+me));if(i!==null)return i}return null}function yn(e){let t;try{t=ol(e,"utf8")}catch{return null}return nx(t)}function nx(e){let t=e.split(`
33
+ `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==ro)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===ro){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=el(o,Xs),s=el(o,Ks);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function el(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(tl(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>tl(s.trim())).filter(s=>s!=="")}return null}function tl(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function ox(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...Mt.map(n=>e.toolNamePrefix+n)]}function sr(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(qs)?rx(o):o}function rx(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||Vs.indexOf(n)>=0;t+=o?n:"_"}return t}function sx(e,t){if(!e.startsWith(j))return!1;let n=ke+"*",o=e.slice(j.length,e.endsWith(n)?-n.length:e.length);return o===""||o.indexOf("*")>=0||o.indexOf(ke)>=0?!1:t.startsWith(j+o+ke)}function ix(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(j)){let n=e.slice(j.length);if(n!==""&&n.indexOf(ke)<0)return t.startsWith(e+ke)}return!1}function nl(e){return[...new Set(e.filter(t=>t!==""))]}var ne="",rl=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:ne,subcommands:[]},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:ne,subcommands:[]},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:ne,subcommands:[]},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:ne,subcommands:[]},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:ne,subcommands:[]},command:{valueShorts:ne,valueLongs:[],assignments:!1,duration:!1,refuseShorts:"vV",subcommands:[]},xargs:{valueShorts:"aEdILnPs",valueLongs:["--arg-file","--delimiter","--max-args","--max-procs","--max-chars"],assignments:!1,duration:!1,refuseShorts:ne,subcommands:[]},rtk:{valueShorts:ne,valueLongs:[],assignments:!1,duration:!1,refuseShorts:ne,subcommands:["proxy","bypass"]}}),cx=["bash","sh","zsh"],ax="c",lx=" -c",ux=["-o","+o","-O","+O"],In="-",dx="+",ar="--",fx="smhd",px=".",sl=e=>e!==""&&e>="0"&&e<="9";function xx(e){if(e===""||!sl(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(sl(n)||n===px))return t===e.length-1&&fx.includes(n)}return!0}function _x(e,t){let n=0;if(e.subcommands.length>0){if(t.length===0||!e.subcommands.includes(t[0]))return null;n=1}for(;n<t.length;){let o=t[n];if(o===ar){n++;break}if(e.assignments&&mn(o)){n++;continue}if(o.startsWith(ar)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(In)&&o.length>In.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=In.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||!xx(t[n]))return null;n++}return n<t.length?t.slice(n):null}function Ex(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(ar)){if(o.startsWith(In)||o.startsWith(dx)){o.includes(ax)&&(t=!0),ux.includes(o)&&n++;continue}return t?o:null}}return null}function il(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function lr(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let a=s.toLowerCase();if(cx.includes(a)){let d=Ex(i),f=d!==null&&n<J?Fe(d):null;if(f===null||!f.ok)break;for(let p of f.commands){let x=il(p,e);x.redirectsToFile=p.redirectsToFile||c,x.endsInBoundedSink=p.endsInBoundedSink||e.endsInBoundedSink,lr(x,[...r,a+lx],n+1,o)}return}let l=Object.hasOwn(rl,a)?rl[a]:void 0,u=l===void 0?null:_x(l,i);if(u===null)break;r.push(a),s=zo(u[0]),i=u.slice(1),c=c||$o(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=J))for(let a of gn(e.raw)){let l=Fe(a.body);if(l.ok)for(let u of l.commands)lr(il(u,e),[...t,a.wrapper],n+1,o)}}function ur(e){let t=[];for(let n of e)lr(n,[],0,t);return t}import{isAbsolute as mx,join as dr,relative as hx,sep as fr}from"node:path";var{readFileSync:gx}=process.getBuiltinModule("node:fs"),cl=".claude",Sx="settings.local.json",al="settings.json",_l="Bash",Ox="Read",ll=":*",ul="//",dl="~/",fl="./",pl="..",bx=`
34
+ \r`,Tx=Object.freeze({tool:_l});function Rx(e,t){if(t!=="claude-code")return[];let n=W(process.env),o=process.env[en],r=o!==void 0&&o!==""?o:n===null?null:te(process.env,n),s=[dr(e,cl,Sx),dr(e,cl,al)];return r===null?s:[...s,dr(r,al)]}function xl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ax(e){let t;try{t=An(gx(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!xl(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!xl(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 El(e,t){let n=[];for(let o of Rx(e,t)){let r=Ax(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function pr(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 xr(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,p=f?t[d]:"";switch(a.t){case"lit":i[d]=f&&p===a.c?s[d+1]:0;break;case"any1":i[d]=f&&!(n&&p==="/")?s[d+1]:0;break;case"star":i[d]=s[d]||(f&&!(n&&p==="/")?i[d+1]:0);break;case"globstar":i[d]=s[d]||(f?i[d+1]:0);break;case"globstarDir":f&&p==="/"&&s[d+1]&&(l=1),i[d]=s[d]||l;break}}let u=i;i=s,s=u}return s}function Ot(e,t,n){let o=pr(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,xr(o,t,n,s)[0]===1}function gl(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 ml(e,t){let n=t.length,o=new Uint8Array(n+1);if(o[n]=1,!e.endsWith(ll))return xr(pr(e,!1),t,!1,o);for(let r=0;r<n;r++)bx.includes(t[r])&&(o[r]=1);return xr(pr(e.slice(0,e.length-ll.length),!1),t,!1,o)}function Nx(e,t){return ml(e,t)[0]===1}function hl(e,t,n){for(let o of t){let r=gl(o);if(r===null||r.tool!==_l)continue;let s=ml(r.glob,e);for(let i=0;i<=e.length;i++)if(n[i]===1&&s[i]===1)return o}return null}var yx=/^[A-Za-z]:(?=\/)/;function bt(e){return fr==="/"?e:e.split(fr).join("/")}function Ix(e,t,n){if(e.startsWith(fl)){if(n===void 0)return!1;let r=hx(n,t);return r===""||r===pl||r.startsWith(pl+fr)||mx(r)?!1:Ot(e.slice(fl.length),bt(r),!0)}let o=bt(t);if(e.startsWith(ul)){let r=bt(e.slice(ul.length-1));return Ot(r,o,!0)||Ot(r,o.replace(yx,""),!0)}if(e.startsWith(dl)){let r=W(process.env);return r!==null&&Ot(bt(r)+e.slice(dl.length-1),o,!0)}return Ot(bt(e),o,!0)}function Be(e,t,n=Tx){for(let o of t){let r=gl(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===Ox?Ix(r.glob,e,n.projectDir):Nx(r.glob,e))return o}return null}var aS=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. Set `source` with queries `[""]` to read that source whole, in order, a full page per call; `More:` gives the next `offset`. 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.'}),Sl='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.',Ol=`context-mode: {size}-byte file, over the one-read limit. Read "{path}" in parts with offset and limit, or sed -n '1,200p'.`;var bl="{size}",Tl="{path}";function Rl(e,t,n=""){return U(Sl,n).split(bl).join(String(t)).split(Tl).join(e)}function Al(e,t){return Ol.split(bl).join(String(t)).split(Tl).join(e)}import{extname as Lx,join as _r,resolve as Px}from"node:path";import{dirname as Nl,isAbsolute as Cl,join as _S,relative as ES,resolve as Dl,sep as kl}from"node:path";var{lstatSync:pS,realpathSync:Cx}=process.getBuiltinModule("node:fs");function Tt(e){try{return Cx.native(e)}catch{return}}function D(e){return e.split(kl).filter(t=>t!=="")}function Ll(e,t){let n=Tt(e),o=Tt(t);if(n===void 0||o===void 0)return!1;let r=D(n),s=D(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 yl=new Map;function Dx(e){let t=yl.get(e);if(t!==void 0)return t;let n=Tt(e);return n!==void 0&&yl.set(e,n),n}function We(e,t){if(e.length===0)return!1;let n=Tt(t);if(n===void 0)return!1;let o=D(n);return e.some(r=>{let s=Dx(r);if(s===void 0)return!1;let i=D(s);return o.length>=i.length&&i.every((c,a)=>c===o[a])})}function Pl(e,t){return(Cl(t)?D(t):[...D(e),...D(t)]).includes("..")}var Il=new Map;function kx(e){let t=Il.get(e);return t===void 0&&(t=D(Dl(e)),Il.set(e,t)),t}function wl(e,t){if(e.length===0)return!1;let n=D(t);if(n.includes(".."))return!1;let o=kl==="/"&&Cl(t)?n.filter(r=>r!=="."):D(Dl(t));return e.some(r=>{let s=kx(r);return o.length>=s.length&&s.every((i,c)=>i===o[c])})}function Ml(e){let t=e.map(Tt).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=D(n).length;for(let s of t){let i=D(s),c=D(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;D(r).length>o&&Nl(r)!==r;)r=Nl(r);return r}function wx(e,t){let n=W(t);if(n===null)return[];let o=_r(n,...Js);return[...e==="claude-code"?[te(t,n)]:e==="codex"?[Xa(t,n)]:e==="gemini"?[Ya(t,n)]:e==="copilot-cli"?[Ka(t,n)]:e==="kiro"?[qa(t,n)]:e==="opencode"?[Va(t,n)]:e==="pi"?[Ja(t,n)]:e==="vscode"?[_r(n,...k.vscode),za(t,n)]:[_r(n,...k[e])],o]}function Xe(e,t,n,o=process.env){if(Lx(n).toLowerCase()!==me)return!1;let r=wx(e,o),s=Px(t,n);return!Pl(t,n)&&wl(r,s)||We(r,s)}import{extname as Fx}from"node:path";var{closeSync:Mx,openSync:Ux,readSync:Hx}=process.getBuiltinModule("node:fs");function vx(e){let t=null;try{t=Ux(e,"r");let n=Buffer.alloc(uo),o=Hx(t,n,0,uo,0);return n.subarray(0,o)}catch{return null}finally{t!==null&&Mx(t)}}function Cn(e,t){let n=Ni[e]??[];if(n.length===0)return!1;let o=Fx(t).toLowerCase(),r=n.filter(i=>lo[i].exts.includes(o));if(r.length===0)return!1;let s=vx(t);return s===null?!1:r.some(i=>lo[i].sig.every(c=>c.bytes.every((a,l)=>s[c.at+l]===a)))}var{statSync:jx}=process.getBuiltinModule("node:fs"),Gl="Bash",gr="Read",Gx="WebFetch",Bx="ctx_execute",Wx="ctx_batch",Bl="shell",Xx="1",ue="-",mr="--",Kx="=",Yx=".",Ul=",",Er="p",qx=["-e","--expression"],Hl=".exe",Vx=";&|(`\n\r",Ae=Object.freeze({kind:"allow"}),Te=e=>({kind:"deny",reason:e}),Re=e=>typeof e=="string"?e:void 0,Fl=e=>e!=null,oe=(e,t)=>e.includes(t);function Wl(e,t,n,o=e.cwd){let r=e.tool;if(r===void 0)return Ae;let s=r.canonicalName,i=r.input,c;if(n===null){if(process.env[vs]===Xx)return Te(U(Wt,t.toolNamePrefix));process.stderr.write(fi+`
35
+ `),c=[]}else c=n;let a=zx(s,i,e.cwd,c);return a!==null?Te(st+a):s===Gx?e_(i,t):s===Gl?t_(e,t,i,c,o):s===gr?a_(e,t,i,o):Ae}function Xl(e,t,n,o){let r=e==="webfetch",s=r?ni.map(c=>n.toolNamePrefix+c).join(di):n.toolNamePrefix+ti,i=JSON.stringify(r?{url:t}:{language:Bl,code:t,intent:o??ei});return[so+zs[e]+$s,Qs,Zs+s,i].join(`
36
+ `)}function Jx(e){for(let t of ae){let n=Re(e[t]);if(n!==void 0&&n!=="")return n}}function Kl(e){let t=Jx(e),n=Array.isArray(e[Le])?e[Le].filter(o=>typeof o=="string"&&o!==""):[];return t===void 0?n:[t,...n]}function zx(e,t,n,o){if(o.length===0)return null;let r=s=>Be(Rt(n,s),o,{tool:gr,projectDir:n});if(e===Gl){let s=Re(t.command);return s===void 0?null:Be(s,o)}if(e===gr){for(let s of Kl(t)){let i=r(s);if(i!==null)return i}return null}if(e===Bx){let s=Re(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=Re(t.code);return $x(t.language)&&c!==void 0?vl(c,o):null}if(e===Wx&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?vl(s,o):null;if(i!==null)return i}return null}function $x(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(Hl)&&(t=t.slice(0,t.length-Hl.length)),t===Bl||oe(ws,t)}function vl(e,t){let n=Be(e,t);if(n!==null)return n;let o=Fe(e);if(!o.ok)return ql(e,t);for(let r of ur(o.commands)){let s=Yl(r,t);if(s!==null)return s}return null}function Yl(e,t){return t.length===0?null:Be([e.argv0,...e.args].join(" "),t)??Be(e.raw,t)}function ql(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||Vx.includes(e.charAt(r-1)))&&(o=!0),o&&(r===e.length||e.charAt(r).trim()!=="")&&(n[r]=1,o=!1);return hl(e,t,n)}function Qx(e,t){return ql(e,t)!==null}function Zx(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return pi.some(n=>t===n||t.endsWith(Yx+n))}function e_(e,t){let n=Re(e.url)??"";return Zx(n)?Ae:Te(Xl("webfetch",n,t))}function t_(e,t,n,o,r){let s=Re(n.command)??"",i=Fe(s);if(!i.ok)return Qx(s,o)?Te(U(Xt,t.toolNamePrefix)):jl(e,s,t,r)??Ae;let c=ur(i.commands);for(let a of c){let l=Yl(a,o);if(l!==null)return Te(st+l)}if(!Se(t)||Ge(e))for(let a of c){let l=n_(a);if(l!==null)return Te(Xl(l,s,t,Re(n.description)))}return l_(e,c,t,r)??jl(e,s,t,r)??Ae}function n_(e){let t=e.argv0.toLowerCase();return oe(xi,t)&&o_(t,e)?"curl":s_(e.raw)?"http":oe(mi,t)?"build":null}function o_(e,t){return t.redirectsToFile?!r_(e,t.args):!t.endsInBoundedSink}function r_(e,t){let n=_i[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===mr)break;if(oe(Ei,s)||s===gi&&t[r+1]===ue)return!1;(s===n.long||s.startsWith(ue)&&!s.startsWith(mr)&&s.includes(n.short,ue.length))&&(o=!0)}return o}function s_(e){let t=e.toLowerCase();for(let n of Oi)if(t.includes(n))return!0;for(let n=t.indexOf(ct);n>=0;n=t.indexOf(ct,n+1)){let o=t.charAt(n+ct.length);if(o!==""&&hi.includes(o)&&t.startsWith(Si,n+ct.length+o.length))return!0}return!1}var i_="cd";function hr(e){try{let t=jx(e);return t.isFile()?t.size:-1}catch{return-1}}function Sr(e,t,n,o,r,s){let i=Rt(n,o);return r<=Y||Xe(e.agent,n,o)?null:Te(c_(s,i)?Rl(i,r,t.toolNamePrefix):Al(i,r))}function c_(e,t){if(typeof e=="string")return We([e],t);if(We([e.worktree],t))return!0;try{return We([e.containmentRoot],t)}catch{return!1}}function a_(e,t,n,o){if(!Fl(n.offset)&&!Fl(n.limit))for(let r of Kl(n)){let s=Rt(e.cwd,r),i=hr(s);if(i>Y&&!Cn(e.agent,s)){let c=Sr(e,t,e.cwd,r,i,o);if(c!==null)return c}}return Ae}function l_(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&vo(n))return null;let r=e.cwd,s=null;for(let i of t){let c=i.argv0.toLowerCase();if(c===i_&&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||!oe(bi,c))continue;let a=f_(c,i.args);if(a===null)continue;if(a.bounded){s=Ae;continue}let l=Rt(r,a.file),u=Sr(e,n,r,a.file,hr(l),o);if(u!==null)return u}return s}function jl(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&vo(n))return null;for(let r of va(t,e.cwd)){let s=Sr(e,n,e.cwd,r,hr(r),o);if(s!==null)return s}return null}var Dn=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function u_(e){if(oe(ao,e))return 1;for(let t of ao)if(t.startsWith(mr)?e.startsWith(t+Kx):e.startsWith(t))return 0;return e.startsWith(ue)&&Dn(e.slice(ue.length))?0:-1}function d_(e){if(e===Er)return"all";if(!e.endsWith(Er))return null;let t=e.slice(0,e.length-Er.length),n=t.indexOf(Ul);return(n<0?Dn(t):Dn(t.slice(0,n))&&Dn(t.slice(n+Ul.length)))?"range":null}function f_(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(oe(Ti,e)){let a=u_(c);if(a>=0){o=!0,i+=a;continue}}if(e===Kt&&oe(Ri,c)){r=!0;continue}if(e===Kt&&oe(qx,c)){s=t[i+1],i++;continue}c.startsWith(ue)&&c!==ue||n.push(c)}if(e===Kt){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:d_(s);if(i===null)return null;o=i==="range"}return e===Ai&&n.shift()!==H.identity?null:n.length===1&&n[0]!==ue?{file:n[0],bounded:o}:null}import{basename as m_,dirname as Nt,isAbsolute as h_,join as yt,resolve as Or}from"node:path";var p_=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]),x_=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],X=(e,t)=>e>>>t|e<<32-t;function Vl(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=x_.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=X(i[E-15],7)^X(i[E-15],18)^i[E-15]>>>3,S=X(i[E-2],17)^X(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,p,x,g]=s;for(let E=0;E<64;E++){let h=g+(X(f,6)^X(f,11)^X(f,25))+(f&p^~f&x)+p_[E]+i[E]>>>0,S=(X(a,2)^X(a,13)^X(a,22))+(a&l^a&u^l&u)>>>0;g=x,x=p,p=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]+p>>>0,s[6]=s[6]+x>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:__,readFileSync:E_,realpathSync:Jl,statSync:g_}=process.getBuiltinModule("node:fs");function S_(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":case"omp":return"pi:ctx.cwd"}}function At(e){return e===void 0||e===""?void 0:e}function O_(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return At(t.env.CLAUDE_PROJECT_DIR)??At(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return At(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(Gt);return n<0?void 0:At(t.argv[n+1])}case"pi:ctx.cwd":return At(t.piCwd)}}function b_(e){let t=T_(e),n=t;for(;;){let o=R_(yt(t,to));if(o!==null){let s=zl(yt(o,Ls));return{commonDir:Jl.native(s===null?o:Or(o,s)),worktree:t,start:n}}let r=Nt(t);if(r===t)return{commonDir:null,start:n};t=r}}function T_(e){let t=h_(e);for(let n=t?Or(e):e;;)try{return Jl.native(n)}catch{let o=Nt(n);if(!t||o===n)throw new R("NO_GIT_DIR",{path:e});n=o}}function R_(e){let t;try{if(g_(e).isDirectory())t=e;else{let n=zl(e);if(n===null||!n.startsWith(oo))return null;t=Or(Nt(e),n.slice(oo.length))}}catch{return null}return __(yt(t,Ps))?t:null}function zl(e){let t;try{t=E_(e,"utf8")}catch{return null}let n=t.indexOf(`
37
+ `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function A_(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 N_(e,t){let n=m_(t)===to?Nt(t):t,o=A_(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(no)).map(r=>r.slice(no.length));return Ml([Nt(n),...o])}function $l(e,t){let n=S_(e),o=O_(n,t);if(o===void 0)throw new R("NO_PROJECT",{kind:n});let r=b_(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??=Vl(i).slice(0,Ds),a},get projectDir(){return l??=yt($a(process.env),jt,this.projectKey),l},get dbPath(){return yt(this.projectDir,ks)},worktree:c,get containmentRoot(){return u??=s??N_(c,i),u},agent:e,source:n}}var kn=tt,y_=`
39
+ PRAGMA busy_timeout = ${v};
40
40
  PRAGMA journal_mode = WAL;
41
- `,yn="tokenize = 'porter unicode61 remove_diacritics 2'",u_="tokenize = 'unicode61 remove_diacritics 2'",d_=`
41
+ `,Ln="tokenize = 'porter unicode61 remove_diacritics 2'",I_="tokenize = 'unicode61 remove_diacritics 2'",C_=`
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
- ${u_}
86
+ ${I_}
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
- `,f_=`
93
+ `,D_=`
94
94
  CREATE UNIQUE INDEX IF NOT EXISTS idx_events_cost_session_turn ON events(session_id, turn) WHERE kind = 'cost';
95
- `,p_=`
95
+ `,k_=`
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
- ${yn}
104
+ ${Ln}
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
- `,x_=`
110
+ `,L_=`
111
111
  CREATE VIRTUAL TABLE chunks_tri USING fts5(
112
112
  body,
113
113
  title,
@@ -116,24 +116,31 @@ 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
- `,__=`
119
+ `,P_=`
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
- ${yn}
125
+ ${Ln}
126
126
  );
127
- `,E_=`
127
+ `,w_=`
128
128
  UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
129
- `,g_=[{version:1,sql:d_},{version:2,sql:f_},{version:3,sql:p_},{version:4,sql:x_},{version:5,sql:__},{version:6,sql:E_}];function _r(e,t){if(t!==Nn){if(t>Nn)throw new T("SCHEMA_STALE",{found:t,want:Nn});e.exec(l_),e.exec("BEGIN IMMEDIATE");try{for(let n of g_)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${Nn}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}function Xl(e,t,n={}){if(("bun"in n?n.bun:process.versions.bun)===void 0)return new e.DatabaseSync(t,{timeout:H,readOnly:!0});let r=new e.DatabaseSync(t,{timeout:H});return n.queryOnly!==!1&&r.exec("PRAGMA query_only = ON"),r}var{existsSync:Te,linkSync:m_,mkdirSync:ql,renameSync:h_,rmSync:Er,statSync:S_}=process.getBuiltinModule("node:fs");function Kl(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function b_(e,t){let n=Kl(e),o=Kl(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 O_(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&Mt;return n===hs||n===Ss}async function T_(){try{return await import("node:sqlite")}catch{throw new T("NO_SQLITE")}}function gr(e){return e.prepare("PRAGMA user_version").get().user_version}function zl(e){return e.code??""}function R_(e,t){let n=t+Es,o=Date.now();for(;;){if(Te(t))return;try{ql(n)}catch(r){if(!gs.includes(zl(r)))throw r;if(Date.now()-o<H){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms);continue}let s=S_(n,{throwIfNoEntry:!1});throw s!==void 0&&s.mtimeMs<o&&Er(n,{recursive:!0,force:!0}),new Error(`context.db was not published within ${H} ms: ${n} was held; open again`)}try{Te(t)||h_(e,t)}finally{Er(n,{recursive:!0,force:!0})}return}}function A_(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+xs;try{let r=new e.DatabaseSync(o,{timeout:H});try{_r(r,gr(r))}finally{r.close()}try{m_(o,t)}catch(s){let i=zl(s);if(_s.includes(i))R_(o,t);else if(i!=="EEXIST")throw s}}finally{for(let r of["",wt,Pt])Er(o+r,{force:!0})}}function Yl(e,t){let n=null;try{return Te(t)||A_(e,t),n=new e.DatabaseSync(t,{timeout:H}),_r(n,gr(n)),n}catch(o){throw n&&n.close(),o}}function N_(e,t){let n=Xl(e,t);try{let o=gr(n);if(o!==$e)throw new T("SCHEMA_STALE",{found:o,want:$e});return n}catch(o){throw n.close(),o}}async function Vl(e,t){if(b_(process.version,Qe))throw new T("NODE_TOO_OLD",{v:process.version});let n=await T_();ql(e.projectDir,{recursive:!0});let o=e.dbPath;if((Te(o+wt)||Te(o+Pt))&&!Te(o))throw new T("DB_GONE");try{let s;return t?.readOnly===!0?(Te(o)||Yl(n,o).close(),s=N_(n,o)):s=Yl(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw O_(s)?new T("DB_CORRUPT"):s}}function L(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 Jl(e,t){return e.raw.isTransaction?t(e):L(e,t)}function ae(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function ee(e,t,n){Jl(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function In(e,t){return Jl(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var $l="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",y_="INSERT INTO "+$l,I_="INSERT OR IGNORE INTO "+$l,C_="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function Ql(e,t,n){return L(e,o=>{let r=n??Date.now(),s=t.kind==="cost",i=o.raw.prepare(s?I_:y_).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,r,r);return i.changes===1?Number(i.lastInsertRowid):o.raw.prepare(C_).get(t.session_id,t.turn).seq})}function Zl(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 mr(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 eu(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 tu(e,t,n,o,r=Number.MAX_SAFE_INTEGER){return t===""?[]:e.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND ((session_id = ? AND seq <= ?) OR (worktree = ? AND session_id <> ?)) ORDER BY seq DESC LIMIT ?").all(t,r,n,t,o)}function nu(e){let t=e.raw.prepare("SELECT COALESCE(MAX(seq), 0) AS n FROM events").get();return Number(t.n)}function ou(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function ru(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}function su(e,t){return e.raw.prepare("SELECT MAX(seq) AS m FROM events WHERE session_id = ?").get(t)?.m??0}var hr=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 D_(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=hr.length/2-1;for(;t<=n;){let o=t+n>>1,r=hr[2*o],s=hr[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function k_(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 Xe(e){return k_(e,t=>!D_(t))}var L_=`
129
+ `,M_=`
130
+ ALTER TABLE sources ADD COLUMN unit_lo INTEGER;
131
+ ALTER TABLE sources ADD COLUMN unit_hi INTEGER;
132
+ CREATE INDEX IF NOT EXISTS idx_sources_session ON sources(session_id, id);
133
+ UPDATE sources SET unit_lo = g.lo, unit_hi = g.hi
134
+ FROM (SELECT source_id, MIN(rowid) AS lo, MAX(rowid) AS hi FROM line_units GROUP BY source_id) AS g
135
+ WHERE g.source_id = sources.id;
136
+ `,U_=[{version:1,sql:C_},{version:2,sql:D_},{version:3,sql:k_},{version:4,sql:L_},{version:5,sql:P_},{version:6,sql:w_},{version:7,sql:M_}];function br(e,t){if(t!==kn){if(t>kn)throw new R("SCHEMA_STALE",{found:t,want:kn});e.exec(y_),e.exec("BEGIN IMMEDIATE");try{for(let n of U_)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${kn}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}function Ql(e,t,n={}){if(("bun"in n?n.bun:process.versions.bun)===void 0)return new e.DatabaseSync(t,{timeout:v,readOnly:!0});let r=new e.DatabaseSync(t,{timeout:v});return n.queryOnly!==!1&&r.exec("PRAGMA query_only = ON"),r}var{existsSync:Ne,linkSync:H_,mkdirSync:tu,renameSync:F_,rmSync:Tr,statSync:v_}=process.getBuiltinModule("node:fs");function Zl(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function j_(e,t){let n=Zl(e),o=Zl(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 G_(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&Ft;return n===Is||n===Cs}async function B_(){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 nu(e){return e.code??""}function W_(e,t){let n=t+As,o=Date.now();for(;;){if(Ne(t))return;try{tu(n)}catch(r){if(!Ns.includes(nu(r)))throw r;if(Date.now()-o<v){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ys);continue}let s=v_(n,{throwIfNoEntry:!1});throw s!==void 0&&s.mtimeMs<o&&Tr(n,{recursive:!0,force:!0}),new Error(`context.db was not published within ${v} ms: ${n} was held; open again`)}try{Ne(t)||F_(e,t)}finally{Tr(n,{recursive:!0,force:!0})}return}}function X_(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+Ts;try{let r=new e.DatabaseSync(o,{timeout:v});try{br(r,Rr(r))}finally{r.close()}try{H_(o,t)}catch(s){let i=nu(s);if(Rs.includes(i))W_(o,t);else if(i!=="EEXIST")throw s}}finally{for(let r of["",Ut,Ht])Tr(o+r,{force:!0})}}function eu(e,t){let n=null;try{return Ne(t)||X_(e,t),n=new e.DatabaseSync(t,{timeout:v}),br(n,Rr(n)),n}catch(o){throw n&&n.close(),o}}function K_(e,t){let n=Ql(e,t);try{let o=Rr(n);if(o!==tt)throw new R("SCHEMA_STALE",{found:o,want:tt});return n}catch(o){throw n.close(),o}}async function ou(e,t){if(j_(process.version,nt))throw new R("NODE_TOO_OLD",{v:process.version});let n=await B_();tu(e.projectDir,{recursive:!0});let o=e.dbPath;if((Ne(o+Ut)||Ne(o+Ht))&&!Ne(o))throw new R("DB_GONE");try{let s;return t?.readOnly===!0?(Ne(o)||eu(n,o).close(),s=K_(n,o)):s=eu(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw G_(s)?new R("DB_CORRUPT"):s}}function y(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 ru(e,t){return e.raw.isTransaction?t(e):y(e,t)}function P(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function w(e,t,n){ru(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 ru(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}function su(e,t){return Vt+e+":"+t}function Ar(e,t,n){return t!==""&&P(e,su(t,n))!==null}function iu(e,t,n,o,r){if(!(t===""||n===""))try{w(e,su(t,n),JSON.stringify({at:Date.now(),reason:o,source:r}))}catch{}}function Nr(e,t,n){return t!==""&&P(e,Eo+t+":"+n)!==null}function cu(e,t,n,o){if(!(t===""||n===""))try{w(e,Eo+t+":"+n,o)}catch{}}function au(e,t){if(t==="")return;let n=Vt+t+":",o=Vt+t+";",r=s=>{s.raw.prepare("DELETE FROM meta WHERE key >= ? AND key < ?").run(n,o)};e.raw.isTransaction?r(e):y(e,r)}function lu(e){if(e.startsWith(zt))return null;let t=e.lastIndexOf("#");if(t<=0)return null;let n=e.slice(0,t),o=n.indexOf(":");return o<=0?null:o+1<n.length||n.startsWith(j)?n:null}var uu="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",Y_="INSERT INTO "+uu,q_="INSERT OR IGNORE INTO "+uu,V_="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function du(e,t,n){return y(e,o=>{let r=n??Date.now(),s=t.kind==="cost",i=o.raw.prepare(s?q_:Y_).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,r,r);return i.changes===1?Number(i.lastInsertRowid):o.raw.prepare(V_).get(t.session_id,t.turn).seq})}function fu(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 yr(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 pu(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 xu(e,t,n,o,r=Number.MAX_SAFE_INTEGER){return t===""?[]:e.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND ((session_id = ? AND seq <= ?) OR (worktree = ? AND session_id <> ?)) ORDER BY seq DESC LIMIT ?").all(t,r,n,t,o)}function _u(e){let t=e.raw.prepare("SELECT COALESCE(MAX(seq), 0) AS n FROM events").get();return Number(t.n)}function Eu(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function gu(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}function mu(e,t){return e.raw.prepare("SELECT MAX(seq) AS m FROM events WHERE session_id = ?").get(t)?.m??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 J_(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 z_(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 Ke(e){return z_(e,t=>!J_(t))}var $_=`
130
137
  INSERT INTO sources(session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts)
131
138
  VALUES (:session_id, :worktree, :agent, :kind, :label, :bytes_total, :chunk_count, :created_ts, :created_at, :created_ts)
132
- RETURNING id`,w_=`
133
- INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,cu=1,iu=" (raw)",au=`AND (:source IS NOT NULL OR substr(s.label, -${iu.length}) <> '${iu}')`,lu=`
139
+ RETURNING id`,Q_=`
140
+ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,bu=1,hu=" (raw)",Tu=`AND (:source IS NOT NULL OR substr(s.label, -${hu.length}) <> '${hu}')`,Ru=`
134
141
  SELECT chunks.rowid AS rid, chunks.source_id AS source_id, chunks.session_id AS session_id,
135
142
  chunks.worktree AS worktree, chunks.ord AS ord, s.created_ts AS created_ts,
136
- bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${cu}) AS bm,
143
+ bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${bu}) AS bm,
137
144
  (chunks.rowid IN (SELECT rowid FROM chunks WHERE chunks MATCH :all)) AS full
138
145
  FROM chunks JOIN sources s ON s.id = chunks.source_id
139
146
  WHERE chunks MATCH :match
@@ -141,9 +148,9 @@ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VAL
141
148
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
142
149
  AND (:source IS NULL OR s.label = :source)
143
150
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
144
- ${au}`,uu=`
145
- ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,s1=`
146
- WITH m AS (${lu}
151
+ ${Tu}`,Au=`
152
+ ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,yO=`
153
+ WITH m AS (${Ru}
147
154
  ), r AS (
148
155
  SELECT *,
149
156
  ROW_NUMBER() OVER (ORDER BY full DESC, bm ASC, source_id DESC, ord ASC) AS rank_a,
@@ -151,11 +158,11 @@ WITH m AS (${lu}
151
158
  FROM m
152
159
  )
153
160
  SELECT rid, source_id, session_id, worktree, ord, full, 1.0 / (:k + rank_a) + 1.0 / (:k + rank_b) AS score
154
- FROM r${uu}`,i1=`
155
- WITH m AS (${lu}
161
+ FROM r${Au}`,IO=`
162
+ WITH m AS (${Ru}
156
163
  )
157
164
  SELECT rid, source_id, session_id, worktree, ord, full, -bm AS score
158
- FROM m${uu}`;var c1=`
165
+ FROM m${Au}`;var CO=`
159
166
  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
167
  FROM chunks_tri t JOIN chunks c ON c.rowid = t.rowid JOIN sources s ON s.id = c.source_id
161
168
  WHERE chunks_tri MATCH :match
@@ -163,65 +170,65 @@ WHERE chunks_tri MATCH :match
163
170
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
164
171
  AND (:source IS NULL OR s.label = :source)
165
172
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
166
- ${au}
167
- ORDER BY bm25(chunks_tri, 1.0, ${cu}) ASC, c.source_id DESC, c.ord ASC`;var P_="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",M_="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function Dn(e,t,n){let o=0;for(let r of n)o+=r.bytes;return L(e,r=>{let s=r.raw.prepare(L_).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 du(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>Wn&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)L(e,a=>{let l=a.raw.prepare(w_),u=a.raw.prepare(P_);for(let d of c){let f=d.title??"",p=l.run(t,n.sessionId,n.worktree,n.agent,d.ord,d.text,f).lastInsertRowid;u.run(p,d.text,f)}})}function Sr(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(M_+" 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 br(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 U_(e){return[...new Set(br(e).split(" ").filter(n=>n!==""))].join(" OR ")}var fu=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 H_(e){let t=[...new Set(br(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!fu.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var Cn=`
173
+ ${Tu}
174
+ ORDER BY bm25(chunks_tri, 1.0, ${bu}) ASC, c.source_id DESC, c.ord ASC`;var Z_="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",eE="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function Mn(e,t,n){let o=0;for(let r of n)o+=r.bytes;return y(e,r=>{let s=r.raw.prepare($_).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 Nu(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>Jn&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)y(e,a=>{let l=a.raw.prepare(Q_),u=a.raw.prepare(Z_);for(let d of c){let f=d.title??"",p=l.run(t,n.sessionId,n.worktree,n.agent,d.ord,d.text,f).lastInsertRowid;u.run(p,d.text,f)}})}function Cr(e,t){if(t==="all")return e.exec("INSERT INTO chunks_tri(chunks_tri) VALUES ('delete-all')"),e.exec("DELETE FROM line_units"),e.exec("UPDATE sources SET unit_lo = NULL, unit_hi = NULL WHERE unit_lo IS NOT NULL"),Number(e.prepare("DELETE FROM chunks").run().changes);let[n,o,r]="sourceId"in t?["source_id = ?",t.sourceId,"id = ?"]:["source_id IN (SELECT id FROM sources WHERE label = ?)",t.label,"label = ?"];return e.prepare(eE+" WHERE "+n).run(o),e.prepare("DELETE FROM line_units WHERE "+n).run(o),e.prepare("UPDATE sources SET unit_lo = NULL, unit_hi = NULL WHERE "+r).run(o),Number(e.prepare("DELETE FROM chunks WHERE "+n).run(o).changes)}function Dr(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 tE(e){return[...new Set(Dr(e).split(" ").filter(n=>n!==""))].join(" OR ")}var yu=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 nE(e){let t=[...new Set(Dr(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!yu.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var Su=new WeakMap;function Ou(e,t){let n=Su.get(e);n===void 0&&(n=new Map,Su.set(e,n));let o=n.get(t);return o===void 0&&(o=e.prepare(t),n.set(t,o)),o}var wn=`
168
175
  AND (:scope <> 'session' OR session_id = :session_id)
169
- AND (:scope <> 'worktree' OR worktree = :worktree)`,a1=`
176
+ AND (:scope <> 'worktree' OR worktree = :worktree)`,DO=`
170
177
  WITH e AS (
171
178
  SELECT seq, kind, key, path, body, created_at FROM events
172
- WHERE created_at > :after${Cn}
179
+ WHERE created_at > :after${wn}
173
180
  AND (:source IS NULL OR kind = :source)
174
181
  )
175
182
  SELECT seq, kind, key, path, body, created_at FROM e
176
183
  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`,l1=`
184
+ ORDER BY created_at ASC, seq ASC`,kO=`
178
185
  WITH s AS (
179
186
  SELECT id, label, created_ts FROM sources
180
- WHERE created_ts > :after${Cn}
187
+ WHERE created_ts > :after${wn}
181
188
  AND (:source IS NULL OR label = :source)
182
189
  AND label <> :reserved
183
190
  )
184
191
  SELECT id, label, created_ts FROM s
185
192
  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 u1=`
187
- SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${Cn} AND (:source IS NULL OR kind = :source))
188
- OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${Cn} AND (:source IS NULL OR label = :source)
189
- AND label <> :reserved) AS more`;var F_=`CREATE VIRTUAL TABLE r USING fts5(body, ${yn}, content='')`,v_="INSERT INTO r(rowid, body) VALUES (?, ?)",j_="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function te(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?U_(t):br(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(F_);let c=i.prepare(v_);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(j_).all(r))o[Number(a.id)-1]=-a.bm;return o}finally{i.close()}}var G_="s";function pu(e){return G_+e.toString(36)}function xu(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<=Wn);)i+=o[s].body.length,s++;let c=r;L(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 _u(e){let t=new Set,n=new Set,o=s=>{n.size<Kt&&n.add(s),fu.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 Eu(e){let t=e.raw.prepare("SELECT COALESCE(MAX(id), 0) AS n FROM sources").get();return Number(t.n)}function gu(e,t,n,o,r=Number.MAX_SAFE_INTEGER){let s=H_(n).join(" OR ");return s===""||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 = ? AND s.id <= ? ORDER BY bm25(line_units) LIMIT ?").all(s,t,r,o).map(c=>({sourceId:Number(c.source_id),ord:Number(c.ord),label:c.label,body:c.body,score:c.score}))}function Or(e){let t=e.length-e.trimStart().length;if(t===e.length)return"";let n=t===0?0:e.lastIndexOf(`
193
+ ORDER BY created_ts ASC, id ASC`;var LO=`
194
+ SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${wn} AND (:source IS NULL OR kind = :source))
195
+ OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${wn} AND (:source IS NULL OR label = :source)
196
+ AND label <> :reserved) AS more`;var oE=`CREATE VIRTUAL TABLE r USING fts5(body, ${Ln}, content='')`,rE="INSERT INTO r(rowid, body) VALUES (?, ?)",sE="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function re(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?tE(t):Dr(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(oE);let c=i.prepare(rE);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(sE).all(r))o[Number(a.id)-1]=-a.bm;return o}finally{i.close()}}var iE="s";function Iu(e){return iE+e.toString(36)}function Cu(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<=Jn);)i+=o[s].body.length,s++;let c=r;y(e,a=>{let l=a.raw.prepare("INSERT INTO line_units(body, source_id, session_id, ord) VALUES (?, ?, ?, ?)"),u=Number.MAX_SAFE_INTEGER,d=0;for(let f=c;f<s;f++){let p=o[f],x=Number(l.run(p.body,t,n,p.ord).lastInsertRowid);x<u&&(u=x),x>d&&(d=x)}a.raw.prepare("UPDATE sources SET unit_lo = min(coalesce(unit_lo, ?), ?), unit_hi = max(coalesce(unit_hi, ?), ?) WHERE id = ?").run(u,u,d,d,t)}),r=s}}function Du(e){let t=new Set,n=new Set,o=s=>{n.size<Jt&&n.add(s),yu.has(s.toLowerCase())||t.add(s)},r="";for(let s of e){if(t.size>=Jt)break;s.trim()===""||s==="\0"?(r!==""&&o(r),r=""):r+=s}return r!==""&&t.size<Jt&&o(r),[...t.size>0?t:n].join(" ")}function ku(e){let t=e.raw.prepare("SELECT COALESCE(MAX(id), 0) AS n FROM sources").get();return Number(t.n)}function Lu(e,t,n,o,r=Number.MAX_SAFE_INTEGER){let s=nE(n).join(" OR ");if(s===""||t==="")return[];let i=Ou(e.raw,"SELECT MIN(unit_lo) AS lo, MAX(unit_hi) AS hi FROM sources WHERE session_id = ? AND id <= ? AND unit_lo IS NOT NULL").get(t,r);return i===void 0||i.lo===null||i.hi===null?[]:Ou(e.raw,"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.rowid BETWEEN ? AND ? AND u.session_id = ? AND s.id <= ? ORDER BY bm25(line_units) LIMIT ?").all(s,i.lo,i.hi,t,r,o).map(a=>({sourceId:Number(a.source_id),ord:Number(a.ord),label:a.label,body:a.body,score:a.score}))}function kr(e){let t=e.length-e.trimStart().length;if(t===e.length)return"";let n=t===0?0:e.lastIndexOf(`
190
197
  `,t)+1,o=e.indexOf(`
191
- `,t);return(n===0&&o<0?e:e.slice(n,o<0?e.length:o)).replaceAll("\r"," ")}function Ke(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 Rt(e){return e.length>Kn?e.slice(e.length-Kn):e}function B_(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function mu(e,t){if(!t)return B_();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:Ke("last_request",r,"now: "+Or(r.body),1,null),i=o.slice(0,o.length-1).map(_=>Ke("earlier_requests",_,"asked #"+_.seq+": "+Or(_.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(Ke("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 A=Ke("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);d.push({...A,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 p=[];for(let[_,m]of f)p.push(Ke("decisions",m.row,"decided #"+m.row.seq+": "+Or(m.row.body),m.count,_));p.sort((_,m)=>_.seq-m.seq);let x=n.filter(_=>_.kind==="index").map(_=>Ke("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:Rt(l),changedFiles:Rt(d),decisions:Rt(p),earlierRequests:Rt(i),indexedSources:Rt(x)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=Yn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-Yn));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 W_(e){if(!Object.hasOwn(qn,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=zn[Math.min(t,zn.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(qn[e.section]*n*o/wi)}function X_(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 hu(e,t){return e.map(n=>({...n,score:W_({section:X_(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function Ou(e){return e.sourceId+":"+e.ord}function Ln(e){return"@"+e.label+" line "+(e.ord+1)+`:
192
- `+e.body}function K_(e){return new Set(Xe(e.toLowerCase()))}function Y_(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 Rr(e,t,n){let o=e.filter(l=>!t.has(Ou(l))&&l.score>=co);if(o.length===0)return[];let r=Math.max(...o.map(l=>l.score)),s=o.map(l=>K_(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 p=0;for(let g of i)p=Math.max(p,Y_(s[f],s[g]));let x=cs*(o[f].score/r)-as*p;x>u&&(u=x,l=f)}c.delete(l);let d=kn(Ln(o[l]))+1;a+d>n||(a+=d,i.push(l))}return i.map(l=>o[l])}var Su={text:"",seqs:[]};function kn(e){return Buffer.byteLength(e,"utf8")}function Tr(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
193
- `)}function bu(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+Tr(e)}function Tu(e,t,n,o=[],r=new Set){if(t.trim()==="")return Su;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&Tr(f)!==""),i=s.length===0?[]:te(s.map(Tr),t,"any"),c=s.map((f,p)=>({r:f,score:i[p]})).filter(f=>f.score>=co).sort((f,p)=>p.score-f.score||p.r.seq-f.r.seq),a=kn(lo)+1+kn(uo),l=[];for(let{r:f}of c){let p=kn(bu(f))+1;a+p>st||(a+=p,l.push(f))}let u=Rr(o,r,st-a);if(l.length===0&&u.length===0)return Su;l.sort((f,p)=>f.seq-p.seq);let d=[...l.map(bu),...u.map(Ln)];return{text:[lo,...d,uo].join(`
194
- `),seqs:l.map(f=>f.seq),...u.length>0?{units:u.map(Ou)}:{}}}function le(e){return Buffer.byteLength(e,"utf8")}function Ar(e,t){return e.bytes>zr?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function Nr(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function Ru(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=mu(e,s),a=`<context_mode_state session="${s}" upto="${i}">`,l=le(Nr([],o)),u=qr-(le(a)+1+l+1+le(Bn)),d=0,f=c.lastRequest===null?null:Ar(c.lastRequest,o);f!==null&&(d+=le(f)+1);let p=hu([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),x=new Map,g=[],E=[];for(;p.length>0;){let m=0,A=-1/0;for(let w=0;w<p.length;w++){let ye=p[w],fe=ye.score*is**(x.get(ye.section)??0)/ye.bytes;(fe>A||fe===A&&ye.seq>p[m].seq)&&(m=w,A=fe)}let y=p.splice(m,1)[0],oe=le(Ar(y,o))+1;d+oe<=u?(d+=oe,g.push(y),x.set(y.section,(x.get(y.section)??0)+1)):E.push(y)}let h=[a];f!==null&&h.push(f);for(let m of["open_errors","changed_files","decisions","earlier_requests","indexed_sources"])for(let A of g.filter(y=>y.section===m).sort((y,oe)=>y.seq-oe.seq))h.push(Ar(A,o));if(n!==void 0){for(let m of n.sources){let A=le(m)+1;d+A>u||(d+=A,h.push(m))}for(let m of Rr(n.units,new Set,u-d)){let A=Ln(m);d+=le(A)+1,h.push(A)}}let S=[],_=new Set;for(let m of E.sort((A,y)=>A.seq-y.seq))if(!(m.query===null||_.has(m.query))){if(le(Nr([...S,m.query],o))-l>u-d)break;S.push(m.query),_.add(m.query)}return h.push(Nr(S,o),Bn),h.join(`
195
- `)}var q_=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),z_=new Set(["script","style"]),V_=new TextEncoder;function wn(e,t,n=W){let o=Q_(e);if(o.length===0)return[];let r=Math.max(4,Math.min(W,Math.floor(n)));if(t==="md")return J_(o,r,r<W);let s=t==="html"?nE(o):yr(o,!1);return Ir(o,s,t!=="text",r,r<W)}function J_(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 Ir(e,i,!0,t,n))c(l.text,l.bytes);i=[]}};for(let l of yr(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&&ue(e.slice(l.start,l.end))>t){let u=$_(e,l,l.fence,t);if(u!==void 0){a();for(let d of u)c(d,ue(d));continue}}i.push(l)}return a(),o}function $_(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-ue(r)-ue(s)-2;if(!(a<16||c.length===0))return Ir(c,yr(c,!1),!0,a,!0).map(l=>r+`
198
+ `,t);return(n===0&&o<0?e:e.slice(n,o<0?e.length:o)).replaceAll("\r"," ")}function Ye(e,t,n,o,r){let s=Buffer.byteLength(n,"utf8");if(s<1)throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");return{section:e,seq:t.seq,turn:t.turn,text:n,bytes:s,repeatCount:o,pinned:e==="last_request",query:r}}function It(e){return e.length>$n?e.slice(e.length-$n):e}function cE(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function Pu(e,t){if(!t)return cE();let n=e.filter(_=>_.session_id===t).sort((_,m)=>_.seq-m.seq),o=n.filter(_=>_.kind==="prompt"),r=o.length>0?o[o.length-1]:void 0,s=r===void 0?null:Ye("last_request",r,"now: "+kr(r.body),1,null),i=o.slice(0,o.length-1).map(_=>Ye("earlier_requests",_,"asked #"+_.seq+": "+kr(_.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(Ye("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 N=Ye("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);d.push({...N,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 p=[];for(let[_,m]of f)p.push(Ye("decisions",m.row,"decided #"+m.row.seq+": "+kr(m.row.body),m.count,_));p.sort((_,m)=>_.seq-m.seq);let x=n.filter(_=>_.kind==="index").map(_=>Ye("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:It(l),changedFiles:It(d),decisions:It(p),earlierRequests:It(i),indexedSources:It(x)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=Qn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-Qn));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 aE(e){if(!Object.hasOwn(Zn,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=eo[Math.min(t,eo.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(Zn[e.section]*n*o/Gi)}function lE(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 wu(e,t){return e.map(n=>({...n,score:aE({section:lE(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function Hu(e){return e.sourceId+":"+e.ord}function Hn(e){return"@"+e.label+" line "+(e.ord+1)+`:
199
+ `+e.body}function uE(e){return new Set(Ke(e.toLowerCase()))}function dE(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 Pr(e,t,n){let o=e.filter(l=>!t.has(Hu(l))&&l.score>=xo);if(o.length===0)return[];let r=Math.max(...o.map(l=>l.score)),s=o.map(l=>uE(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 p=0;for(let g of i)p=Math.max(p,dE(s[f],s[g]));let x=gs*(o[f].score/r)-ms*p;x>u&&(u=x,l=f)}c.delete(l);let d=Un(Hn(o[l]))+1;a+d>n||(a+=d,i.push(l))}return i.map(l=>o[l])}var Mu={text:"",seqs:[]};function Un(e){return Buffer.byteLength(e,"utf8")}function Lr(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
200
+ `)}function Uu(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+Lr(e)}function Fu(e,t,n,o=[],r=new Set){if(t.trim()==="")return Mu;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&Lr(f)!==""),i=s.length===0?[]:re(s.map(Lr),t,"any"),c=s.map((f,p)=>({r:f,score:i[p]})).filter(f=>f.score>=xo).sort((f,p)=>p.score-f.score||p.r.seq-f.r.seq),a=Un(go)+1+Un(mo),l=[];for(let{r:f}of c){let p=Un(Uu(f))+1;a+p>lt||(a+=p,l.push(f))}let u=Pr(o,r,lt-a);if(l.length===0&&u.length===0)return Mu;l.sort((f,p)=>f.seq-p.seq);let d=[...l.map(Uu),...u.map(Hn)];return{text:[go,...d,mo].join(`
201
+ `),seqs:l.map(f=>f.seq),...u.length>0?{units:u.map(Hu)}:{}}}function de(e){return Buffer.byteLength(e,"utf8")}function wr(e,t){return e.bytes>rs?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function Mr(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function vu(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=Pu(e,s),a=`<context_mode_state session="${s}" upto="${i}">`,l=de(Mr([],o)),u=os-(de(a)+1+l+1+de(Vn)),d=0,f=c.lastRequest===null?null:wr(c.lastRequest,o);f!==null&&(d+=de(f)+1);let p=wu([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),x=new Map,g=[],E=[];for(;p.length>0;){let m=0,N=-1/0;for(let ie=0;ie<p.length;ie++){let M=p[ie],$e=M.score*Es**(x.get(M.section)??0)/M.bytes;($e>N||$e===N&&M.seq>p[m].seq)&&(m=ie,N=$e)}let C=p.splice(m,1)[0],_e=de(wr(C,o))+1;d+_e<=u?(d+=_e,g.push(C),x.set(C.section,(x.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 N of g.filter(C=>C.section===m).sort((C,_e)=>C.seq-_e.seq))h.push(wr(N,o));if(n!==void 0){for(let m of n.sources){let N=de(m)+1;d+N>u||(d+=N,h.push(m))}for(let m of Pr(n.units,new Set,u-d)){let N=Hn(m);d+=de(N)+1,h.push(N)}}let S=[],_=new Set;for(let m of E.sort((N,C)=>N.seq-C.seq))if(!(m.query===null||_.has(m.query))){if(de(Mr([...S,m.query],o))-l>u-d)break;S.push(m.query),_.add(m.query)}return h.push(Mr(S,o),Vn),h.join(`
202
+ `)}var fE=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),pE=new Set(["script","style"]),xE=new TextEncoder;function Fn(e,t,n=q){let o=gE(e);if(o.length===0)return[];let r=Math.max(4,Math.min(q,Math.floor(n)));if(t==="md")return _E(o,r,r<q);let s=t==="html"?OE(o):Ur(o,!1);return Hr(o,s,t!=="text",r,r<q)}function _E(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 Hr(e,i,!0,t,n))c(l.text,l.bytes);i=[]}};for(let l of Ur(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&&fe(e.slice(l.start,l.end))>t){let u=EE(e,l,l.fence,t);if(u!==void 0){a();for(let d of u)c(d,fe(d));continue}}i.push(l)}return a(),o}function EE(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-fe(r)-fe(s)-2;if(!(a<16||c.length===0))return Hr(c,Ur(c,!1),!0,a,!0).map(l=>r+`
196
203
  `+l.text+`
197
- `+s)}function Q_(e){let t=e.split(`\r
204
+ `+s)}function gE(e){let t=e.split(`\r
198
205
  `).join(`
199
- `);return t.startsWith("\uFEFF")?t.slice(1):t}function yr(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,p,x)=>{o<0&&(o=f),r=p,s=x},d=0;for(;d<=e.length;){let f=e.indexOf(`
200
- `,d),p=f<0?e.length:f,x=e.slice(d,p);if(i!=="")u(d,p,!1),tE(x,i)&&(i="",t&&a!==void 0&&(a.closeStart=d,l()));else if(x.length===0)l();else{let g=t?eE(x):"",E=t&&g===""?Z_(x):void 0,h=t&&g===""&&E===void 0&&x.includes("|");t&&o>=0&&(h!==s||g!==""||E!==void 0)&&l(),u(d,p,h),i=g,g!==""&&(a={fence:g,openEnd:p,closeStart:-1}),E!==void 0&&(c=E,l())}d=p+1}return l(),n}function Z_(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 eE(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 tE(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 nE(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{Nu(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=oE(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||q_.has(c.name))){if(z_.has(c.name)){s=rE(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return Nu(t,e,r,e.length),t}function Iu(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function Cu(e){return Iu(e)||e>="0"&&e<="9"||e==="-"||e===":"}function oE(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!Iu(e[n]))return;let r=n;for(;n<e.length&&Cu(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 rE(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||!Cu(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function Au(e){return e===" "||e===`
201
- `||e===" "||e==="\f"||e==="\r"}function Nu(e,t,n,o){let r=n,s=o;for(;r<s&&Au(t[r]);)r+=1;for(;s>r&&Au(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function ue(e){return Buffer.byteLength(e,"utf8")}function yu(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=V_.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function Ir(e,t,n,o,r){let s=[],i=new Uint8Array(o),c,a,l=0,u=(d,f,p)=>{s.push({ord:s.length,text:e.slice(d,f),bytes:p})};for(let d of t){if(a!==void 0&&!n&&(u(a.start,a.end,l),a=void 0),a!==void 0){let x=ue(e.slice(a.end,d.end));if(l+x<=o){a.end=d.end,l+=x;continue}u(a.start,a.end,l),a=void 0}let f=d.start,p=ue(e.slice(d.start,d.end));for(;p>o;){let x=yu(e,f,d.end,i),g=r?e.lastIndexOf(`
202
- `,x.end-1):-1;if(g>f){let E=ue(e.slice(f,g+1));u(f,g+1,E),f=g+1,p-=E;continue}if(r){let E=e.indexOf(`
203
- `,f),h=E<0||E>=d.end?d.end:E+1,S=ue(e.slice(f,h));if(S<=W){u(f,h,S),f=h,p-=S;continue}c??=new Uint8Array(W);let _=yu(e,f,h,c);u(f,_.end,_.written),f=_.end,p-=_.written;continue}u(f,x.end,x.written),f=x.end,p-=x.written}f>=d.end||(a={start:f,end:d.end},l=p)}return a!==void 0&&u(a.start,a.end,l),s}var sE=`
204
- `,iE=1;function Du(e,t,n,o,r){return cE(e,t,n,o,r)}function cE(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?te(s,t):te(s,r,"any"),c=e.map((f,p)=>p).sort((f,p)=>i[p]-i[f]||e[p].ord-e[f].ord),a=[],l=0,u=!1;for(let f of c){let p=e[f].bytes+(a.length>0?iE:0);if(l+p>n){u=!0;continue}a.push(e[f]),l+=p}return a.sort((f,p)=>f.ord-p.ord),{text:a.map(f=>f.text).join(sE),more:u?Cr(t,o):null}}function Cr(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>it?"...":JSON.stringify(e))+"]"+n+"})"}var ku=20,B=2,Lu=9,wu=8,aE=.9,lE=.5,uE=64,dE=2,fE=4,Dr=`
205
- `,pE="(absent)",ne=e=>Buffer.byteLength(e,"utf8");function Pu(e,t,n){let o=EE(e,t)??hE(e,t)??OE(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):te(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?ne(Dr):0,d=o.units[l].render(n-c-u);d===null||c+u+ne(d)>n||(i.push({pos:o.units[l].pos,text:d}),c+=u+ne(d))}if(i.length===0)return null;i.sort((l,u)=>l.pos-u.pos);let a=i.map(l=>l.text);return c+ne(Dr)+ne(o.header)<=n&&a.unshift(o.header),a.join(Dr)}function xE(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
206
- `&&n!=="\r"&&n!==" ")return n}return""}function _E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mu(e,t,n){if(n.size<2||n.size>wu)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=B+1)return o[0][1]<aE*e||e-o[0][1]>B?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>B),s=o.filter(([,i])=>i<=B);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function Uu(e){if(xE(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<ku||!t.every(_E))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 Hu=(e,t)=>e+" objects {"+t.join(",")+"}";function EE(e,t){let n=Uu(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 p=0;p<o.length&&f;p++){let x=l in o[p]?o[p][l]:void 0;if(typeof x=="object"&&x!==null){f=!1;break}let g=x===void 0?pE:JSON.stringify(x);d.set(g,(d.get(g)??0)+1);let E=u.get(g)??[];if(E.length<=B&&E.push(p),u.set(g,E),d.size>wu)break}if(f)for(let p of Mu(o.length,u,d))s.set(p,[...s.get(p)??[],l])}if(s.size===0||s.size>Lu)return null;let i=te(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=>Fu(l,o[l],u,c,d)}));return{header:Hu(o.length,r)+", "+s.size+" rare:",units:a}}function Fu(e,t,n,o,r){let s="["+e+"] ",i=gE(t,n,o,r-ne(s));return i===null?null:s+i}function gE(e,t,n,o){let r=JSON.stringify(e);if(ne(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=ne(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 mE(e,t){let n=te(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function hE(e,t){let n=Uu(e);if(n===null)return null;let{objs:o,keys:r}=n,s=mE(r,t),i=new Map,c=0;for(let l of r){if(!s.has(l)||c>=dE||!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=>Fu(l,o[l],[u],s,d)}));return{header:Hu(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:a,direct:!0}}function SE(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function bE(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 OE(e){let t=e.split(`
207
- `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<ku)return null;let n=new Map,o=[];for(let a=0;a<t.length;a++){let l=t[a].split(" ").filter(x=>x!==""),u=l.map(x=>SE(x)?"<*>":x),d=u.length+" "+(u[0]??""),f=n.get(d)??[],p;for(let x of f)if(bE(x.tpl,u)>=lE){p=x;break}if(p===void 0){if(p={tpl:[...u],count:0,lines:[],pos:l.map(()=>({counts:new Map,totals:new Map}))},f.push(p),n.set(d,f),o.push(p),o.length>uE)return null}else for(let x=0;x<p.tpl.length;x++)p.tpl[x]!==u[x]&&(p.tpl[x]="<*>");p.count++,p.lines.length<=B&&p.lines.push(a);for(let x=0;x<p.pos.length;x++){let g=p.pos[x];if(g===null)continue;g.totals.set(l[x],(g.totals.get(l[x])??0)+1);let E=g.counts.get(l[x])??[];E.length<=B&&E.push(a),g.counts.set(l[x],E),g.totals.size>B+1&&(p.pos[x]=null)}}let r=o.filter(a=>a.count>B);if(r.length===0||r.length>fE||r.some(a=>a.tpl.every(l=>l==="<*>")))return null;let s=new Set(o.filter(a=>a.count<=B).flatMap(a=>a.lines));for(let a of r)for(let l of a.pos)if(l!==null)for(let u of Mu(a.count,l.counts,l.totals))s.add(u);if(s.size===0||s.size>Lu)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=>ne(l)<=u?l:null}});return{header:i,units:c}}import{join as Ae}from"node:path";function TE(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function vu(e){let t=e.split(`
208
- `),n=[],o=[],r=Ai*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=TE(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>st||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(`
209
- `)}),n.push({indent:c,line:i,bytes:a})}return o}var{mkdirSync:RE,readdirSync:AE,readFileSync:NE,renameSync:Re,statSync:yE,unlinkSync:ju,utimesSync:IE,writeFileSync:Bu}=process.getBuiltinModule("node:fs"),kr=".json",Pn=".claim",Lr=".tmp",Gu=".bad",CE=15,DE=6,kE=0;function Ye(e){let t=e?.errcode;return typeof t=="number"&&(t&Mt)===Pi}function wr(e){return e instanceof Error?e.message:String(e)}async function D(e){let t=await Vl(e);return t.raw.exec("PRAGMA busy_timeout = "+String(us)),t}function Wu(e){return Ae(e.projectDir,ds)}function At(e,t){let n=Wu(e);RE(n,{recursive:!0});let o=String(Date.now()).padStart(CE,"0")+"-"+String(process.pid)+"-"+String(kE++).padStart(DE,"0"),r=Ae(n,o+Lr);Bu(r,JSON.stringify(t)),Re(r,Ae(n,o+kr))}function Xu(e,t,n,o){if(t.t==="row")return Ql(e,t.row,t.at),null;let r=n??wn(t.text,"text",t.max),s=t.id;if(s===null)s=Dn(e,t.src,r),o.op={...t,id:s};else if(n===void 0){let i=s;if(L(e,a=>a.raw.prepare("SELECT 1 AS x FROM sources WHERE id = ?").get(i)===void 0?!0:(Sr(a.raw,{sourceId:i}),!1)))return null}try{du(e,s,t.src,r),t.units&&xu(e,s,t.src.sessionId,vu(t.text))}catch(i){if(Ye(i))throw i;let c=s;throw L(e,a=>{Sr(a.raw,{sourceId:c}),a.raw.prepare("DELETE FROM sources WHERE id = ?").run(c)}),i}return s}function Nt(e,t,n,o){let r={op:n};try{return Xu(t,n,o,r)}catch(s){if(!Ye(s))throw s;return At(e,r.op),r.op.t==="src"?r.op.id:null}}function Mn(e,t,n,o){(async()=>{try{let r=await D(e);wE(e,r)?At(e,t):Nt(e,r,t,o)}catch(r){try{if(!Ye(r))throw r;At(e,t)}catch(s){process.stderr.write("hooks: "+n+" write failed: "+wr(s)+`
210
- `)}}})()}function LE(e,t){let n=t;if(t.endsWith(kr+Pn)){let r=Ae(e,t);try{if(Date.now()-yE(r).mtimeMs<fs)return null;n=t.slice(0,-Pn.length),Re(r,Ae(e,n))}catch{return null}}else if(!t.endsWith(kr))return null;let o=Ae(e,n+Pn);try{Re(Ae(e,n),o);let r=new Date;return IE(o,r,r),o}catch{return null}}function wE(e,t){let n=Wu(e),o;try{o=AE(n)}catch{return!1}let r=Date.now();for(let s of o.sort()){if(Date.now()-r>ps)return!1;let i=LE(n,s);if(i===null)continue;let c=i.slice(0,-Pn.length),a;try{a=JSON.parse(NE(i,"utf8"))}catch(u){process.stderr.write("hooks: pending write unreadable: "+wr(u)+`
211
- `),Re(i,c+Gu);continue}let l={op:a};try{Xu(t,a,void 0,l)}catch(u){if(Ye(u))return l.op===a?Re(i,c):(Bu(c+Lr,JSON.stringify(l.op)),Re(c+Lr,c),ju(i)),!0;process.stderr.write("hooks: pending write failed: "+wr(u)+`
212
- `),Re(i,c+Gu);continue}ju(i)}return!1}function Un(e,t,n){Mn(e,{t:"row",row:n,at:Date.now()},"journal")}function Ku(e,t,n){let o=new Set(Xe(t.toLowerCase()));for(let i of Xe(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of Xe(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,ss).map(i=>i[0]).join(" ")}function yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function PE(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(Ui):""}function ME(e){return Array.isArray(e)?e.filter(yt).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):yt(e)?Object.entries(e):[]}function qu(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!yt(t))return[];let n=[];for(let[o,r]of ME(t[Mi])){let s=PE(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function zu(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!yt(o)||!Array.isArray(o.options)))for(let r of o.options)yt(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function Yu(e){return e.trim().toLowerCase()}function Vu(e,t,n){let o=Yu(e);if(o==="")return null;let r=t.find(s=>Yu(s)===o);return r===void 0?null:{key:zt,body:"A: "+r+`
213
- ref: #`+n}}function UE(e,t){return"hint:"+e+":"+t}function HE(e,t){return ae(e,t)!==null?!1:(ee(e,t,"1"),!0)}function FE(e,t,n){let o=ae(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return ee(e,t,String(r)),(r-1)%n===0}function Hn(e,t,n,o){if(t==="")return!1;let r=UE(t,n),s=i=>o===void 0?HE(i,r):FE(i,r,o);return e.raw.isTransaction?s(e):L(e,s)}import{join as Mr,resolve as Ju}from"node:path";var Pr=process.getBuiltinModule("node:fs");function Ur(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function vE(e){for(let t of Js){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(Ur(n))return n}return{}}function jE(e){return e.HOME??e.USERPROFILE??""}function GE(e){let t=e[Ze];if(t!==void 0&&t!=="")return Mr(bn(e,""),eo);let n=jE(e);return n===""?"":Mr(bn(e,n),eo)}function Qu(e){let t=Ur(e)?e.code:void 0;return typeof t=="string"&&t!==""?t:e instanceof Error?e.name:"Error"}function qe(e,t,n,o){try{let r=GE(e);if(r==="")return;Pr.mkdirSync(Mr(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:Qu(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});Pr.appendFileSync(r,s+`
206
+ `);return t.startsWith("\uFEFF")?t.slice(1):t}function Ur(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,p,x)=>{o<0&&(o=f),r=p,s=x},d=0;for(;d<=e.length;){let f=e.indexOf(`
207
+ `,d),p=f<0?e.length:f,x=e.slice(d,p);if(i!=="")u(d,p,!1),SE(x,i)&&(i="",t&&a!==void 0&&(a.closeStart=d,l()));else if(x.length===0)l();else{let g=t?hE(x):"",E=t&&g===""?mE(x):void 0,h=t&&g===""&&E===void 0&&x.includes("|");t&&o>=0&&(h!==s||g!==""||E!==void 0)&&l(),u(d,p,h),i=g,g!==""&&(a={fence:g,openEnd:p,closeStart:-1}),E!==void 0&&(c=E,l())}d=p+1}return l(),n}function mE(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 hE(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 SE(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 OE(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{Gu(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=bE(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||fE.has(c.name))){if(pE.has(c.name)){s=TE(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return Gu(t,e,r,e.length),t}function Wu(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function Xu(e){return Wu(e)||e>="0"&&e<="9"||e==="-"||e===":"}function bE(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!Wu(e[n]))return;let r=n;for(;n<e.length&&Xu(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 TE(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||!Xu(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function ju(e){return e===" "||e===`
208
+ `||e===" "||e==="\f"||e==="\r"}function Gu(e,t,n,o){let r=n,s=o;for(;r<s&&ju(t[r]);)r+=1;for(;s>r&&ju(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function fe(e){return Buffer.byteLength(e,"utf8")}function Bu(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=xE.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function Hr(e,t,n,o,r){let s=[],i=new Uint8Array(o),c,a,l=0,u=(d,f,p)=>{s.push({ord:s.length,text:e.slice(d,f),bytes:p})};for(let d of t){if(a!==void 0&&!n&&(u(a.start,a.end,l),a=void 0),a!==void 0){let x=fe(e.slice(a.end,d.end));if(l+x<=o){a.end=d.end,l+=x;continue}u(a.start,a.end,l),a=void 0}let f=d.start,p=fe(e.slice(d.start,d.end));for(;p>o;){let x=Bu(e,f,d.end,i),g=r?e.lastIndexOf(`
209
+ `,x.end-1):-1;if(g>f){let E=fe(e.slice(f,g+1));u(f,g+1,E),f=g+1,p-=E;continue}if(r){let E=e.indexOf(`
210
+ `,f),h=E<0||E>=d.end?d.end:E+1,S=fe(e.slice(f,h));if(S<=q){u(f,h,S),f=h,p-=S;continue}c??=new Uint8Array(q);let _=Bu(e,f,h,c);u(f,_.end,_.written),f=_.end,p-=_.written;continue}u(f,x.end,x.written),f=x.end,p-=x.written}f>=d.end||(a={start:f,end:d.end},l=p)}return a!==void 0&&u(a.start,a.end,l),s}var RE=`
211
+ `,AE=1;function Ku(e,t,n,o,r){return NE(e,t,n,o,r)}function NE(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?re(s,t):re(s,r,"any"),c=e.map((f,p)=>p).sort((f,p)=>i[p]-i[f]||e[p].ord-e[f].ord),a=[],l=0,u=!1;for(let f of c){let p=e[f].bytes+(a.length>0?AE:0);if(l+p>n){u=!0;continue}a.push(e[f]),l+=p}return a.sort((f,p)=>f.ord-p.ord),{text:a.map(f=>f.text).join(RE),more:u?Fr(t,o):null}}function Fr(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>ut?"...":JSON.stringify(e))+"]"+n+"})"}var Yu=20,K=2,qu=9,Vu=8,yE=.9,IE=.5,CE=64,DE=2,kE=4,vr=`
212
+ `,LE="(absent)",se=e=>Buffer.byteLength(e,"utf8");function Ju(e,t,n){let o=ME(e,t)??FE(e,t)??GE(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):re(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?se(vr):0,d=o.units[l].render(n-c-u);d===null||c+u+se(d)>n||(i.push({pos:o.units[l].pos,text:d}),c+=u+se(d))}if(i.length===0)return null;i.sort((l,u)=>l.pos-u.pos);let a=i.map(l=>l.text);return c+se(vr)+se(o.header)<=n&&a.unshift(o.header),a.join(vr)}function PE(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
213
+ `&&n!=="\r"&&n!==" ")return n}return""}function wE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zu(e,t,n){if(n.size<2||n.size>Vu)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=K+1)return o[0][1]<yE*e||e-o[0][1]>K?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>K),s=o.filter(([,i])=>i<=K);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function $u(e){if(PE(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<Yu||!t.every(wE))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 Qu=(e,t)=>e+" objects {"+t.join(",")+"}";function ME(e,t){let n=$u(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 p=0;p<o.length&&f;p++){let x=l in o[p]?o[p][l]:void 0;if(typeof x=="object"&&x!==null){f=!1;break}let g=x===void 0?LE:JSON.stringify(x);d.set(g,(d.get(g)??0)+1);let E=u.get(g)??[];if(E.length<=K&&E.push(p),u.set(g,E),d.size>Vu)break}if(f)for(let p of zu(o.length,u,d))s.set(p,[...s.get(p)??[],l])}if(s.size===0||s.size>qu)return null;let i=re(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=>Zu(l,o[l],u,c,d)}));return{header:Qu(o.length,r)+", "+s.size+" rare:",units:a}}function Zu(e,t,n,o,r){let s="["+e+"] ",i=UE(t,n,o,r-se(s));return i===null?null:s+i}function UE(e,t,n,o){let r=JSON.stringify(e);if(se(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=se(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 HE(e,t){let n=re(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function FE(e,t){let n=$u(e);if(n===null)return null;let{objs:o,keys:r}=n,s=HE(r,t),i=new Map,c=0;for(let l of r){if(!s.has(l)||c>=DE||!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=>Zu(l,o[l],[u],s,d)}));return{header:Qu(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:a,direct:!0}}function vE(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function jE(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 GE(e){let t=e.split(`
214
+ `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<Yu)return null;let n=new Map,o=[];for(let a=0;a<t.length;a++){let l=t[a].split(" ").filter(x=>x!==""),u=l.map(x=>vE(x)?"<*>":x),d=u.length+" "+(u[0]??""),f=n.get(d)??[],p;for(let x of f)if(jE(x.tpl,u)>=IE){p=x;break}if(p===void 0){if(p={tpl:[...u],count:0,lines:[],pos:l.map(()=>({counts:new Map,totals:new Map}))},f.push(p),n.set(d,f),o.push(p),o.length>CE)return null}else for(let x=0;x<p.tpl.length;x++)p.tpl[x]!==u[x]&&(p.tpl[x]="<*>");p.count++,p.lines.length<=K&&p.lines.push(a);for(let x=0;x<p.pos.length;x++){let g=p.pos[x];if(g===null)continue;g.totals.set(l[x],(g.totals.get(l[x])??0)+1);let E=g.counts.get(l[x])??[];E.length<=K&&E.push(a),g.counts.set(l[x],E),g.totals.size>K+1&&(p.pos[x]=null)}}let r=o.filter(a=>a.count>K);if(r.length===0||r.length>kE||r.some(a=>a.tpl.every(l=>l==="<*>")))return null;let s=new Set(o.filter(a=>a.count<=K).flatMap(a=>a.lines));for(let a of r)for(let l of a.pos)if(l!==null)for(let u of zu(a.count,l.counts,l.totals))s.add(u);if(s.size===0||s.size>qu)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=>se(l)<=u?l:null}});return{header:i,units:c}}import{join as pe}from"node:path";function BE(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function ed(e){let t=e.split(`
215
+ `),n=[],o=[],r=wi*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=BE(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>lt||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(`
216
+ `)}),n.push({indent:c,line:i,bytes:a})}return o}var{mkdirSync:WE,readdirSync:od,readFileSync:rd,renameSync:ye,statSync:XE,unlinkSync:td,utimesSync:KE,writeFileSync:sd}=process.getBuiltinModule("node:fs"),id=".seen",jn=".json",Ie=".claim",jr=".tmp",nd=".bad",YE=15,qE=6,VE=0;function Ve(e){let t=e?.errcode;return typeof t=="number"&&(t&Ft)===Bi}function Gr(e){return e instanceof Error?e.message:String(e)}async function I(e){let t=await ou(e);return t.raw.exec("PRAGMA busy_timeout = "+String(et)),t}function Br(e){return pe(e.projectDir,Ss)}function qe(e,t){let n=Br(e);WE(n,{recursive:!0});let o=String(Date.now()).padStart(YE,"0")+"-"+String(process.pid)+"-"+String(VE++).padStart(qE,"0"),r=pe(n,o+jr);sd(r,JSON.stringify(t)),ye(r,pe(n,o+(t.t==="seen"?id:"")+jn))}function cd(e,t,n,o){if(t.t==="row")return du(e,t.row,t.at),null;if(t.t==="seen")return y(e,i=>{let c=ad(P(i,t.key)),a=t.add.filter(l=>!c.includes(l));a.length>0&&w(i,t.key,JSON.stringify([...c,...a]))}),null;let r=n??Fn(t.text,"text",t.max),s=t.id;if(s===null)s=Mn(e,t.src,r),o.op={...t,id:s};else if(n===void 0){let i=s;if(y(e,a=>a.raw.prepare("SELECT 1 AS x FROM sources WHERE id = ?").get(i)===void 0?!0:(Cr(a.raw,{sourceId:i}),!1)))return null}try{Nu(e,s,t.src,r),t.units&&Cu(e,s,t.src.sessionId,ed(t.text))}catch(i){if(Ve(i))throw i;let c=s;throw y(e,a=>{Cr(a.raw,{sourceId:c}),a.raw.prepare("DELETE FROM sources WHERE id = ?").run(c)}),i}return s}function ad(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"||typeof n=="string"):[]}catch{return[]}}function Wr(e,t,n){let o=[],r=Br(e),s=[];try{s=od(r)}catch{}for(let i of s){let c=i.endsWith(Ie)?i.slice(0,-Ie.length):i;if(!c.endsWith(id+jn))continue;let a=null;for(let l of[i,c+Ie,c])try{a=JSON.parse(rd(pe(r,l),"utf8"));break}catch{}a!==null&&a.t==="seen"&&a.key===n&&o.push(...a.add)}for(let i of ad(P(t,n)))o.includes(i)||o.push(i);return o}var vn=0;function Ct(e,t,n,o){let r={op:n};try{return cd(t,n,o,r)}catch(s){if(!Ve(s))throw s;return vn=Date.now()+et,qe(e,r.op),r.op.t==="src"?r.op.id:null}}function Je(e,t,n,o){(async()=>{try{let r=await I(e);Date.now()<vn?qe(e,t):zE(e,r)?(vn=Date.now()+et,qe(e,t)):Ct(e,r,t,o)}catch(r){try{if(!Ve(r))throw r;vn=Date.now()+et,qe(e,t)}catch(s){process.stderr.write("hooks: "+n+" write failed: "+Gr(s)+`
217
+ `)}}})()}function JE(e,t){let n=t;if(t.endsWith(jn+Ie)){let r=pe(e,t);try{if(Date.now()-XE(r).mtimeMs<Os)return null;n=t.slice(0,-Ie.length),ye(r,pe(e,n))}catch{return null}}else if(!t.endsWith(jn))return null;let o=pe(e,n+Ie);try{ye(pe(e,n),o);let r=new Date;return KE(o,r,r),o}catch{return null}}function zE(e,t){let n=Br(e),o;try{o=od(n)}catch{return!1}let r=Date.now();for(let s of o.sort()){if(Date.now()-r>bs)return!1;let i=JE(n,s);if(i===null)continue;let c=i.slice(0,-Ie.length),a;try{a=JSON.parse(rd(i,"utf8"))}catch(u){process.stderr.write("hooks: pending write unreadable: "+Gr(u)+`
218
+ `),ye(i,c+nd);continue}let l={op:a};try{cd(t,a,void 0,l)}catch(u){if(Ve(u))return l.op===a?ye(i,c):(sd(c+jr,JSON.stringify(l.op)),ye(c+jr,c),td(i)),!0;process.stderr.write("hooks: pending write failed: "+Gr(u)+`
219
+ `),ye(i,c+nd);continue}td(i)}return!1}function Gn(e,t,n){Je(e,{t:"row",row:n,at:Date.now()},"journal")}function ld(e,t,n){let o=new Set(Ke(t.toLowerCase()));for(let i of Ke(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of Ke(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,_s).map(i=>i[0]).join(" ")}function Dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $E(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(Xi):""}function QE(e){return Array.isArray(e)?e.filter(Dt).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):Dt(e)?Object.entries(e):[]}function dd(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!Dt(t))return[];let n=[];for(let[o,r]of QE(t[Wi])){let s=$E(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function fd(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!Dt(o)||!Array.isArray(o.options)))for(let r of o.options)Dt(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function ud(e){return e.trim().toLowerCase()}function pd(e,t,n){let o=ud(e);if(o==="")return null;let r=t.find(s=>ud(s)===o);return r===void 0?null:{key:Zt,body:"A: "+r+`
220
+ ref: #`+n}}function ZE(e,t){return"hint:"+e+":"+t}function eg(e,t){return P(e,t)!==null?!1:(w(e,t,"1"),!0)}function tg(e,t,n){let o=P(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return w(e,t,String(r)),(r-1)%n===0}function Bn(e,t,n,o){if(t==="")return!1;let r=ZE(t,n),s=i=>o===void 0?eg(i,r):tg(i,r,o);return e.raw.isTransaction?s(e):y(e,s)}import{join as Kr,resolve as xd}from"node:path";var Xr=process.getBuiltinModule("node:fs");function Yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function ng(e){for(let t of si){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(Yr(n))return n}return{}}function og(e){return e.HOME??e.USERPROFILE??""}function rg(e){let t=e[ot];if(t!==void 0&&t!=="")return Kr(Nn(e,""),io);let n=og(e);return n===""?"":Kr(Nn(e,n),io)}function Ed(e){let t=Yr(e)?e.code:void 0;return typeof t=="string"&&t!==""?t:e instanceof Error?e.name:"Error"}function ze(e,t,n,o){try{let r=rg(e);if(r==="")return;Xr.mkdirSync(Kr(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:Ed(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});Xr.appendFileSync(r,s+`
214
221
  `)}catch{process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
215
- `)}}var $u=!1;function It(e,t){if(!($u||e[Zs]!==t))throw $u=!0,new Error("injected fault at "+t)}function Zu(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=Qe.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 de(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function BE(e,t){let n=t.toLowerCase();return de(e.nativeTools.shell,n)||de(nt.shell,n)?"shell":de(e.nativeTools.read,n)||de(nt.read,n)?"read":de(e.nativeTools.grep,n)||de(nt.grep,n)?"grep":de(e.nativeTools.webfetch,n)||de(nt.fetch,n)?"fetch":null}function WE(e,t){let n=t.toLowerCase();return Qs.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function XE(e){try{let t=Pr.statSync(e);return t.isFile()&&t.size>xe}catch{return!1}}function KE(e,t,n){if((t.offset??null)!==null||(t.limit??null)!==null)return!1;let o=Array.isArray(t[De])?t[De].filter(r=>typeof r=="string"):[];return[Fn(t,Ee),...o].some(r=>r!==""&&XE(Ju(n,r))&&!Rn(e,Ju(n,r))&&!We(e,n,r))}function Ne(e){try{return q(e).encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"})}catch{return{stdout:"",exitCode:0}}}function Ct(e,t,n,o=""){let r=q(e);try{if(!Ur(t)||!WE(r,Fn(t,Vs)))return Ne(e);let s=Fn(t,zs);if(s===""||s.includes(Wt))return Ne(e);let i=BE(r,s);if(i===null)return Ne(e);let c=Fn(t,$s)||o;if(i==="read"&&!KE(e,vE(t),c))return Ne(e);let a=i==="read"?to.read:to[i],l=P(a,r.toolNamePrefix)+`
216
- `+ei(Qu(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:YE,writeSync:qE}=process.getBuiltinModule("node:fs"),ed=65536;function zE(e){let t=Buffer.allocUnsafe(ed);return new Promise(n=>{let o=()=>{YE(0,t,0,ed,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 Hr(){let e=[];if(!await zE(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function Fr(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=qE(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{lstatSync:od,readFileSync:VE}=process.getBuiltinModule("node:fs"),R={kind:"allow"},$E={stdout:"",exitCode:0},QE=48;function ZE(e){return ze.includes(e)}function vn(e){return e instanceof Error?e.message:String(e)}function Dt(e){return typeof e=="string"?e:""}async function id(e,t,n){if(!ZE(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
217
- `),$E;let o=q(e),r=(u,d,f)=>{qe(n,e,u,d),process.stderr.write(f??"hooks: "+u+" failed: "+vn(d)+`
218
- `)},s=(u,d,f)=>(r(u,d,f),Ct(e,t,d));if(Zu(process.version)){let u=new T("NODE_TOO_OLD",{v:process.version});return o.installMode==="in-process"?s("node",u):(r("node",u),Ne(e))}let i;try{It(n,"decode"),i=o.decode(t)}catch(u){return s("decode",u)}if(i.event==="Stop")return o.encode(i,R);let c;try{It(n,"project");let u=e==="vscode"?[Ft,i.cwd]:process.argv;c=Wl(e,{env:n,argv:u,cwd:i.cwd,piCwd:q(e).projectSource==="pi:ctx.cwd"?i.cwd:void 0})}catch(u){return s("project",u,"hooks: no project: "+String(u.code??"ERROR")+" "+vn(u)+`
219
- `)}let a,l={};try{It(n,"policy"),a=await eg(i,o,c,n,l)}catch(u){return s("store",u)}try{It(n,"encode");let u=o.encode(i,a);return l.run?.(!0),u}catch(u){return l.run?.(!1),s("encode",u)}}function eg(e,t,n,o,r){switch(e.event){case"SessionStart":return tg(e,t,n);case"UserPromptSubmit":return ng(e,t,n);case"PreToolUse":return dg(e,t,n,o);case"PostToolUse":return Eg(e,t,n,o,r);case"PreCompact":return Pg(e,t,n);case"Usage":return Mg(e,n)}return Promise.resolve(R)}function cd(e,t){return e.split(ti).join(t.toolNamePrefix)}function Gr(e,t,n){return n.compactSummary==="host"?P(ls,n.toolNamePrefix):Ru(mr(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function tg(e,t,n){if(e.source==="compact"&&an(t)&&ad(await D(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await D(n),s=bi+":"+su(r,e.sessionId);return Hn(r,e.sessionId,s)?{kind:"hint",text:Gr(r,e,t),onceKey:s}:R}let o=await D(n);return t.compactDelivery==="opencode-cache"&&In(o,Xt+e.sessionId)!==null?{kind:"hint",text:Gr(o,e,t),onceKey:io}:Hn(o,e.sessionId,rt)?{kind:"hint",text:cd(fo,t),onceKey:rt}:R}async function ng(e,t,n){let o=e.prompt??"",r=await og(e,t,n);if(Un(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}),lg(e,n,o),t.compactDelivery==="pending-flag"){let s=await D(n);if(In(s,Xt+e.sessionId)!==null)return{kind:"hint",text:Gr(s,e,t),onceKey:io}}return r!==null?r:cg(e,t,n,o)}async function og(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await D(n);return ru(o,e.sessionId)||!Hn(o,e.sessionId,rt)||!ou(o,n.worktree,e.agent)?null:{kind:"hint",text:cd(fo,t),onceKey:rt}}function ad(e,t){t!==""&&ee(e,ao+t,JSON.stringify({seq:nu(e),source:Eu(e)}))}function rg(e){let t={seq:Number.MAX_SAFE_INTEGER,source:Number.MAX_SAFE_INTEGER};try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return t;let{seq:o,source:r}=n;return{seq:typeof o=="number"?o:t.seq,source:typeof r=="number"?r:t.source}}catch{return t}}function sg(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function ig(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 cg(e,t,n,o){if(!an(t)||e.sessionId==="")return R;let r=await D(n),s=ae(r,ao+e.sessionId);if(s===null)return R;let i=rg(s),c=yi+e.sessionId,a=sg(ae(r,c)),l=Ri+e.sessionId,u=ig(ae(r,l)),d=gu(r,e.sessionId,_u(o),Ni,i.source),f=tu(r,e.sessionId,n.worktree,Ti,i.seq),p=Tu(f,o,new Set(a),d,new Set(u));return p.text===""?R:(p.seqs.length>0&&ee(r,c,JSON.stringify([...a,...p.seqs])),p.units!==void 0&&ee(r,l,JSON.stringify([...u,...p.units])),{kind:"hint",text:p.text,onceKey:Ii})}function ld(e){return qt+":"+zt+":"+e}function ag(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 lg(e,t,n){if(e.sessionId==="")return;let o=ld(e.sessionId);D(t).then(r=>{if(ae(r,o)===null)return;let s=In(r,o),i=s===null?null:ag(s);if(i===null)return;let c=Vu(n,i.labels,i.seq);c!==null&&ud(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+vn(r)+`
220
- `)})}function ud(e,t,n,o){for(let r of o)Nt(n,e,{t:"row",at:Date.now(),row:{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:po,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}}),Nt(n,e,{t:"src",id:null,src:xd(n,t.sessionId,qt),text:r.body,max:W,units:!1})}function ug(e,t,n,o){let r=qu(o),s=r.length===0?zu(n.input):[];r.length===0&&s.length===0||D(t).then(i=>{if(r.length>0)return ud(i,e,t,r);let c=mr(i,e.sessionId,"prompt"),a=c[c.length-1];a===void 0||e.sessionId===""||ee(i,ld(e.sessionId),JSON.stringify({seq:a.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+vn(i)+`
221
- `)})}function dd(e,t,n){let o={projectDir:t.worktree,env:n};return e.agentTools!==void 0&&(o.manifestTools=e.agentTools),o}async function dg(e,t,n,o){let r=al(n.worktree,e.agent),s=Ml(e,t,r,n),i=s;if(s.kind==="deny"&&je(e)&&!fd(s.reason,t)){let c=er(e,dd(e,n,o)),a=Zo(e,c),l=e.tool,u=c!==null||(e.agentType??"")!==""&&ke(t);a==="B"&&l!==void 0&&Xr(l,t)?i=fg(e,t,s,r):a!=="A"&&u&&(i=R)}return i}function Xr(e,t){return e.canonicalName===mi||t.nativeTools.shell.includes(e.name)}function fd(e,t){return e.startsWith(tt)||e===P(jt,t.toolNamePrefix)||e===P(Gt,t.toolNamePrefix)}function vr(e){return Buffer.from(e,"utf8").toString("base64url")}function fg(e,t,n,o){let r=e.tool;if(r===void 0||!Xr(r,t)||fd(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+Wr(rd(process.argv[1]??""),Di)+'"',c=[ki,i,vr(s),vr(JSON.stringify(o??[])),vr(Dt(r.input.description))].join(" ");return{kind:"deny",reason:Li,rewritten:c}}function pg(e,t,n){return n?"toolerr":hi.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":Xr(e,t)?"cmd":null}function Br(e){if(Array.isArray(e))return"["+e.map(Br).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)+":"+Br(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function xg(e){let t=e.indexOf(`
222
- `),n=t<0?e:e.slice(0,t);if(!n.startsWith(so))return null;let o=0,r=0;for(let s of n.slice(so.length)){let i=s.charCodeAt(0)-QE;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function _g(e){for(let t of Si)if(typeof e[t]=="string")return e[t];return null}async function Eg(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(Wt))return R;let i=e.result??{isError:!1,bytes:0},c=Cg(i,e.sessionId,o),a=c.text;i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(a)),s.canonicalName===po&&ug(e,n,s,a);let l=pg(s,t,i.isError),u=p=>{if(l===null)return;let x=l==="cmd"?Zl(s.canonicalName,Dt(s.input.command)):l==="toolerr"?s.canonicalName+":"+Br(s.input):null;Un(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:l,tool:s.canonicalName,key:x,path:_g(s.input),ok:i.isError?0:1,exit_code:xg(a),bytes:i.bytes,body:a,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:p})},d;try{d=await mg(e,t,n,o,s,i,a,c.file)}catch(p){throw u(i.bytes),p}let f=d;return r.run=p=>u(p&&f.kind==="replace"?Buffer.byteLength(f.output):i.bytes),d}function gg(e,t,n){if(!Je.includes(t.canonicalName))return!1;let o=Ee.map(r=>t.input[r]).find(r=>typeof r=="string"&&r!=="");return o!==void 0&&We(e.agent,e.cwd,o,n)}async function mg(e,t,n,o,r,s,i,c){if(s.bytes<=Jr||bg(r)||Og(e,r)||gg(e,r,o)||Qr.includes(r.canonicalName)||s.keep===!0||!ke(t))return R;let a,l={ctx:!0,shell:!0,read:!1},u=!0;if(je(e)){let w=er(e,dd(e,n,o)),ye=Zo(e,w),fe=gd=>w!==null&&gd.some(md=>w.includes(md));if(u=fe(t.nativeTools.read??[]),l={ctx:ye==="A",shell:fe(t.nativeTools.shell),read:Je.includes(r.canonicalName)&&fe(t.nativeTools.read??[])},w!==null&&!l.ctx&&!l.shell&&!l.read)return R;a=Ci+r.canonicalName+":"+(r.callId??String(e.turn??0))}else a=kg(r,e);let d=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url,r.name].map(Dt).find(w=>w.trim()!=="")??r.canonicalName,f=wn(i,"text",Xn),p=await D(n),x={t:"src",id:null,src:xd(n,e.sessionId,a),text:i,max:Xn,units:!0},g;if(s.bytes<=Vr?g=Nt(n,p,x,f):(g=wg(n,p,x,f),g!==null&&Lg(n,{...x,id:g},f)),hg(r))return R;let E=g===null?a:pu(g),h=await Dg(n,e.sessionId),S=h.trim()===""?void 0:d+" "+h,_=l.ctx?ts(d,E,s.bytes,t.toolNamePrefix,Ku(d,h,i)):ns(E,s.bytes,l.read),m=yg(_,Cr(d,a)),A=_+(l.shell&&e.agent===Is&&g!==null?Sg(E,d,n):"")+(c!==void 0&&u?rs(c):""),y=Pu(i,S??d,es);if(y!==null)return{kind:"replace",output:nd(y,A)};let oe=Du(f,d,m,a,S);return{kind:"replace",output:oe.more!==null?nd(oe.text,A):oe.text}}function hg(e){return e.callId!==void 0&&e.callId.startsWith(Hs)&&e.name.startsWith(se)}function Sg(e,t,n){let o=Buffer.byteLength(t,"utf8")>it?"":t;return os(Wr(rd(process.argv[1]??""),ys),e,o,n.worktree)}function bg(e){return Je.includes(e.canonicalName)&&$r.some(t=>e.input[t]!==void 0&&e.input[t]!==null)}function Og(e,t){if(e.agent!=="omp"||!Je.includes(t.canonicalName))return!1;let n=Ee.map(o=>t.input[o]).find(o=>typeof o=="string"&&o!=="");if(n===void 0||!Tg(n))return!1;try{return od(sd(e.cwd,n),{throwIfNoEntry:!1})===void 0}catch{return!1}}function Tg(e){let t=e.lastIndexOf(":"),n=e.slice(t+1);if(n.toLowerCase()==="raw"&&(t=e.lastIndexOf(":",t-1),n=e.slice(t+1,e.length-4)),t<=0||!Rg(n))return!1;let o=e.slice(0,t);return o.toLowerCase().endsWith(":raw")&&(o=o.slice(0,-4)),o.length>1||!Ng(o)}function Rg(e){return e!==""&&e.split(",").every(Ag)}function Ag(e){if(e.startsWith("-"))return jr(e.slice(1));let t=0;for(;t<e.length&&pd(e[t]);)t++;if(t===0)return!1;if(t===e.length)return!0;let n=e[t],o=e.slice(t+1);return n==="-"&&(o===""||jr(o))||n==="+"&&jr(o)}function jr(e){if(e==="")return!1;for(let t of e)if(!pd(t))return!1;return!0}function pd(e){return e>="0"&&e<="9"}function Ng(e){let t=e.toLowerCase();return t.length===1&&t>="a"&&t<="z"}function nd(e,t){return e===""?t:e+`
223
- `+t}function yg(e,t){return Math.max(0,Zr+Buffer.byteLength(`
224
- `+t)-1-Buffer.byteLength(e))}function Ig(e,t,n){if(t===""||t.includes(td)||t.includes("/"))return!1;let o=Wr($(n,j(n)??""),Ht),r=JE(o,sd(e)).split(td);if(r.length!==4||r.includes("..")||r.includes("")||r[1]!==t||r[2]!==Hi)return!1;let s=od(e);return s.isFile()&&s.size<=Fi&&Rl(o,e)}function Cg(e,t,n){let o=e.text??"";if(e.persistedPath===void 0)return{text:o};try{return Ig(e.persistedPath,t,n)?{text:VE(e.persistedPath,"utf8"),file:e.persistedPath}:(qe(n,"claude-code","persisted-output",new Error("persisted output path is outside this session's tool-results dir or too large; kept the head")),{text:o})}catch{return{text:o}}}async function Dg(e,t){try{return eu(await D(e),t)}catch{return""}}function kg(e,t){let n=Dt(e.input.command)??Dt(e.input.file_path)??"",o=n.indexOf(`
225
- `);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,Ns)+"#"+(e.callId??String(t.turn??0))}function Lg(e,t,n){Mn(e,t,"index",n)}function wg(e,t,n,o){try{return Dn(t,n.src,o)}catch(r){if(!Ye(r))throw r;return At(e,n),null}}function xd(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function Pg(e,t,n){let o=await D(n);return ee(o,Xt+e.sessionId,Oi),an(t)&&ad(o,e.sessionId),R}function Mg(e,t){return Un(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(R)}var Ed={stdout:"",exitCode:0};function Ug(e){return ze.includes(e)}function jn(e){process.exitCode=e.exitCode,e.stdout!==""&&Fr(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
226
- `)}function _d(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
227
- `);try{return qe(r,e,n,o),Ct(e,t,o)}catch{return Ed}}async function Hg(e,t){let n=e.indexOf(Yt),o=n>=0?e[n+1]??"":"";if(!Ug(o))return console.error("hooks: unknown "+Yt+" "+JSON.stringify(o)+". Fix: pass "+Yt+" with one of "+ze.join(", ")+"."),jn(Ed);let r;try{r=JSON.parse(await Hr())}catch(s){return jn(_d(o,void 0,"stdin",s,t))}try{return jn(await id(o,r,t))}catch(s){return jn(_d(o,r,"load",s,t))}}Hg(process.argv.slice(2),process.env);export{Hg as main};
222
+ `)}}var _d=!1;function kt(e,t){if(!(_d||e[ai]!==t))throw _d=!0,new Error("injected fault at "+t)}function gd(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=nt.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 xe(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function sg(e,t){let n=t.toLowerCase();return xe(e.nativeTools.shell,n)||xe(it.shell,n)?"shell":xe(e.nativeTools.read,n)||xe(it.read,n)?"read":xe(e.nativeTools.grep,n)||xe(it.grep,n)?"grep":xe(e.nativeTools.webfetch,n)||xe(it.fetch,n)?"fetch":null}function ig(e,t){let n=t.toLowerCase();return ci.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function cg(e){try{let t=Xr.statSync(e);return t.isFile()&&t.size>Y}catch{return!1}}function ag(e,t,n){if((t.offset??null)!==null||(t.limit??null)!==null)return!1;let o=Array.isArray(t[Le])?t[Le].filter(r=>typeof r=="string"):[];return[Wn(t,ae),...o].some(r=>r!==""&&cg(xd(n,r))&&!Cn(e,xd(n,r))&&!Xe(e,n,r))}function Ce(e){try{return $(e).encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"})}catch{return{stdout:"",exitCode:0}}}function Lt(e,t,n,o=""){let r=$(e);try{if(!Yr(t)||!ig(r,Wn(t,ri)))return Ce(e);let s=Wn(t,oi);if(s===""||s.includes(Yt))return Ce(e);let i=sg(r,s);if(i===null)return Ce(e);let c=Wn(t,ii)||o;if(i==="read"&&!ag(e,ng(t),c))return Ce(e);let a=i==="read"?co.read:co[i],l=U(a,r.toolNamePrefix)+`
223
+ `+li(Ed(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:lg,writeSync:ug}=process.getBuiltinModule("node:fs"),md=65536;function dg(e){let t=Buffer.allocUnsafe(md);return new Promise(n=>{let o=()=>{lg(0,t,0,md,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 qr(){let e=[];if(!await dg(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function Vr(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=ug(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{lstatSync:Od,readFileSync:fg}=process.getBuiltinModule("node:fs"),T={kind:"allow"},xg={stdout:"",exitCode:0},_g=48;function Eg(e){return Qe.includes(e)}function Xn(e){return e instanceof Error?e.message:String(e)}function Pt(e){return typeof e=="string"?e:""}async function Td(e,t,n){if(!Eg(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
224
+ `),xg;let o=$(e),r=(u,d,f)=>{ze(n,e,u,d),process.stderr.write(f??"hooks: "+u+" failed: "+Xn(d)+`
225
+ `)},s=(u,d,f)=>(r(u,d,f),Lt(e,t,d));if(gd(process.version)){let u=new R("NODE_TOO_OLD",{v:process.version});return o.installMode==="in-process"?s("node",u):(r("node",u),Ce(e))}let i;try{kt(n,"decode"),i=o.decode(t)}catch(u){return s("decode",u)}if(i.event==="Stop")return o.encode(i,T);let c;try{kt(n,"project");let u=e==="vscode"?[Gt,i.cwd]:process.argv;c=$l(e,{env:n,argv:u,cwd:i.cwd,piCwd:$(e).projectSource==="pi:ctx.cwd"?i.cwd:void 0})}catch(u){return s("project",u,"hooks: no project: "+String(u.code??"ERROR")+" "+Xn(u)+`
226
+ `)}let a,l={};try{kt(n,"policy"),a=await gg(i,o,c,n,l)}catch(u){return s("store",u)}try{kt(n,"encode");let u=o.encode(i,a);return l.run?.(!0),u}catch(u){return l.run?.(!1),s("encode",u)}}function gg(e,t,n,o,r){switch(e.event){case"SessionStart":return mg(e,t,n);case"UserPromptSubmit":return hg(e,t,n);case"PreToolUse":return Ng(e,t,n,o);case"PostToolUse":return kg(e,t,n,o,r);case"PreCompact":return Jg(e,t,n);case"Usage":return zg(e,n)}return Promise.resolve(T)}function Rd(e,t){return e.split(ui).join(t.toolNamePrefix)}function $r(e,t,n){return n.compactSummary==="host"?U(hs,n.toolNamePrefix):vu(yr(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function mg(e,t,n){if(e.source==="compact"&&pn(t)&&Ad(await I(n),e.sessionId),e.source==="compact"&&wd(await I(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await I(n),s=Di+":"+mu(r,e.sessionId);return Bn(r,e.sessionId,s)?{kind:"hint",text:$r(r,e,t),onceKey:s}:T}let o=await I(n);return t.compactDelivery==="opencode-cache"&&Pn(o,qt+e.sessionId)!==null?{kind:"hint",text:$r(o,e,t),onceKey:po}:Bn(o,e.sessionId,at)?{kind:"hint",text:Rd(ho,t),onceKey:at}:T}async function hg(e,t,n){let o=e.prompt??"",r=await Sg(e,t,n);if(Gn(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}),Rg(e,n,o),t.compactDelivery==="pending-flag"){let s=await I(n);if(Pn(s,qt+e.sessionId)!==null)return{kind:"hint",text:$r(s,e,t),onceKey:po}}return r!==null?r:bg(e,t,n,o)}async function Sg(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await I(n);return gu(o,e.sessionId)||!Bn(o,e.sessionId,at)||!Eu(o,n.worktree,e.agent)?null:{kind:"hint",text:Rd(ho,t),onceKey:at}}function Ad(e,t){t!==""&&w(e,_o+t,JSON.stringify({seq:_u(e),source:ku(e)}))}function Og(e){let t={seq:Number.MAX_SAFE_INTEGER,source:Number.MAX_SAFE_INTEGER};try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return t;let{seq:o,source:r}=n;return{seq:typeof o=="number"?o:t.seq,source:typeof r=="number"?r:t.source}}catch{return t}}async function bg(e,t,n,o){if(!pn(t)||e.sessionId==="")return T;let r=await I(n),s=P(r,_o+e.sessionId);if(s===null)return T;let i=Og(s),c=Ui+e.sessionId,a=Wr(n,r,c).filter(x=>typeof x=="number"),l=Pi+e.sessionId,u=Wr(n,r,l).filter(x=>typeof x=="string"),d=Lu(r,e.sessionId,Du(o),Mi,i.source),f=xu(r,e.sessionId,n.worktree,Li,i.seq),p=Fu(f,o,new Set(a),d,new Set(u));return p.text===""?T:(p.seqs.length>0&&Je(n,{t:"seen",key:c,add:p.seqs},"recall"),p.units!==void 0&&Je(n,{t:"seen",key:l,add:p.units},"recall"),{kind:"hint",text:p.text,onceKey:Hi})}function Nd(e){return Qt+":"+Zt+":"+e}function Tg(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 Rg(e,t,n){if(e.sessionId==="")return;let o=Nd(e.sessionId);I(t).then(r=>{if(P(r,o)===null)return;let s=Pn(r,o),i=s===null?null:Tg(s);if(i===null)return;let c=pd(n,i.labels,i.seq);c!==null&&yd(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+Xn(r)+`
227
+ `)})}function yd(e,t,n,o){for(let r of o)Ct(n,e,{t:"row",at:Date.now(),row:{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}}),Ct(n,e,{t:"src",id:null,src:Pd(n,t.sessionId,Qt),text:r.body,max:q,units:!1})}function Ag(e,t,n,o){let r=dd(o),s=r.length===0?fd(n.input):[];r.length===0&&s.length===0||I(t).then(i=>{if(r.length>0)return yd(i,e,t,r);let c=yr(i,e.sessionId,"prompt"),a=c[c.length-1];a===void 0||e.sessionId===""||w(i,Nd(e.sessionId),JSON.stringify({seq:a.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+Xn(i)+`
228
+ `)})}function Id(e,t,n){let o={projectDir:t.worktree,env:n};return e.agentTools!==void 0&&(o.manifestTools=e.agentTools),o}async function Ng(e,t,n,o){let r=El(n.worktree,e.agent),s=Wl(e,t,r,n),i=s;if(s.kind==="deny"&&Ge(e)&&!Cd(s.reason,t)){let c=cr(e,Id(e,n,o)),a=ir(e,c),l=e.tool,u=c!==null||(e.agentType??"")!==""&&Se(t);a==="B"&&l!==void 0&&ts(l,t)?i=yg(e,t,s,r):a!=="A"&&u&&(i=T)}return i}function ts(e,t){return e.canonicalName===yi||t.nativeTools.shell.includes(e.name)}function Cd(e,t){return e.startsWith(st)||e===U(Wt,t.toolNamePrefix)||e===U(Xt,t.toolNamePrefix)}function Jr(e){return Buffer.from(e,"utf8").toString("base64url")}function yg(e,t,n,o){let r=e.tool;if(r===void 0||!ts(r,t)||Cd(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+Zr(bd(process.argv[1]??""),Fi)+'"',c=[vi,i,Jr(s),Jr(JSON.stringify(o??[])),Jr(Pt(r.input.description))].join(" ");return{kind:"deny",reason:ji,rewritten:c}}function Ig(e,t,n){return n?"toolerr":Ii.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":ts(e,t)?"cmd":null}function Qr(e){if(Array.isArray(e))return"["+e.map(Qr).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)+":"+Qr(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function Cg(e){let t=e.indexOf(`
229
+ `),n=t<0?e:e.slice(0,t);if(!n.startsWith(fo))return null;let o=0,r=0;for(let s of n.slice(fo.length)){let i=s.charCodeAt(0)-_g;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function Dg(e){for(let t of Ci)if(typeof e[t]=="string")return e[t];return null}async function kg(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(Yt))return T;let i=e.result??{isError:!1,bytes:0},c=Kg(i,e.sessionId,o),a=c.text;i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(a)),s.canonicalName===So&&Ag(e,n,s,a);let l=Ig(s,t,i.isError),u=p=>{if(l===null)return;let x=l==="cmd"?fu(s.canonicalName,Pt(s.input.command)):l==="toolerr"?s.canonicalName+":"+Qr(s.input):null;Gn(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:l,tool:s.canonicalName,key:x,path:Dg(s.input),ok:i.isError?0:1,exit_code:Cg(a),bytes:i.bytes,body:a,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:p})},d;try{d=await Pg(e,t,n,o,s,i,a,c.file)}catch(p){throw u(i.bytes),p}let f=d;return r.run=p=>u(p&&f.kind==="replace"?Buffer.byteLength(f.output):i.bytes),d}function Lg(e,t,n){if(!ge.includes(t.canonicalName))return!1;let o=ae.map(r=>t.input[r]).find(r=>typeof r=="string"&&r!=="");return o!==void 0&&Xe(e.agent,e.cwd,o,n)}async function Pg(e,t,n,o,r,s,i,c){if(Hg(r))return await wg(e,t,n,r),T;if(s.bytes<=is||Fg(e,r)||Lg(e,r,o)||as.includes(r.canonicalName)||s.keep===!0||!Se(t))return T;let a,l={ctx:!0,shell:!0,read:!1},u=!0;if(Ge(e)){let M=cr(e,Id(e,n,o)),$e=ir(e,M),Yn=Hd=>M!==null&&Hd.some(Fd=>M.includes(Fd));if(u=Yn(t.nativeTools.read??[]),l={ctx:$e==="A",shell:Yn(t.nativeTools.shell),read:ge.includes(r.canonicalName)&&Yn(t.nativeTools.read??[])},M!==null&&!l.ctx&&!l.shell&&!l.read)return T;a=zt+r.canonicalName+":"+(r.callId??String(e.turn??0))}else a=Ld(r,e);let d=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url,r.name].map(Pt).find(M=>M.trim()!=="")??r.canonicalName,f=Fn(i,"text",zn),p=await I(n),x=Dd(e,r);if(s.bytes<=Y&&x!==""&&Ar(p,e.sessionId,x))return T;let g={t:"src",id:null,src:Pd(n,e.sessionId,a),text:i,max:zn,units:!0},E;if(s.bytes<=ss?E=Ct(n,p,g,f):(E=Vg(n,p,g,f),E!==null&&qg(n,{...g,id:E},f)),Mg(r))return T;let h=E===null?a:Iu(E);ge.includes(r.canonicalName)&&x!==""&&!Nr(p,e.sessionId,x)&&cu(p,e.sessionId,x,h);let S=await Yg(n,e.sessionId),_=S.trim()===""?void 0:d+" "+S,m=l.ctx?ds(d,h,s.bytes,t.toolNamePrefix,ld(d,S,i)):fs(h,s.bytes,l.read),N=Wg(m,Fr(d,a)),C=m+(l.shell&&e.agent===Hs&&E!==null?Ug(h,d,n):"")+(c!==void 0&&u?xs(c):""),_e=Ju(i,_??d,us);if(_e!==null)return{kind:"replace",output:Sd(_e,C)};let ie=Ku(f,d,N,a,_);return{kind:"replace",output:ie.more!==null?Sd(ie.text,C):ie.text}}function Dd(e,t){if(ge.includes(t.canonicalName)){let n=ae.map(o=>t.input[o]).find(o=>typeof o=="string"&&o!=="");return n===void 0?"":t.canonicalName+":"+es(e.cwd,n)}return lu(Ld(t,e))??""}async function wg(e,t,n,o){if(e.sessionId===""||!Se(t))return;let r=Dd(e,o);if(r!=="")try{let s=await I(n);Nr(s,e.sessionId,r)&&!Ar(s,e.sessionId,r)&&iu(s,e.sessionId,r,"ranged-read",o.callId??"")}catch{}}function Mg(e){return e.callId!==void 0&&e.callId.startsWith(Ys)&&e.name.startsWith(j)}function Ug(e,t,n){let o=Buffer.byteLength(t,"utf8")>ut?"":t;return ps(Zr(bd(process.argv[1]??""),Us),e,o,n.worktree)}function Hg(e){return ge.includes(e.canonicalName)&&cs.some(t=>e.input[t]!==void 0&&e.input[t]!==null)}function Fg(e,t){if(e.agent!=="omp"||!ge.includes(t.canonicalName))return!1;let n=ae.map(o=>t.input[o]).find(o=>typeof o=="string"&&o!=="");if(n===void 0||!vg(n))return!1;try{return Od(es(e.cwd,n),{throwIfNoEntry:!1})===void 0}catch{return!1}}function vg(e){let t=e.lastIndexOf(":"),n=e.slice(t+1);if(n.toLowerCase()==="raw"&&(t=e.lastIndexOf(":",t-1),n=e.slice(t+1,e.length-4)),t<=0||!jg(n))return!1;let o=e.slice(0,t);return o.toLowerCase().endsWith(":raw")&&(o=o.slice(0,-4)),o.length>1||!Bg(o)}function jg(e){return e!==""&&e.split(",").every(Gg)}function Gg(e){if(e.startsWith("-"))return zr(e.slice(1));let t=0;for(;t<e.length&&kd(e[t]);)t++;if(t===0)return!1;if(t===e.length)return!0;let n=e[t],o=e.slice(t+1);return n==="-"&&(o===""||zr(o))||n==="+"&&zr(o)}function zr(e){if(e==="")return!1;for(let t of e)if(!kd(t))return!1;return!0}function kd(e){return e>="0"&&e<="9"}function Bg(e){let t=e.toLowerCase();return t.length===1&&t>="a"&&t<="z"}function Sd(e,t){return e===""?t:e+`
230
+ `+t}function Wg(e,t){return Math.max(0,ls+Buffer.byteLength(`
231
+ `+t)-1-Buffer.byteLength(e))}function Xg(e,t,n){if(t===""||t.includes(hd)||t.includes("/"))return!1;let o=Zr(te(n,W(n)??""),jt),r=pg(o,es(e)).split(hd);if(r.length!==4||r.includes("..")||r.includes("")||r[1]!==t||r[2]!==Ki)return!1;let s=Od(e);return s.isFile()&&s.size<=Yi&&Ll(o,e)}function Kg(e,t,n){let o=e.text??"";if(e.persistedPath===void 0)return{text:o};try{return Xg(e.persistedPath,t,n)?{text:fg(e.persistedPath,"utf8"),file:e.persistedPath}:(ze(n,"claude-code","persisted-output",new Error("persisted output path is outside this session's tool-results dir or too large; kept the head")),{text:o})}catch{return{text:o}}}async function Yg(e,t){try{return pu(await I(e),t)}catch{return""}}function Ld(e,t){let n=Pt(e.input.command)??Pt(e.input.file_path)??"",o=n.indexOf(`
232
+ `);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,Ms)+"#"+(e.callId??String(t.turn??0))}function qg(e,t,n){Je(e,t,"index",n)}function Vg(e,t,n,o){try{return Mn(t,n.src,o)}catch(r){if(!Ve(r))throw r;return qe(e,n),null}}function Pd(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function Jg(e,t,n){let o=await I(n);return w(o,qt+e.sessionId,ki),pn(t)&&Ad(o,e.sessionId),wd(o,e.sessionId),T}function wd(e,t){try{au(e,t)}catch{}}function zg(e,t){return Gn(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(T)}var Ud={stdout:"",exitCode:0};function $g(e){return Qe.includes(e)}function Kn(e){process.exitCode=e.exitCode,e.stdout!==""&&Vr(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
233
+ `)}function Md(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
234
+ `);try{return ze(r,e,n,o),Lt(e,t,o)}catch{return Ud}}async function Qg(e,t){let n=e.indexOf($t),o=n>=0?e[n+1]??"":"";if(!$g(o))return console.error("hooks: unknown "+$t+" "+JSON.stringify(o)+". Fix: pass "+$t+" with one of "+Qe.join(", ")+"."),Kn(Ud);let r;try{r=JSON.parse(await qr())}catch(s){return Kn(Md(o,void 0,"stdin",s,t))}try{return Kn(await Td(o,r,t))}catch(s){return Kn(Md(o,r,"load",s,t))}}Qg(process.argv.slice(2),process.env);export{Qg as main};