context-mode 2.0.0-next.16 → 2.0.0-next.18

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