context-mode 2.0.1 → 2.1.0

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,37 +1,39 @@
1
1
  import{createRequire as __cmRequire}from"node:module";if(typeof process.getBuiltinModule!=="function")process.getBuiltinModule=(id)=>__cmRequire(import.meta.url)(id);
2
- var Oe=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode"];var te="context-mode",ot=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function k(e,t){if(t==="")return e;let n=e;for(let o of ot)n=n.split(o).join(t+o);return n}var K=16384;var Zo=2048;var er=640,ln="</context_mode_state>",un=1048576,tr=65536,nr=4096,or=96,rr=256,sr=48;function ir(e,t,n,o="",r=""){let s=r===""?[e]:[e,r];return o+"ctx_search({queries:["+s.map(i=>JSON.stringify(i)).join(",")+"], source:"+JSON.stringify(t)+"}) searches the whole output ("+n+" B)."}var cr=3,ne=4096;var dn=85,fn=340,xn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var ar=.7,lr=.7,ur=.3,pn=Object.freeze([1e3,881,780,696,625,565,515,473,438,408,383,361,344,329,316,306,297,289,283,278,273,270,267,264,262,260,258,257,256,255,254,253,253,252,252,252,251,251,251,251,251,251,251,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250]),dr='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var Qa=6e5;var ue=5e3,rt="-wal",st="-shm",fr=".tmp",xr=255,pr=11,_r=26;var U=5e3;var _n=0;var Er=16,Re=6;var gr="projects",mr="context.db";var En=".git",gn="worktree ",mn="gitdir: ",hr="commondir",Sr="HEAD",it="--workspace-folder",gp=Object.freeze(["shell","powershell","javascript","typescript","python"]);var br=80;var mp=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var hp=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),Ae="24.15.0",ct="~/.context-mode";var Or="CONTEXT_MODE_REQUIRE_SECURITY",Tr=".claude",at="agents",lt=".md",hn="plugins",Rr="installed_plugins.json",de=":",Ar="@";var Sp=Object.freeze(["local","project"]),bp=Object.freeze({local:0,project:1,user:2,managed:2}),Sn="---",Nr="tools",yr="disallowedTools",bn="mcp__",On="__",Cr="mcp_",Ir="_-.:",Qo=10;function Za(e){if(e===void 0||e.trim()==="")return Qo;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Qo}var Op=Za(process.env.CTX_MCP_HINT_EVERY);var H=32;var Tn="context-mode: ",kr=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),Dr=" sends its body into the conversation.",Lr="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",wr="Tool: ",Pr="state what you need",Mr="ctx_execute",Ur=Object.freeze(["ctx_index","ctx_search"]),Ne="Blocked by security policy: matches deny pattern ",ut="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",dt="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",Hr="hook-errors.log";var Fr=Object.freeze(["tool_name","toolName","tool"]),vr=Object.freeze(["hook_event_name","hookEventName","type"]),jr=Object.freeze(["tool_input","toolArgs","input","args"]),Gr=Object.freeze(["cwd","directory"]),Br=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),Wr="CM_HOOK_FAULT",Tp=Object.freeze(["decode","project","policy","store","encode"]),ye=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 Xr(e,t){return`${Tn}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var Rn=Object.freeze({read:"Read the file in parts with offset and limit, or process it with ctx_execute(language, code); only what you print comes back.",shell:"Run the command with ctx_execute(language, code) or ctx_batch instead; only the part that matches your intent comes back.",grep:"Search with ctx_execute(language, code), or index the files with ctx_index and query them with ctx_search.",fetch:"Index the URL with ctx_index and query it with ctx_search."});var Rp=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),Ap=Object.freeze(["status"]),Np=Object.freeze(["--version","-v"]),yp=Object.freeze(["cp","mv","rm"]),Cp=Object.freeze(["-v","--verbose"]),D=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),Kr="{prefix}",qr=", then ",Yr="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",Vr=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),zr=Object.freeze(["curl","wget"]),Jr=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),$r=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),Qr="-D",Zr=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),Ce="fetch(",es="'\"`",ts="http",ns=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),os=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),rs=Object.freeze(["head","tail"]),An=Object.freeze(["-n","-c","--lines","--bytes"]),ft="sed",ss=Object.freeze(["-n","--quiet","--silent"]),is="jq",xt=Object.freeze(["file_path","absolute_path","path"]),pt="ctx_",cs="Bash",as=Object.freeze(["Write","Edit"]),ls=Object.freeze(["file_path","path"]),Nn="Exit code ",Ie="resume-hint",yn="compact-state",Cn="pending-compact",_t="pending_compact:",In="1",kn=2048,Dn=5,us=340,Ln="compacted:",ds="recall_units_seen:",fs=64,xs="recall_seen:",wn="<context_mode_recall>",Pn="</context_mode_recall>",ps="recall",Mn="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",_s="subagent:",Es="run.mjs",gs="node",ms=`context-mode: This command sends its body into the conversation.
3
- Run the command on the line above with Bash instead. It runs the same command in the same folder, indexes the full output and prints only the part that matches your intent, with the same exit code.`,Et="--agent",hs=1e3;var Ip=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var kp=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."]),Dp=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),Lp=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 wp=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),Pp=Object.freeze(["ctx_index","ctx_search"]);var Mp=Object.freeze(["session","source","project"]);var gt="decision";var Un="AskUserQuestion",Ss="answers",mt="option",bs=" | ",el="https://github.com/mksglu/context-mode.git";var Up=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),Hp=Object.freeze({D1:"version",D2:"node",D3:"host config",D4:"old entries",D5:"hook round trip",D5b:"double-fire",D6:"MCP",D7:"project and worktree",D8:"context.db",D9:"index",D10:"enforcement mode",D11:"shell"});var Hn=256;var tl="ctx_doctor:report";var Fp=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(tl)}})`;var vp=Object.freeze(["--tags","--refs"]),nl="v*";var jp=`git ls-remote --tags --refs ${el} "${nl}"`;var Gp=`install Node ${Ae} or later`;var Bp=Object.freeze(["MCP entry","hook entries","hook timeout"]);var Os=Object.freeze({"claude-code":[".claude"],codex:[".codex"],gemini:[".gemini"],qwen:[".qwen"],"copilot-cli":[".copilot"],vscode:[".vscode"],kiro:[".kiro"],zcode:[".zcode"],pi:[".pi"],opencode:[".config","opencode"]});var Wp=Object.freeze(["upgrade","uninstall"]);var Xp=Object.freeze(["clone","--depth","1","--branch"]),Kp=Object.freeze(["rev-parse","HEAD"]);var qp=Object.freeze(["pi","opencode"]);var Yp=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),Vp=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var zp=Object.freeze(["shell","bash","sh"]),Jp=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var $p=Object.freeze(["doctor-env.ts","doctor-config.ts","doctor-hook.ts","doctor-db.ts","doctor-heal.ts","release-fetch.ts","verify-sums.ts","plugin-swap.ts","host-write.ts","v1-remove.ts","uninstall.ts"]);var Qp=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}),Zp=Object.freeze(["PreToolUse","PostToolUse"]);var e_=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var t_=Object.freeze(["features","hooks"]);var n_=Object.freeze(["",rt,st]);var o_=Object.freeze({"claude-code":"claude plugin marketplace update context-mode && claude plugin update context-mode@context-mode",codex:"rewrite config.toml's [mcp_servers.context-mode*] block to the v2 entry, then restart Codex",gemini:"gemini extensions install https://github.com/mksglu/context-mode --ref release --auto-update",qwen:"qwen extensions install https://github.com/mksglu/context-mode --ref release --auto-update"});var r_=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 s_=Object.freeze(["hooks","codex"]);var i_=Object.freeze([".mjs",".sh"]);var ht="CLAUDE_CONFIG_DIR";var ol=Object.freeze(["Code","User"]);var rl="mcp.json",c_=Object.freeze(["agents","default.json"]);var a_=Object.freeze(["steering","KIRO.md"]);var l_=Object.freeze(["opencode.jsonc","opencode.json"]);var u_=Object.freeze(["content","platform.json"]);var Ts="custom";var sl=Object.freeze(["/","\\"]),il="${/}",d_=Object.freeze([...sl,il]),Te=Object.freeze({hook:"old context-mode hook entry: command contains context-mode and an old script name or context-mode hook",cacheHealHook:"old context-mode cache-heal SessionStart hook entry",cacheHealFile:"old context-mode cache-heal script file",statusLine:"old context-mode statusLine (context-mode statusline): report only, never removed",mcpEntry:"old context-mode MCP entry mcpServers.context-mode",codexHook:"old context-mode Codex hook entry: context-mode hook codex or hooks/codex/*.mjs",codexToml:"old context-mode config.toml [mcp_servers.context-mode*] section",hookFile:"old context-mode hook file context-mode.json (runs context-mode hook)",vscodeMcp:"old context-mode MCP entry servers.context-mode in .vscode/mcp.json: report only, never removed",kiroHook:"old Kiro hook entry: command contains context-mode and an old script name or context-mode hook",kiroAgentFile:"old context-mode Kiro agent file agents/*.json with name context-mode",kiroSteering:"old context-mode Kiro steering doc .kiro/steering/KIRO.md: manual review, report only, never removed",piNpm:"old context-mode Pi package npm:context-mode",opencodePlugin:"old context-mode OpenCode plugin spec context-mode",zcodeHook:"old context-mode ZCode hook entry: command contains context-mode hook",dataDir:"old context-mode data dir <agent home>/context-mode/",dataDirShared:"old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",dataRoot:"old context-mode content under ~/.context-mode/",tmpFile:"old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep"}),f_=Object.freeze([Te.statusLine,Te.vscodeMcp,Te.dataDirShared,Te.tmpFile,Te.kiroSteering]);var x_=te+"_";var p_=Object.freeze(["opencode","plugin.js"]);var cl=Object.freeze(["features","mcp"]),al="omit_tools_from",ll=Object.freeze(["deferred"]),ul="default_tools_approval_mode",dl="approve",__=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",te],fields:{[al]:ll,[ul]:dl}},vscode:{file:[rl],key:["servers",te]},kiro:{file:[".kiro","settings","mcp.json"],key:["mcpServers",te]},zcode:{file:[".zcode","cli","config.json"],key:["mcp","servers",te],fields:{type:"stdio",enabled:!0,timeoutMs:Qa},also:[[cl,!0]]}});var E_=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),fl="Environment: ";var xl="Docs: ";var pl="Report file: ",_l="File it: ",El="Or open: ",gl=" --",g_=Object.freeze([fl,xl,pl,_l,gl.trim(),El]),ml="mksglu/context-mode",hl="agent-report.yml";var m_=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var h_=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"]),S_=Object.freeze(["node","git","sh"]),b_=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var O_=Object.freeze({"claude-code":["claude plugin marketplace add mksglu/context-mode#release","claude plugin install context-mode@context-mode"],codex:["codex plugin marketplace add mksglu/context-mode@release","codex plugin add context-mode@context-mode"],gemini:["gemini extensions install https://github.com/mksglu/context-mode --ref release"],qwen:["qwen extensions install https://github.com/mksglu/context-mode:context-mode --ref release"],opencode:["opencode plugin add context-mode@next"],pi:["pi install npm:context-mode@next"],"copilot-cli":["npm i -g context-mode@next","context-mode setup --agents copilot-cli"],vscode:["npm i -g context-mode@next","context-mode setup --agents vscode"],kiro:["npm i -g context-mode@next","context-mode setup --agents kiro"],zcode:["npm i -g context-mode@next","context-mode setup --agents zcode"]}),T_=`https://github.com/${ml}/issues/new?template=${hl}`;import{dirname as Fx,join as vx}from"node:path";var Fn="mcp__plugin_context-mode_context-mode__",Ns=Object.freeze(["Bash","PowerShell"]),Sl="PowerShell",bl="Bash",Ol=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],Rs="mcp__",As="__",Tl={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function Rl(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(Rs))return e;let n=e.slice(Rs.length),o=n.indexOf(As);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+As.length)}function Al(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return Cs(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}}return typeof e=="object"&&e!==null&&ys(e)?e.content:JSON.stringify(e)}function ys(e){let t=e;return t.mode==="content"&&typeof t.content=="string"}function Cs(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(`
5
- `),keep:n}}function Nl(e){let t=Al(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)&&ys(e)&&(o.shape=e),Array.isArray(e)&&(o.blocks=!0,Cs(e).keep&&(o.keep=!0)),typeof e=="object"&&e!==null){let r=e;typeof r.persistedOutputPath=="string"&&r.persistedOutputPath!==""&&typeof r.persistedOutputSize=="number"&&r.persistedOutputSize>o.bytes&&(o.persistedPath=r.persistedOutputPath)}return o}function oe(e,t,n,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(t+": hook payload is not a JSON object");let r=e,s=Ol.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:Rl(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=Nl(r.tool_response)),i}function yl(e,t){return e.tool?.canonicalName==="Bash"?{stdout:t,stderr:"",interrupted:!1}:e.result?.shape!==void 0?{...e.result.shape,content:t}:e.result?.blocks===!0?[{type:"text",text:t}]:t}function F(e,t,n){let o=r=>({stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e.event,...r}}),exitCode:0});switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return o({additionalContext:t.text});case"deny":return o({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
6
- `+t.reason});case"replace":return n&&e.event==="PostToolUse"?o({updatedToolOutput:yl(e,t.output)}):{stdout:"",exitCode:0}}}var Cl={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function Il(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 kl(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 Cl[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function Is(e){kl(e);let t=oe(e,"claude-code",Fn,Tl);if(t.tool!==void 0&&t.tool.name===Sl&&(t.tool.canonicalName=bl),t.cwd===""&&(t.cwd=process.env.CLAUDE_PROJECT_DIR||process.cwd()),t.event==="PostToolUse"&&t.tool!==void 0&&t.tool.callId===void 0){let n=typeof t.tool.input.command=="string"?t.tool.input.command:JSON.stringify(t.tool.input);t.tool.callId="h"+Il(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function ks(e,t,n){return F(e,t,!0)}var vn="mcp__context_mode__",Ll={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"};function Ds(e){return oe(e,"codex",vn,Ll)}function Ls(e,t,n){return F(e,t,!1)}var bt="mcp_context-mode_",ws={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},Ps={startup:"startup",resume:"resume",clear:"clear"},Pl=["SessionStart","UserPromptSubmit","PostToolUse"],Ml=["UserPromptSubmit","PreToolUse"],St={stdout:"",exitCode:0};function N(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var Ms={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function Ul(e,t){if(e.startsWith(bt))return e.slice(bt.length);if(Object.hasOwn(Ms,e))return Ms[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 Hl(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:JSON.stringify(e),r=t===void 0?void 0:N(t,"error");return{isError:r!=null,bytes:Buffer.byteLength(o),text:o}}function Us(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(ws,n)?ws[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(Ps,s)&&(r.source=Ps[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:Ul(c,N(t,"mcp_context")),input:typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{}}}return o==="PostToolUse"&&(r.result=Hl(N(t,"tool_response"))),r}function Hs(e,t,n){switch(t.kind){case"allow":return St;case"hint":return Pl.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:St;case"deny":return Ml.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
7
- `+t.reason}),exitCode:0}:St;case"replace":return e.event!=="PostToolUse"?St:{stdout:JSON.stringify({decision:"deny",reason:t.output}),exitCode:0}}}var jn="mcp__context-mode__",vl={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Fs={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},jl="PostToolUseFailure";function vs(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===jl,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=oe(n,"qwen",jn,vl);if(o.tool!==void 0&&Object.hasOwn(Fs,o.tool.name)&&(o.tool.canonicalName=Fs[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 js(e,t,n){return F(e,t,!1)}var Tt="context-mode-",Bl={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}},Gs={startup:"startup",resume:"resume",new:"startup"},Wl={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"}},Ws="success";function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Gn=Object.freeze(["bash","powershell"]),Bs=Object.fromEntries(Gn.map(e=>[e,"Bash"]));function Xl(e){return e.startsWith(Tt)?e.slice(Tt.length):Object.hasOwn(Bs,e)?Bs[e]:e}function Kl(e){if(Rt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Rt(t)?t:{}}catch{return{}}}var ql={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function Yl(e,t,n){let o=ql[t],r=Rt(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==Ws,bytes:Buffer.byteLength(s),text:s}}var Vl=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function zl(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:Vl.find(([t])=>Object.hasOwn(e,t))?.[1]}function Xs(e){if(!Rt(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=zl(e),n=typeof t=="string"?Bl[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Wl[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"&&Gs[e.source]!==void 0&&(s.source=Gs[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:Xl(i),input:Kl(e[o.args])};s.tool=c}return r==="PostToolUse"&&(s.result=Yl(e[o.result],n.casing,n.failure)),s}var Ot={stdout:"",exitCode:0};function Ks(e,t,n){switch(t.kind){case"allow":return Ot;case"hint":return e.event==="PostToolUse"?Ot:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?Ot:{stdout:JSON.stringify({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
8
- `+t.reason}),exitCode:0};case"replace":return e.event!=="PostToolUse"?Ot:{stdout:JSON.stringify({modifiedResult:{resultType:Ws,textResultForLlm:t.output}}),exitCode:0}}}var At="mcp_context-mode_",$s=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],qs="mcp_",Ys="_",$l="new",Bn=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),yt=Object.freeze(["read_file","view"]),Wn=Object.freeze(["fetch_webpage","web_fetch"]),Vs=Object.fromEntries([...Bn.map(e=>[e,"Bash"]),...yt.map(e=>[e,"Read"]),...Wn.map(e=>[e,"WebFetch"])]);function Qs(e){if(e.startsWith(At))return e.slice(At.length);if(Object.hasOwn(Vs,e))return Vs[e];if(!e.startsWith(qs))return e;let t=e.slice(qs.length),n=t.indexOf(Ys);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+Ys.length)}var ke=e=>typeof e=="number"&&Number.isFinite(e);function Zs(e,t,n){if(t==="Read"&&yt.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),ke(n.startLine)&&(o.offset=n.startLine),ke(n.startLine)&&ke(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&ke(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];ke(r)&&r>=n.view_range[0]&&(o.limit=r-n.view_range[0]+1)}return o}return t==="WebFetch"&&e==="fetch_webpage"&&Array.isArray(n.urls)&&typeof n.urls[0]=="string"?{...n,url:n.urls[0]}:n}function Ql(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 Zl={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},eu=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],zs={new:"startup",startup:"startup",resume:"resume"},tu="success";function Nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nu(e){if(Nt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Nt(t)?t:{}}catch{return{}}}function ou(e){let t=Nt(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==tu,bytes:Buffer.byteLength(n),text:n}}function Js(e,t){let n=typeof t=="string"?Zl[t]??$s.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"&&zs[e.source]!==void 0&&(o.source=zs[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=Qs(r);o.tool={name:r,canonicalName:s,input:Zs(r,s,nu(e.toolArgs))}}return n==="PostToolUse"&&(o.result=ou(e.toolResult)),o}function ei(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 Js(t,t.hookEventName);if(t.hook_event_name===void 0){let r=eu.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return Js(t,r)}let n=$s.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===$l&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=Nt(t.tool_input)?t.tool_input:{},i=Qs(r);o.tool={name:r,canonicalName:i,input:Zs(r,i,s)}}return n==="PostToolUse"&&(o.result=Ql(t.tool_response)),o}function ti(e,t,n){return F(e,t,!1)}var Ct="mcp_context-mode_",ni={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},su="USER_PROMPT",oi="mcp_",Xn=Object.freeze(["execute_bash","execute_pwsh","shell"]),ri=Object.fromEntries(Xn.map(e=>[e,"Bash"])),si="_",ii={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function iu(e){if(e.startsWith(Ct))return e.slice(Ct.length);if(Object.hasOwn(ri,e))return ri[e];if(!e.startsWith(oi))return e;let t=e.slice(oi.length),n=t.indexOf(si);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+si.length)}function cu(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function ci(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(ni,n)?ni[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"&&ii[t.source]!==void 0&&(r.source=ii[t.source]),o==="UserPromptSubmit"){let s=process.env[su];s!==void 0&&(r.prompt=s)}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:iu(s),input:i}}return o==="PostToolUse"&&(r.result=cu(t.tool_response)),r}function ai(e,t,n){if(e.event==="UserPromptSubmit")return{stdout:"",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+`
9
- `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var Kn="mcp__context-mode__",lu={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},uu={hook_event_name:"hookEventName",session_id:"sessionId"},du="PostToolUseFailure";function li(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("zcode: hook payload is not a JSON object");let t={...e};for(let[r,s]of Object.entries(uu))t[r]===void 0&&(t[r]=t[s]);let n=t.hook_event_name===du;n&&(t.hook_event_name="PostToolUse");let o=oe(t,"zcode",Kn,lu);if(n){let r=typeof t.error=="string"?t.error:t.error===void 0?"":JSON.stringify(t.error);o.result={isError:!0,bytes:Buffer.byteLength(r),text:r}}return o}function ui(e,t,n){return F(e,t,!1)}var xi="",di={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},fi={bash:"Bash",read:"Read"};function xu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function pu(e){let t=e.content===void 0?"":typeof e.content=="string"?e.content:JSON.stringify(e.content),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function pi(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(di,n)?di[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(fi,s)?fi[s]:s,input:xu(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=pu(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function _u(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+`
10
- `+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function _i(e,t,n){let o=_u(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:Ts,content:o.stdout,timestamp:Date.now()}}function Ei(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var Si="",gi=te+"_",mi={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},qn="bash",gu=Object.freeze([qn,"shell"]),hi={webfetch:"WebFetch",...Object.fromEntries(gu.map(e=>[e,"Bash"]))};function Yn(e){return e.startsWith(gi)?e.slice(gi.length):Object.prototype.hasOwnProperty.call(hi,e)?hi[e]:e}function mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function hu(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 bi(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(mi,n)?mi[n]:void 0;if(o===void 0)throw new Error("opencode: unknown hook event "+String(t.type));let r={event:o,agent:"opencode",sessionId:String(t.sessionID??""),cwd:String(t.directory??"")};if(o==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool??"");r.tool={name:s,canonicalName:Yn(s),input:mu(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=hu(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Oi(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+`
11
- `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var De={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},Ti={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},bu={...Ti,shell:[...Ns]},Ou=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:Fn,nativeTools:bu,execReadOnlyHint:!1,eventMap:De,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"claude-code/skills"},decode:Is,encode:ks},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:vn,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:De,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:Ds,encode:Ls},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:bt,nativeTools:{shell:["run_shell_command"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:{UserPromptSubmit:"BeforeAgent",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",PreCompact:"PreCompress"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:Us,encode:Hs},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:jn,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:De,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:vs,encode:js},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:Tt,nativeTools:{shell:[...Gn]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:Xs,encode:Ks},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:At,nativeTools:{shell:[...Bn],read:[...yt],webfetch:[...Wn]},execReadOnlyHint:!1,eventMap:{...De,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:ei,encode:ti},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:Ct,nativeTools:{shell:[...Xn]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:U,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:ci,encode:ai},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:Kn,nativeTools:Ti,execReadOnlyHint:!1,eventMap:De,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:li,encode:ui},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:xi,nativeTools:{shell:["bash"],read:["read"]},execReadOnlyHint:!1,eventMap:{SessionStart:"session_start",UserPromptSubmit:"input",PreToolUse:"tool_call",PostToolUse:"tool_result"},compactDelivery:"pi-flag",compactSummary:"none",hookTimeoutMs:_n,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:pi,encode:_i,checkPermission:Ei},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:Si,nativeTools:{shell:[qn]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:_n,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:bi,encode:Oi,toCanonicalTool:Yn}]),Tu=new Map(Ou.map(e=>[e.id,e])),Ru=new Set(["claude-code","gemini","copilot-cli","pi"]);function Le(e){return Ru.has(e.id)}var Au=new Set(["claude-code","copilot-cli","pi"]);function Vn(e){return Au.has(e.id)&&Le(e)}var Nu=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode"]);function It(e){return Nu.has(e.id)}function re(e){return Tu.get(e)}import{resolve as qt}from"node:path";var yu=["&&","||",";;","|&",";","|","&","(",")"],Cu=["&>>","&>"],Iu=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],ku="&",Du="<<",Ri="<<-",Lu=";",Ai=`\r
12
- `,Ni=`\\
13
- `,yi=`\\\r
14
- `,wu="$(",ki="${",Di="$'",we="((",Ci="))",fe="[[",kt="]]",zn="<(",Li=">(",L=2,wi=`
15
- \r;&|()<>`,Pu=`
16
- \r`,Mu='$`"\\\n',Uu="case",Hu="esac";function xe(e,t){e.end==="complete"&&(e.end=t)}function Jn(e){return e!==""&&e>="0"&&e<="9"}function Ii(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function Pi(e){return e===""||wi.includes(e)}function $n(e){return e!==""&&Pu.includes(e)}function v(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function Dt(e,t){let n=e.s.indexOf("'",t+1);return n<0?(xe(e,"unterminated-quote"),e.n):n+1}function Mi(e,t){let n=t+Di.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=L;continue}if(o==="'")return n+1;n++}return xe(e,"unterminated-quote"),e.n}function Qn(e,t,n){let o=t+1;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(r==="\\"){o+=L;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=Pe(e,o,n);continue}if(r==="$"&&s==="{"){o=Zn(e,o,n);continue}if(r==="`"){o=pe(e,o);continue}o++}return xe(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+=L;continue}if(o==="`")return n+1;n++}return e.n}function Zn(e,t,n){let o=t+ki.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=L;continue}if(s==="'"){o=Dt(e,o);continue}if(s==='"'){o=Qn(e,o,n);continue}if(s==="$"&&i==="("){o=Pe(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 eo(e,t){let n=0,o=t+we.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(Ci,o)?o+Ci.length:-1;n--}o++}return-1}function Pe(e,t,n){let o=t+wu.length-1;if(e.s.startsWith(we,o)){let r=eo(e.s,o);if(r>0)return r}return Lt(e,o+1,!0,n+1,null,null)}function Fu(e,t,n){let o=t+fe.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=L;continue}if(s==="'"){o=Dt(e,o);continue}if(s==='"'){o=Qn(e,o,n);continue}if(s==="$"&&i==="("){o=Pe(e,o,n);continue}if(s==="$"&&i==="{"){o=Zn(e,o,n);continue}if(s==="`"){o=pe(e,o);continue}let c=$n(e.s.charAt(o-1));if(c&&e.s.startsWith(kt,o)&&Pi(e.s.charAt(o+kt.length))){if(r===0)return o+kt.length;r--,o+=kt.length;continue}if(c&&e.s.startsWith(fe,o)&&$n(e.s.charAt(o+fe.length))){r++,o+=fe.length;continue}o++}return-1}function vu(e,t){let n=t;for(;Jn(e.charAt(n));)n++;if(n===t){for(let o of Cu)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of Iu){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(ku))if(e.charAt(r)==="-")r++;else for(;Jn(e.charAt(r));)r++;return{end:r,op:o}}return null}function ju(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(wi.includes(r))break;if(r==="\\"){o+=L;continue}if(r==="'"){o=Dt(e,o);continue}if(r==='"'){o=Qn(e,o,n);continue}if(r==="$"&&s==="'"){o=Mi(e,o);continue}if(r==="$"&&s==="("){o=Pe(e,o,n);continue}if(r==="$"&&s==="{"){o=Zn(e,o,n);continue}if(r==="`"){o=pe(e,o);continue}o++}return Math.min(o,e.n)}function Gu(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(`
17
- `,s),u=l<0?e.n:l,d=e.s.slice(s,u);if(d.endsWith("\r")&&(d=d.slice(0,-1)),s=l<0?e.n:l+1,(i.strip?d.trim():d)===i.tag){a=!0;break}}if(o!==null&&r!==null&&r.push(o.length),v(o,"unhandled",e.s.slice(c,s),c,s),!a)return xe(e,"unterminated-heredoc"),e.n}return n.length=0,s}function Lt(e,t,n,o,r,s){if(o>H)return xe(e,"too-deep"),e.n;let i=e.s,c=t,a=0,l=0,u=null,d=[];for(;c<e.n;){let f=i.charAt(c),x=i.charAt(c+1);if(f===" "||f===" "){c++;continue}if(i.startsWith(Ni,c)){c+=Ni.length;continue}if(i.startsWith(yi,c)){c+=yi.length;continue}if(f===`
18
- `||f==="\r"){let S=c;c+=i.startsWith(Ai,c)?Ai.length:1,v(r,"op",Lu,S,c),u=null,d.length>0&&(c=Gu(e,c,d,r,s));continue}if(f==="#"){for(;c<e.n&&i.charAt(c)!==`
19
- `&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(zn,c)||i.startsWith(Li,c)){let S=Lt(e,c+zn.length,!0,o+1,null,null);v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}let p=vu(i,c);if(p!==null){v(r,"io",i.slice(c,p.end),c,p.end),u=p.op===Du||p.op===Ri?p.op===Ri:null,c=p.end;continue}if(i.startsWith(fe,c)&&$n(i.charAt(c+fe.length))){let S=Fu(e,c,o);if(S>0){v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}if(i.startsWith(we,c)){let S=eo(i,c);if(S>0){v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let g=yu.find(S=>i.startsWith(S,c));if(g!==void 0){if(n&&g==="("&&a++,n&&g===")"){if(a>0)a--;else if(l===0)return c+1}v(r,"op",g,c,c+g.length),c+=g.length,u=null;continue}if(f==="$"&&x==="("||f==="`"){let S=f==="`"?pe(e,c):Pe(e,c,o);if(Pi(i.charAt(S))){v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let E=c;c=ju(e,c,o);let h=i.slice(E,c);v(r,"word",h,E,c),u!==null&&(d.push({tag:_e(h),strip:u}),u=null),n&&h===Uu&&l++,n&&h===Hu&&l>0&&l--}return d.length>0&&xe(e,"unterminated-heredoc"),e.n}function Ui(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return Lt(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function _e(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=L;continue}if(r==="'"){let s=e.indexOf("'",n+1),i=s<0?o:s;t+=e.slice(n+1,i),n=i+1;continue}if(r==="$"&&e.charAt(n+1)==="'"){let s=n+Di.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=L;continue}t+=e.charAt(s),s++}n=s+1;continue}if(r==='"'){let s=n+1;for(;s<o&&e.charAt(s)!=='"';){let i=e.charAt(s+1);if(e.charAt(s)==="\\"&&i!==""&&Mu.includes(i)){t+=i,s+=L;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function wt(e){let t={s:e,n:e.length,end:"complete"},n=[],o=!1,r=0;for(;r<t.n;){let s=e.charAt(r),i=e.charAt(r+1);if(s==="\\"){r+=L;continue}if(!o&&s==="'"){r=Dt(t,r);continue}if(!o&&s==="$"&&i==="'"){r=Mi(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=ki.length;continue}let c=e.startsWith(zn,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(Li,r))){let a=r+1;if(s==="$"&&e.startsWith(we,a)&&eo(e,a)>0){r=a+we.length;continue}let l=Lt(t,a+1,!0,1,null,null),u=l>a+1&&e.charAt(l-1)===")"?l-1:l;n.push({wrapper:s==="$"?"$()":c?"<()":">()",body:e.slice(a+1,u)}),r=l;continue}if(s==="`"){let a=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 Pt(e){let t=e.charAt(0);if(!(Ii(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(!(Ii(o)||Jn(o)||o==="_"))return!1}return!1}var ji=[";","&","&&","||"],Gi=["|","|&"],Me="(",Ue=")",Bi=";;",oo=["(",")"],Bu="!",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"}),Wi=[],Wu="[[",Xu="((",Xi=[">",">>",">|","&>","&>>",">&"],Ku=[...Xi,"<","<>","<<<","<<","<<-"],qu=["","1"],Ki=["-","/dev/stdout","/dev/stderr"],Ut="-",He="--",Fe="=",Yu="/",Vu=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),Mt=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),to="-c",no="--bytes",zu="c",Ju="--count",se=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],q=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,C=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,ro=e=>e!==""&&e>="0"&&e<="9",$u=e=>ro(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function so(e){let t=e.lastIndexOf(Yu);return t>=0&&t<e.length-1?e.slice(t+1):e}function io(e,t){let n=Vu[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===He)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+Fe))s=r.slice(n.long.length+Fe.length);else if(r.startsWith(Ut)&&!r.startsWith(He)){let i=r.indexOf(n.short,Ut.length);if(i<0)continue;s=i+n.short.length<r.length?r.slice(i+n.short.length):t[o+1]}else continue;if(s!==void 0&&!Ki.includes(s))return!0}return!1}function Qu(e){if(e==="")return!1;for(let t of e)if(!ro(t))return!1;return!0}function Zu(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===to||n===no?o=e[t+1]:n.startsWith(no+Fe)?o=n.slice(no.length+Fe.length):n.startsWith(to)&&!n.startsWith(He)&&(o=n.slice(to.length)),o!==void 0)return Qu(o)&&Number(o)<=K}return!1}function ed(e){for(let t of e){if(t===He)return!1;if(t===Ju||t.startsWith(Ut)&&!t.startsWith(He)&&t.includes(zu))return!0}return!1}function Hi(e){if(!e.startsWith(D.fieldSep))return!1;for(let t of e.slice(D.fieldSep.length).split(D.fieldSep)){if(t==="")return!1;for(let n of t)if(!$u(n))return!1}return!0}function td(e){let t=e.trim();if(t===D.identity||t===D.length)return!0;let n=t.indexOf(D.pipeLength.charAt(0));if(n<0)return Hi(t);let o=t.slice(0,n).trim(),r=D.pipeLength.slice(1).trim();return(o===D.identity||Hi(o))&&t.slice(n+1).trim()===r}function nd(e){let t=e.argv0.toLowerCase();if(t===Mt.wc)return!0;if(t===Mt.head)return Zu(e.args);if(t===Mt.grep)return ed(e.args);if(t===Mt.jq){let n=e.args.filter(o=>!o.startsWith(Ut));return n.length===1&&td(n[0])}return!1}function co(e){return wt(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function qi(e,t,n){return n<=t?[]:co(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function Yi(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function od(e){let t=0;for(;ro(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Vi(e){let t=od(e.toks[e.i].text);if(e.i++,!Ku.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,Xi.includes(t.op)&&qu.includes(t.fd)&&!Ki.includes(_e(n.text)))}function zi(e){let t=!1;for(;O(e)?.kind==="io";)t=Vi(e)||t;return t}function Ji(e){for(;O(e)?.kind==="op"&&ji.includes(O(e)?.text??"");)e.i++}function Ee(e,t){if(e.depth++,e.depth>H)return e.err="nesting-too-deep",se();let n=t();if(e.depth--,zi(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function $i(e){if(Ji(e),!C(O(e),b.do))return[];e.i++;let t=j(e,[b.done]);return C(O(e),b.done)&&e.i++,t}function rd(e){e.i++;let t=j(e,[b.then]);for(;e.err===null;){let n=O(e);if(C(n,b.then)||C(n,b.else)){e.i++,t.push(...j(e,[b.elif,b.else,b.fi]));continue}if(C(n,b.elif)){e.i++,t.push(...j(e,[b.then]));continue}C(n,b.fi)&&e.i++;break}return t}function sd(e){e.i++;let t=j(e,[b.do]);return t.push(...$i(e)),t}function id(e){e.i++;let t=[],n=O(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,C(O(e),b.in)){e.i++;let o=e.i;for(;(O(e)?.kind==="word"||O(e)?.kind==="unhandled")&&!C(O(e),b.do);)e.i++;t.push(...qi(e,o,e.i))}return t.push(...$i(e)),t}function cd(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,t.push(...qi(e,e.i-1,e.i))),C(O(e),b.in)&&e.i++;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)||o.kind==="op"&&(ji.includes(o.text)||o.text===Bi)){e.i++;continue}if(C(o,b.esac)){e.i++;break}for(q(o,Me)&&e.i++;e.i<e.toks.length&&!q(O(e),Ue);){let s=e.toks[e.i];if(s.kind==="op"&&!Gi.includes(s.text))break;e.i++}if(!q(O(e),Ue))break;e.i++;let r=j(e,[b.esac]);Yi(r,b.case),t.push(...r)}return t}function Fi(e,t){Ji(e);let n=Qi(e);return Yi(n.cmds,t),{cmds:n.cmds,simple:null}}function vi(e,t){return oo.every((n,o)=>q(e.toks[t+o],n))}function ad(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=Vi(e)||o;continue}if(n.length===0&&l.kind==="word"&&Pt(l.text)){e.i++;let u=O(e);if(l.text.endsWith(Fe)&&u!==void 0&&q(u,Me)&&u.start===l.end){let d=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,q(f,Me)&&d++,q(f,Ue)&&--d===0)break}}continue}n.push(l),e.i++}if(e.i===t)return se();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:co(r),simple:null};let s=l=>l.kind==="word"?_e(l.text):l.text,i=so(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||io(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function Qi(e){let t=O(e);if(t===void 0)return se();if(t.kind==="op")return t.text!==Me?se():Ee(e,()=>{e.i++;let n=j(e,Wi);return q(O(e),Ue)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(Wu)||t.text.startsWith(Xu)))return e.i++,zi(e),{cmds:co(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return Ee(e,()=>{e.i++;let n=j(e,[b.groupEnd]);return C(O(e),b.groupEnd)&&e.i++,n});case b.if:return Ee(e,()=>rd(e));case b.while:case b.until:return Ee(e,()=>sd(e));case b.for:return Ee(e,()=>id(e));case b.case:return Ee(e,()=>cd(e));case b.coproc:return e.err="coproc",se();case b.select:return e.err="select",se();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=_e(n.text),e.i++),vi(e,e.i)&&(e.i+=oo.length),Fi(e,o)}default:if(vi(e,e.i+1))return e.i+=oo.length+1,Fi(e,_e(t.text))}return ad(e)}function ld(e){C(O(e),Bu)&&e.i++;let t=[],n=se();for(;e.err===null;){n=Qi(e),t.push(...n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&Gi.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&nd(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function j(e,t){let n=[];for(;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)){e.i++;continue}if(o.kind==="op"){if(o.text===Ue||o.text===Bi)return n;if(o.text!==Me){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;n.push(...ld(e)),e.i===r&&e.err===null&&e.i++}return n}function ve(e){let t=Ui(e);if(t.end==="unterminated-quote")return{ok:!1,construct:"unterminated-quote"};if(t.end==="unterminated-heredoc")return{ok:!1,construct:"unterminated-heredoc"};if(t.end==="too-deep")return{ok:!1,construct:"nesting-too-deep"};let n={toks:t.tokens,src:e,bodies:new Set(t.heredocBodies),i:0,depth:0,err:null},o=[];for(;n.i<n.toks.length&&n.err===null;)o.push(...j(n,Wi)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as Zi}from"node:path";var Ft="'",ge='"',vt="`",ud=" \r",Ge="([{",fo=")]}",ao=` \r
20
- |;>`,nc="*",ec="1",lo="::",Ht=lo.length,dd=Ht;function jt(e,t){let n=e.charAt(t);for(let o=t+1;o<e.length;o++){let r=e.charAt(o);if(n===ge&&r===vt){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function fd(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===ge&&r===vt&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function je(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Ft||r===ge){let s=jt(e,o);if(s<0)return-1;o=s;continue}if(r===vt){o++;continue}if(Ge.includes(r))n++;else if(fo.includes(r)&&--n===0)return o}return-1}function xd(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Ft||r===ge){let s=jt(e,o);if(s<0)return e.length;o=s;continue}if(Ge.includes(r))n++;else if(fo.includes(r))n--;else if(n<=0&&ao.includes(r))return o}return e.length}function pd(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===Ft||s===ge){let i=jt(e,r);if(i<0)break;r=i;continue}Ge.includes(s)?n++:fo.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var _d=e=>e!==""&&(e===nc||[...e].every(t=>t>="0"&&t<="9")),tc=()=>({words:[],toFile:!1,chained:!1});function oc(e){let t=[],n=[],o=tc(),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=tc()},d=()=>{u(),n.length>0&&t.push(n),n=[]},f=(p,g)=>{r+=p,s=!0,g&&(i=!1)},x=0;for(;x<a;){let p=e.charAt(x),g=e.charAt(x+1);if(p===Ft||p===ge){let E=jt(e,x);f(fd(e.slice(x+1,E<0?a:E),p),!0),x=E<0?a:E+1}else if(p===vt)g!==`
2
+ var Oe=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode"];var K="context-mode",ot=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function k(e,t){if(t==="")return e;let n=e;for(let o of ot)n=n.split(o).join(t+o);return n}var q=16384;var er=2048;var tr=640,ln="</context_mode_state>",un=1048576,nr=65536,or=4096,rr=96,sr=256,ir=48;function cr(e,t,n,o="",r=""){let s=r===""?[e]:[e,r];return o+"ctx_search({queries:["+s.map(i=>JSON.stringify(i)).join(",")+"], source:"+JSON.stringify(t)+"}) searches the whole output ("+n+" B)."}var ar=3,ne=4096;var dn=85,fn=340,xn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var lr=.7,ur=.7,dr=.3,pn=Object.freeze([1e3,881,780,696,625,565,515,473,438,408,383,361,344,329,316,306,297,289,283,278,273,270,267,264,262,260,258,257,256,255,254,253,253,252,252,252,251,251,251,251,251,251,251,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250]),fr='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var el=6e5;var ue=5e3,rt="-wal",st="-shm",xr=".tmp",pr=255,_r=11,Er=26;var U=5e3;var _n=0;var gr=16,Re=6;var mr="projects",hr="context.db";var En=".git",gn="worktree ",mn="gitdir: ",Sr="commondir",br="HEAD",it="--workspace-folder",Op=Object.freeze(["shell","powershell","javascript","typescript","python"]);var Or=80;var Tp=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var Rp=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),Ae="24.15.0",ct="~/.context-mode";var Tr="CONTEXT_MODE_REQUIRE_SECURITY",Rr=".claude",at="agents",lt=".md",hn="plugins",Ar="installed_plugins.json",de=":",Nr="@";var Ap=Object.freeze(["local","project"]),Np=Object.freeze({local:0,project:1,user:2,managed:2}),Sn="---",yr="tools",Cr="disallowedTools",bn="mcp__",On="__",Ir="mcp_",kr="_-.:",Zo=10;function tl(e){if(e===void 0||e.trim()==="")return Zo;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Zo}var yp=tl(process.env.CTX_MCP_HINT_EVERY);var H=32;var Tn="context-mode: ",Dr=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),Lr=" sends its body into the conversation.",wr="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",Pr="Tool: ",Mr="state what you need",Ur="ctx_execute",Hr=Object.freeze(["ctx_index","ctx_search"]),Ne="Blocked by security policy: matches deny pattern ",ut="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",dt="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",Fr="hook-errors.log";var vr=Object.freeze(["tool_name","toolName","tool"]),jr=Object.freeze(["hook_event_name","hookEventName","type"]),Gr=Object.freeze(["tool_input","toolArgs","input","args"]),Br=Object.freeze(["cwd","directory"]),Wr=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),Xr="CM_HOOK_FAULT",Cp=Object.freeze(["decode","project","policy","store","encode"]),ye=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 Kr(e,t){return`${Tn}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var Rn=Object.freeze({read:"Read the file in parts with offset and limit, or process it with ctx_execute(language, code); only what you print comes back.",shell:"Run the command with ctx_execute(language, code) or ctx_batch instead; only the part that matches your intent comes back.",grep:"Search with ctx_execute(language, code), or index the files with ctx_index and query them with ctx_search.",fetch:"Index the URL with ctx_index and query it with ctx_search."});var Ip=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),kp=Object.freeze(["status"]),Dp=Object.freeze(["--version","-v"]),Lp=Object.freeze(["cp","mv","rm"]),wp=Object.freeze(["-v","--verbose"]),D=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),qr="{prefix}",Yr=", then ",Vr="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",zr=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),Jr=Object.freeze(["curl","wget"]),$r=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),Qr=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),Zr="-D",es=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),Ce="fetch(",ts="'\"`",ns="http",os=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),rs=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),ss=Object.freeze(["head","tail"]),An=Object.freeze(["-n","-c","--lines","--bytes"]),ft="sed",is=Object.freeze(["-n","--quiet","--silent"]),cs="jq",xt=Object.freeze(["file_path","absolute_path","path"]),pt="ctx_",as="Bash",ls=Object.freeze(["Write","Edit"]),us=Object.freeze(["file_path","path"]),Nn="Exit code ",Ie="resume-hint",yn="compact-state",Cn="pending-compact",_t="pending_compact:",In="1",kn=2048,Dn=5,ds=340,Ln="compacted:",fs="recall_units_seen:",xs=64,ps="recall_seen:",wn="<context_mode_recall>",Pn="</context_mode_recall>",_s="recall",Mn="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",Es="subagent:",gs="run.mjs",ms="node",hs=`context-mode: This command sends its body into the conversation.
3
+ Run the command on the line above with Bash instead. It runs the same command in the same folder, indexes the full output and prints only the part that matches your intent, with the same exit code.`,Et="--agent",Ss=1e3;var Pp=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var Mp=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."]),Up=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),Hp=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 Fp=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),vp=Object.freeze(["ctx_index","ctx_search"]);var jp=Object.freeze(["session","source","project"]);var gt="decision";var Un="AskUserQuestion",bs="answers",mt="option",Os=" | ",nl="https://github.com/mksglu/context-mode.git";var Gp=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),Bp=Object.freeze({D1:"version",D2:"node",D3:"host config",D4:"old entries",D5:"hook round trip",D5b:"double-fire",D6:"MCP",D7:"project and worktree",D8:"context.db",D9:"index",D10:"enforcement mode",D11:"shell"});var Hn=256;var ol="ctx_doctor:report";var Wp=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(ol)}})`;var Xp=Object.freeze(["--tags","--refs"]),rl="v*";var Kp=`git ls-remote --tags --refs ${nl} "${rl}"`;var qp=`install Node ${Ae} or later`;var Yp=Object.freeze(["MCP entry","hook entries","hook timeout"]);var Ts=Object.freeze({"claude-code":[".claude"],codex:[".codex"],gemini:[".gemini"],qwen:[".qwen"],"copilot-cli":[".copilot"],vscode:[".vscode"],kiro:[".kiro"],zcode:[".zcode"],pi:[".pi"],opencode:[".config","opencode"]});var Vp=Object.freeze(["upgrade","uninstall"]);var zp=Object.freeze(["clone","--depth","1","--branch"]),Jp=Object.freeze(["rev-parse","HEAD"]);var $p=Object.freeze(["pi","opencode"]);var Qp=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),Zp=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var e_=Object.freeze(["shell","bash","sh"]),t_=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var n_=Object.freeze(["doctor-env.ts","doctor-config.ts","doctor-hook.ts","doctor-db.ts","doctor-heal.ts","release-fetch.ts","verify-sums.ts","plugin-swap.ts","host-write.ts","v1-remove.ts","uninstall.ts"]);var o_=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}),r_=Object.freeze(["PreToolUse","PostToolUse"]);var s_=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var i_=Object.freeze(["features","hooks"]);var c_=Object.freeze(["",rt,st]);var a_=Object.freeze({"claude-code":"claude plugin marketplace update context-mode && claude plugin update context-mode@context-mode",codex:"rewrite config.toml's [mcp_servers.context-mode*] block to the v2 entry, then restart Codex",gemini:"gemini extensions install https://github.com/mksglu/context-mode --auto-update",qwen:"qwen extensions install https://github.com/mksglu/context-mode --auto-update"});var l_=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 u_=Object.freeze(["hooks","codex"]);var d_=Object.freeze([".mjs",".sh"]);var ht="CLAUDE_CONFIG_DIR";var sl=Object.freeze(["Code","User"]);var il="mcp.json",f_=Object.freeze(["agents","default.json"]);var x_=Object.freeze(["steering","KIRO.md"]);var p_=Object.freeze(["opencode.jsonc","opencode.json"]);var __=`${K}@`;var E_=Object.freeze(["content","platform.json"]);var Rs="custom";var cl=Object.freeze(["/","\\"]),al="${/}",g_=Object.freeze([...cl,al]),Te=Object.freeze({hook:"old context-mode hook entry: command contains context-mode and an old script name or context-mode hook",cacheHealHook:"old context-mode cache-heal SessionStart hook entry",cacheHealFile:"old context-mode cache-heal script file",statusLine:"old context-mode statusLine (context-mode statusline): report only, never removed",mcpEntry:"old context-mode MCP entry mcpServers.context-mode",codexHook:"old context-mode Codex hook entry: context-mode hook codex or hooks/codex/*.mjs",codexToml:"old context-mode config.toml [mcp_servers.context-mode*] section",hookFile:"old context-mode hook file context-mode.json (runs context-mode hook)",vscodeMcp:"old context-mode MCP entry servers.context-mode in .vscode/mcp.json: report only, never removed",kiroHook:"old Kiro hook entry: command contains context-mode and an old script name or context-mode hook",kiroAgentFile:"old context-mode Kiro agent file agents/*.json with name context-mode",kiroSteering:"old context-mode Kiro steering doc .kiro/steering/KIRO.md: manual review, report only, never removed",piNpm:"old context-mode Pi package npm:context-mode",opencodePlugin:"old context-mode OpenCode plugin spec context-mode",zcodeHook:"old context-mode ZCode hook entry: command contains context-mode hook",dataDir:"old context-mode data dir <agent home>/context-mode/",dataDirShared:"old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",dataRoot:"old context-mode content under ~/.context-mode/",tmpFile:"old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep"}),m_=Object.freeze([Te.statusLine,Te.vscodeMcp,Te.dataDirShared,Te.tmpFile,Te.kiroSteering]);var h_=K+"_";var S_=Object.freeze(["opencode","plugin.js"]);var ll=Object.freeze(["features","mcp"]),ul="omit_tools_from",dl=Object.freeze(["deferred"]),fl="default_tools_approval_mode",xl="approve",b_=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",K],fields:{[ul]:dl,[fl]:xl}},vscode:{file:[il],key:["servers",K]},kiro:{file:[".kiro","settings","mcp.json"],key:["mcpServers",K]},zcode:{file:[".zcode","cli","config.json"],key:["mcp","servers",K],fields:{type:"stdio",enabled:!0,timeoutMs:el},also:[[ll,!0]]}});var O_=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),pl="Environment: ";var _l="Docs: ";var El="Report file: ",gl="File it: ",ml="Or open: ",hl="Rules: ",Sl=" --",T_=Object.freeze([pl,_l,El,gl,Sl.trim(),ml,hl]),As="mksglu/context-mode",bl="agent-report.yml",R_=`https://github.com/${As}/blob/main/.github/AGENT_ISSUE.md`,A_=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 N_=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var y_=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"]),C_=Object.freeze(["node","git","sh"]),I_=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var k_=Object.freeze({"claude-code":["claude plugin marketplace add mksglu/context-mode","claude plugin install context-mode@context-mode"],codex:["codex plugin marketplace add mksglu/context-mode","codex plugin add context-mode@context-mode"],gemini:["gemini extensions install https://github.com/mksglu/context-mode"],qwen:["qwen extensions install https://github.com/mksglu/context-mode:context-mode"],opencode:["opencode plugin add context-mode"],pi:["pi install npm:context-mode"],"copilot-cli":["npm i -g context-mode","context-mode setup --agents copilot-cli"],vscode:["npm i -g context-mode","context-mode setup --agents vscode"],kiro:["npm i -g context-mode","context-mode setup --agents kiro"],zcode:["npm i -g context-mode","context-mode setup --agents zcode"]}),D_=`https://github.com/${As}/issues/new?template=${bl}`;import{dirname as Wx,join as Xx}from"node:path";var Fn="mcp__plugin_context-mode_context-mode__",Cs=Object.freeze(["Bash","PowerShell"]),Ol="PowerShell",Tl="Bash",Rl=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],Ns="mcp__",ys="__",Al={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function Nl(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(Ns))return e;let n=e.slice(Ns.length),o=n.indexOf(ys);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+ys.length)}function yl(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return Is(e).text;if(typeof e=="object"&&e!==null){let t=e;if(typeof t.stdout=="string"||typeof t.stderr=="string"){let n=typeof t.stdout=="string"?t.stdout:"",o=typeof t.stderr=="string"?t.stderr:"";return o===""?n:n===""?o:n+`
4
+ `+o}}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=vn(e);if(t!==null)return t.text}return JSON.stringify(e)}function vn(e){let t=e.file;return e.type==="text"&&typeof t=="object"&&t!==null&&typeof t.content=="string"?{text:t.content,put:(n,o)=>({...n,file:{...n.file,content:o}})}:Il(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
+ `),put:(n,o)=>({...n,filenames:o.split(`
6
+ `)})}:typeof e.result=="string"?{text:e.result,put:(n,o)=>({...n,result:o})}:null}function Cl(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function Il(e){let t=e;return t.mode==="content"&&typeof t.content=="string"}function Is(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(`
7
+ `),keep:n}}function kl(e){let t=yl(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)&&!Cl(e)&&(vn(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,Is(e).keep&&(o.keep=!0)),typeof e=="object"&&e!==null){let r=e;typeof r.persistedOutputPath=="string"&&r.persistedOutputPath!==""&&typeof r.persistedOutputSize=="number"&&r.persistedOutputSize>o.bytes&&(o.persistedPath=r.persistedOutputPath)}return o}function oe(e,t,n,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(t+": hook payload is not a JSON object");let r=e,s=Rl.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:Nl(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=kl(r.tool_response)),i}function Dl(e,t){if(e.tool?.canonicalName==="Bash")return{stdout:t,stderr:"",interrupted:!1};let n=e.result?.shape,o=n===void 0?null:vn(n);return n!==void 0&&o!==null?o.put(n,t):e.result?.blocks===!0?[{type:"text",text:t}]:t}function F(e,t,n){let o=r=>({stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e.event,...r}}),exitCode:0});switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return o({additionalContext:t.text});case"deny":return o({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
8
+ `+t.reason});case"replace":return n&&e.event==="PostToolUse"?o({updatedToolOutput:Dl(e,t.output)}):{stdout:"",exitCode:0}}}var Ll={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function wl(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 Pl(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 Ll[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function ks(e){Pl(e);let t=oe(e,"claude-code",Fn,Al);if(t.tool!==void 0&&t.tool.name===Ol&&(t.tool.canonicalName=Tl),t.cwd===""&&(t.cwd=process.env.CLAUDE_PROJECT_DIR||process.cwd()),t.event==="PostToolUse"&&t.tool!==void 0&&t.tool.callId===void 0){let n=typeof t.tool.input.command=="string"?t.tool.input.command:JSON.stringify(t.tool.input);t.tool.callId="h"+wl(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function Ds(e,t,n){return F(e,t,!0)}var jn="mcp__context_mode__",Ul={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"};function Ls(e){return oe(e,"codex",jn,Ul)}function ws(e,t,n){return F(e,t,!1)}var bt="mcp_context-mode_",Ps={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},Ms={startup:"startup",resume:"resume",clear:"clear"},Fl=["SessionStart","UserPromptSubmit","PostToolUse"],vl=["UserPromptSubmit","PreToolUse"],St={stdout:"",exitCode:0};function N(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var Us={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function jl(e,t){if(e.startsWith(bt))return e.slice(bt.length);if(Object.hasOwn(Us,e))return Us[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 Gl(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:JSON.stringify(e),r=t===void 0?void 0:N(t,"error");return{isError:r!=null,bytes:Buffer.byteLength(o),text:o}}function Hs(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(Ps,n)?Ps[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(Ms,s)&&(r.source=Ms[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:jl(c,N(t,"mcp_context")),input:typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{}}}return o==="PostToolUse"&&(r.result=Gl(N(t,"tool_response"))),r}function Fs(e,t,n){switch(t.kind){case"allow":return St;case"hint":return Fl.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:St;case"deny":return vl.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
9
+ `+t.reason}),exitCode:0}:St;case"replace":return e.event!=="PostToolUse"?St:{stdout:JSON.stringify({decision:"deny",reason:t.output}),exitCode:0}}}var Gn="mcp__context-mode__",Wl={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},vs={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},Xl="PostToolUseFailure";function js(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===Xl,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=oe(n,"qwen",Gn,Wl);if(o.tool!==void 0&&Object.hasOwn(vs,o.tool.name)&&(o.tool.canonicalName=vs[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 Gs(e,t,n){return F(e,t,!1)}var Tt="context-mode-",ql={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}},Bs={startup:"startup",resume:"resume",new:"startup"},Yl={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"}},Xs="success";function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Bn=Object.freeze(["bash","powershell"]),Ws=Object.fromEntries(Bn.map(e=>[e,"Bash"]));function Vl(e){return e.startsWith(Tt)?e.slice(Tt.length):Object.hasOwn(Ws,e)?Ws[e]:e}function zl(e){if(Rt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Rt(t)?t:{}}catch{return{}}}var Jl={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function $l(e,t,n){let o=Jl[t],r=Rt(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==Xs,bytes:Buffer.byteLength(s),text:s}}var Ql=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function Zl(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:Ql.find(([t])=>Object.hasOwn(e,t))?.[1]}function Ks(e){if(!Rt(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=Zl(e),n=typeof t=="string"?ql[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Yl[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"&&Bs[e.source]!==void 0&&(s.source=Bs[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:Vl(i),input:zl(e[o.args])};s.tool=c}return r==="PostToolUse"&&(s.result=$l(e[o.result],n.casing,n.failure)),s}var Ot={stdout:"",exitCode:0};function qs(e,t,n){switch(t.kind){case"allow":return Ot;case"hint":return e.event==="PostToolUse"?Ot:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?Ot:{stdout:JSON.stringify({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
10
+ `+t.reason}),exitCode:0};case"replace":return e.event!=="PostToolUse"?Ot:{stdout:JSON.stringify({modifiedResult:{resultType:Xs,textResultForLlm:t.output}}),exitCode:0}}}var At="mcp_context-mode_",Qs=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],Ys="mcp_",Vs="_",tu="new",Wn=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),yt=Object.freeze(["read_file","view"]),Xn=Object.freeze(["fetch_webpage","web_fetch"]),zs=Object.fromEntries([...Wn.map(e=>[e,"Bash"]),...yt.map(e=>[e,"Read"]),...Xn.map(e=>[e,"WebFetch"])]);function Zs(e){if(e.startsWith(At))return e.slice(At.length);if(Object.hasOwn(zs,e))return zs[e];if(!e.startsWith(Ys))return e;let t=e.slice(Ys.length),n=t.indexOf(Vs);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+Vs.length)}var ke=e=>typeof e=="number"&&Number.isFinite(e);function ei(e,t,n){if(t==="Read"&&yt.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),ke(n.startLine)&&(o.offset=n.startLine),ke(n.startLine)&&ke(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&ke(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];ke(r)&&r>=n.view_range[0]&&(o.limit=r-n.view_range[0]+1)}return o}return t==="WebFetch"&&e==="fetch_webpage"&&Array.isArray(n.urls)&&typeof n.urls[0]=="string"?{...n,url:n.urls[0]}:n}function nu(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 ou={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},ru=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],Js={new:"startup",startup:"startup",resume:"resume"},su="success";function Nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iu(e){if(Nt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Nt(t)?t:{}}catch{return{}}}function cu(e){let t=Nt(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==su,bytes:Buffer.byteLength(n),text:n}}function $s(e,t){let n=typeof t=="string"?ou[t]??Qs.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"&&Js[e.source]!==void 0&&(o.source=Js[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=Zs(r);o.tool={name:r,canonicalName:s,input:ei(r,s,iu(e.toolArgs))}}return n==="PostToolUse"&&(o.result=cu(e.toolResult)),o}function ti(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 $s(t,t.hookEventName);if(t.hook_event_name===void 0){let r=ru.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return $s(t,r)}let n=Qs.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===tu&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=Nt(t.tool_input)?t.tool_input:{},i=Zs(r);o.tool={name:r,canonicalName:i,input:ei(r,i,s)}}return n==="PostToolUse"&&(o.result=nu(t.tool_response)),o}function ni(e,t,n){return F(e,t,!1)}var Ct="mcp_context_mode_",oi="mcp_context-mode_",ri={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},lu="prompt",uu="USER_PROMPT",si="mcp_",Kn=Object.freeze(["execute_bash","execute_pwsh","shell"]),ii=Object.fromEntries(Kn.map(e=>[e,"Bash"])),ci="_",ai={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function du(e){if(e.startsWith(Ct))return e.slice(Ct.length);if(e.startsWith(oi))return e.slice(oi.length);if(Object.hasOwn(ii,e))return ii[e];if(!e.startsWith(si))return e;let t=e.slice(si.length),n=t.indexOf(ci);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+ci.length)}function fu(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function li(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(ri,n)?ri[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"&&ai[t.source]!==void 0&&(r.source=ai[t.source]),o==="UserPromptSubmit"){let s=t[lu],i=typeof s=="string"?s:process.env[uu];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:du(s),input:i}}return o==="PostToolUse"&&(r.result=fu(t.tool_response)),r}function ui(e,t,n){if(e.event==="UserPromptSubmit")return{stdout:t.kind==="hint"?t.text:"",exitCode:0};switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:t.text,exitCode:0};case"deny":return{stdout:"",stderr:t.rewritten===void 0?t.reason:t.rewritten+`
11
+ `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var qn="mcp__context-mode__",pu={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},_u={hook_event_name:"hookEventName",session_id:"sessionId"},Eu="PostToolUseFailure";function di(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("zcode: hook payload is not a JSON object");let t={...e};for(let[r,s]of Object.entries(_u))t[r]===void 0&&(t[r]=t[s]);let n=t.hook_event_name===Eu;n&&(t.hook_event_name="PostToolUse");let o=oe(t,"zcode",qn,pu);if(n){let r=typeof t.error=="string"?t.error:t.error===void 0?"":JSON.stringify(t.error);o.result={isError:!0,bytes:Buffer.byteLength(r),text:r}}return o}function fi(e,t,n){return F(e,t,!1)}var _i="",xi={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},pi={bash:"Bash",read:"Read"};function mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function hu(e){let t=e.content===void 0?"":typeof e.content=="string"?e.content:JSON.stringify(e.content),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function Ei(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(xi,n)?xi[n]:void 0;if(o===void 0)throw new Error("pi: unknown hook event "+String(t.type));let r={event:o.event,agent:"pi",sessionId:String(t.sessionId??""),cwd:String(t.cwd??"")};if(o.source!==void 0&&(r.source=o.source),o.event==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o.event==="PreToolUse"||o.event==="PostToolUse"){let s=String(t.toolName??"");r.tool={name:s,canonicalName:Object.hasOwn(pi,s)?pi[s]:s,input:mu(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=hu(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Su(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+`
12
+ `+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function gi(e,t,n){let o=Su(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:Rs,content:o.stdout,timestamp:Date.now()}}function mi(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var Oi="",hi=K+"_",Si={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},Yn="bash",Ou=Object.freeze([Yn,"shell"]),bi={webfetch:"WebFetch",...Object.fromEntries(Ou.map(e=>[e,"Bash"]))};function Vn(e){return e.startsWith(hi)?e.slice(hi.length):Object.prototype.hasOwnProperty.call(bi,e)?bi[e]:e}function Tu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Ru(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 Ti(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(Si,n)?Si[n]:void 0;if(o===void 0)throw new Error("opencode: unknown hook event "+String(t.type));let r={event:o,agent:"opencode",sessionId:String(t.sessionID??""),cwd:String(t.directory??"")};if(o==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool??"");r.tool={name:s,canonicalName:Vn(s),input:Tu(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=Ru(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Ri(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+`
13
+ `+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var De={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},Ai={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},Nu={...Ai,shell:[...Cs]},yu=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:Fn,nativeTools:Nu,execReadOnlyHint:!1,eventMap:De,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"claude-code/skills"},decode:ks,encode:Ds},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:jn,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:De,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:Ls,encode:ws},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:bt,nativeTools:{shell:["run_shell_command"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:{UserPromptSubmit:"BeforeAgent",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",PreCompact:"PreCompress"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:Hs,encode:Fs},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Gn,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:De,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:js,encode:Gs},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:Tt,nativeTools:{shell:[...Bn]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:Ks,encode:qs},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:At,nativeTools:{shell:[...Wn],read:[...yt],webfetch:[...Xn]},execReadOnlyHint:!1,eventMap:{...De,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:ti,encode:ni},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:Ct,nativeTools:{shell:[...Kn]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:U,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:li,encode:ui},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:qn,nativeTools:Ai,execReadOnlyHint:!1,eventMap:De,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:U,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:di,encode:fi},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:_i,nativeTools:{shell:["bash"],read:["read"]},execReadOnlyHint:!1,eventMap:{SessionStart:"session_start",UserPromptSubmit:"input",PreToolUse:"tool_call",PostToolUse:"tool_result"},compactDelivery:"pi-flag",compactSummary:"none",hookTimeoutMs:_n,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:Ei,encode:gi,checkPermission:mi},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:Oi,nativeTools:{shell:[Yn]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:_n,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:Ti,encode:Ri,toCanonicalTool:Vn}]),Cu=new Map(yu.map(e=>[e.id,e])),Iu=new Set(["claude-code","gemini","copilot-cli","pi"]);function Le(e){return Iu.has(e.id)}var ku=new Set(["claude-code","copilot-cli","pi"]);function zn(e){return ku.has(e.id)&&Le(e)}var Du=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function It(e){return Du.has(e.id)}function re(e){return Cu.get(e)}import{resolve as qt}from"node:path";var Lu=["&&","||",";;","|&",";","|","&","(",")"],wu=["&>>","&>"],Pu=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],Mu="&",Uu="<<",Ni="<<-",Hu=";",yi=`\r
14
+ `,Ci=`\\
15
+ `,Ii=`\\\r
16
+ `,Fu="$(",Li="${",wi="$'",we="((",ki="))",fe="[[",kt="]]",Jn="<(",Pi=">(",L=2,Mi=`
17
+ \r;&|()<>`,vu=`
18
+ \r`,ju='$`"\\\n',Gu="case",Bu="esac";function xe(e,t){e.end==="complete"&&(e.end=t)}function $n(e){return e!==""&&e>="0"&&e<="9"}function Di(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function Ui(e){return e===""||Mi.includes(e)}function Qn(e){return e!==""&&vu.includes(e)}function v(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function Dt(e,t){let n=e.s.indexOf("'",t+1);return n<0?(xe(e,"unterminated-quote"),e.n):n+1}function Hi(e,t){let n=t+wi.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=L;continue}if(o==="'")return n+1;n++}return xe(e,"unterminated-quote"),e.n}function Zn(e,t,n){let o=t+1;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(r==="\\"){o+=L;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=Pe(e,o,n);continue}if(r==="$"&&s==="{"){o=eo(e,o,n);continue}if(r==="`"){o=pe(e,o);continue}o++}return xe(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+=L;continue}if(o==="`")return n+1;n++}return e.n}function eo(e,t,n){let o=t+Li.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=L;continue}if(s==="'"){o=Dt(e,o);continue}if(s==='"'){o=Zn(e,o,n);continue}if(s==="$"&&i==="("){o=Pe(e,o,n);continue}if(s==="`"){o=pe(e,o);continue}if(s==="{"&&r++,s==="}"){if(r===0)return o+1;r--}o++}return e.n}function to(e,t){let n=0,o=t+we.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(ki,o)?o+ki.length:-1;n--}o++}return-1}function Pe(e,t,n){let o=t+Fu.length-1;if(e.s.startsWith(we,o)){let r=to(e.s,o);if(r>0)return r}return Lt(e,o+1,!0,n+1,null,null)}function Wu(e,t,n){let o=t+fe.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=L;continue}if(s==="'"){o=Dt(e,o);continue}if(s==='"'){o=Zn(e,o,n);continue}if(s==="$"&&i==="("){o=Pe(e,o,n);continue}if(s==="$"&&i==="{"){o=eo(e,o,n);continue}if(s==="`"){o=pe(e,o);continue}let c=Qn(e.s.charAt(o-1));if(c&&e.s.startsWith(kt,o)&&Ui(e.s.charAt(o+kt.length))){if(r===0)return o+kt.length;r--,o+=kt.length;continue}if(c&&e.s.startsWith(fe,o)&&Qn(e.s.charAt(o+fe.length))){r++,o+=fe.length;continue}o++}return-1}function Xu(e,t){let n=t;for(;$n(e.charAt(n));)n++;if(n===t){for(let o of wu)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of Pu){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(Mu))if(e.charAt(r)==="-")r++;else for(;$n(e.charAt(r));)r++;return{end:r,op:o}}return null}function Ku(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(Mi.includes(r))break;if(r==="\\"){o+=L;continue}if(r==="'"){o=Dt(e,o);continue}if(r==='"'){o=Zn(e,o,n);continue}if(r==="$"&&s==="'"){o=Hi(e,o);continue}if(r==="$"&&s==="("){o=Pe(e,o,n);continue}if(r==="$"&&s==="{"){o=eo(e,o,n);continue}if(r==="`"){o=pe(e,o);continue}o++}return Math.min(o,e.n)}function qu(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(`
19
+ `,s),u=l<0?e.n:l,d=e.s.slice(s,u);if(d.endsWith("\r")&&(d=d.slice(0,-1)),s=l<0?e.n:l+1,(i.strip?d.trim():d)===i.tag){a=!0;break}}if(o!==null&&r!==null&&r.push(o.length),v(o,"unhandled",e.s.slice(c,s),c,s),!a)return xe(e,"unterminated-heredoc"),e.n}return n.length=0,s}function Lt(e,t,n,o,r,s){if(o>H)return xe(e,"too-deep"),e.n;let i=e.s,c=t,a=0,l=0,u=null,d=[];for(;c<e.n;){let f=i.charAt(c),x=i.charAt(c+1);if(f===" "||f===" "){c++;continue}if(i.startsWith(Ci,c)){c+=Ci.length;continue}if(i.startsWith(Ii,c)){c+=Ii.length;continue}if(f===`
20
+ `||f==="\r"){let S=c;c+=i.startsWith(yi,c)?yi.length:1,v(r,"op",Hu,S,c),u=null,d.length>0&&(c=qu(e,c,d,r,s));continue}if(f==="#"){for(;c<e.n&&i.charAt(c)!==`
21
+ `&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(Jn,c)||i.startsWith(Pi,c)){let S=Lt(e,c+Jn.length,!0,o+1,null,null);v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}let p=Xu(i,c);if(p!==null){v(r,"io",i.slice(c,p.end),c,p.end),u=p.op===Uu||p.op===Ni?p.op===Ni:null,c=p.end;continue}if(i.startsWith(fe,c)&&Qn(i.charAt(c+fe.length))){let S=Wu(e,c,o);if(S>0){v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}if(i.startsWith(we,c)){let S=to(i,c);if(S>0){v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let g=Lu.find(S=>i.startsWith(S,c));if(g!==void 0){if(n&&g==="("&&a++,n&&g===")"){if(a>0)a--;else if(l===0)return c+1}v(r,"op",g,c,c+g.length),c+=g.length,u=null;continue}if(f==="$"&&x==="("||f==="`"){let S=f==="`"?pe(e,c):Pe(e,c,o);if(Ui(i.charAt(S))){v(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let E=c;c=Ku(e,c,o);let h=i.slice(E,c);v(r,"word",h,E,c),u!==null&&(d.push({tag:_e(h),strip:u}),u=null),n&&h===Gu&&l++,n&&h===Bu&&l>0&&l--}return d.length>0&&xe(e,"unterminated-heredoc"),e.n}function Fi(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return Lt(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function _e(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=L;continue}if(r==="'"){let s=e.indexOf("'",n+1),i=s<0?o:s;t+=e.slice(n+1,i),n=i+1;continue}if(r==="$"&&e.charAt(n+1)==="'"){let s=n+wi.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=L;continue}t+=e.charAt(s),s++}n=s+1;continue}if(r==='"'){let s=n+1;for(;s<o&&e.charAt(s)!=='"';){let i=e.charAt(s+1);if(e.charAt(s)==="\\"&&i!==""&&ju.includes(i)){t+=i,s+=L;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function wt(e){let t={s:e,n:e.length,end:"complete"},n=[],o=!1,r=0;for(;r<t.n;){let s=e.charAt(r),i=e.charAt(r+1);if(s==="\\"){r+=L;continue}if(!o&&s==="'"){r=Dt(t,r);continue}if(!o&&s==="$"&&i==="'"){r=Hi(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Li.length;continue}let c=e.startsWith(Jn,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(Pi,r))){let a=r+1;if(s==="$"&&e.startsWith(we,a)&&to(e,a)>0){r=a+we.length;continue}let l=Lt(t,a+1,!0,1,null,null),u=l>a+1&&e.charAt(l-1)===")"?l-1:l;n.push({wrapper:s==="$"?"$()":c?"<()":">()",body:e.slice(a+1,u)}),r=l;continue}if(s==="`"){let a=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 Pt(e){let t=e.charAt(0);if(!(Di(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(!(Di(o)||$n(o)||o==="_"))return!1}return!1}var Bi=[";","&","&&","||"],Wi=["|","|&"],Me="(",Ue=")",Xi=";;",ro=["(",")"],Yu="!",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"}),Ki=[],Vu="[[",zu="((",qi=[">",">>",">|","&>","&>>",">&"],Ju=[...qi,"<","<>","<<<","<<","<<-"],$u=["","1"],Yi=["-","/dev/stdout","/dev/stderr"],Ut="-",He="--",Fe="=",Qu="/",Zu=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),Mt=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),no="-c",oo="--bytes",ed="c",td="--count",se=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],Y=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,C=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,so=e=>e!==""&&e>="0"&&e<="9",nd=e=>so(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function io(e){let t=e.lastIndexOf(Qu);return t>=0&&t<e.length-1?e.slice(t+1):e}function co(e,t){let n=Zu[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===He)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+Fe))s=r.slice(n.long.length+Fe.length);else if(r.startsWith(Ut)&&!r.startsWith(He)){let i=r.indexOf(n.short,Ut.length);if(i<0)continue;s=i+n.short.length<r.length?r.slice(i+n.short.length):t[o+1]}else continue;if(s!==void 0&&!Yi.includes(s))return!0}return!1}function od(e){if(e==="")return!1;for(let t of e)if(!so(t))return!1;return!0}function rd(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===no||n===oo?o=e[t+1]:n.startsWith(oo+Fe)?o=n.slice(oo.length+Fe.length):n.startsWith(no)&&!n.startsWith(He)&&(o=n.slice(no.length)),o!==void 0)return od(o)&&Number(o)<=q}return!1}function sd(e){for(let t of e){if(t===He)return!1;if(t===td||t.startsWith(Ut)&&!t.startsWith(He)&&t.includes(ed))return!0}return!1}function vi(e){if(!e.startsWith(D.fieldSep))return!1;for(let t of e.slice(D.fieldSep.length).split(D.fieldSep)){if(t==="")return!1;for(let n of t)if(!nd(n))return!1}return!0}function id(e){let t=e.trim();if(t===D.identity||t===D.length)return!0;let n=t.indexOf(D.pipeLength.charAt(0));if(n<0)return vi(t);let o=t.slice(0,n).trim(),r=D.pipeLength.slice(1).trim();return(o===D.identity||vi(o))&&t.slice(n+1).trim()===r}function cd(e){let t=e.argv0.toLowerCase();if(t===Mt.wc)return!0;if(t===Mt.head)return rd(e.args);if(t===Mt.grep)return sd(e.args);if(t===Mt.jq){let n=e.args.filter(o=>!o.startsWith(Ut));return n.length===1&&id(n[0])}return!1}function ao(e){return wt(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function Vi(e,t,n){return n<=t?[]:ao(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function zi(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function ad(e){let t=0;for(;so(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Ji(e){let t=ad(e.toks[e.i].text);if(e.i++,!Ju.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,qi.includes(t.op)&&$u.includes(t.fd)&&!Yi.includes(_e(n.text)))}function $i(e){let t=!1;for(;O(e)?.kind==="io";)t=Ji(e)||t;return t}function Qi(e){for(;O(e)?.kind==="op"&&Bi.includes(O(e)?.text??"");)e.i++}function Ee(e,t){if(e.depth++,e.depth>H)return e.err="nesting-too-deep",se();let n=t();if(e.depth--,$i(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function Zi(e){if(Qi(e),!C(O(e),b.do))return[];e.i++;let t=j(e,[b.done]);return C(O(e),b.done)&&e.i++,t}function ld(e){e.i++;let t=j(e,[b.then]);for(;e.err===null;){let n=O(e);if(C(n,b.then)||C(n,b.else)){e.i++,t.push(...j(e,[b.elif,b.else,b.fi]));continue}if(C(n,b.elif)){e.i++,t.push(...j(e,[b.then]));continue}C(n,b.fi)&&e.i++;break}return t}function ud(e){e.i++;let t=j(e,[b.do]);return t.push(...Zi(e)),t}function dd(e){e.i++;let t=[],n=O(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,C(O(e),b.in)){e.i++;let o=e.i;for(;(O(e)?.kind==="word"||O(e)?.kind==="unhandled")&&!C(O(e),b.do);)e.i++;t.push(...Vi(e,o,e.i))}return t.push(...Zi(e)),t}function fd(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,t.push(...Vi(e,e.i-1,e.i))),C(O(e),b.in)&&e.i++;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)||o.kind==="op"&&(Bi.includes(o.text)||o.text===Xi)){e.i++;continue}if(C(o,b.esac)){e.i++;break}for(Y(o,Me)&&e.i++;e.i<e.toks.length&&!Y(O(e),Ue);){let s=e.toks[e.i];if(s.kind==="op"&&!Wi.includes(s.text))break;e.i++}if(!Y(O(e),Ue))break;e.i++;let r=j(e,[b.esac]);zi(r,b.case),t.push(...r)}return t}function ji(e,t){Qi(e);let n=ec(e);return zi(n.cmds,t),{cmds:n.cmds,simple:null}}function Gi(e,t){return ro.every((n,o)=>Y(e.toks[t+o],n))}function xd(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=Ji(e)||o;continue}if(n.length===0&&l.kind==="word"&&Pt(l.text)){e.i++;let u=O(e);if(l.text.endsWith(Fe)&&u!==void 0&&Y(u,Me)&&u.start===l.end){let d=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,Y(f,Me)&&d++,Y(f,Ue)&&--d===0)break}}continue}n.push(l),e.i++}if(e.i===t)return se();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:ao(r),simple:null};let s=l=>l.kind==="word"?_e(l.text):l.text,i=io(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||co(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function ec(e){let t=O(e);if(t===void 0)return se();if(t.kind==="op")return t.text!==Me?se():Ee(e,()=>{e.i++;let n=j(e,Ki);return Y(O(e),Ue)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(Vu)||t.text.startsWith(zu)))return e.i++,$i(e),{cmds:ao(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return Ee(e,()=>{e.i++;let n=j(e,[b.groupEnd]);return C(O(e),b.groupEnd)&&e.i++,n});case b.if:return Ee(e,()=>ld(e));case b.while:case b.until:return Ee(e,()=>ud(e));case b.for:return Ee(e,()=>dd(e));case b.case:return Ee(e,()=>fd(e));case b.coproc:return e.err="coproc",se();case b.select:return e.err="select",se();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=_e(n.text),e.i++),Gi(e,e.i)&&(e.i+=ro.length),ji(e,o)}default:if(Gi(e,e.i+1))return e.i+=ro.length+1,ji(e,_e(t.text))}return xd(e)}function pd(e){C(O(e),Yu)&&e.i++;let t=[],n=se();for(;e.err===null;){n=ec(e),t.push(...n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&Wi.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&cd(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function j(e,t){let n=[];for(;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)){e.i++;continue}if(o.kind==="op"){if(o.text===Ue||o.text===Xi)return n;if(o.text!==Me){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;n.push(...pd(e)),e.i===r&&e.err===null&&e.i++}return n}function ve(e){let t=Fi(e);if(t.end==="unterminated-quote")return{ok:!1,construct:"unterminated-quote"};if(t.end==="unterminated-heredoc")return{ok:!1,construct:"unterminated-heredoc"};if(t.end==="too-deep")return{ok:!1,construct:"nesting-too-deep"};let n={toks:t.tokens,src:e,bodies:new Set(t.heredocBodies),i:0,depth:0,err:null},o=[];for(;n.i<n.toks.length&&n.err===null;)o.push(...j(n,Ki)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as tc}from"node:path";var Ft="'",ge='"',vt="`",_d=" \r",Ge="([{",xo=")]}",lo=` \r
22
+ |;>`,rc="*",nc="1",uo="::",Ht=uo.length,Ed=Ht;function jt(e,t){let n=e.charAt(t);for(let o=t+1;o<e.length;o++){let r=e.charAt(o);if(n===ge&&r===vt){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function gd(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===ge&&r===vt&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function je(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Ft||r===ge){let s=jt(e,o);if(s<0)return-1;o=s;continue}if(r===vt){o++;continue}if(Ge.includes(r))n++;else if(xo.includes(r)&&--n===0)return o}return-1}function md(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===Ft||r===ge){let s=jt(e,o);if(s<0)return e.length;o=s;continue}if(Ge.includes(r))n++;else if(xo.includes(r))n--;else if(n<=0&&lo.includes(r))return o}return e.length}function hd(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===Ft||s===ge){let i=jt(e,r);if(i<0)break;r=i;continue}Ge.includes(s)?n++:xo.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var Sd=e=>e!==""&&(e===rc||[...e].every(t=>t>="0"&&t<="9")),oc=()=>({words:[],toFile:!1,chained:!1});function sc(e){let t=[],n=[],o=oc(),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=oc()},d=()=>{u(),n.length>0&&t.push(n),n=[]},f=(p,g)=>{r+=p,s=!0,g&&(i=!1)},x=0;for(;x<a;){let p=e.charAt(x),g=e.charAt(x+1);if(p===Ft||p===ge){let E=jt(e,x);f(gd(e.slice(x+1,E<0?a:E),p),!0),x=E<0?a:E+1}else if(p===vt)g!==`
21
23
  `&&g!==""&&f(g,!1),x+=Ht;else if(p===`
22
- `)d(),x++;else if(ud.includes(p))l(),x++;else if(p===";")d(),x++;else if(p==="|")g==="|"?(d(),x+=Ht):(u(),x++);else if(p==="&")g==="&"?(d(),x+=Ht):((s||o.words.length>0)&&f(p,!1),x++);else if(p==="#"&&!s)for(;x<a&&e.charAt(x)!==`
23
- `;)x++;else if(p===">"){let E=ec;s&&i&&_d(r)?(E=r,r="",s=!1):s&&l();let h=x+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<a&&!ao.includes(e.charAt(h));)h++;else c=E===ec||E===nc?"file":"skip";x=h}else if(p==="("&&s&&i&&r.includes(lo)){let E=je(e,x),h=e.slice(x+1,E<0?a:E);l();for(let S of h.trim()===""?[]:pd(h)){let _=oc(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}x=E<0?a:E+1,x<a&&!ao.includes(e.charAt(x))&&(o.chained=!0,x=xd(e,x))}else if(p==="["&&!s&&e.startsWith(lo,je(e,x)+1)&&je(e,x)>=0){let E=je(e,x);f(e.slice(x,E+1),!1),x=E+1}else if(Ge.includes(p)&&(p!=="["||!s)||(p==="$"||p==="@")&&Ge.includes(g)&&g!=="["){let E=p==="$"||p==="@"?x+1:x,h=je(e,E);f(e.slice(x,h<0?a:h+1),!0),x=h<0?a:h+1}else f(p,!1),x++}return d(),t}var Ed=["get-content","gc","cat","type"],gd=["[io.file]::","[system.io.file]::"],md=["readalltext","readalllines","readallbytes","readlines"],xo=["path","literalpath"],rc=["totalcount","head","first","tail","last"],sc=[...xo,...rc,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],hd=["raw","wait","force","asbytestream"],Sd=[...sc,...hd],bd=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],Od=["cd","chdir","sl","set-location","pushd","push-location"],Td=["powershell","powershell.exe","pwsh","pwsh.exe"],Rd=["cmd","cmd.exe"],Ad=["/c","/k","/r"],Nd="command",ie="-";function uo(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function po(e,t){let n=e.slice(ie.length),o=n.indexOf(":"),r=(o<0?n:n.slice(0,o)).toLowerCase(),s=o<0?void 0:n.slice(o+1);if(r==="")return{full:void 0,inline:s};if(t.includes(r))return{full:r,inline:s};let i=t.filter(c=>c.startsWith(r));return{full:i.length===1?i[0]:void 0,inline:s}}function yd(e){if(e.length===0)return null;let t=uo(e[0]);if(!Ed.includes(t)){let r=e[0].toLowerCase(),s=gd.find(i=>r.startsWith(i));return s===void 0||!md.includes(r.slice(s.length))||e.length<dd?null:{file:e[1],bounded:!1}}let n=[],o=!1;for(let r=1;r<e.length;r++){let s=e[r];if(!s.startsWith(ie)||s.length===ie.length){n.push(s);continue}let i=po(s,Sd);if(i.full===void 0||!sc.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;xo.includes(i.full)&&n.push(c),rc.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function Cd(e,t){if(Td.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(ie)||o.length===ie.length)continue;let r=po(o,[Nd]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(Rd.includes(e)){for(let n=1;n<t.length;n++)if(Ad.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function Id(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(ie)||n.length===ie.length)return n;let o=po(n,xo);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function ic(e,t,n,o){let r=t;for(let s of oc(e)){let i=s[0];if(i.words.length===0)continue;let c=uo(i.words[0]);if(s.length===1&&Od.includes(c)){let d=Id(i.words);d!==null&&(r=Zi(r,d));continue}let a=n<H?Cd(c,i.words):null;if(a!==null){ic(a,r,n+1,o);continue}if(i.toFile||i.chained)continue;let l=yd(i.words);if(l===null||l.bounded)continue;let u=!0;for(let d=1;d<s.length;d++)if(s[d].toFile||!bd.includes(uo(s[d].words[0]??""))){u=!1;break}u&&o.push(Zi(r,l.file))}}function cc(e,t){let n=[];return ic(e,t,0,n),n}import{join as Bt}from"node:path";var ac=`\r
24
- `,kd=`
25
- `;function Gt(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(ac)<0?t:t.split(ac).join(kd)}import{basename as Z_,dirname as eE,join as lc,posix as tE,resolve as nE,win32 as oE}from"node:path";var Dd=Object.freeze({NODE_TOO_OLD:"Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",NO_SQLITE:"node:sqlite failed to load. Fix: run ctx_doctor.",DB_GONE:"context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",NO_PROJECT:"Project source <kind> is missing. Fix: run ctx_doctor.",UNKNOWN_FIELD:'Unknown field "<f>". Fix: use "queries".',TIMEOUT:"Timed out after <ms> ms. Fix: pass background: true.",NO_GIT_BASH:"Git Bash not found. Fix: install Git for Windows.",NO_RUNTIME:"No <lang> runtime on PATH. Fix: install it or pick another language.",FETCH_FAILED:"Fetch failed: <code>. Fix: check the URL or proxy.",SSRF:"Blocked private address <host>. Fix: use a public URL.",OUTSIDE_ROOT:"Path <p> is outside the project. Fix: use a path inside <root>.",INVALID_ARGS:"Invalid argument <field>. Fix: <action>.",ONE_OF_INPUT:"Pass exactly one of <names>. Fix: drop the extra field.",SPAWN_FAILED:"Failed to start the process: <detail>. Fix: check the command and PATH.",DB_CORRUPT:"context.db failed integrity_check. Fix: run ctx_doctor.",SCHEMA_STALE:"context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.",NO_GIT_DIR:"No git repository at <path>. Fix: run context-mode inside a git repository.",NO_HOME:"Env var <name> is not set. Fix: set <name> to your home directory.",PLUGIN_ROOT_MISSING:"Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.",BUNDLE_HASH_MISMATCH:"Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.",CONFIG_PARSE_FAILED:"<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade."});function Ld(e,t){let n=Dd[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(Ld(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{mkdirSync:wd,realpathSync:Pd}=process.getBuiltinModule("node:fs");function me(e,t=process.platform){let n=o=>o!==void 0&&o!=="";return t==="win32"?n(e.USERPROFILE)?e.USERPROFILE:n(e.HOMEDRIVE)&&n(e.HOMEPATH)?e.HOMEDRIVE+e.HOMEPATH:n(e.HOME)?e.HOME:null:n(e.HOME)?e.HOME:n(e.USERPROFILE)?e.USERPROFILE:null}function Be(e,t){let n=e[ht];return n!==void 0&&n!==""?n:lc(t,...Os["claude-code"])}function Md(e,t=process.platform){let n=me(e,t);if(n!==null)return n;throw new T("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function uc(e){let t=lc(Md(e),ct.slice(1));return wd(t,{recursive:!0}),Pd.native(t)}var{readFileSync:pc}=process.getBuiltinModule("node:fs");function he(e){return e.agentId!==void 0&&e.agentId!==""}function go(e,t){if(t===null)return"C";let n=re(e.agent),o=new Set(t);for(let r of ot)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function mo(e,t){if(!he(e))return null;let n=re(e.agent);if(t.manifestTools!==void 0)return xc(t.manifestTools.map(c=>_o(n,c)));let o=e.agentType??"",r=Ud(o,t);if(r===null)return null;let s=(r.tools??Gd(n)).map(c=>_o(n,c)),i=r.disallowed.map(c=>_o(n,c));return xc(s.filter(c=>!i.some(a=>Wd(a,c))))}function Ud(e,t){if(!Hd(e))return null;let n=Fd(t.env);if(e.indexOf(de)>=0){if(n!==null){let s=vd(Be(t.env,n),e);if(s!==null)return s}}else{let s=Eo(Bt(t.projectDir,Tr,at,e+lt));if(s!==null)return s;if(n!==null){let i=Eo(Bt(Be(t.env,n),at,e+lt));if(i!==null)return i}}let r=t.cliAgents;if(r!==void 0&&Object.prototype.hasOwnProperty.call(r,e)){let s=r[e];return{tools:Array.isArray(s.tools)?s.tools:null,disallowed:Array.isArray(s.disallowedTools)?s.disallowedTools:[]}}return null}function Hd(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 Fd(e){return me(e)}function vd(e,t){let n=t.indexOf(de),o=t.slice(0,n),r=t.slice(n+de.length);if(r.indexOf(de)>=0)return null;let s;try{s=JSON.parse(Gt(pc(Bt(e,hn,Rr),"utf8")))}catch{return null}let i=s?.plugins;if(i===null||typeof i!="object")return null;for(let c of Object.keys(i)){let a=c.indexOf(Ar);if((a<0?c:c.slice(0,a))!==o)continue;let l=i[c];if(Array.isArray(l))for(let u of l){let d=u?.installPath;if(typeof d!="string"||d==="")continue;let f=Eo(Bt(d,at,r+lt));if(f!==null)return f}}return null}function Eo(e){let t;try{t=pc(e,"utf8")}catch{return null}return jd(t)}function jd(e){let t=e.split(`
26
- `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Sn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Sn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=dc(o,Nr),s=dc(o,yr);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function dc(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(fc(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>fc(s.trim())).filter(s=>s!=="")}return null}function fc(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function Gd(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...ot.map(n=>e.toolNamePrefix+n)]}function _o(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(Cr)?Bd(o):o}function Bd(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||Ir.indexOf(n)>=0;t+=o?n:"_"}return t}function Wd(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(bn)){let n=e.slice(bn.length);if(n!==""&&n.indexOf(On)<0)return t.startsWith(e+On)}return!1}function xc(e){return[...new Set(e.filter(t=>t!==""))]}var ce="",_c=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:ce},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:ce},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:ce},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:ce},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:ce},command:{valueShorts:ce,valueLongs:[],assignments:!1,duration:!1,refuseShorts:"vV"},xargs:{valueShorts:"aEdILnPs",valueLongs:["--arg-file","--delimiter","--max-args","--max-procs","--max-chars"],assignments:!1,duration:!1,refuseShorts:ce}}),Xd=["bash","sh","zsh"],Kd="c",qd=" -c",Yd=["-o","+o","-O","+O"],Wt="-",Vd="+",ho="--",zd="smhd",Jd=".",Ec=e=>e!==""&&e>="0"&&e<="9";function $d(e){if(e===""||!Ec(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(Ec(n)||n===Jd))return t===e.length-1&&zd.includes(n)}return!0}function Qd(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===ho){n++;break}if(e.assignments&&Pt(o)){n++;continue}if(o.startsWith(ho)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(Wt)&&o.length>Wt.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=Wt.length;r<o.length;r++)if(e.valueShorts.includes(o.charAt(r))){r===o.length-1&&n++;break}continue}break}if(e.duration){if(n>=t.length||!$d(t[n]))return null;n++}return n<t.length?t.slice(n):null}function Zd(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(ho)){if(o.startsWith(Wt)||o.startsWith(Vd)){o.includes(Kd)&&(t=!0),Yd.includes(o)&&n++;continue}return t?o:null}}return null}function gc(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function So(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let a=s.toLowerCase();if(Xd.includes(a)){let d=Zd(i),f=d!==null&&n<H?ve(d):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=gc(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,So(p,[...r,a+qd],n+1,o)}return}let l=Object.hasOwn(_c,a)?_c[a]:void 0,u=l===void 0?null:Qd(l,i);if(u===null)break;r.push(a),s=so(u[0]),i=u.slice(1),c=c||io(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=H))for(let a of wt(e.raw)){let l=ve(a.body);if(l.ok)for(let u of l.commands)So(gc(u,e),[...t,a.wrapper],n+1,o)}}function mc(e){let t=[];for(let n of e)So(n,[],0,t);return t}import{isAbsolute as tf,join as bo,relative as nf,sep as Oo}from"node:path";var{readFileSync:ef}=process.getBuiltinModule("node:fs"),hc=".claude",of="settings.local.json",Sc="settings.json",rf="Bash",sf="Read",bc=":*",Oc="//",Tc="~/",Rc="./",Ac="..",cf=`
27
- \r`,af=Object.freeze({tool:rf});function lf(e,t){if(t!=="claude-code")return[];let n=me(process.env),o=process.env[ht],r=o!==void 0&&o!==""?o:n===null?null:Be(process.env,n),s=[bo(e,hc,of),bo(e,hc,Sc)];return r===null?s:[...s,bo(r,Sc)]}function Nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function uf(e){let t;try{t=Gt(ef(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Nc(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Nc(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 yc(e,t){let n=[];for(let o of lf(e,t)){let r=uf(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function df(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 Y(e,t,n){let o=df(e,n),r=t.length,s=new Uint8Array(r+1);s[r]=1;for(let i=o.length-1;i>=0;i--){let c=o[i],a=new Uint8Array(r+1),l=0;for(let u=r;u>=0;u--){let d=u<r,f=d?t[u]:"";switch(c.t){case"lit":a[u]=d&&f===c.c?s[u+1]:0;break;case"any1":a[u]=d&&!(n&&f==="/")?s[u+1]:0;break;case"star":a[u]=s[u]||(d&&!(n&&f==="/")?a[u+1]:0);break;case"globstar":a[u]=s[u]||(d?a[u+1]:0);break;case"globstarDir":d&&f==="/"&&s[u+1]&&(l=1),a[u]=s[u]||l;break}}s=a}return s[0]===1}function ff(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 xf(e,t){if(!e.endsWith(bc))return Y(e,t,!1);let n=e.slice(0,e.length-bc.length);if(Y(n,t,!1))return!0;for(let o=0;o<t.length;o++)if(cf.includes(t[o])&&Y(n,t.slice(0,o),!1))return!0;return!1}var pf=/^[A-Za-z]:(?=\/)/;function We(e){return Oo==="/"?e:e.split(Oo).join("/")}function _f(e,t,n){if(e.startsWith(Rc)){if(n===void 0)return!1;let r=nf(n,t);return r===""||r===Ac||r.startsWith(Ac+Oo)||tf(r)?!1:Y(e.slice(Rc.length),We(r),!0)}let o=We(t);if(e.startsWith(Oc)){let r=We(e.slice(Oc.length-1));return Y(r,o,!0)||Y(r,o.replace(pf,""),!0)}if(e.startsWith(Tc)){let r=me(process.env);return r!==null&&Y(We(r)+e.slice(Tc.length-1),o,!0)}return Y(We(e),o,!0)}function V(e,t,n=af){for(let o of t){let r=ff(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===sf?_f(r.glob,e,n.projectDir):xf(r.glob,e))return o}return null}var OE=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.'}),Cc='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var Ef="{size}",gf="{path}";function Xt(e,t,n=""){return k(Cc,n).split(Ef).join(String(t)).split(gf).join(e)}var{statSync:mf}=process.getBuiltinModule("node:fs"),Lc="Bash",Ro="Read",hf="WebFetch",Sf="ctx_execute",bf="ctx_batch",wc="shell",Of="1",z="-",Ao="--",Tf="=",Rf=".",Ic=",",To="p",Af=["-e","--expression"],Nf=";&|(`\n\r",le=Object.freeze({kind:"allow"}),G=e=>({kind:"deny",reason:e}),ae=e=>typeof e=="string"?e:void 0,kc=e=>e!=null,J=(e,t)=>e.includes(t);function Pc(e,t,n){let o=e.tool;if(o===void 0)return le;let r=o.canonicalName,s=o.input,i;if(n===null){if(process.env[Or]===Of)return G(k(ut,t.toolNamePrefix));process.stderr.write(Yr+`
28
- `),i=[]}else i=n;let c=yf(r,s,e.cwd,i);return c!==null?G(Ne+c):r===hf?Df(s,t):r===Lc?Lf(e,t,s,i):r===Ro?Ff(e,t,s):le}function Mc(e,t,n,o){let r=e==="webfetch",s=r?Ur.map(c=>n.toolNamePrefix+c).join(qr):n.toolNamePrefix+Mr,i=JSON.stringify(r?{url:t}:{language:wc,code:t,intent:o??Pr});return[Tn+kr[e]+Dr,Lr,wr+s,i].join(`
29
- `)}function Uc(e){for(let t of xt){let n=ae(e[t]);if(n!==void 0&&n!=="")return n}}function yf(e,t,n,o){if(o.length===0)return null;let r=s=>V(qt(n,s),o,{tool:Ro,projectDir:n});if(e===Lc){let s=ae(t.command);return s===void 0?null:V(s,o)}if(e===Ro){let s=Uc(t);return s===void 0?null:r(s)}if(e===Sf){let s=ae(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=ae(t.code);return t.language===wc&&c!==void 0?V(c,o):null}if(e===bf&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?V(s,o):null;if(i!==null)return i}return null}function Cf(e,t){return t.length===0?null:V([e.argv0,...e.args].join(" "),t)??V(e.raw,t)}function If(e,t){if(t.length===0)return!1;for(let n=0;n<=e.length;n++)if(!(n>0&&!Nf.includes(e.charAt(n-1)))&&V(e.slice(n).trimStart(),t)!==null)return!0;return!1}function kf(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return Vr.some(n=>t===n||t.endsWith(Rf+n))}function Df(e,t){let n=ae(e.url)??"";return kf(n)?le:G(Mc("webfetch",n,t))}function Lf(e,t,n,o){let r=ae(n.command)??"",s=ve(r);if(!s.ok)return If(r,o)?G(k(dt,t.toolNamePrefix)):Dc(r,e.cwd,t)??le;let i=mc(s.commands);for(let c of i){let a=Cf(c,o);if(a!==null)return G(Ne+a)}if(!Le(t)||he(e))for(let c of i){let a=wf(c);if(a!==null)return G(Mc(a,r,t,ae(n.description)))}return vf(i,e.cwd,t)??Dc(r,e.cwd,t)??le}function wf(e){let t=e.argv0.toLowerCase();return J(zr,t)&&Pf(t,e)?"curl":Uf(e.raw)?"http":J(Zr,t)?"build":null}function Pf(e,t){return t.redirectsToFile?!Mf(e,t.args):!t.endsInBoundedSink}function Mf(e,t){let n=Jr[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===Ao)break;if(J($r,s)||s===Qr&&t[r+1]===z)return!1;(s===n.long||s.startsWith(z)&&!s.startsWith(Ao)&&s.includes(n.short,z.length))&&(o=!0)}return o}function Uf(e){let t=e.toLowerCase();for(let n of ns)if(t.includes(n))return!0;for(let n=t.indexOf(Ce);n>=0;n=t.indexOf(Ce,n+1)){let o=t.charAt(n+Ce.length);if(o!==""&&es.includes(o)&&t.startsWith(ts,n+Ce.length+o.length))return!0}return!1}var Hf="cd";function No(e){try{let t=mf(e);return t.isFile()?t.size:-1}catch{return-1}}function Ff(e,t,n){if(!kc(n.offset)&&!kc(n.limit)){let o=Uc(n);if(o!==void 0){let r=qt(e.cwd,o),s=No(r);if(s>K)return G(Xt(r,s,t.toolNamePrefix))}}return le}function vf(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&Vn(n))return null;let o=t,r=null;for(let s of e){let i=s.argv0.toLowerCase();if(i===Hf&&s.args.length===1&&s.insideConstruct===void 0&&(o=qt(o,s.args[0])),s.redirectsToFile||s.endsInBoundedSink||s.pipesOut===!0||s.insideConstruct!==void 0||!J(os,i))continue;let c=Bf(i,s.args);if(c===null)continue;if(c.bounded){r=le;continue}let a=qt(o,c.file),l=No(a);if(l>K)return G(Xt(a,l,n.toolNamePrefix))}return r}function Dc(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&Vn(n))return null;for(let o of cc(e,t)){let r=No(o);if(r>K)return G(Xt(o,r,n.toolNamePrefix))}return null}var Kt=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function jf(e){if(J(An,e))return 1;for(let t of An)if(t.startsWith(Ao)?e.startsWith(t+Tf):e.startsWith(t))return 0;return e.startsWith(z)&&Kt(e.slice(z.length))?0:-1}function Gf(e){if(e===To)return"all";if(!e.endsWith(To))return null;let t=e.slice(0,e.length-To.length),n=t.indexOf(Ic);return(n<0?Kt(t):Kt(t.slice(0,n))&&Kt(t.slice(n+Ic.length)))?"range":null}function Bf(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(J(rs,e)){let a=jf(c);if(a>=0){o=!0,i+=a;continue}}if(e===ft&&J(ss,c)){r=!0;continue}if(e===ft&&J(Af,c)){s=t[i+1],i++;continue}c.startsWith(z)&&c!==z||n.push(c)}if(e===ft){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:Gf(s);if(i===null)return null;o=i==="range"}return e===is&&n.shift()!==D.identity?null:n.length===1&&n[0]!==z?{file:n[0],bounded:o}:null}import{basename as $f,dirname as Vt,join as Ke,resolve as Gc}from"node:path";import{dirname as Hc,sep as Xf}from"node:path";var{realpathSync:Wf}=process.getBuiltinModule("node:fs");function Kf(e){try{return Wf.native(e)}catch{return}}function Yt(e){return e.split(Xf).filter(t=>t!=="")}function Fc(e){let t=e.map(Kf).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=Yt(n).length;for(let s of t){let i=Yt(s),c=Yt(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;Yt(r).length>o&&Hc(r)!==r;)r=Hc(r);return r}var qf=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]),Yf=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],w=(e,t)=>e>>>t|e<<32-t;function vc(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=Yf.slice(),i=new Uint32Array(64);for(let c=0;c<o;c+=64){for(let E=0;E<16;E++)i[E]=r.readUInt32BE(c+E*4);for(let E=16;E<64;E++){let h=w(i[E-15],7)^w(i[E-15],18)^i[E-15]>>>3,S=w(i[E-2],17)^w(i[E-2],19)^i[E-2]>>>10;i[E]=i[E-16]+h+i[E-7]+S>>>0}let[a,l,u,d,f,x,p,g]=s;for(let E=0;E<64;E++){let h=g+(w(f,6)^w(f,11)^w(f,25))+(f&x^~f&p)+qf[E]+i[E]>>>0,S=(w(a,2)^w(a,13)^w(a,22))+(a&l^a&u^l&u)>>>0;g=p,p=x,x=f,f=d+h>>>0,d=u,u=l,l=a,a=h+S>>>0}s[0]=s[0]+a>>>0,s[1]=s[1]+l>>>0,s[2]=s[2]+u>>>0,s[3]=s[3]+d>>>0,s[4]=s[4]+f>>>0,s[5]=s[5]+x>>>0,s[6]=s[6]+p>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:Vf,readFileSync:zf,realpathSync:jc,statSync:Jf}=process.getBuiltinModule("node:fs");function Qf(e){switch(e){case"claude-code":return"env:CLAUDE_PROJECT_DIR";case"codex":case"copilot-cli":case"kiro":return"arg:--agent+cwd";case"vscode":return"arg:workspaceFolder";case"gemini":case"qwen":case"zcode":case"opencode":return"spawn-cwd";case"pi":return"pi:ctx.cwd"}}function Xe(e){return e===void 0||e===""?void 0:e}function Zf(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return Xe(t.env.CLAUDE_PROJECT_DIR)??Xe(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return Xe(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(it);return n<0?void 0:Xe(t.argv[n+1])}case"pi:ctx.cwd":return Xe(t.piCwd)}}function e0(e){let t;try{t=jc.native(e)}catch{throw new T("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=t0(Ke(t,En));if(o!==null){let s=Bc(Ke(o,hr));return{commonDir:jc.native(s===null?o:Gc(o,s)),worktree:t,start:n}}let r=Vt(t);if(r===t)return{commonDir:null,start:n};t=r}}function t0(e){let t;try{if(Jf(e).isDirectory())t=e;else{let n=Bc(e);if(n===null||!n.startsWith(mn))return null;t=Gc(Vt(e),n.slice(mn.length))}}catch{return null}return Vf(Ke(t,Sr))?t:null}function Bc(e){let t;try{t=zf(e,"utf8")}catch{return null}let n=t.indexOf(`
30
- `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function n0(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(`
31
- `).filter(r=>r!=="")}function o0(e,t){let n=$f(t)===En?Vt(t):t,o=n0(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(gn)).map(r=>r.slice(gn.length));return Fc([Vt(n),...o])}function Wc(e,t){let n=Qf(e),o=Zf(n,t);if(o===void 0)throw new T("NO_PROJECT",{kind:n});let r=e0(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??=vc(i).slice(0,Er),a},get projectDir(){return l??=Ke(uc(process.env),gr,this.projectKey),l},get dbPath(){return Ke(this.projectDir,mr)},worktree:c,get containmentRoot(){return u??=s??o0(o,i),u},agent:e,source:n}}var zt=Re,r0=`
24
+ `)d(),x++;else if(_d.includes(p))l(),x++;else if(p===";")d(),x++;else if(p==="|")g==="|"?(d(),x+=Ht):(u(),x++);else if(p==="&")g==="&"?(d(),x+=Ht):((s||o.words.length>0)&&f(p,!1),x++);else if(p==="#"&&!s)for(;x<a&&e.charAt(x)!==`
25
+ `;)x++;else if(p===">"){let E=nc;s&&i&&Sd(r)?(E=r,r="",s=!1):s&&l();let h=x+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<a&&!lo.includes(e.charAt(h));)h++;else c=E===nc||E===rc?"file":"skip";x=h}else if(p==="("&&s&&i&&r.includes(uo)){let E=je(e,x),h=e.slice(x+1,E<0?a:E);l();for(let S of h.trim()===""?[]:hd(h)){let _=sc(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}x=E<0?a:E+1,x<a&&!lo.includes(e.charAt(x))&&(o.chained=!0,x=md(e,x))}else if(p==="["&&!s&&e.startsWith(uo,je(e,x)+1)&&je(e,x)>=0){let E=je(e,x);f(e.slice(x,E+1),!1),x=E+1}else if(Ge.includes(p)&&(p!=="["||!s)||(p==="$"||p==="@")&&Ge.includes(g)&&g!=="["){let E=p==="$"||p==="@"?x+1:x,h=je(e,E);f(e.slice(x,h<0?a:h+1),!0),x=h<0?a:h+1}else f(p,!1),x++}return d(),t}var bd=["get-content","gc","cat","type"],Od=["[io.file]::","[system.io.file]::"],Td=["readalltext","readalllines","readallbytes","readlines"],po=["path","literalpath"],ic=["totalcount","head","first","tail","last"],cc=[...po,...ic,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],Rd=["raw","wait","force","asbytestream"],Ad=[...cc,...Rd],Nd=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],yd=["cd","chdir","sl","set-location","pushd","push-location"],Cd=["powershell","powershell.exe","pwsh","pwsh.exe"],Id=["cmd","cmd.exe"],kd=["/c","/k","/r"],Dd="command",ie="-";function fo(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function _o(e,t){let n=e.slice(ie.length),o=n.indexOf(":"),r=(o<0?n:n.slice(0,o)).toLowerCase(),s=o<0?void 0:n.slice(o+1);if(r==="")return{full:void 0,inline:s};if(t.includes(r))return{full:r,inline:s};let i=t.filter(c=>c.startsWith(r));return{full:i.length===1?i[0]:void 0,inline:s}}function Ld(e){if(e.length===0)return null;let t=fo(e[0]);if(!bd.includes(t)){let r=e[0].toLowerCase(),s=Od.find(i=>r.startsWith(i));return s===void 0||!Td.includes(r.slice(s.length))||e.length<Ed?null:{file:e[1],bounded:!1}}let n=[],o=!1;for(let r=1;r<e.length;r++){let s=e[r];if(!s.startsWith(ie)||s.length===ie.length){n.push(s);continue}let i=_o(s,Ad);if(i.full===void 0||!cc.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;po.includes(i.full)&&n.push(c),ic.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function wd(e,t){if(Cd.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(ie)||o.length===ie.length)continue;let r=_o(o,[Dd]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(Id.includes(e)){for(let n=1;n<t.length;n++)if(kd.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function Pd(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(ie)||n.length===ie.length)return n;let o=_o(n,po);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function ac(e,t,n,o){let r=t;for(let s of sc(e)){let i=s[0];if(i.words.length===0)continue;let c=fo(i.words[0]);if(s.length===1&&yd.includes(c)){let d=Pd(i.words);d!==null&&(r=tc(r,d));continue}let a=n<H?wd(c,i.words):null;if(a!==null){ac(a,r,n+1,o);continue}if(i.toFile||i.chained)continue;let l=Ld(i.words);if(l===null||l.bounded)continue;let u=!0;for(let d=1;d<s.length;d++)if(s[d].toFile||!Nd.includes(fo(s[d].words[0]??""))){u=!1;break}u&&o.push(tc(r,l.file))}}function lc(e,t){let n=[];return ac(e,t,0,n),n}import{join as Bt}from"node:path";var uc=`\r
26
+ `,Md=`
27
+ `;function Gt(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(uc)<0?t:t.split(uc).join(Md)}import{basename as cE,dirname as aE,join as dc,posix as lE,resolve as uE,win32 as dE}from"node:path";var Ud=Object.freeze({NODE_TOO_OLD:"Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",NO_SQLITE:"node:sqlite failed to load. Fix: run ctx_doctor.",DB_GONE:"context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",NO_PROJECT:"Project source <kind> is missing. Fix: run ctx_doctor.",UNKNOWN_FIELD:'Unknown field "<f>". Fix: use "queries".',TIMEOUT:"Timed out after <ms> ms. Fix: pass background: true.",NO_GIT_BASH:"Git Bash not found. Fix: install Git for Windows.",NO_RUNTIME:"No <lang> runtime on PATH. Fix: install it or pick another language.",FETCH_FAILED:"Fetch failed: <code>. Fix: check the URL or proxy.",SSRF:"Blocked private address <host>. Fix: use a public URL.",OUTSIDE_ROOT:"Path <p> is outside the project. Fix: use a path inside <root>.",INVALID_ARGS:"Invalid argument <field>. Fix: <action>.",ONE_OF_INPUT:"Pass exactly one of <names>. Fix: drop the extra field.",SPAWN_FAILED:"Failed to start the process: <detail>. Fix: check the command and PATH.",DB_CORRUPT:"context.db failed integrity_check. Fix: run ctx_doctor.",SCHEMA_STALE:"context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.",NO_GIT_DIR:"No git repository at <path>. Fix: run context-mode inside a git repository.",NO_HOME:"Env var <name> is not set. Fix: set <name> to your home directory.",PLUGIN_ROOT_MISSING:"Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.",BUNDLE_HASH_MISMATCH:"Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.",CONFIG_PARSE_FAILED:"<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade."});function Hd(e,t){let n=Ud[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(Hd(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{mkdirSync:Fd,realpathSync:vd}=process.getBuiltinModule("node:fs");function me(e,t=process.platform){let n=o=>o!==void 0&&o!=="";return t==="win32"?n(e.USERPROFILE)?e.USERPROFILE:n(e.HOMEDRIVE)&&n(e.HOMEPATH)?e.HOMEDRIVE+e.HOMEPATH:n(e.HOME)?e.HOME:null:n(e.HOME)?e.HOME:n(e.USERPROFILE)?e.USERPROFILE:null}function Be(e,t){let n=e[ht];return n!==void 0&&n!==""?n:dc(t,...Ts["claude-code"])}function jd(e,t=process.platform){let n=me(e,t);if(n!==null)return n;throw new T("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function fc(e){let t=dc(jd(e),ct.slice(1));return Fd(t,{recursive:!0}),vd.native(t)}var{readFileSync:Ec}=process.getBuiltinModule("node:fs");function he(e){return e.agentId!==void 0&&e.agentId!==""}function mo(e,t){if(t===null)return"C";let n=re(e.agent),o=new Set(t);for(let r of ot)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function ho(e,t){if(!he(e))return null;let n=re(e.agent);if(t.manifestTools!==void 0)return _c(t.manifestTools.map(c=>Eo(n,c)));let o=e.agentType??"",r=Gd(o,t);if(r===null)return null;let s=(r.tools??qd(n)).map(c=>Eo(n,c)),i=r.disallowed.map(c=>Eo(n,c));return _c(s.filter(c=>!i.some(a=>Vd(a,c))))}function Gd(e,t){if(!Bd(e))return null;let n=Wd(t.env);if(e.indexOf(de)>=0){if(n!==null){let s=Xd(Be(t.env,n),e);if(s!==null)return s}}else{let s=go(Bt(t.projectDir,Rr,at,e+lt));if(s!==null)return s;if(n!==null){let i=go(Bt(Be(t.env,n),at,e+lt));if(i!==null)return i}}let r=t.cliAgents;if(r!==void 0&&Object.prototype.hasOwnProperty.call(r,e)){let s=r[e];return{tools:Array.isArray(s.tools)?s.tools:null,disallowed:Array.isArray(s.disallowedTools)?s.disallowedTools:[]}}return null}function Bd(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 Wd(e){return me(e)}function Xd(e,t){let n=t.indexOf(de),o=t.slice(0,n),r=t.slice(n+de.length);if(r.indexOf(de)>=0)return null;let s;try{s=JSON.parse(Gt(Ec(Bt(e,hn,Ar),"utf8")))}catch{return null}let i=s?.plugins;if(i===null||typeof i!="object")return null;for(let c of Object.keys(i)){let a=c.indexOf(Nr);if((a<0?c:c.slice(0,a))!==o)continue;let l=i[c];if(Array.isArray(l))for(let u of l){let d=u?.installPath;if(typeof d!="string"||d==="")continue;let f=go(Bt(d,at,r+lt));if(f!==null)return f}}return null}function go(e){let t;try{t=Ec(e,"utf8")}catch{return null}return Kd(t)}function Kd(e){let t=e.split(`
28
+ `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Sn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Sn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=xc(o,yr),s=xc(o,Cr);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function xc(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(t+":"))continue;let r=o.slice(t.length+1).trim();if(r===""){let s=[];for(let i=n+1;i<e.length;i++){let c=e[i].trim();if(!c.startsWith("-"))break;s.push(pc(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>pc(s.trim())).filter(s=>s!=="")}return null}function pc(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function qd(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...ot.map(n=>e.toolNamePrefix+n)]}function Eo(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(Ir)?Yd(o):o}function Yd(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||kr.indexOf(n)>=0;t+=o?n:"_"}return t}function Vd(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(bn)){let n=e.slice(bn.length);if(n!==""&&n.indexOf(On)<0)return t.startsWith(e+On)}return!1}function _c(e){return[...new Set(e.filter(t=>t!==""))]}var ce="",gc=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:ce},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:ce},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:ce},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:ce},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:ce},command:{valueShorts:ce,valueLongs:[],assignments:!1,duration:!1,refuseShorts:"vV"},xargs:{valueShorts:"aEdILnPs",valueLongs:["--arg-file","--delimiter","--max-args","--max-procs","--max-chars"],assignments:!1,duration:!1,refuseShorts:ce}}),zd=["bash","sh","zsh"],Jd="c",$d=" -c",Qd=["-o","+o","-O","+O"],Wt="-",Zd="+",So="--",ef="smhd",tf=".",mc=e=>e!==""&&e>="0"&&e<="9";function nf(e){if(e===""||!mc(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(mc(n)||n===tf))return t===e.length-1&&ef.includes(n)}return!0}function of(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===So){n++;break}if(e.assignments&&Pt(o)){n++;continue}if(o.startsWith(So)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(Wt)&&o.length>Wt.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=Wt.length;r<o.length;r++)if(e.valueShorts.includes(o.charAt(r))){r===o.length-1&&n++;break}continue}break}if(e.duration){if(n>=t.length||!nf(t[n]))return null;n++}return n<t.length?t.slice(n):null}function rf(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(So)){if(o.startsWith(Wt)||o.startsWith(Zd)){o.includes(Jd)&&(t=!0),Qd.includes(o)&&n++;continue}return t?o:null}}return null}function hc(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function bo(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let a=s.toLowerCase();if(zd.includes(a)){let d=rf(i),f=d!==null&&n<H?ve(d):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=hc(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,bo(p,[...r,a+$d],n+1,o)}return}let l=Object.hasOwn(gc,a)?gc[a]:void 0,u=l===void 0?null:of(l,i);if(u===null)break;r.push(a),s=io(u[0]),i=u.slice(1),c=c||co(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=H))for(let a of wt(e.raw)){let l=ve(a.body);if(l.ok)for(let u of l.commands)bo(hc(u,e),[...t,a.wrapper],n+1,o)}}function Sc(e){let t=[];for(let n of e)bo(n,[],0,t);return t}import{isAbsolute as cf,join as Oo,relative as af,sep as To}from"node:path";var{readFileSync:sf}=process.getBuiltinModule("node:fs"),bc=".claude",lf="settings.local.json",Oc="settings.json",uf="Bash",df="Read",Tc=":*",Rc="//",Ac="~/",Nc="./",yc="..",ff=`
29
+ \r`,xf=Object.freeze({tool:uf});function pf(e,t){if(t!=="claude-code")return[];let n=me(process.env),o=process.env[ht],r=o!==void 0&&o!==""?o:n===null?null:Be(process.env,n),s=[Oo(e,bc,lf),Oo(e,bc,Oc)];return r===null?s:[...s,Oo(r,Oc)]}function Cc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _f(e){let t;try{t=Gt(sf(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Cc(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Cc(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 Ic(e,t){let n=[];for(let o of pf(e,t)){let r=_f(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function Ef(e,t){let n=[],o=0;for(;o<e.length;){let r=e[o];if(r==="*"&&t&&e[o+1]==="*"){let s=e[o+2]==="/";n.push({t:s?"globstarDir":"globstar"}),o+=s?3:2;continue}r==="*"?(n.length===0||n[n.length-1].t!=="star")&&n.push({t:"star"}):r==="?"?n.push({t:"any1"}):n.push({t:"lit",c:r}),o++}return n}function V(e,t,n){let o=Ef(e,n),r=t.length,s=new Uint8Array(r+1);s[r]=1;for(let i=o.length-1;i>=0;i--){let c=o[i],a=new Uint8Array(r+1),l=0;for(let u=r;u>=0;u--){let d=u<r,f=d?t[u]:"";switch(c.t){case"lit":a[u]=d&&f===c.c?s[u+1]:0;break;case"any1":a[u]=d&&!(n&&f==="/")?s[u+1]:0;break;case"star":a[u]=s[u]||(d&&!(n&&f==="/")?a[u+1]:0);break;case"globstar":a[u]=s[u]||(d?a[u+1]:0);break;case"globstarDir":d&&f==="/"&&s[u+1]&&(l=1),a[u]=s[u]||l;break}}s=a}return s[0]===1}function gf(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 mf(e,t){if(!e.endsWith(Tc))return V(e,t,!1);let n=e.slice(0,e.length-Tc.length);if(V(n,t,!1))return!0;for(let o=0;o<t.length;o++)if(ff.includes(t[o])&&V(n,t.slice(0,o),!1))return!0;return!1}var hf=/^[A-Za-z]:(?=\/)/;function We(e){return To==="/"?e:e.split(To).join("/")}function Sf(e,t,n){if(e.startsWith(Nc)){if(n===void 0)return!1;let r=af(n,t);return r===""||r===yc||r.startsWith(yc+To)||cf(r)?!1:V(e.slice(Nc.length),We(r),!0)}let o=We(t);if(e.startsWith(Rc)){let r=We(e.slice(Rc.length-1));return V(r,o,!0)||V(r,o.replace(hf,""),!0)}if(e.startsWith(Ac)){let r=me(process.env);return r!==null&&V(We(r)+e.slice(Ac.length-1),o,!0)}return V(We(e),o,!0)}function z(e,t,n=xf){for(let o of t){let r=gf(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===df?Sf(r.glob,e,n.projectDir):mf(r.glob,e))return o}return null}var kE=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.'}),kc='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var bf="{size}",Of="{path}";function Xt(e,t,n=""){return k(kc,n).split(bf).join(String(t)).split(Of).join(e)}var{statSync:Tf}=process.getBuiltinModule("node:fs"),Pc="Bash",Ao="Read",Rf="WebFetch",Af="ctx_execute",Nf="ctx_batch",Mc="shell",yf="1",J="-",No="--",Cf="=",If=".",Dc=",",Ro="p",kf=["-e","--expression"],Df=";&|(`\n\r",le=Object.freeze({kind:"allow"}),G=e=>({kind:"deny",reason:e}),ae=e=>typeof e=="string"?e:void 0,Lc=e=>e!=null,$=(e,t)=>e.includes(t);function Uc(e,t,n){let o=e.tool;if(o===void 0)return le;let r=o.canonicalName,s=o.input,i;if(n===null){if(process.env[Tr]===yf)return G(k(ut,t.toolNamePrefix));process.stderr.write(Vr+`
30
+ `),i=[]}else i=n;let c=Lf(r,s,e.cwd,i);return c!==null?G(Ne+c):r===Rf?Uf(s,t):r===Pc?Hf(e,t,s,i):r===Ao?Wf(e,t,s):le}function Hc(e,t,n,o){let r=e==="webfetch",s=r?Hr.map(c=>n.toolNamePrefix+c).join(Yr):n.toolNamePrefix+Ur,i=JSON.stringify(r?{url:t}:{language:Mc,code:t,intent:o??Mr});return[Tn+Dr[e]+Lr,wr,Pr+s,i].join(`
31
+ `)}function Fc(e){for(let t of xt){let n=ae(e[t]);if(n!==void 0&&n!=="")return n}}function Lf(e,t,n,o){if(o.length===0)return null;let r=s=>z(qt(n,s),o,{tool:Ao,projectDir:n});if(e===Pc){let s=ae(t.command);return s===void 0?null:z(s,o)}if(e===Ao){let s=Fc(t);return s===void 0?null:r(s)}if(e===Af){let s=ae(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=ae(t.code);return t.language===Mc&&c!==void 0?z(c,o):null}if(e===Nf&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?z(s,o):null;if(i!==null)return i}return null}function wf(e,t){return t.length===0?null:z([e.argv0,...e.args].join(" "),t)??z(e.raw,t)}function Pf(e,t){if(t.length===0)return!1;for(let n=0;n<=e.length;n++)if(!(n>0&&!Df.includes(e.charAt(n-1)))&&z(e.slice(n).trimStart(),t)!==null)return!0;return!1}function Mf(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return zr.some(n=>t===n||t.endsWith(If+n))}function Uf(e,t){let n=ae(e.url)??"";return Mf(n)?le:G(Hc("webfetch",n,t))}function Hf(e,t,n,o){let r=ae(n.command)??"",s=ve(r);if(!s.ok)return Pf(r,o)?G(k(dt,t.toolNamePrefix)):wc(r,e.cwd,t)??le;let i=Sc(s.commands);for(let c of i){let a=wf(c,o);if(a!==null)return G(Ne+a)}if(!Le(t)||he(e))for(let c of i){let a=Ff(c);if(a!==null)return G(Hc(a,r,t,ae(n.description)))}return Xf(i,e.cwd,t)??wc(r,e.cwd,t)??le}function Ff(e){let t=e.argv0.toLowerCase();return $(Jr,t)&&vf(t,e)?"curl":Gf(e.raw)?"http":$(es,t)?"build":null}function vf(e,t){return t.redirectsToFile?!jf(e,t.args):!t.endsInBoundedSink}function jf(e,t){let n=$r[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===No)break;if($(Qr,s)||s===Zr&&t[r+1]===J)return!1;(s===n.long||s.startsWith(J)&&!s.startsWith(No)&&s.includes(n.short,J.length))&&(o=!0)}return o}function Gf(e){let t=e.toLowerCase();for(let n of os)if(t.includes(n))return!0;for(let n=t.indexOf(Ce);n>=0;n=t.indexOf(Ce,n+1)){let o=t.charAt(n+Ce.length);if(o!==""&&ts.includes(o)&&t.startsWith(ns,n+Ce.length+o.length))return!0}return!1}var Bf="cd";function yo(e){try{let t=Tf(e);return t.isFile()?t.size:-1}catch{return-1}}function Wf(e,t,n){if(!Lc(n.offset)&&!Lc(n.limit)){let o=Fc(n);if(o!==void 0){let r=qt(e.cwd,o),s=yo(r);if(s>q)return G(Xt(r,s,t.toolNamePrefix))}}return le}function Xf(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&zn(n))return null;let o=t,r=null;for(let s of e){let i=s.argv0.toLowerCase();if(i===Bf&&s.args.length===1&&s.insideConstruct===void 0&&(o=qt(o,s.args[0])),s.redirectsToFile||s.endsInBoundedSink||s.pipesOut===!0||s.insideConstruct!==void 0||!$(rs,i))continue;let c=Yf(i,s.args);if(c===null)continue;if(c.bounded){r=le;continue}let a=qt(o,c.file),l=yo(a);if(l>q)return G(Xt(a,l,n.toolNamePrefix))}return r}function wc(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&zn(n))return null;for(let o of lc(e,t)){let r=yo(o);if(r>q)return G(Xt(o,r,n.toolNamePrefix))}return null}var Kt=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function Kf(e){if($(An,e))return 1;for(let t of An)if(t.startsWith(No)?e.startsWith(t+Cf):e.startsWith(t))return 0;return e.startsWith(J)&&Kt(e.slice(J.length))?0:-1}function qf(e){if(e===Ro)return"all";if(!e.endsWith(Ro))return null;let t=e.slice(0,e.length-Ro.length),n=t.indexOf(Dc);return(n<0?Kt(t):Kt(t.slice(0,n))&&Kt(t.slice(n+Dc.length)))?"range":null}function Yf(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if($(ss,e)){let a=Kf(c);if(a>=0){o=!0,i+=a;continue}}if(e===ft&&$(is,c)){r=!0;continue}if(e===ft&&$(kf,c)){s=t[i+1],i++;continue}c.startsWith(J)&&c!==J||n.push(c)}if(e===ft){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:qf(s);if(i===null)return null;o=i==="range"}return e===cs&&n.shift()!==D.identity?null:n.length===1&&n[0]!==J?{file:n[0],bounded:o}:null}import{basename as n0,dirname as Vt,join as Ke,resolve as Wc}from"node:path";import{dirname as vc,sep as zf}from"node:path";var{realpathSync:Vf}=process.getBuiltinModule("node:fs");function Jf(e){try{return Vf.native(e)}catch{return}}function Yt(e){return e.split(zf).filter(t=>t!=="")}function jc(e){let t=e.map(Jf).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=Yt(n).length;for(let s of t){let i=Yt(s),c=Yt(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;Yt(r).length>o&&vc(r)!==r;)r=vc(r);return r}var $f=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]),Qf=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],w=(e,t)=>e>>>t|e<<32-t;function Gc(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=Qf.slice(),i=new Uint32Array(64);for(let c=0;c<o;c+=64){for(let E=0;E<16;E++)i[E]=r.readUInt32BE(c+E*4);for(let E=16;E<64;E++){let h=w(i[E-15],7)^w(i[E-15],18)^i[E-15]>>>3,S=w(i[E-2],17)^w(i[E-2],19)^i[E-2]>>>10;i[E]=i[E-16]+h+i[E-7]+S>>>0}let[a,l,u,d,f,x,p,g]=s;for(let E=0;E<64;E++){let h=g+(w(f,6)^w(f,11)^w(f,25))+(f&x^~f&p)+$f[E]+i[E]>>>0,S=(w(a,2)^w(a,13)^w(a,22))+(a&l^a&u^l&u)>>>0;g=p,p=x,x=f,f=d+h>>>0,d=u,u=l,l=a,a=h+S>>>0}s[0]=s[0]+a>>>0,s[1]=s[1]+l>>>0,s[2]=s[2]+u>>>0,s[3]=s[3]+d>>>0,s[4]=s[4]+f>>>0,s[5]=s[5]+x>>>0,s[6]=s[6]+p>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:Zf,readFileSync:e0,realpathSync:Bc,statSync:t0}=process.getBuiltinModule("node:fs");function o0(e){switch(e){case"claude-code":return"env:CLAUDE_PROJECT_DIR";case"codex":case"copilot-cli":case"kiro":return"arg:--agent+cwd";case"vscode":return"arg:workspaceFolder";case"gemini":case"qwen":case"zcode":case"opencode":return"spawn-cwd";case"pi":return"pi:ctx.cwd"}}function Xe(e){return e===void 0||e===""?void 0:e}function r0(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return Xe(t.env.CLAUDE_PROJECT_DIR)??Xe(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return Xe(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(it);return n<0?void 0:Xe(t.argv[n+1])}case"pi:ctx.cwd":return Xe(t.piCwd)}}function s0(e){let t;try{t=Bc.native(e)}catch{throw new T("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=i0(Ke(t,En));if(o!==null){let s=Xc(Ke(o,Sr));return{commonDir:Bc.native(s===null?o:Wc(o,s)),worktree:t,start:n}}let r=Vt(t);if(r===t)return{commonDir:null,start:n};t=r}}function i0(e){let t;try{if(t0(e).isDirectory())t=e;else{let n=Xc(e);if(n===null||!n.startsWith(mn))return null;t=Wc(Vt(e),n.slice(mn.length))}}catch{return null}return Zf(Ke(t,br))?t:null}function Xc(e){let t;try{t=e0(e,"utf8")}catch{return null}let n=t.indexOf(`
32
+ `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function c0(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(`
33
+ `).filter(r=>r!=="")}function a0(e,t){let n=n0(t)===En?Vt(t):t,o=c0(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(gn)).map(r=>r.slice(gn.length));return jc([Vt(n),...o])}function Kc(e,t){let n=o0(e),o=r0(n,t);if(o===void 0)throw new T("NO_PROJECT",{kind:n});let r=s0(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??=Gc(i).slice(0,gr),a},get projectDir(){return l??=Ke(fc(process.env),mr,this.projectKey),l},get dbPath(){return Ke(this.projectDir,hr)},worktree:c,get containmentRoot(){return u??=s??a0(o,i),u},agent:e,source:n}}var zt=Re,l0=`
32
34
  PRAGMA busy_timeout = ${ue};
33
35
  PRAGMA journal_mode = WAL;
34
- `,Jt="tokenize = 'porter unicode61 remove_diacritics 2'",s0="tokenize = 'unicode61 remove_diacritics 2'",i0=`
36
+ `,Jt="tokenize = 'porter unicode61 remove_diacritics 2'",u0="tokenize = 'unicode61 remove_diacritics 2'",d0=`
35
37
  CREATE TABLE IF NOT EXISTS events (
36
38
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
37
39
  session_id TEXT NOT NULL,
@@ -76,16 +78,16 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
76
78
  agent UNINDEXED,
77
79
  ord UNINDEXED,
78
80
  body,
79
- ${s0}
81
+ ${u0}
80
82
  );
81
83
 
82
84
  CREATE TABLE IF NOT EXISTS meta (
83
85
  key TEXT PRIMARY KEY,
84
86
  value TEXT NOT NULL
85
87
  );
86
- `,c0=`
88
+ `,f0=`
87
89
  CREATE UNIQUE INDEX IF NOT EXISTS idx_events_cost_session_turn ON events(session_id, turn) WHERE kind = 'cost';
88
- `,a0=`
90
+ `,x0=`
89
91
  CREATE VIRTUAL TABLE chunks_v3 USING fts5(
90
92
  source_id UNINDEXED,
91
93
  session_id UNINDEXED,
@@ -100,7 +102,7 @@ INSERT INTO chunks_v3(rowid, source_id, session_id, worktree, agent, ord, body,
100
102
  SELECT rowid, source_id, session_id, worktree, agent, ord, body, '' FROM chunks;
101
103
  DROP TABLE chunks;
102
104
  ALTER TABLE chunks_v3 RENAME TO chunks;
103
- `,l0=`
105
+ `,p0=`
104
106
  CREATE VIRTUAL TABLE chunks_tri USING fts5(
105
107
  body,
106
108
  title,
@@ -109,7 +111,7 @@ CREATE VIRTUAL TABLE chunks_tri USING fts5(
109
111
  );
110
112
  INSERT INTO chunks_tri(rowid, body, title) SELECT rowid, body, title FROM chunks;
111
113
  CREATE VIRTUAL TABLE chunks_vocab USING fts5vocab(chunks, 'row');
112
- `,u0=`
114
+ `,_0=`
113
115
  CREATE VIRTUAL TABLE line_units USING fts5(
114
116
  body,
115
117
  source_id UNINDEXED,
@@ -117,16 +119,16 @@ CREATE VIRTUAL TABLE line_units USING fts5(
117
119
  ord UNINDEXED,
118
120
  ${Jt}
119
121
  );
120
- `,d0=`
122
+ `,E0=`
121
123
  UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
122
- `,f0=[{version:1,sql:i0},{version:2,sql:c0},{version:3,sql:a0},{version:4,sql:l0},{version:5,sql:u0},{version:6,sql:d0}];function yo(e,t){if(t!==zt){if(t>zt)throw new T("SCHEMA_STALE",{found:t,want:zt});e.exec(r0),e.exec("BEGIN IMMEDIATE");try{for(let n of f0)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${zt}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}var{existsSync:qe,linkSync:x0,mkdirSync:p0,rmSync:_0}=process.getBuiltinModule("node:fs");function Xc(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function E0(e,t){let n=Xc(e),o=Xc(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 g0(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&xr;return n===pr||n===_r}async function m0(){try{return await import("node:sqlite")}catch{throw new T("NO_SQLITE")}}function Co(e){return e.prepare("PRAGMA user_version").get().user_version}function h0(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+fr;try{let r=new e.DatabaseSync(o,{timeout:ue});try{yo(r,Co(r))}finally{r.close()}try{x0(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",rt,st])_0(o+r,{force:!0})}}function Kc(e,t){let n=null;try{return qe(t)||h0(e,t),n=new e.DatabaseSync(t,{timeout:ue}),yo(n,Co(n)),n}catch(o){throw n&&n.close(),o}}function S0(e,t){let n=new e.DatabaseSync(t,{timeout:ue,readOnly:!0});try{let o=Co(n);if(o!==Re)throw new T("SCHEMA_STALE",{found:o,want:Re});return n}catch(o){throw n.close(),o}}async function A(e,t){if(E0(process.version,Ae))throw new T("NODE_TOO_OLD",{v:process.version});let n=await m0();p0(e.projectDir,{recursive:!0});let o=e.dbPath;if((qe(o+rt)||qe(o+st))&&!qe(o))throw new T("DB_GONE");try{let s;return t?.readOnly===!0?(qe(o)||Kc(n,o).close(),s=S0(n,o)):s=Kc(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw g0(s)?new T("DB_CORRUPT"):s}}function P(e,t){e.raw.exec("BEGIN IMMEDIATE");try{let n=t(e);return e.raw.exec("COMMIT"),n}catch(n){throw e.raw.isTransaction&&e.raw.exec("ROLLBACK"),n}}function qc(e,t){return e.raw.isTransaction?t(e):P(e,t)}function $(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function B(e,t,n){qc(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function $t(e,t){return qc(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var Yc="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",b0="INSERT INTO "+Yc,O0="INSERT OR IGNORE INTO "+Yc,T0="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function Qt(e,t){return P(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?O0:b0).run(t.session_id,t.worktree,t.agent,t.kind,t.tool,t.key,t.path,t.ok,t.exit_code,t.bytes,t.body,t.turn,t.sandbox_bytes,t.returned_bytes,o,o);return s.changes===1?Number(s.lastInsertRowid):n.raw.prepare(T0).get(t.session_id,t.turn).seq})}function Vc(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 Io(e,t,n){return t===""?[]:n===void 0?e.raw.prepare("SELECT * FROM events WHERE session_id = ? ORDER BY seq ASC").all(t):e.raw.prepare("SELECT * FROM events WHERE session_id = ? AND kind = ? ORDER BY seq ASC").all(t,n)}function zc(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq DESC LIMIT 1").get(t);return n===void 0?"":n.body}function Jc(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq ASC LIMIT 1").get(t);return n===void 0?"":n.body}function $c(e,t,n,o){return t===""?[]:e.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND (session_id = ? OR worktree = ?) ORDER BY seq DESC LIMIT ?").all(t,n,o)}function Qc(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function Zc(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var ko=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 R0(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=ko.length/2-1;for(;t<=n;){let o=t+n>>1,r=ko[2*o],s=ko[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function A0(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 Se(e){return A0(e,t=>!R0(t))}var N0=`
124
+ `,g0=[{version:1,sql:d0},{version:2,sql:f0},{version:3,sql:x0},{version:4,sql:p0},{version:5,sql:_0},{version:6,sql:E0}];function Co(e,t){if(t!==zt){if(t>zt)throw new T("SCHEMA_STALE",{found:t,want:zt});e.exec(l0),e.exec("BEGIN IMMEDIATE");try{for(let n of g0)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${zt}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}var{existsSync:qe,linkSync:m0,mkdirSync:h0,rmSync:S0}=process.getBuiltinModule("node:fs");function qc(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function b0(e,t){let n=qc(e),o=qc(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 O0(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&pr;return n===_r||n===Er}async function T0(){try{return await import("node:sqlite")}catch{throw new T("NO_SQLITE")}}function Io(e){return e.prepare("PRAGMA user_version").get().user_version}function R0(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+xr;try{let r=new e.DatabaseSync(o,{timeout:ue});try{Co(r,Io(r))}finally{r.close()}try{m0(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",rt,st])S0(o+r,{force:!0})}}function Yc(e,t){let n=null;try{return qe(t)||R0(e,t),n=new e.DatabaseSync(t,{timeout:ue}),Co(n,Io(n)),n}catch(o){throw n&&n.close(),o}}function A0(e,t){let n=new e.DatabaseSync(t,{timeout:ue,readOnly:!0});try{let o=Io(n);if(o!==Re)throw new T("SCHEMA_STALE",{found:o,want:Re});return n}catch(o){throw n.close(),o}}async function A(e,t){if(b0(process.version,Ae))throw new T("NODE_TOO_OLD",{v:process.version});let n=await T0();h0(e.projectDir,{recursive:!0});let o=e.dbPath;if((qe(o+rt)||qe(o+st))&&!qe(o))throw new T("DB_GONE");try{let s;return t?.readOnly===!0?(qe(o)||Yc(n,o).close(),s=A0(n,o)):s=Yc(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw O0(s)?new T("DB_CORRUPT"):s}}function P(e,t){e.raw.exec("BEGIN IMMEDIATE");try{let n=t(e);return e.raw.exec("COMMIT"),n}catch(n){throw e.raw.isTransaction&&e.raw.exec("ROLLBACK"),n}}function Vc(e,t){return e.raw.isTransaction?t(e):P(e,t)}function Q(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function B(e,t,n){Vc(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function $t(e,t){return Vc(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var zc="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",N0="INSERT INTO "+zc,y0="INSERT OR IGNORE INTO "+zc,C0="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function Qt(e,t){return P(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?y0:N0).run(t.session_id,t.worktree,t.agent,t.kind,t.tool,t.key,t.path,t.ok,t.exit_code,t.bytes,t.body,t.turn,t.sandbox_bytes,t.returned_bytes,o,o);return s.changes===1?Number(s.lastInsertRowid):n.raw.prepare(C0).get(t.session_id,t.turn).seq})}function Jc(e,t){let n="",o="",r=!1,s=!1;for(let i of t){if(o===""&&!r&&i.trim()===""){s=n!=="";continue}s&&(n+=" ",s=!1),n+=i,r?r=!1:i==="\\"&&o!=="'"?r=!0:o===""&&(i==="'"||i==='"')?o=i:i===o&&(o="")}return e+":"+n}function ko(e,t,n){return t===""?[]:n===void 0?e.raw.prepare("SELECT * FROM events WHERE session_id = ? ORDER BY seq ASC").all(t):e.raw.prepare("SELECT * FROM events WHERE session_id = ? AND kind = ? ORDER BY seq ASC").all(t,n)}function $c(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 Qc(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq ASC LIMIT 1").get(t);return n===void 0?"":n.body}function Zc(e,t,n,o){return t===""?[]:e.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND (session_id = ? OR worktree = ?) ORDER BY seq DESC LIMIT ?").all(t,n,o)}function ea(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function ta(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var Do=Object.freeze([170,170,178,179,181,181,185,186,188,190,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,895,895,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1327,1329,1366,1369,1369,1376,1416,1488,1514,1519,1522,1568,1610,1632,1641,1646,1647,1649,1747,1749,1749,1765,1766,1774,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1984,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2144,2154,2160,2183,2185,2191,2208,2249,2308,2361,2365,2365,2384,2384,2392,2401,2406,2415,2417,2432,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2534,2545,2548,2553,2556,2556,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2662,2671,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2790,2799,2809,2809,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2918,2927,2929,2935,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3046,3058,3077,3084,3086,3088,3090,3112,3114,3129,3133,3133,3160,3162,3164,3165,3168,3169,3174,3183,3192,3198,3200,3200,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3292,3294,3296,3297,3302,3311,3313,3314,3332,3340,3342,3344,3346,3386,3389,3389,3406,3406,3412,3414,3416,3425,3430,3448,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3558,3567,3585,3632,3634,3635,3648,3654,3664,3673,3713,3714,3716,3716,3718,3722,3724,3747,3749,3749,3751,3760,3762,3763,3773,3773,3776,3780,3782,3782,3792,3801,3804,3807,3840,3840,3872,3891,3904,3911,3913,3948,3976,3980,4096,4138,4159,4169,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4240,4249,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4969,4988,4992,5007,5024,5109,5112,5117,5121,5740,5743,5759,5761,5786,5792,5866,5870,5880,5888,5905,5919,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6112,6121,6128,6137,6160,6169,6176,6264,6272,6276,6279,6312,6314,6314,6320,6389,6400,6430,6470,6509,6512,6516,6528,6571,6576,6601,6608,6618,6656,6678,6688,6740,6784,6793,6800,6809,6823,6823,6917,6963,6981,6988,6992,7001,7043,7072,7086,7141,7168,7203,7232,7241,7245,7293,7296,7306,7312,7354,7357,7359,7401,7404,7406,7411,7413,7414,7418,7418,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8304,8305,8308,8313,8319,8329,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8528,8585,9312,9371,9450,9471,10102,10131,11264,11492,11499,11502,11506,11507,11517,11517,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12591,12593,12686,12690,12693,12704,12735,12784,12799,12832,12841,12872,12879,12881,12895,12928,12937,12977,12991,13312,19903,19968,42124,42192,42237,42240,42508,42512,42539,42560,42606,42623,42653,42656,42735,42775,42783,42786,42888,42891,42972,42993,43009,43011,43013,43015,43018,43020,43042,43056,43061,43072,43123,43138,43187,43216,43225,43250,43255,43259,43259,43261,43262,43264,43301,43312,43334,43360,43388,43396,43442,43471,43481,43488,43492,43494,43518,43520,43560,43584,43586,43588,43595,43600,43609,43616,43638,43642,43642,43646,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43824,43866,43868,43881,43888,44002,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65296,65305,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500,65536,65547,65549,65574,65576,65594,65596,65597,65599,65613,65616,65629,65664,65786,65799,65843,65856,65912,65930,65931,66176,66204,66208,66256,66273,66299,66304,66339,66349,66378,66384,66421,66432,66461,66464,66499,66504,66511,66513,66517,66560,66717,66720,66729,66736,66771,66776,66811,66816,66855,66864,66915,66928,66938,66940,66954,66956,66962,66964,66965,66967,66977,66979,66993,66995,67001,67003,67004,67008,67059,67072,67382,67392,67413,67424,67431,67456,67461,67463,67504,67506,67514,67584,67589,67592,67592,67594,67637,67639,67640,67644,67644,67647,67669,67672,67702,67705,67742,67751,67759,67808,67826,67828,67829,67835,67867,67872,67897,67904,67929,67968,68023,68028,68047,68050,68096,68112,68115,68117,68119,68121,68149,68160,68168,68192,68222,68224,68255,68288,68295,68297,68324,68331,68335,68352,68405,68416,68437,68440,68466,68472,68497,68521,68527,68608,68680,68736,68786,68800,68850,68858,68899,68912,68921,68928,68965,68975,68997,69216,69246,69248,69289,69296,69297,69314,69319,69376,69415,69424,69445,69457,69460,69488,69505,69552,69579,69600,69622,69635,69687,69714,69743,69745,69746,69749,69749,69763,69807,69840,69864,69872,69881,69891,69926,69942,69951,69956,69956,69959,69959,69968,70002,70006,70006,70019,70066,70081,70084,70096,70106,70108,70108,70113,70132,70144,70161,70163,70187,70207,70208,70272,70278,70280,70280,70282,70285,70287,70301,70303,70312,70320,70366,70384,70393,70405,70412,70415,70416,70419,70440,70442,70448,70450,70451,70453,70457,70461,70461,70480,70480,70493,70497,70528,70537,70539,70539,70542,70542,70544,70581,70583,70583,70609,70609,70611,70611,70656,70708,70727,70730,70736,70745,70751,70753,70784,70831,70852,70853,70855,70855,70864,70873,71040,71086,71128,71131,71168,71215,71236,71236,71248,71257,71296,71338,71352,71352,71360,71369,71376,71395,71424,71450,71472,71483,71488,71494,71680,71723,71840,71922,71935,71942,71945,71945,71948,71955,71957,71958,71960,71983,71999,71999,72001,72001,72016,72025,72096,72103,72106,72144,72161,72161,72163,72163,72192,72192,72203,72242,72250,72250,72272,72272,72284,72329,72349,72349,72368,72440,72640,72672,72688,72697,72704,72712,72714,72750,72768,72768,72784,72812,72818,72847,72960,72966,72968,72969,72971,73008,73030,73030,73040,73049,73056,73061,73063,73064,73066,73097,73112,73112,73120,73129,73136,73179,73184,73193,73440,73458,73474,73474,73476,73488,73490,73523,73552,73561,73648,73648,73664,73684,73728,74649,74752,74862,74880,75075,77712,77808,77824,78895,78913,78918,78944,82938,82944,83526,90368,90397,90416,90425,92160,92728,92736,92766,92768,92777,92784,92862,92864,92873,92880,92909,92928,92975,92992,92995,93008,93017,93019,93025,93027,93047,93053,93071,93504,93548,93552,93561,93760,93846,93856,93880,93883,93907,93952,94026,94032,94032,94099,94111,94176,94177,94179,94179,94194,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,113664,113770,113776,113788,113792,113800,113808,113817,118e3,118009,119488,119507,119520,119539,119648,119672,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,120782,120831,122624,122654,122661,122666,122928,122989,123136,123180,123191,123197,123200,123209,123214,123214,123536,123565,123584,123627,123632,123641,124112,124139,124144,124153,124368,124397,124400,124410,124608,124638,124640,124642,124644,124645,124647,124653,124656,124660,124670,124671,124896,124902,124904,124907,124909,124910,124912,124926,124928,125124,125127,125135,125184,125251,125259,125259,125264,125273,126065,126123,126125,126127,126129,126132,126209,126253,126255,126269,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,127232,127244,130032,130041,131072,173791,173824,178205,178208,183981,183984,191456,191472,192093,194560,195101,196608,201546,201552,210041]);function I0(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=Do.length/2-1;for(;t<=n;){let o=t+n>>1,r=Do[2*o],s=Do[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function k0(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 Se(e){return k0(e,t=>!I0(t))}var D0=`
123
125
  INSERT INTO sources(session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts)
124
126
  VALUES (:session_id, :worktree, :agent, :kind, :label, :bytes_total, :chunk_count, :created_ts, :created_at, :created_ts)
125
- RETURNING id`,y0=`
126
- INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,ta=1,ea=" (raw)",na=`AND (:source IS NOT NULL OR substr(s.label, -${ea.length}) <> '${ea}')`,oa=`
127
+ RETURNING id`,L0=`
128
+ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,oa=1,na=" (raw)",ra=`AND (:source IS NOT NULL OR substr(s.label, -${na.length}) <> '${na}')`,sa=`
127
129
  SELECT chunks.rowid AS rid, chunks.source_id AS source_id, chunks.session_id AS session_id,
128
130
  chunks.worktree AS worktree, chunks.ord AS ord, s.created_ts AS created_ts,
129
- bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${ta}) AS bm,
131
+ bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${oa}) AS bm,
130
132
  (chunks.rowid IN (SELECT rowid FROM chunks WHERE chunks MATCH :all)) AS full
131
133
  FROM chunks JOIN sources s ON s.id = chunks.source_id
132
134
  WHERE chunks MATCH :match
@@ -134,9 +136,9 @@ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VAL
134
136
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
135
137
  AND (:source IS NULL OR s.label = :source)
136
138
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
137
- ${na}`,ra=`
138
- ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,bg=`
139
- WITH m AS (${oa}
139
+ ${ra}`,ia=`
140
+ ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,Ig=`
141
+ WITH m AS (${sa}
140
142
  ), r AS (
141
143
  SELECT *,
142
144
  ROW_NUMBER() OVER (ORDER BY full DESC, bm ASC, source_id DESC, ord ASC) AS rank_a,
@@ -144,11 +146,11 @@ WITH m AS (${oa}
144
146
  FROM m
145
147
  )
146
148
  SELECT rid, source_id, session_id, worktree, ord, full, 1.0 / (:k + rank_a) + 1.0 / (:k + rank_b) AS score
147
- FROM r${ra}`,Og=`
148
- WITH m AS (${oa}
149
+ FROM r${ia}`,kg=`
150
+ WITH m AS (${sa}
149
151
  )
150
152
  SELECT rid, source_id, session_id, worktree, ord, full, -bm AS score
151
- FROM m${ra}`;var Tg=`
153
+ FROM m${ia}`;var Dg=`
152
154
  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
153
155
  FROM chunks_tri t JOIN chunks c ON c.rowid = t.rowid JOIN sources s ON s.id = c.source_id
154
156
  WHERE chunks_tri MATCH :match
@@ -156,10 +158,10 @@ WHERE chunks_tri MATCH :match
156
158
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
157
159
  AND (:source IS NULL OR s.label = :source)
158
160
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
159
- ${na}
160
- ORDER BY bm25(chunks_tri, 1.0, ${ta}) ASC, c.source_id DESC, c.ord ASC`;var C0="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",I0="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function sa(e,t,n){let o=Do(e,t,n);return ca(e,o,t,n),o}function Do(e,t,n){let o=0;for(let r of n)o+=r.bytes;return P(e,r=>{let s=r.raw.prepare(N0).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 ia(e,t,n,o,r){try{ca(e,t,n,o),wo(e,t,n.sessionId,r)}catch(s){throw P(e,i=>{k0(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function ca(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>un&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)P(e,a=>{let l=a.raw.prepare(y0),u=a.raw.prepare(C0);for(let d of c){let f=d.title??"",x=l.run(t,n.sessionId,n.worktree,n.agent,d.ord,d.text,f).lastInsertRowid;u.run(x,d.text,f)}})}function k0(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(I0+" 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 Lo(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 D0(e){return[...new Set(Lo(e).split(" ").filter(n=>n!==""))].join(" OR ")}var L0=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 w0(e){let t=[...new Set(Lo(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!L0.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var Zt=`
161
+ ${ra}
162
+ ORDER BY bm25(chunks_tri, 1.0, ${oa}) ASC, c.source_id DESC, c.ord ASC`;var w0="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",P0="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function ca(e,t,n){let o=Lo(e,t,n);return la(e,o,t,n),o}function Lo(e,t,n){let o=0;for(let r of n)o+=r.bytes;return P(e,r=>{let s=r.raw.prepare(D0).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 aa(e,t,n,o,r){try{la(e,t,n,o),Po(e,t,n.sessionId,r)}catch(s){throw P(e,i=>{M0(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function la(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>un&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)P(e,a=>{let l=a.raw.prepare(L0),u=a.raw.prepare(w0);for(let d of c){let f=d.title??"",x=l.run(t,n.sessionId,n.worktree,n.agent,d.ord,d.text,f).lastInsertRowid;u.run(x,d.text,f)}})}function M0(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(P0+" WHERE "+n).run(o),e.prepare("DELETE FROM line_units WHERE "+n).run(o),Number(e.prepare("DELETE FROM chunks WHERE "+n).run(o).changes)}function wo(e){let t=[],n="";for(let o of e)o.trim()===""||o==="\0"?(n!==""&&t.push(n),n=""):n+=o==='"'?'""':o;return n!==""&&t.push(n),t.map(o=>`"${o}"*`).join(" ")}function U0(e){return[...new Set(wo(e).split(" ").filter(n=>n!==""))].join(" OR ")}var H0=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 F0(e){let t=[...new Set(wo(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!H0.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var Zt=`
161
163
  AND (:scope <> 'session' OR session_id = :session_id)
162
- AND (:scope <> 'worktree' OR worktree = :worktree)`,Rg=`
164
+ AND (:scope <> 'worktree' OR worktree = :worktree)`,Lg=`
163
165
  WITH e AS (
164
166
  SELECT seq, kind, key, path, body, created_at FROM events
165
167
  WHERE created_at > :after${Zt}
@@ -167,7 +169,7 @@ WITH e AS (
167
169
  )
168
170
  SELECT seq, kind, key, path, body, created_at FROM e
169
171
  WHERE created_at <= IFNULL((SELECT created_at FROM e ORDER BY created_at, seq LIMIT 1 OFFSET :off), created_at)
170
- ORDER BY created_at ASC, seq ASC`,Ag=`
172
+ ORDER BY created_at ASC, seq ASC`,wg=`
171
173
  WITH s AS (
172
174
  SELECT id, label, created_ts FROM sources
173
175
  WHERE created_ts > :after${Zt}
@@ -176,43 +178,43 @@ WITH s AS (
176
178
  )
177
179
  SELECT id, label, created_ts FROM s
178
180
  WHERE created_ts <= IFNULL((SELECT created_ts FROM s ORDER BY created_ts, id LIMIT 1 OFFSET :off), created_ts)
179
- ORDER BY created_ts ASC, id ASC`;var Ng=`
181
+ ORDER BY created_ts ASC, id ASC`;var Pg=`
180
182
  SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${Zt} AND (:source IS NULL OR kind = :source))
181
183
  OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${Zt} AND (:source IS NULL OR label = :source)
182
- AND label <> :reserved) AS more`;var P0=`CREATE VIRTUAL TABLE r USING fts5(body, ${Jt}, content='')`,M0="INSERT INTO r(rowid, body) VALUES (?, ?)",U0="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function W(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?D0(t):Lo(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(P0);let c=i.prepare(M0);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(U0).all(r))o[Number(a.id)-1]=-a.bm;return o}finally{i.close()}}var H0="s";function aa(e){return H0+e.toString(36)}function wo(e,t,n,o){let r=0;for(;r<o.length;){let s=r,i=0;for(;s<o.length&&(s===r||i+o[s].body.length<=un);)i+=o[s].body.length,s++;let c=r;P(e,a=>{let l=a.raw.prepare("INSERT INTO line_units(body, source_id, session_id, ord) VALUES (?, ?, ?, ?)");for(let u=c;u<s;u++){let d=o[u];l.run(d.body,t,n,d.ord)}}),r=s}}function la(e,t){return t===e?e:e+" "+t}function ua(e,t,n,o){let r=w0(n).join(" OR ");return r===""||t===""?[]:e.raw.prepare("SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? ORDER BY bm25(line_units) LIMIT ?").all(r,t,o).map(i=>({sourceId:Number(i.source_id),ord:Number(i.ord),label:i.label,body:i.body,score:i.score}))}function F0(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function Po(e){let t=e.split(`
183
- `),n=[],o=[];for(let r=0;r<t.length;r++){let s=t[r].endsWith("\r")?t[r].slice(0,-1):t[r],i=F0(s);if(i!==s.length){for(;n.length>0&&n[n.length-1].indent>=i;)n.pop();o.push({ord:r,body:[...n.map(c=>c.line),s].join(`
184
- `)}),n.push({indent:i,line:s})}}return o}function Mo(e){let t=e.indexOf(`
185
- `);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function be(e,t,n,o,r){let s=Buffer.byteLength(n,"utf8");if(s<1)throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");return{section:e,seq:t.seq,turn:t.turn,text:n,bytes:s,repeatCount:o,pinned:e==="last_request",query:r}}function Ye(e){return e.length>dn?e.slice(e.length-dn):e}function v0(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function da(e,t){if(!t)return v0();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:be("last_request",r,"now: "+Mo(r.body),1,null),i=o.slice(0,o.length-1).map(_=>be("earlier_requests",_,"asked #"+_.seq+": "+Mo(_.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(be("open_errors",m.row,"error #"+m.row.seq+" "+(m.row.tool??"")+": "+_,m.count,_));l.sort((_,m)=>_.seq-m.seq);let u=new Map;for(let _ of n)_.kind!=="edit"||_.path===null||u.set(_.path,{row:_,count:(u.get(_.path)?.count??0)+1});let d=[];for(let[_,m]of u){let R=be("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);d.push({...R,editCount:m.count})}d.sort((_,m)=>_.seq-m.seq);let f=new Map;for(let _ of n){if(_.kind!=="decision"||_.body==="")continue;let m=_.key??_.body;f.set(m,{row:_,count:(f.get(m)?.count??0)+1})}let x=[];for(let[_,m]of f)x.push(be("decisions",m.row,"decided #"+m.row.seq+": "+Mo(m.row.body),m.count,_));x.sort((_,m)=>_.seq-m.seq);let p=n.filter(_=>_.kind==="index").map(_=>be("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:Ye(l),changedFiles:Ye(d),decisions:Ye(x),earlierRequests:Ye(i),indexedSources:Ye(p)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=fn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-fn));return{lastRequest:s,openErrors:g.openErrors.filter(_=>!S.has(_.seq)),changedFiles:g.changedFiles.filter(_=>!S.has(_.seq)),decisions:g.decisions.filter(_=>!S.has(_.seq)),earlierRequests:g.earlierRequests.filter(_=>!S.has(_.seq)),indexedSources:g.indexedSources.filter(_=>!S.has(_.seq))}}function j0(e){if(!Object.hasOwn(xn,e.section))throw new Error(`compaction: "${String(e.section)}" has no weight; only toolerr, decision, prompt, edit and index rows are scored (ADR-0009 \xA73, DECISIONS-r11).`);let t=Math.max(0,e.currentTurn-e.itemTurn),n=pn[Math.min(t,pn.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(xn[e.section]*n*o/hs)}function G0(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 fa(e,t){return e.map(n=>({...n,score:j0({section:G0(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function _a(e){return e.sourceId+":"+e.ord}function tn(e){return"@"+e.label+" line "+(e.ord+1)+`:
186
- `+e.body}function B0(e){return new Set(Se(e.toLowerCase()))}function W0(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 Ho(e,t,n){let o=e.filter(l=>!t.has(_a(l))&&l.score>=Dn);if(o.length===0)return[];let r=Math.max(...o.map(l=>l.score)),s=o.map(l=>B0(l.body)),i=[],c=new Set(o.map((l,u)=>u)),a=0;for(;c.size>0;){let l=-1,u=-1/0;for(let f of c){let x=0;for(let g of i)x=Math.max(x,W0(s[f],s[g]));let p=lr*(o[f].score/r)-ur*x;p>u&&(u=p,l=f)}c.delete(l);let d=en(tn(o[l]))+1;a+d>n||(a+=d,i.push(l))}return i.map(l=>o[l])}var xa={text:"",seqs:[]};function en(e){return Buffer.byteLength(e,"utf8")}function Uo(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
187
- `)}function pa(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+Uo(e)}function Ea(e,t,n,o=[],r=new Set){if(t.trim()==="")return xa;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&Uo(f)!==""),i=s.length===0?[]:W(s.map(Uo),t,"any"),c=s.map((f,x)=>({r:f,score:i[x]})).filter(f=>f.score>=Dn).sort((f,x)=>x.score-f.score||x.r.seq-f.r.seq),a=en(wn)+1+en(Pn),l=[];for(let{r:f}of c){let x=en(pa(f))+1;a+x>kn||(a+=x,l.push(f))}let u=Ho(o,r,kn-a);if(l.length===0&&u.length===0)return xa;l.sort((f,x)=>f.seq-x.seq);let d=[...l.map(pa),...u.map(tn)];return{text:[wn,...d,Pn].join(`
188
- `),seqs:l.map(f=>f.seq),...u.length>0?{units:u.map(_a)}:{}}}function Q(e){return Buffer.byteLength(e,"utf8")}function Fo(e,t){return e.bytes>er?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function vo(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function ga(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=da(e,s),a=`<context_mode_state session="${s}" upto="${i}">`,l=Q(vo([],o)),u=Zo-(Q(a)+1+l+1+Q(ln)),d=0,f=c.lastRequest===null?null:Fo(c.lastRequest,o);f!==null&&(d+=Q(f)+1);let x=fa([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),p=new Map,g=[],E=[];for(;x.length>0;){let m=0,R=-1/0;for(let tt=0;tt<x.length;tt++){let nt=x[tt],an=nt.score*ar**(p.get(nt.section)??0)/nt.bytes;(an>R||an===R&&nt.seq>x[m].seq)&&(m=tt,R=an)}let I=x.splice(m,1)[0],et=Q(Fo(I,o))+1;d+et<=u?(d+=et,g.push(I),p.set(I.section,(p.get(I.section)??0)+1)):E.push(I)}let h=[a];f!==null&&h.push(f);for(let m of["open_errors","changed_files","decisions","earlier_requests","indexed_sources"])for(let R of g.filter(I=>I.section===m).sort((I,et)=>I.seq-et.seq))h.push(Fo(R,o));if(n!==void 0){for(let m of n.sources){let R=Q(m)+1;d+R>u||(d+=R,h.push(m))}for(let m of Ho(n.units,new Set,u-d)){let R=tn(m);d+=Q(R)+1,h.push(R)}}let S=[],_=new Set;for(let m of E.sort((R,I)=>R.seq-I.seq))if(!(m.query===null||_.has(m.query))){if(Q(vo([...S,m.query],o))-l>u-d)break;S.push(m.query),_.add(m.query)}return h.push(vo(S,o),ln),h.join(`
189
- `)}var X0=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),K0=new Set(["script","style"]),q0=new TextEncoder;function nn(e,t,n=ne){let o=z0(e);if(o.length===0)return[];let r=Math.max(4,Math.min(ne,Math.floor(n)));if(t==="md")return Y0(o,r,r<ne);let s=t==="html"?Z0(o):jo(o,!1);return Go(o,s,t!=="text",r,r<ne)}function Y0(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 Go(e,i,!0,t,n))c(l.text,l.bytes);i=[]}};for(let l of jo(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&&Z(e.slice(l.start,l.end))>t){let u=V0(e,l,l.fence,t);if(u!==void 0){a();for(let d of u)c(d,Z(d));continue}}i.push(l)}return a(),o}function V0(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-Z(r)-Z(s)-2;if(!(a<16||c.length===0))return Go(c,jo(c,!1),!0,a,!0).map(l=>r+`
184
+ AND label <> :reserved) AS more`;var v0=`CREATE VIRTUAL TABLE r USING fts5(body, ${Jt}, content='')`,j0="INSERT INTO r(rowid, body) VALUES (?, ?)",G0="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function W(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?U0(t):wo(t);if(r===""||e.length===0)return o;let s=process.getBuiltinModule("node:sqlite");if(s===void 0)throw new T("NO_SQLITE");let i=new s.DatabaseSync(":memory:");try{i.exec(v0);let c=i.prepare(j0);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(G0).all(r))o[Number(a.id)-1]=-a.bm;return o}finally{i.close()}}var B0="s";function ua(e){return B0+e.toString(36)}function Po(e,t,n,o){let r=0;for(;r<o.length;){let s=r,i=0;for(;s<o.length&&(s===r||i+o[s].body.length<=un);)i+=o[s].body.length,s++;let c=r;P(e,a=>{let l=a.raw.prepare("INSERT INTO line_units(body, source_id, session_id, ord) VALUES (?, ?, ?, ?)");for(let u=c;u<s;u++){let d=o[u];l.run(d.body,t,n,d.ord)}}),r=s}}function da(e,t){return t===e?e:e+" "+t}function fa(e,t,n,o){let r=F0(n).join(" OR ");return r===""||t===""?[]:e.raw.prepare("SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? ORDER BY bm25(line_units) LIMIT ?").all(r,t,o).map(i=>({sourceId:Number(i.source_id),ord:Number(i.ord),label:i.label,body:i.body,score:i.score}))}function W0(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function Mo(e){let t=e.split(`
185
+ `),n=[],o=[];for(let r=0;r<t.length;r++){let s=t[r].endsWith("\r")?t[r].slice(0,-1):t[r],i=W0(s);if(i!==s.length){for(;n.length>0&&n[n.length-1].indent>=i;)n.pop();o.push({ord:r,body:[...n.map(c=>c.line),s].join(`
186
+ `)}),n.push({indent:i,line:s})}}return o}function Uo(e){let t=e.indexOf(`
187
+ `);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function be(e,t,n,o,r){let s=Buffer.byteLength(n,"utf8");if(s<1)throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");return{section:e,seq:t.seq,turn:t.turn,text:n,bytes:s,repeatCount:o,pinned:e==="last_request",query:r}}function Ye(e){return e.length>dn?e.slice(e.length-dn):e}function X0(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function xa(e,t){if(!t)return X0();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:be("last_request",r,"now: "+Uo(r.body),1,null),i=o.slice(0,o.length-1).map(_=>be("earlier_requests",_,"asked #"+_.seq+": "+Uo(_.body),1,null)),c=new Map,a=new Map;for(let _ of n)if(!(_.kind!=="cmd"&&_.kind!=="toolerr"||_.key===null)){if(_.ok===1){a.set(_.key,_.seq);continue}c.set(_.key,{row:_,count:(c.get(_.key)?.count??0)+1})}let l=[];for(let[_,m]of c)(a.get(_)??0)>m.row.seq||l.push(be("open_errors",m.row,"error #"+m.row.seq+" "+(m.row.tool??"")+": "+_,m.count,_));l.sort((_,m)=>_.seq-m.seq);let u=new Map;for(let _ of n)_.kind!=="edit"||_.path===null||u.set(_.path,{row:_,count:(u.get(_.path)?.count??0)+1});let d=[];for(let[_,m]of u){let R=be("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);d.push({...R,editCount:m.count})}d.sort((_,m)=>_.seq-m.seq);let f=new Map;for(let _ of n){if(_.kind!=="decision"||_.body==="")continue;let m=_.key??_.body;f.set(m,{row:_,count:(f.get(m)?.count??0)+1})}let x=[];for(let[_,m]of f)x.push(be("decisions",m.row,"decided #"+m.row.seq+": "+Uo(m.row.body),m.count,_));x.sort((_,m)=>_.seq-m.seq);let p=n.filter(_=>_.kind==="index").map(_=>be("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:Ye(l),changedFiles:Ye(d),decisions:Ye(x),earlierRequests:Ye(i),indexedSources:Ye(p)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=fn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-fn));return{lastRequest:s,openErrors:g.openErrors.filter(_=>!S.has(_.seq)),changedFiles:g.changedFiles.filter(_=>!S.has(_.seq)),decisions:g.decisions.filter(_=>!S.has(_.seq)),earlierRequests:g.earlierRequests.filter(_=>!S.has(_.seq)),indexedSources:g.indexedSources.filter(_=>!S.has(_.seq))}}function K0(e){if(!Object.hasOwn(xn,e.section))throw new Error(`compaction: "${String(e.section)}" has no weight; only toolerr, decision, prompt, edit and index rows are scored (ADR-0009 \xA73, DECISIONS-r11).`);let t=Math.max(0,e.currentTurn-e.itemTurn),n=pn[Math.min(t,pn.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(xn[e.section]*n*o/Ss)}function q0(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 pa(e,t){return e.map(n=>({...n,score:K0({section:q0(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function ga(e){return e.sourceId+":"+e.ord}function tn(e){return"@"+e.label+" line "+(e.ord+1)+`:
188
+ `+e.body}function Y0(e){return new Set(Se(e.toLowerCase()))}function V0(e,t){let n=0;for(let o of e)t.has(o)&&n++;return e.size+t.size-n===0?0:n/(e.size+t.size-n)}function Fo(e,t,n){let o=e.filter(l=>!t.has(ga(l))&&l.score>=Dn);if(o.length===0)return[];let r=Math.max(...o.map(l=>l.score)),s=o.map(l=>Y0(l.body)),i=[],c=new Set(o.map((l,u)=>u)),a=0;for(;c.size>0;){let l=-1,u=-1/0;for(let f of c){let x=0;for(let g of i)x=Math.max(x,V0(s[f],s[g]));let p=ur*(o[f].score/r)-dr*x;p>u&&(u=p,l=f)}c.delete(l);let d=en(tn(o[l]))+1;a+d>n||(a+=d,i.push(l))}return i.map(l=>o[l])}var _a={text:"",seqs:[]};function en(e){return Buffer.byteLength(e,"utf8")}function Ho(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
189
+ `)}function Ea(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+Ho(e)}function ma(e,t,n,o=[],r=new Set){if(t.trim()==="")return _a;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&Ho(f)!==""),i=s.length===0?[]:W(s.map(Ho),t,"any"),c=s.map((f,x)=>({r:f,score:i[x]})).filter(f=>f.score>=Dn).sort((f,x)=>x.score-f.score||x.r.seq-f.r.seq),a=en(wn)+1+en(Pn),l=[];for(let{r:f}of c){let x=en(Ea(f))+1;a+x>kn||(a+=x,l.push(f))}let u=Fo(o,r,kn-a);if(l.length===0&&u.length===0)return _a;l.sort((f,x)=>f.seq-x.seq);let d=[...l.map(Ea),...u.map(tn)];return{text:[wn,...d,Pn].join(`
190
+ `),seqs:l.map(f=>f.seq),...u.length>0?{units:u.map(ga)}:{}}}function Z(e){return Buffer.byteLength(e,"utf8")}function vo(e,t){return e.bytes>tr?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function jo(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function ha(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=xa(e,s),a=`<context_mode_state session="${s}" upto="${i}">`,l=Z(jo([],o)),u=er-(Z(a)+1+l+1+Z(ln)),d=0,f=c.lastRequest===null?null:vo(c.lastRequest,o);f!==null&&(d+=Z(f)+1);let x=pa([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),p=new Map,g=[],E=[];for(;x.length>0;){let m=0,R=-1/0;for(let tt=0;tt<x.length;tt++){let nt=x[tt],an=nt.score*lr**(p.get(nt.section)??0)/nt.bytes;(an>R||an===R&&nt.seq>x[m].seq)&&(m=tt,R=an)}let I=x.splice(m,1)[0],et=Z(vo(I,o))+1;d+et<=u?(d+=et,g.push(I),p.set(I.section,(p.get(I.section)??0)+1)):E.push(I)}let h=[a];f!==null&&h.push(f);for(let m of["open_errors","changed_files","decisions","earlier_requests","indexed_sources"])for(let R of g.filter(I=>I.section===m).sort((I,et)=>I.seq-et.seq))h.push(vo(R,o));if(n!==void 0){for(let m of n.sources){let R=Z(m)+1;d+R>u||(d+=R,h.push(m))}for(let m of Fo(n.units,new Set,u-d)){let R=tn(m);d+=Z(R)+1,h.push(R)}}let S=[],_=new Set;for(let m of E.sort((R,I)=>R.seq-I.seq))if(!(m.query===null||_.has(m.query))){if(Z(jo([...S,m.query],o))-l>u-d)break;S.push(m.query),_.add(m.query)}return h.push(jo(S,o),ln),h.join(`
191
+ `)}var z0=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),J0=new Set(["script","style"]),$0=new TextEncoder;function nn(e,t,n=ne){let o=ex(e);if(o.length===0)return[];let r=Math.max(4,Math.min(ne,Math.floor(n)));if(t==="md")return Q0(o,r,r<ne);let s=t==="html"?rx(o):Go(o,!1);return Bo(o,s,t!=="text",r,r<ne)}function Q0(e,t,n){let o=[],r=[],s="",i=[],c=(l,u)=>{o.push({ord:o.length,text:l,bytes:u,title:s})},a=()=>{if(i.length!==0){for(let l of Bo(e,i,!0,t,n))c(l.text,l.bytes);i=[]}};for(let l of Go(e,!0)){if(l.heading!==void 0){for(a();r.length>0&&r[r.length-1].level>=l.heading.level;)r.pop();r.push(l.heading),s=r.map(u=>u.text).join(" > ")}if(l.fence!==void 0&&ee(e.slice(l.start,l.end))>t){let u=Z0(e,l,l.fence,t);if(u!==void 0){a();for(let d of u)c(d,ee(d));continue}}i.push(l)}return a(),o}function Z0(e,t,n,o){let r=e.slice(t.start,n.openEnd),s=n.closeStart>=0?e.slice(n.closeStart,t.end):n.fence,i=n.closeStart>=0?Math.max(n.openEnd+1,n.closeStart-1):t.end,c=e.slice(Math.min(n.openEnd+1,i),i),a=o-ee(r)-ee(s)-2;if(!(a<16||c.length===0))return Bo(c,Go(c,!1),!0,a,!0).map(l=>r+`
190
192
  `+l.text+`
191
- `+s)}function z0(e){let t=e.split(`\r
193
+ `+s)}function ex(e){let t=e.split(`\r
192
194
  `).join(`
193
- `);return t.startsWith("\uFEFF")?t.slice(1):t}function jo(e,t){let n=[],o=-1,r=-1,s=!1,i="",c,a,l=()=>{if(o>=0){let f={start:o,end:r};c!==void 0&&(f.heading=c),a!==void 0&&(f.fence=a),n.push(f)}o=-1,c=void 0,a=void 0},u=(f,x,p)=>{o<0&&(o=f),r=x,s=p},d=0;for(;d<=e.length;){let f=e.indexOf(`
194
- `,d),x=f<0?e.length:f,p=e.slice(d,x);if(i!=="")u(d,x,!1),Q0(p,i)&&(i="",t&&a!==void 0&&(a.closeStart=d,l()));else if(p.length===0)l();else{let g=t?$0(p):"",E=t&&g===""?J0(p):void 0,h=t&&g===""&&E===void 0&&p.includes("|");t&&o>=0&&(h!==s||g!==""||E!==void 0)&&l(),u(d,x,h),i=g,g!==""&&(a={fence:g,openEnd:x,closeStart:-1}),E!==void 0&&(c=E,l())}d=x+1}return l(),n}function J0(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 $0(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 Q0(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 Z0(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{ha(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=ex(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||X0.has(c.name))){if(K0.has(c.name)){s=tx(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return ha(t,e,r,e.length),t}function ba(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function Oa(e){return ba(e)||e>="0"&&e<="9"||e==="-"||e===":"}function ex(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!ba(e[n]))return;let r=n;for(;n<e.length&&Oa(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 tx(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||!Oa(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function ma(e){return e===" "||e===`
195
- `||e===" "||e==="\f"||e==="\r"}function ha(e,t,n,o){let r=n,s=o;for(;r<s&&ma(t[r]);)r+=1;for(;s>r&&ma(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function Z(e){return Buffer.byteLength(e,"utf8")}function Sa(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=q0.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function Go(e,t,n,o,r){let s=[],i=new Uint8Array(o),c,a,l=0,u=(d,f,x)=>{s.push({ord:s.length,text:e.slice(d,f),bytes:x})};for(let d of t){if(a!==void 0&&!n&&(u(a.start,a.end,l),a=void 0),a!==void 0){let p=Z(e.slice(a.end,d.end));if(l+p<=o){a.end=d.end,l+=p;continue}u(a.start,a.end,l),a=void 0}let f=d.start,x=Z(e.slice(d.start,d.end));for(;x>o;){let p=Sa(e,f,d.end,i),g=r?e.lastIndexOf(`
196
- `,p.end-1):-1;if(g>f){let E=Z(e.slice(f,g+1));u(f,g+1,E),f=g+1,x-=E;continue}if(r){let E=e.indexOf(`
197
- `,f),h=E<0||E>=d.end?d.end:E+1,S=Z(e.slice(f,h));if(S<=ne){u(f,h,S),f=h,x-=S;continue}c??=new Uint8Array(ne);let _=Sa(e,f,h,c);u(f,_.end,_.written),f=_.end,x-=_.written;continue}u(f,p.end,p.written),f=p.end,x-=p.written}f>=d.end||(a={start:f,end:d.end},l=x)}return a!==void 0&&u(a.start,a.end,l),s}var nx=`
198
- `,ox=1;function Ta(e,t,n,o,r){return rx(e,t,n,o,r)}function rx(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?W(s,t):W(s,r,"any"),c=e.map((f,x)=>x).sort((f,x)=>i[x]-i[f]||e[x].ord-e[f].ord),a=[],l=0,u=!1;for(let f of c){let x=e[f].bytes+(a.length>0?ox:0);if(l+x>n){u=!0;continue}a.push(e[f]),l+=x}return a.sort((f,x)=>f.ord-x.ord),{text:a.map(f=>f.text).join(nx),more:u?Bo(t,o):null}}function Bo(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>Hn?"...":JSON.stringify(e))+"]"+n+"})"}var Ra=20,M=2,Aa=9,Na=8,sx=.9,ix=.5,cx=64,ax=2,lx=4,Wo=`
199
- `,ux="(absent)",X=e=>Buffer.byteLength(e,"utf8");function ya(e,t,n){let o=xx(e,t)??Ex(e,t)??hx(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):W(o.units.map(l=>l.rank),t,"any"),s=o.units.map((l,u)=>u).filter(l=>r[l]>0).sort((l,u)=>r[u]-r[l]||o.units[l].pos-o.units[u].pos),i=[],c=0;for(let l of s){let u=i.length>0?X(Wo):0,d=o.units[l].render(n-c-u);d===null||c+u+X(d)>n||(i.push({pos:o.units[l].pos,text:d}),c+=u+X(d))}if(i.length===0)return null;i.sort((l,u)=>l.pos-u.pos);let a=i.map(l=>l.text);return c+X(Wo)+X(o.header)<=n&&a.unshift(o.header),a.join(Wo)}function dx(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
200
- `&&n!=="\r"&&n!==" ")return n}return""}function fx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ca(e,t,n){if(n.size<2||n.size>Na)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=M+1)return o[0][1]<sx*e||e-o[0][1]>M?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>M),s=o.filter(([,i])=>i<=M);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function Ia(e){if(dx(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<Ra||!t.every(fx))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 ka=(e,t)=>e+" objects {"+t.join(",")+"}";function xx(e,t){let n=Ia(e);if(n===null)return null;let{objs:o,keys:r}=n,s=new Map;for(let l of r){let u=new Map,d=new Map,f=!0;for(let x=0;x<o.length&&f;x++){let p=l in o[x]?o[x][l]:void 0;if(typeof p=="object"&&p!==null){f=!1;break}let g=p===void 0?ux:JSON.stringify(p);d.set(g,(d.get(g)??0)+1);let E=u.get(g)??[];if(E.length<=M&&E.push(x),u.set(g,E),d.size>Na)break}if(f)for(let x of Ca(o.length,u,d))s.set(x,[...s.get(x)??[],l])}if(s.size===0||s.size>Aa)return null;let i=W(r,t,"any"),c=new Set(r.filter((l,u)=>i[u]>0)),a=[...s.entries()].map(([l,u])=>({pos:l,rank:JSON.stringify(o[l]),render:d=>Da(l,o[l],u,c,d)}));return{header:ka(o.length,r)+", "+s.size+" rare:",units:a}}function Da(e,t,n,o,r){let s="["+e+"] ",i=px(t,n,o,r-X(s));return i===null?null:s+i}function px(e,t,n,o){let r=JSON.stringify(e);if(X(r)<=o)return r;let s=Object.keys(e),i=d=>t.includes(d)?0:n.has(d)?1:typeof e[d]!="object"||e[d]===null?2:3,c=[...s].sort((d,f)=>i(d)-i(f)||s.indexOf(d)-s.indexOf(f)),a=d=>JSON.stringify(d)+":"+JSON.stringify(e[d]),l=new Set,u=2;for(let d of c){let f=X(a(d))+(l.size>0?1:0);u+f>o||(l.add(d),u+=f)}return t.every(d=>l.has(d))?"{"+s.filter(d=>l.has(d)).map(a).join(",")+"}":null}function _x(e,t){let n=W(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function Ex(e,t){let n=Ia(e);if(n===null)return null;let{objs:o,keys:r}=n,s=_x(r,t),i=new Map,c=0;for(let l of r){if(!s.has(l)||c>=ax||!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=>Da(l,o[l],[u],s,d)}));return{header:ka(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:a,direct:!0}}function gx(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function mx(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 hx(e){let t=e.split(`
201
- `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<Ra)return null;let n=new Map,o=[];for(let a=0;a<t.length;a++){let l=t[a].split(" ").filter(p=>p!==""),u=l.map(p=>gx(p)?"<*>":p),d=u.length+" "+(u[0]??""),f=n.get(d)??[],x;for(let p of f)if(mx(p.tpl,u)>=ix){x=p;break}if(x===void 0){if(x={tpl:[...u],count:0,lines:[],pos:l.map(()=>({counts:new Map,totals:new Map}))},f.push(x),n.set(d,f),o.push(x),o.length>cx)return null}else for(let p=0;p<x.tpl.length;p++)x.tpl[p]!==u[p]&&(x.tpl[p]="<*>");x.count++,x.lines.length<=M&&x.lines.push(a);for(let p=0;p<x.pos.length;p++){let g=x.pos[p];if(g===null)continue;g.totals.set(l[p],(g.totals.get(l[p])??0)+1);let E=g.counts.get(l[p])??[];E.length<=M&&E.push(a),g.counts.set(l[p],E),g.totals.size>M+1&&(x.pos[p]=null)}}let r=o.filter(a=>a.count>M);if(r.length===0||r.length>lx||r.some(a=>a.tpl.every(l=>l==="<*>")))return null;let s=new Set(o.filter(a=>a.count<=M).flatMap(a=>a.lines));for(let a of r)for(let l of a.pos)if(l!==null)for(let u of Ca(a.count,l.counts,l.totals))s.add(u);if(s.size===0||s.size>Aa)return null;let i=t.length+" lines, "+s.size+" rare:",c=[...s].sort((a,l)=>a-l).map(a=>{let l=a+1+": "+t[a];return{pos:a,rank:t[a],render:u=>X(l)<=u?l:null}});return{header:i,units:c}}function Sx(e,t,n,o,r,s,i,c=nn(s,i)){return{sourceId:sa(e,{projectKey:t.projectKey,sessionId:n,worktree:t.worktree,agent:t.agent,kind:o,label:r,bytes:Buffer.byteLength(s,"utf8"),chunkCount:c.length,createdAt:Date.now()},c),chunks:c.length}}function Xo(e,t,n,o,r,s,i){return Sx(e,t,n,"content",o,r,s,i)}async function bx(e,t){try{let n=await A(e);Qt(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
202
- `)}}function on(e,t,n){bx(e,n)}function La(e,t,n){let o=new Set(Se(t.toLowerCase()));for(let i of Se(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of Se(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,cr).map(i=>i[0]).join(" ")}function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ox(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(bs):""}function Tx(e){return Array.isArray(e)?e.filter(Ve).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):Ve(e)?Object.entries(e):[]}function Pa(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!Ve(t))return[];let n=[];for(let[o,r]of Tx(t[Ss])){let s=Ox(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function Ma(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!Ve(o)||!Array.isArray(o.options)))for(let r of o.options)Ve(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function wa(e){return e.trim().toLowerCase()}function Ua(e,t,n){let o=wa(e);if(o==="")return null;let r=t.find(s=>wa(s)===o);return r===void 0?null:{key:mt,body:"A: "+r+`
203
- ref: #`+n}}function Rx(e,t){return"hint:"+e+":"+t}function Ax(e,t){return $(e,t)!==null?!1:(B(e,t,"1"),!0)}function Nx(e,t,n){let o=$(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return B(e,t,String(r)),(r-1)%n===0}function rn(e,t,n,o){if(t==="")return!1;let r=Rx(t,n),s=i=>o===void 0?Ax(i,r):Nx(i,r,o);return e.raw.isTransaction?s(e):P(e,s)}import{join as Fa,resolve as yx}from"node:path";var Ko=process.getBuiltinModule("node:fs");function qo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function Cx(e){for(let t of jr){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(qo(n))return n}return{}}function Ix(e){return e.HOME??e.USERPROFILE??""}function kx(e){let t=Ix(e);return t===""?"":Fa(t,ct.slice(1),Hr)}function va(e){let t=qo(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=kx(e);if(r==="")return;Ko.mkdirSync(Fa(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:va(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});Ko.appendFileSync(r,s+`
195
+ `);return t.startsWith("\uFEFF")?t.slice(1):t}function Go(e,t){let n=[],o=-1,r=-1,s=!1,i="",c,a,l=()=>{if(o>=0){let f={start:o,end:r};c!==void 0&&(f.heading=c),a!==void 0&&(f.fence=a),n.push(f)}o=-1,c=void 0,a=void 0},u=(f,x,p)=>{o<0&&(o=f),r=x,s=p},d=0;for(;d<=e.length;){let f=e.indexOf(`
196
+ `,d),x=f<0?e.length:f,p=e.slice(d,x);if(i!=="")u(d,x,!1),ox(p,i)&&(i="",t&&a!==void 0&&(a.closeStart=d,l()));else if(p.length===0)l();else{let g=t?nx(p):"",E=t&&g===""?tx(p):void 0,h=t&&g===""&&E===void 0&&p.includes("|");t&&o>=0&&(h!==s||g!==""||E!==void 0)&&l(),u(d,x,h),i=g,g!==""&&(a={fence:g,openEnd:x,closeStart:-1}),E!==void 0&&(c=E,l())}d=x+1}return l(),n}function tx(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 nx(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 ox(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 rx(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{ba(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=sx(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||z0.has(c.name))){if(J0.has(c.name)){s=ix(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return ba(t,e,r,e.length),t}function Ta(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function Ra(e){return Ta(e)||e>="0"&&e<="9"||e==="-"||e===":"}function sx(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!Ta(e[n]))return;let r=n;for(;n<e.length&&Ra(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 ix(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||!Ra(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function Sa(e){return e===" "||e===`
197
+ `||e===" "||e==="\f"||e==="\r"}function ba(e,t,n,o){let r=n,s=o;for(;r<s&&Sa(t[r]);)r+=1;for(;s>r&&Sa(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function ee(e){return Buffer.byteLength(e,"utf8")}function Oa(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=$0.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function Bo(e,t,n,o,r){let s=[],i=new Uint8Array(o),c,a,l=0,u=(d,f,x)=>{s.push({ord:s.length,text:e.slice(d,f),bytes:x})};for(let d of t){if(a!==void 0&&!n&&(u(a.start,a.end,l),a=void 0),a!==void 0){let p=ee(e.slice(a.end,d.end));if(l+p<=o){a.end=d.end,l+=p;continue}u(a.start,a.end,l),a=void 0}let f=d.start,x=ee(e.slice(d.start,d.end));for(;x>o;){let p=Oa(e,f,d.end,i),g=r?e.lastIndexOf(`
198
+ `,p.end-1):-1;if(g>f){let E=ee(e.slice(f,g+1));u(f,g+1,E),f=g+1,x-=E;continue}if(r){let E=e.indexOf(`
199
+ `,f),h=E<0||E>=d.end?d.end:E+1,S=ee(e.slice(f,h));if(S<=ne){u(f,h,S),f=h,x-=S;continue}c??=new Uint8Array(ne);let _=Oa(e,f,h,c);u(f,_.end,_.written),f=_.end,x-=_.written;continue}u(f,p.end,p.written),f=p.end,x-=p.written}f>=d.end||(a={start:f,end:d.end},l=x)}return a!==void 0&&u(a.start,a.end,l),s}var cx=`
200
+ `,ax=1;function Aa(e,t,n,o,r){return lx(e,t,n,o,r)}function lx(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?W(s,t):W(s,r,"any"),c=e.map((f,x)=>x).sort((f,x)=>i[x]-i[f]||e[x].ord-e[f].ord),a=[],l=0,u=!1;for(let f of c){let x=e[f].bytes+(a.length>0?ax:0);if(l+x>n){u=!0;continue}a.push(e[f]),l+=x}return a.sort((f,x)=>f.ord-x.ord),{text:a.map(f=>f.text).join(cx),more:u?Wo(t,o):null}}function Wo(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>Hn?"...":JSON.stringify(e))+"]"+n+"})"}var Na=20,M=2,ya=9,Ca=8,ux=.9,dx=.5,fx=64,xx=2,px=4,Xo=`
201
+ `,_x="(absent)",X=e=>Buffer.byteLength(e,"utf8");function Ia(e,t,n){let o=mx(e,t)??bx(e,t)??Rx(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):W(o.units.map(l=>l.rank),t,"any"),s=o.units.map((l,u)=>u).filter(l=>r[l]>0).sort((l,u)=>r[u]-r[l]||o.units[l].pos-o.units[u].pos),i=[],c=0;for(let l of s){let u=i.length>0?X(Xo):0,d=o.units[l].render(n-c-u);d===null||c+u+X(d)>n||(i.push({pos:o.units[l].pos,text:d}),c+=u+X(d))}if(i.length===0)return null;i.sort((l,u)=>l.pos-u.pos);let a=i.map(l=>l.text);return c+X(Xo)+X(o.header)<=n&&a.unshift(o.header),a.join(Xo)}function Ex(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
202
+ `&&n!=="\r"&&n!==" ")return n}return""}function gx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ka(e,t,n){if(n.size<2||n.size>Ca)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=M+1)return o[0][1]<ux*e||e-o[0][1]>M?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>M),s=o.filter(([,i])=>i<=M);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function Da(e){if(Ex(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<Na||!t.every(gx))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 La=(e,t)=>e+" objects {"+t.join(",")+"}";function mx(e,t){let n=Da(e);if(n===null)return null;let{objs:o,keys:r}=n,s=new Map;for(let l of r){let u=new Map,d=new Map,f=!0;for(let x=0;x<o.length&&f;x++){let p=l in o[x]?o[x][l]:void 0;if(typeof p=="object"&&p!==null){f=!1;break}let g=p===void 0?_x:JSON.stringify(p);d.set(g,(d.get(g)??0)+1);let E=u.get(g)??[];if(E.length<=M&&E.push(x),u.set(g,E),d.size>Ca)break}if(f)for(let x of ka(o.length,u,d))s.set(x,[...s.get(x)??[],l])}if(s.size===0||s.size>ya)return null;let i=W(r,t,"any"),c=new Set(r.filter((l,u)=>i[u]>0)),a=[...s.entries()].map(([l,u])=>({pos:l,rank:JSON.stringify(o[l]),render:d=>wa(l,o[l],u,c,d)}));return{header:La(o.length,r)+", "+s.size+" rare:",units:a}}function wa(e,t,n,o,r){let s="["+e+"] ",i=hx(t,n,o,r-X(s));return i===null?null:s+i}function hx(e,t,n,o){let r=JSON.stringify(e);if(X(r)<=o)return r;let s=Object.keys(e),i=d=>t.includes(d)?0:n.has(d)?1:typeof e[d]!="object"||e[d]===null?2:3,c=[...s].sort((d,f)=>i(d)-i(f)||s.indexOf(d)-s.indexOf(f)),a=d=>JSON.stringify(d)+":"+JSON.stringify(e[d]),l=new Set,u=2;for(let d of c){let f=X(a(d))+(l.size>0?1:0);u+f>o||(l.add(d),u+=f)}return t.every(d=>l.has(d))?"{"+s.filter(d=>l.has(d)).map(a).join(",")+"}":null}function Sx(e,t){let n=W(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function bx(e,t){let n=Da(e);if(n===null)return null;let{objs:o,keys:r}=n,s=Sx(r,t),i=new Map,c=0;for(let l of r){if(!s.has(l)||c>=xx||!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=>wa(l,o[l],[u],s,d)}));return{header:La(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:a,direct:!0}}function Ox(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function Tx(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 Rx(e){let t=e.split(`
203
+ `);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<Na)return null;let n=new Map,o=[];for(let a=0;a<t.length;a++){let l=t[a].split(" ").filter(p=>p!==""),u=l.map(p=>Ox(p)?"<*>":p),d=u.length+" "+(u[0]??""),f=n.get(d)??[],x;for(let p of f)if(Tx(p.tpl,u)>=dx){x=p;break}if(x===void 0){if(x={tpl:[...u],count:0,lines:[],pos:l.map(()=>({counts:new Map,totals:new Map}))},f.push(x),n.set(d,f),o.push(x),o.length>fx)return null}else for(let p=0;p<x.tpl.length;p++)x.tpl[p]!==u[p]&&(x.tpl[p]="<*>");x.count++,x.lines.length<=M&&x.lines.push(a);for(let p=0;p<x.pos.length;p++){let g=x.pos[p];if(g===null)continue;g.totals.set(l[p],(g.totals.get(l[p])??0)+1);let E=g.counts.get(l[p])??[];E.length<=M&&E.push(a),g.counts.set(l[p],E),g.totals.size>M+1&&(x.pos[p]=null)}}let r=o.filter(a=>a.count>M);if(r.length===0||r.length>px||r.some(a=>a.tpl.every(l=>l==="<*>")))return null;let s=new Set(o.filter(a=>a.count<=M).flatMap(a=>a.lines));for(let a of r)for(let l of a.pos)if(l!==null)for(let u of ka(a.count,l.counts,l.totals))s.add(u);if(s.size===0||s.size>ya)return null;let i=t.length+" lines, "+s.size+" rare:",c=[...s].sort((a,l)=>a-l).map(a=>{let l=a+1+": "+t[a];return{pos:a,rank:t[a],render:u=>X(l)<=u?l:null}});return{header:i,units:c}}function Ax(e,t,n,o,r,s,i,c=nn(s,i)){return{sourceId:ca(e,{projectKey:t.projectKey,sessionId:n,worktree:t.worktree,agent:t.agent,kind:o,label:r,bytes:Buffer.byteLength(s,"utf8"),chunkCount:c.length,createdAt:Date.now()},c),chunks:c.length}}function Ko(e,t,n,o,r,s,i){return Ax(e,t,n,"content",o,r,s,i)}async function Nx(e,t){try{let n=await A(e);Qt(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
204
+ `)}}function on(e,t,n){Nx(e,n)}function Pa(e,t,n){let o=new Set(Se(t.toLowerCase()));for(let i of Se(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of Se(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,ar).map(i=>i[0]).join(" ")}function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yx(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(Os):""}function Cx(e){return Array.isArray(e)?e.filter(Ve).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):Ve(e)?Object.entries(e):[]}function Ua(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!Ve(t))return[];let n=[];for(let[o,r]of Cx(t[bs])){let s=yx(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function Ha(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!Ve(o)||!Array.isArray(o.options)))for(let r of o.options)Ve(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function Ma(e){return e.trim().toLowerCase()}function Fa(e,t,n){let o=Ma(e);if(o==="")return null;let r=t.find(s=>Ma(s)===o);return r===void 0?null:{key:mt,body:"A: "+r+`
205
+ ref: #`+n}}function Ix(e,t){return"hint:"+e+":"+t}function kx(e,t){return Q(e,t)!==null?!1:(B(e,t,"1"),!0)}function Dx(e,t,n){let o=Q(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return B(e,t,String(r)),(r-1)%n===0}function rn(e,t,n,o){if(t==="")return!1;let r=Ix(t,n),s=i=>o===void 0?kx(i,r):Dx(i,r,o);return e.raw.isTransaction?s(e):P(e,s)}import{join as ja,resolve as Lx}from"node:path";var qo=process.getBuiltinModule("node:fs");function Yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function wx(e){for(let t of Gr){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(Yo(n))return n}return{}}function Px(e){return e.HOME??e.USERPROFILE??""}function Mx(e){let t=Px(e);return t===""?"":ja(t,ct.slice(1),Fr)}function Ga(e){let t=Yo(e)?e.code:void 0;return typeof t=="string"&&t!==""?t:e instanceof Error?e.name:"Error"}function ze(e,t,n,o){try{let r=Mx(e);if(r==="")return;qo.mkdirSync(ja(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:Ga(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});qo.appendFileSync(r,s+`
204
206
  `)}catch{process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
205
- `)}}var Ha=!1;function Je(e,t){if(!(Ha||e[Wr]!==t))throw Ha=!0,new Error("injected fault at "+t)}function ja(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=Ae.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 ee(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function Dx(e,t){let n=t.toLowerCase();return ee(e.nativeTools.shell,n)||ee(ye.shell,n)?"shell":ee(e.nativeTools.read,n)||ee(ye.read,n)?"read":ee(e.nativeTools.grep,n)||ee(ye.grep,n)?"grep":ee(e.nativeTools.webfetch,n)||ee(ye.fetch,n)?"fetch":null}function Lx(e,t){let n=t.toLowerCase();return Br.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function wx(e,t){if((e.offset??null)!==null||(e.limit??null)!==null)return!1;let n=sn(e,xt);if(n==="")return!1;try{let o=Ko.statSync(yx(t,n));return o.isFile()&&o.size>K}catch{return!1}}function $e(e,t,n,o=""){let r=re(e),s=()=>r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"});try{if(!qo(t)||!Lx(r,sn(t,vr)))return s();let i=sn(t,Fr);if(i===""||i.includes(pt))return s();let c=Dx(r,i);if(c===null)return s();let a=sn(t,Gr)||o;if(c==="read"&&!wx(Cx(t),a))return s();let l=c==="read"?Rn.read:Rn[c],u=k(l,r.toolNamePrefix)+`
206
- `+Xr(va(n),r.toolNamePrefix);return r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:a,turn:0},{kind:"deny",reason:u})}catch{return{stdout:"",exitCode:0}}}var{read:Px,writeSync:Mx}=process.getBuiltinModule("node:fs"),Ga=65536;function Ux(e){let t=Buffer.allocUnsafe(Ga);return new Promise(n=>{let o=()=>{Px(0,t,0,Ga,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 Yo(){let e=[];if(!await Ux(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function Vo(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=Mx(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{readFileSync:Hx}=process.getBuiltinModule("node:fs"),y={kind:"allow"},jx={stdout:"",exitCode:0},Gx=48;function Bx(e){return Oe.includes(e)}function Qe(e){return e instanceof Error?e.message:String(e)}function Ze(e){return typeof e=="string"?e:""}async function Wa(e,t,n){if(!Bx(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
207
- `),jx;let o=re(e),r=(l,u,d)=>(ze(n,e,l,u),process.stderr.write(d??"hooks: "+l+" failed: "+Qe(u)+`
208
- `),$e(e,t,u));if(ja(process.version))return r("node",new T("NODE_TOO_OLD",{v:process.version}));let s;try{Je(n,"decode"),s=o.decode(t)}catch(l){return r("decode",l)}let i;try{Je(n,"project");let l=e==="vscode"?[it,s.cwd]:process.argv;i=Wc(e,{env:n,argv:l,cwd:s.cwd,piCwd:e==="pi"?s.cwd:void 0})}catch(l){return r("project",l,"hooks: no project: "+String(l.code??"ERROR")+" "+Qe(l)+`
209
- `)}let c,a={};try{Je(n,"policy"),c=await Wx(s,o,i,n,a)}catch(l){return r("store",l)}try{Je(n,"encode");let l=o.encode(s,c);return a.run?.(!0),l}catch(l){return a.run?.(!1),r("encode",l)}}function Wx(e,t,n,o,r){switch(e.event){case"SessionStart":return Xx(e,t,n);case"UserPromptSubmit":return Kx(e,t,n);case"PreToolUse":return Zx(e,t,n,o);case"PostToolUse":return sp(e,t,n,o,r);case"PreCompact":return fp(e,t,n);case"Usage":return xp(e,n)}return Promise.resolve(y)}function Xa(e,t){return e.split(Kr).join(t.toolNamePrefix)}function Jo(e,t,n){return n.compactSummary==="host"?k(dr,n.toolNamePrefix):ga(Io(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function Xx(e,t,n){if(e.source==="compact"&&It(t)&&Ka(await A(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await A(n);return rn(r,e.sessionId,yn)?{kind:"hint",text:Jo(r,e,t),onceKey:yn}:y}let o=await A(n);return t.compactDelivery==="opencode-cache"&&$t(o,_t+e.sessionId)!==null?{kind:"hint",text:Jo(o,e,t),onceKey:Cn}:rn(o,e.sessionId,Ie)?{kind:"hint",text:Xa(Mn,t),onceKey:Ie}:y}async function Kx(e,t,n){let o=e.prompt??"",r=await qx(e,t,n);if(on(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:"prompt",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(o),body:o,turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),$x(e,n,o),t.compactDelivery==="pending-flag"){let s=await A(n);if($t(s,_t+e.sessionId)!==null)return{kind:"hint",text:Jo(s,e,t),onceKey:Cn}}return r!==null?r:zx(e,t,n,o)}async function qx(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await A(n);return Zc(o,e.sessionId)||!rn(o,e.sessionId,Ie)||!Qc(o,n.worktree,e.agent)?null:{kind:"hint",text:Xa(Mn,t),onceKey:Ie}}function Ka(e,t){t!==""&&B(e,Ln+t,In)}function Yx(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function Vx(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 zx(e,t,n,o){if(!It(t)||e.sessionId==="")return y;let r=await A(n);if($(r,Ln+e.sessionId)===null)return y;let s=xs+e.sessionId,i=Yx($(r,s)),c=ds+e.sessionId,a=Vx($(r,c)),l=Jc(r,e.sessionId),u=ua(r,e.sessionId,la(o,l),fs),d=Ea($c(r,e.sessionId,n.worktree,us),o,new Set(i),u,new Set(a));return d.text===""?y:(d.seqs.length>0&&B(r,s,JSON.stringify([...i,...d.seqs])),d.units!==void 0&&B(r,c,JSON.stringify([...a,...d.units])),{kind:"hint",text:d.text,onceKey:ps})}function qa(e){return gt+":"+mt+":"+e}function Jx(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 $x(e,t,n){if(e.sessionId==="")return;let o=qa(e.sessionId);A(t).then(r=>{if($(r,o)===null)return;let s=$t(r,o),i=s===null?null:Jx(s);if(i===null)return;let c=Ua(n,i.labels,i.seq);c!==null&&Ya(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+Qe(r)+`
210
- `)})}function Ya(e,t,n,o){for(let r of o)Qt(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:Un,key:r.key,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(r.body),body:r.body,turn:t.turn??0,sandbox_bytes:0,returned_bytes:0}),Xo(e,n,t.sessionId,gt,r.body,"text")}function Qx(e,t,n,o){let r=Pa(o),s=r.length===0?Ma(n.input):[];r.length===0&&s.length===0||A(t).then(i=>{if(r.length>0)return Ya(i,e,t,r);let c=Io(i,e.sessionId,"prompt"),a=c[c.length-1];a===void 0||e.sessionId===""||B(i,qa(e.sessionId),JSON.stringify({seq:a.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+Qe(i)+`
211
- `)})}async function Zx(e,t,n,o){let r=yc(n.worktree,e.agent),s=Pc(e,t,r),i=s;return s.kind==="deny"&&he(e)&&go(e,mo(e,{projectDir:n.worktree,env:o}))==="B"&&(i=tp(e,t,s,r)),i}function Va(e,t){return e.canonicalName===cs||t.nativeTools.shell.includes(e.name)}function ep(e,t){return e.startsWith(Ne)||e===k(ut,t.toolNamePrefix)||e===k(dt,t.toolNamePrefix)}function zo(e){return Buffer.from(e,"utf8").toString("base64url")}function tp(e,t,n,o){let r=e.tool;if(r===void 0||!Va(r,t)||ep(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+vx(Fx(process.argv[1]??""),Es)+'"',c=[gs,i,zo(s),zo(JSON.stringify(o??[])),zo(Ze(r.input.description))].join(" ");return{kind:"deny",reason:ms,rewritten:c}}function np(e,t,n){return n?"toolerr":as.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":Va(e,t)?"cmd":null}function $o(e){if(Array.isArray(e))return"["+e.map($o).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)+":"+$o(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function op(e){let t=e.indexOf(`
212
- `),n=t<0?e:e.slice(0,t);if(!n.startsWith(Nn))return null;let o=0,r=0;for(let s of n.slice(Nn.length)){let i=s.charCodeAt(0)-Gx;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function rp(e){for(let t of ls)if(typeof e[t]=="string")return e[t];return null}async function sp(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(pt))return y;let i=e.result??{isError:!1,bytes:0},c=ap(i);i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(c)),s.canonicalName===Un&&Qx(e,n,s,c);let a=np(s,t,i.isError),l=f=>{if(a===null)return;let x=a==="cmd"?Vc(s.canonicalName,Ze(s.input.command)):a==="toolerr"?s.canonicalName+":"+$o(s.input):null;on(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:a,tool:s.canonicalName,key:x,path:rp(s.input),ok:i.isError?0:1,exit_code:op(c),bytes:i.bytes,body:c,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:f})},u;try{u=await ip(e,t,n,o,s,i,c)}catch(f){throw l(i.bytes),f}let d=u;return r.run=f=>l(f&&d.kind==="replace"?Buffer.byteLength(d.output):i.bytes),u}async function ip(e,t,n,o,r,s,i){if(s.bytes<=nr||s.keep===!0||!Le(t))return y;let c;if(he(e)){if(go(e,mo(e,{projectDir:n.worktree,env:o}))==="A")return y;c=_s+r.canonicalName+":"+String(e.turn??0)}else c=up(r,e);let a=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url].map(Ze).find(_=>_.trim()!=="")??"",l=nn(i,"text",sr),u=await A(n),d;s.bytes<=tr?(d=Xo(u,n,e.sessionId,c,i,"text",l).sourceId,wo(u,d,e.sessionId,Po(i))):(d=Do(u,za(n,e.sessionId,c),l),dp(n,e.sessionId,d,c,i,l));let f=aa(d),x=await lp(n,e.sessionId),p=x.trim()===""?void 0:a+" "+x,g=ir(a,f,s.bytes,t.toolNamePrefix,La(a,x,i)),E=cp(g,Bo(a,c)),h=ya(i,p??a,rr);if(h!==null)return{kind:"replace",output:Ba(h,g)};let S=Ta(l,a,E,c,p);return{kind:"replace",output:S.more!==null?Ba(S.text,g):S.text}}function Ba(e,t){return e===""?t:e+`
213
- `+t}function cp(e,t){return Math.max(0,or+Buffer.byteLength(`
214
- `+t)-1-Buffer.byteLength(e))}function ap(e){let t=e.text??"";if(e.persistedPath===void 0)return t;try{return Hx(e.persistedPath,"utf8")}catch{return t}}async function lp(e,t){try{return zc(await A(e),t)}catch{return""}}function up(e,t){let n=Ze(e.input.command)??Ze(e.input.file_path)??"",o=n.indexOf(`
215
- `);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,br)+"#"+(e.callId??String(t.turn??0))}function dp(e,t,n,o,r,s){A(e).then(i=>{ia(i,n,za(e,t,o),s,Po(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+Qe(i)+`
216
- `)})}function za(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function fp(e,t,n){let o=await A(n);return B(o,_t+e.sessionId,In),It(t)&&Ka(o,e.sessionId),y}function xp(e,t){return on(t,e.sessionId,{session_id:e.sessionId,worktree:t.worktree,agent:e.agent,kind:"cost",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:0,body:"",turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),Promise.resolve(y)}var $a={stdout:"",exitCode:0};function pp(e){return Oe.includes(e)}function cn(e){process.exitCode=e.exitCode,e.stdout!==""&&Vo(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
217
- `)}function Ja(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
218
- `);try{return ze(r,e,n,o),$e(e,t,o)}catch{return $a}}async function _p(e,t){let n=e.indexOf(Et),o=n>=0?e[n+1]??"":"";if(!pp(o))return console.error("hooks: unknown "+Et+" "+JSON.stringify(o)+". Fix: pass "+Et+" with one of "+Oe.join(", ")+"."),cn($a);let r;try{r=JSON.parse(await Yo())}catch(s){return cn(Ja(o,void 0,"stdin",s,t))}try{return cn(await Wa(o,r,t))}catch(s){return cn(Ja(o,r,"load",s,t))}}_p(process.argv.slice(2),process.env);export{_p as main};
207
+ `)}}var va=!1;function Je(e,t){if(!(va||e[Xr]!==t))throw va=!0,new Error("injected fault at "+t)}function Ba(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=Ae.split(".");for(let o=0;o<n.length;o++){let r=Number(t[o]??0)||0,s=Number(n[o]);if(r!==s)return r<s}return!1}function te(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function Ux(e,t){let n=t.toLowerCase();return te(e.nativeTools.shell,n)||te(ye.shell,n)?"shell":te(e.nativeTools.read,n)||te(ye.read,n)?"read":te(e.nativeTools.grep,n)||te(ye.grep,n)?"grep":te(e.nativeTools.webfetch,n)||te(ye.fetch,n)?"fetch":null}function Hx(e,t){let n=t.toLowerCase();return Wr.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function Fx(e,t){if((e.offset??null)!==null||(e.limit??null)!==null)return!1;let n=sn(e,xt);if(n==="")return!1;try{let o=qo.statSync(Lx(t,n));return o.isFile()&&o.size>q}catch{return!1}}function $e(e,t,n,o=""){let r=re(e),s=()=>r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"});try{if(!Yo(t)||!Hx(r,sn(t,jr)))return s();let i=sn(t,vr);if(i===""||i.includes(pt))return s();let c=Ux(r,i);if(c===null)return s();let a=sn(t,Br)||o;if(c==="read"&&!Fx(wx(t),a))return s();let l=c==="read"?Rn.read:Rn[c],u=k(l,r.toolNamePrefix)+`
208
+ `+Kr(Ga(n),r.toolNamePrefix);return r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:a,turn:0},{kind:"deny",reason:u})}catch{return{stdout:"",exitCode:0}}}var{read:vx,writeSync:jx}=process.getBuiltinModule("node:fs"),Wa=65536;function Gx(e){let t=Buffer.allocUnsafe(Wa);return new Promise(n=>{let o=()=>{vx(0,t,0,Wa,null,(r,s)=>{if(r)return n(r.code==="EOF");if(s===0)return n(!0);e.push(Buffer.from(t.subarray(0,s))),o()})};o()})}async function Vo(){let e=[];if(!await Gx(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function zo(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=jx(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{readFileSync:Bx}=process.getBuiltinModule("node:fs"),y={kind:"allow"},Kx={stdout:"",exitCode:0},qx=48;function Yx(e){return Oe.includes(e)}function Qe(e){return e instanceof Error?e.message:String(e)}function Ze(e){return typeof e=="string"?e:""}async function Ka(e,t,n){if(!Yx(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
209
+ `),Kx;let o=re(e),r=(l,u,d)=>(ze(n,e,l,u),process.stderr.write(d??"hooks: "+l+" failed: "+Qe(u)+`
210
+ `),$e(e,t,u));if(Ba(process.version))return r("node",new T("NODE_TOO_OLD",{v:process.version}));let s;try{Je(n,"decode"),s=o.decode(t)}catch(l){return r("decode",l)}let i;try{Je(n,"project");let l=e==="vscode"?[it,s.cwd]:process.argv;i=Kc(e,{env:n,argv:l,cwd:s.cwd,piCwd:e==="pi"?s.cwd:void 0})}catch(l){return r("project",l,"hooks: no project: "+String(l.code??"ERROR")+" "+Qe(l)+`
211
+ `)}let c,a={};try{Je(n,"policy"),c=await Vx(s,o,i,n,a)}catch(l){return r("store",l)}try{Je(n,"encode");let l=o.encode(s,c);return a.run?.(!0),l}catch(l){return a.run?.(!1),r("encode",l)}}function Vx(e,t,n,o,r){switch(e.event){case"SessionStart":return zx(e,t,n);case"UserPromptSubmit":return Jx(e,t,n);case"PreToolUse":return rp(e,t,n,o);case"PostToolUse":return up(e,t,n,o,r);case"PreCompact":return gp(e,t,n);case"Usage":return mp(e,n)}return Promise.resolve(y)}function qa(e,t){return e.split(qr).join(t.toolNamePrefix)}function $o(e,t,n){return n.compactSummary==="host"?k(fr,n.toolNamePrefix):ha(ko(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function zx(e,t,n){if(e.source==="compact"&&It(t)&&Ya(await A(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await A(n);return rn(r,e.sessionId,yn)?{kind:"hint",text:$o(r,e,t),onceKey:yn}:y}let o=await A(n);return t.compactDelivery==="opencode-cache"&&$t(o,_t+e.sessionId)!==null?{kind:"hint",text:$o(o,e,t),onceKey:Cn}:rn(o,e.sessionId,Ie)?{kind:"hint",text:qa(Mn,t),onceKey:Ie}:y}async function Jx(e,t,n){let o=e.prompt??"",r=await $x(e,t,n);if(on(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:"prompt",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(o),body:o,turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),np(e,n,o),t.compactDelivery==="pending-flag"){let s=await A(n);if($t(s,_t+e.sessionId)!==null)return{kind:"hint",text:$o(s,e,t),onceKey:Cn}}return r!==null?r:ep(e,t,n,o)}async function $x(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await A(n);return ta(o,e.sessionId)||!rn(o,e.sessionId,Ie)||!ea(o,n.worktree,e.agent)?null:{kind:"hint",text:qa(Mn,t),onceKey:Ie}}function Ya(e,t){t!==""&&B(e,Ln+t,In)}function Qx(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function Zx(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 ep(e,t,n,o){if(!It(t)||e.sessionId==="")return y;let r=await A(n);if(Q(r,Ln+e.sessionId)===null)return y;let s=ps+e.sessionId,i=Qx(Q(r,s)),c=fs+e.sessionId,a=Zx(Q(r,c)),l=Qc(r,e.sessionId),u=fa(r,e.sessionId,da(o,l),xs),d=ma(Zc(r,e.sessionId,n.worktree,ds),o,new Set(i),u,new Set(a));return d.text===""?y:(d.seqs.length>0&&B(r,s,JSON.stringify([...i,...d.seqs])),d.units!==void 0&&B(r,c,JSON.stringify([...a,...d.units])),{kind:"hint",text:d.text,onceKey:_s})}function Va(e){return gt+":"+mt+":"+e}function tp(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 np(e,t,n){if(e.sessionId==="")return;let o=Va(e.sessionId);A(t).then(r=>{if(Q(r,o)===null)return;let s=$t(r,o),i=s===null?null:tp(s);if(i===null)return;let c=Fa(n,i.labels,i.seq);c!==null&&za(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+Qe(r)+`
212
+ `)})}function za(e,t,n,o){for(let r of o)Qt(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:Un,key:r.key,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(r.body),body:r.body,turn:t.turn??0,sandbox_bytes:0,returned_bytes:0}),Ko(e,n,t.sessionId,gt,r.body,"text")}function op(e,t,n,o){let r=Ua(o),s=r.length===0?Ha(n.input):[];r.length===0&&s.length===0||A(t).then(i=>{if(r.length>0)return za(i,e,t,r);let c=ko(i,e.sessionId,"prompt"),a=c[c.length-1];a===void 0||e.sessionId===""||B(i,Va(e.sessionId),JSON.stringify({seq:a.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+Qe(i)+`
213
+ `)})}async function rp(e,t,n,o){let r=Ic(n.worktree,e.agent),s=Uc(e,t,r),i=s;return s.kind==="deny"&&he(e)&&mo(e,ho(e,{projectDir:n.worktree,env:o}))==="B"&&(i=ip(e,t,s,r)),i}function Ja(e,t){return e.canonicalName===as||t.nativeTools.shell.includes(e.name)}function sp(e,t){return e.startsWith(Ne)||e===k(ut,t.toolNamePrefix)||e===k(dt,t.toolNamePrefix)}function Jo(e){return Buffer.from(e,"utf8").toString("base64url")}function ip(e,t,n,o){let r=e.tool;if(r===void 0||!Ja(r,t)||sp(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+Xx(Wx(process.argv[1]??""),gs)+'"',c=[ms,i,Jo(s),Jo(JSON.stringify(o??[])),Jo(Ze(r.input.description))].join(" ");return{kind:"deny",reason:hs,rewritten:c}}function cp(e,t,n){return n?"toolerr":ls.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":Ja(e,t)?"cmd":null}function Qo(e){if(Array.isArray(e))return"["+e.map(Qo).join(",")+"]";if(typeof e=="object"&&e!==null){let t=e;return"{"+Object.keys(t).filter(o=>t[o]!==void 0).sort().map(o=>JSON.stringify(o)+":"+Qo(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function ap(e){let t=e.indexOf(`
214
+ `),n=t<0?e:e.slice(0,t);if(!n.startsWith(Nn))return null;let o=0,r=0;for(let s of n.slice(Nn.length)){let i=s.charCodeAt(0)-qx;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function lp(e){for(let t of us)if(typeof e[t]=="string")return e[t];return null}async function up(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(pt))return y;let i=e.result??{isError:!1,bytes:0},c=xp(i);i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(c)),s.canonicalName===Un&&op(e,n,s,c);let a=cp(s,t,i.isError),l=f=>{if(a===null)return;let x=a==="cmd"?Jc(s.canonicalName,Ze(s.input.command)):a==="toolerr"?s.canonicalName+":"+Qo(s.input):null;on(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:a,tool:s.canonicalName,key:x,path:lp(s.input),ok:i.isError?0:1,exit_code:ap(c),bytes:i.bytes,body:c,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:f})},u;try{u=await dp(e,t,n,o,s,i,c)}catch(f){throw l(i.bytes),f}let d=u;return r.run=f=>l(f&&d.kind==="replace"?Buffer.byteLength(d.output):i.bytes),u}async function dp(e,t,n,o,r,s,i){if(s.bytes<=or||s.keep===!0||!Le(t))return y;let c;if(he(e)){if(mo(e,ho(e,{projectDir:n.worktree,env:o}))==="A")return y;c=Es+r.canonicalName+":"+String(e.turn??0)}else c=_p(r,e);let a=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url].map(Ze).find(_=>_.trim()!=="")??"",l=nn(i,"text",ir),u=await A(n),d;s.bytes<=nr?(d=Ko(u,n,e.sessionId,c,i,"text",l).sourceId,Po(u,d,e.sessionId,Mo(i))):(d=Lo(u,$a(n,e.sessionId,c),l),Ep(n,e.sessionId,d,c,i,l));let f=ua(d),x=await pp(n,e.sessionId),p=x.trim()===""?void 0:a+" "+x,g=cr(a,f,s.bytes,t.toolNamePrefix,Pa(a,x,i)),E=fp(g,Wo(a,c)),h=Ia(i,p??a,sr);if(h!==null)return{kind:"replace",output:Xa(h,g)};let S=Aa(l,a,E,c,p);return{kind:"replace",output:S.more!==null?Xa(S.text,g):S.text}}function Xa(e,t){return e===""?t:e+`
215
+ `+t}function fp(e,t){return Math.max(0,rr+Buffer.byteLength(`
216
+ `+t)-1-Buffer.byteLength(e))}function xp(e){let t=e.text??"";if(e.persistedPath===void 0)return t;try{return Bx(e.persistedPath,"utf8")}catch{return t}}async function pp(e,t){try{return $c(await A(e),t)}catch{return""}}function _p(e,t){let n=Ze(e.input.command)??Ze(e.input.file_path)??"",o=n.indexOf(`
217
+ `);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,Or)+"#"+(e.callId??String(t.turn??0))}function Ep(e,t,n,o,r,s){A(e).then(i=>{aa(i,n,$a(e,t,o),s,Mo(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+Qe(i)+`
218
+ `)})}function $a(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function gp(e,t,n){let o=await A(n);return B(o,_t+e.sessionId,In),It(t)&&Ya(o,e.sessionId),y}function mp(e,t){return on(t,e.sessionId,{session_id:e.sessionId,worktree:t.worktree,agent:e.agent,kind:"cost",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:0,body:"",turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),Promise.resolve(y)}var Za={stdout:"",exitCode:0};function hp(e){return Oe.includes(e)}function cn(e){process.exitCode=e.exitCode,e.stdout!==""&&zo(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
219
+ `)}function Qa(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
220
+ `);try{return ze(r,e,n,o),$e(e,t,o)}catch{return Za}}async function Sp(e,t){let n=e.indexOf(Et),o=n>=0?e[n+1]??"":"";if(!hp(o))return console.error("hooks: unknown "+Et+" "+JSON.stringify(o)+". Fix: pass "+Et+" with one of "+Oe.join(", ")+"."),cn(Za);let r;try{r=JSON.parse(await Vo())}catch(s){return cn(Qa(o,void 0,"stdin",s,t))}try{return cn(await Ka(o,r,t))}catch(s){return cn(Qa(o,r,"load",s,t))}}Sp(process.argv.slice(2),process.env);export{Sp as main};