context-mode 2.2.0 → 2.2.1
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.zcode-plugin/plugin.json +1 -1
- package/README.md +75 -75
- package/SHA256SUMS +16 -16
- package/cli.mjs +12 -9
- package/copilot/plugin.json +1 -1
- package/gemini-extension.json +1 -1
- package/hook.mjs +91 -91
- package/opencode/plugin.js +214 -61
- package/package.json +1 -1
- package/pi/index.js +228 -63
- package/qwen-extension.json +1 -1
- package/run.mjs +60 -16
- package/search.mjs +60 -16
- package/server.mjs +100 -39
package/hook.mjs
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
1
1
|
import{createRequire as __cmRequire}from"node:module";if(typeof process.getBuiltinModule!=="function")process.getBuiltinModule=(id)=>__cmRequire(import.meta.url)(id);
|
|
2
|
-
var
|
|
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.`,vt="--agent",fi=1e3;var VE=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var JE=Object.freeze(["Ready. Your savings show up here after the first tool call.","Large outputs from ctx_execute, ctx_batch and ctx_index stay in the","sandbox, and only the short answer goes to the chat."]),$E=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),QE=Object.freeze(["ctx_resume brings back your last task, files changed and open issues","after a compact or a restart; ctx_search finds indexed content by words."]);var ZE=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),eg=Object.freeze(["ctx_index","ctx_search"]);var tg=Object.freeze(["session","source","project"]);var jt="decision";var so="AskUserQuestion",xi="answers",Gt="option",pi=" | ",vu="https://github.com/mksglu/context-mode.git";var ng=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),og=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 et=256;var ju="ctx_doctor:report";var rg=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(ju)}})`;var sg=Object.freeze(["--tags","--refs"]),Gu="v*";var ig=`git ls-remote --tags --refs ${vu} "${Gu}"`;var cg=`nvm install ${Ye.split(".")[0]}, or install it from https://nodejs.org`;var ag=Object.freeze(["MCP entry","hook entries","hook timeout"]);var k=Object.freeze({"claude-code":[".claude"],codex:[".codex"],gemini:[".gemini"],qwen:[".qwen"],"copilot-cli":[".copilot"],vscode:[".vscode"],kiro:[".kiro"],zcode:[".zcode"],pi:[".pi"],opencode:[".config","opencode"],omp:[".omp"]});var lg=Object.freeze(["upgrade","uninstall"]);var ug=Object.freeze(["clone","--depth","1","--branch"]),dg=Object.freeze(["rev-parse","HEAD"]);var fg=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),xg=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var pg=Object.freeze(["shell","bash","sh"]),_g=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var _i="tool-results",Ei=16*1024*1024;var Eg=Object.freeze(["doctor-env.ts","doctor-config.ts","doctor-hook.ts","doctor-db.ts","doctor-heal.ts","verify-sums.ts","plugin-swap.ts","host-write.ts","v1-remove.ts","uninstall.ts"]);var ae=e=>Object.freeze(e),gg=Object.freeze([ae({id:"antigravity",name:"Antigravity",clientNames:["antigravity","antigravity-client","antigravity-cli","agy"],envVars:["ANTIGRAVITY_CLI_ALIAS"],pluginPaths:[[".gemini","config","plugins"],[".gemini","antigravity","plugins"],[".gemini","antigravity-cli","plugins"],[".gemini","antigravity-ide","plugins"]],configDirs:[".gemini/antigravity",".gemini/antigravity-cli",".gemini/config"],binaries:["agy"],source:"v1.0.169:src/adapters/client-map.ts:15-17; detect.ts:156,481-483; #1340"}),ae({id:"cursor",name:"Cursor",clientNames:["cursor-vscode"],envVars:["CURSOR_TRACE_ID","CURSOR_CLI","CURSOR_CWD"],pluginPaths:[],configDirs:[".cursor"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:18; detect.ts:163-165,584"}),ae({id:"openclaw",name:"OpenClaw",clientNames:[],envVars:[],pluginPaths:[],configDirs:[".openclaw"],binaries:[],source:"v1.0.169:src/adapters/detect.ts:252,575 (the runtime sets no env var)"}),ae({id:"kimi",name:"Kimi Code",clientNames:["kimi-code","kimi"],envVars:[],pluginPaths:[],configDirs:[".kimi-code"],binaries:["kimi"],source:"v1.0.169:src/adapters/client-map.ts:42-44; detect.ts:567; adapters/kimi/index.ts:127"}),ae({id:"kilo",name:"Kilo Code",clientNames:["kilo code"],envVars:["KILO","KILO_PID"],pluginPaths:[],configDirs:[".config/kilo"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:28; detect.ts:170-171,592"}),ae({id:"zed",name:"Zed",clientNames:["zed"],envVars:["ZED_SESSION_ID","ZED_TERM"],pluginPaths:[],configDirs:[".config/zed"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:38-39; detect.ts:189-190,616"}),ae({id:"jetbrains-copilot",name:"JetBrains Copilot",clientNames:["jetbrains client","intellij idea","pycharm"],envVars:["IDEA_INITIAL_DIRECTORY"],pluginPaths:[],configDirs:[".config/JetBrains"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:23-25; detect.ts:213,600"})]);var mg=Object.freeze({"claude-code":{root:"plugin",file:["hooks","claude-code.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},codex:{root:"home",file:[".codex","hooks.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},gemini:{root:"plugin",file:["hooks","hooks.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!1},qwen:{root:"plugin",file:["hooks","qwen.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},"copilot-cli":{root:"home",file:[".copilot","hooks","context-mode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeoutSec",matcher:!1},vscode:{root:"home",file:[".copilot","hooks","context-mode-vscode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeout",matcher:!1},kiro:{root:"home",file:[".kiro","hooks","context-mode.json"],key:["hooks"],shape:"kiro",timeoutKey:"timeout",matcher:!1},zcode:{root:"home",file:[".zcode","cli","config.json"],key:["hooks","events"],shape:"zcode",timeoutKey:"timeoutMs",matcher:!0},pi:null,opencode:null,omp:null}),hg=Object.freeze(["PreToolUse","PostToolUse"]);var Sg=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var bg=Object.freeze(["features","hooks"]);var Og=Object.freeze(["",yt,It]);var Bu=Object.freeze({"claude-code":"claude plugin marketplace update context-mode && claude plugin update context-mode@context-mode",codex:"codex plugin marketplace upgrade context-mode",gemini:"gemini extensions update context-mode",qwen:"qwen extensions update context-mode",pi:"pi update --extensions",omp:"omp plugin upgrade context-mode",opencode:"opencode plugin update","copilot-cli":"npm i -g context-mode && context-mode setup --agents copilot-cli",vscode:"npm i -g context-mode && context-mode setup --agents vscode",kiro:"npm i -g context-mode && context-mode setup --agents kiro",zcode:"npm i -g context-mode && context-mode setup --agents zcode"});var Tg=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 Rg=Object.freeze(["hooks","codex"]),Ag=Object.freeze(["pretooluse.mjs","posttooluse.mjs","sessionstart.mjs","precompact.mjs","userpromptsubmit.mjs","stop.mjs"]);var Ng=Object.freeze([".mjs",".sh"]);var Wu="npm:context-mode";var Bt="CLAUDE_CONFIG_DIR";var gi="CODEX_HOME",mi="COPILOT_HOME",hi="GEMINI_CLI_HOME",Si="KIRO_HOME",bi="OPENCODE_CONFIG_DIR",io="APPDATA",Wt=Object.freeze(["Code","User"]),Xt="XDG_CONFIG_HOME";var Xu="mcp.json",yg=Object.freeze(["agents","default.json"]);var Ig=Object.freeze(["steering","KIRO.md"]),Oi="agent",Cg=Object.freeze(["opencode.jsonc","opencode.json"]);var Ku=`${Z}@`,Yu="@",kg=`${Ku}latest`,Dg=`${Wu}${Yu}latest`;var Lg=Object.freeze(["content","platform.json"]);var Ti="custom",Ri="PI_CODING_AGENT_DIR";var qu=Object.freeze(["/","\\"]),zu="${/}",Pg=Object.freeze([...qu,zu]),w=Object.freeze({hook:"old context-mode hook entry: command contains context-mode and an old script name or context-mode hook",cacheHealHook:"old context-mode cache-heal SessionStart hook entry",cacheHealFile:"old context-mode cache-heal script file",statusLine:"old context-mode statusLine (context-mode statusline): report only, never removed",mcpEntry:"old context-mode MCP entry mcpServers.context-mode",codexHook:"old context-mode Codex hook entry: context-mode hook codex or hooks/codex/<event>.mjs",codexToml:"old context-mode config.toml [mcp_servers.context-mode*] section",hookFile:"old context-mode hook file context-mode.json (runs context-mode hook)",vscodeMcp:"old context-mode MCP entry servers.context-mode in .vscode/mcp.json: report only, never removed",kiroHook:"old Kiro hook entry: command contains context-mode and an old script name or context-mode hook",kiroAgentFile:"old context-mode Kiro agent file agents/*.json with name context-mode",kiroSteering:"old context-mode Kiro steering doc .kiro/steering/KIRO.md: manual review, report only, never removed",piNpm:"old context-mode Pi package npm:context-mode",opencodePlugin:"old context-mode OpenCode plugin spec context-mode",piGit:"old context-mode Pi entry git:github.com/mksglu/context-mode@release: ctx_upgrade replaces it with npm:context-mode@latest",opencodeGit:"old context-mode OpenCode entry git+https://github.com/mksglu/context-mode.git#release: ctx_upgrade replaces it with context-mode@latest",zcodeHook:"old context-mode ZCode hook entry: command contains context-mode hook",dataDir:"old context-mode data dir <agent home>/context-mode/",dataDirShared:"old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",dataRoot:"old context-mode content under ~/.context-mode/",tmpFile:"old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep",projectLink:"context-mode path in the project reached through a link: report only, upgrade keeps it as is and never follows a link"}),wg=Object.freeze([w.statusLine,w.vscodeMcp,w.dataDirShared,w.tmpFile,w.kiroSteering,w.piGit,w.opencodeGit,w.projectLink]),Mg=Object.freeze([w.dataDir,w.dataRoot]);var Ug=Z+"_";var Hg=Object.freeze(["opencode","plugin.js"]);var Vu=Object.freeze(["features","mcp"]),Ju="omit_tools_from",$u=Object.freeze(["deferred"]),Qu="default_tools_approval_mode",Zu="approve",Fg=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",Z],fields:{[Ju]:$u,[Qu]:Zu}},vscode:{file:[Xu],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:Hu},also:[[Vu,!0]]}});var vg=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),ed="Environment: ";var td="Docs: ";var nd="Report file: ",od="File it: ",rd="Or open: ",sd="Rules: ",id=" --",jg=Object.freeze([ed,td,nd,od,id.trim(),rd,sd]),Ai="mksglu/context-mode",cd="agent-report.yml",Gg=`https://github.com/${Ai}/blob/main/.github/AGENT_ISSUE.md`,Bg=Object.freeze(['Search for the same problem first: `gh issue list -R mksglu/context-mode --state all --search "<check id or error>"`. When one matches, add your facts there as a comment.',"File one bug per issue.","Call the `ctx_doctor` tool and paste its full output unchanged in the `ctx-report` field.","Give the versions: context-mode, the agent, the OS and arch, and Node.","Write numbered repro steps that start from a fresh project (`mktemp -d`) and the agent's own install command.","Give the exact command and its exact output in a fenced code block.","Say what you expected and what happened instead.","Name the source file and line when you found the cause.","Replace every secret with `<masked>` and the home folder with `~` before you send."]);var Wg=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var Xg=Object.freeze(["CODEX_HOME","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_ROOT","COPILOT_HOME","KIRO_HOME","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","XDG_CONFIG_HOME","SHELL"]),Kg=Object.freeze(["node","git","sh"]),Yg=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var qg=Object.freeze({"claude-code":["claude plugin marketplace add mksglu/context-mode","claude plugin install context-mode@context-mode"],codex:["codex plugin marketplace add mksglu/context-mode","codex plugin add context-mode@context-mode"],gemini:["gemini extensions install https://github.com/mksglu/context-mode"],qwen:["qwen extensions install https://github.com/mksglu/context-mode:context-mode"],opencode:["opencode plugin add context-mode"],pi:["pi install npm:context-mode"],omp:["omp plugin install context-mode"],"copilot-cli":["npm i -g context-mode","context-mode setup --agents copilot-cli"],vscode:["npm i -g context-mode","context-mode setup --agents vscode"],kiro:["npm i -g context-mode","context-mode setup --agents kiro"],zcode:["zcode plugins marketplace add mksglu/context-mode","zcode plugins install context-mode@context-mode"]}),zg=`https://github.com/${Ai}/issues/new?template=${cd}`;import{dirname as Ru,join as Pr,relative as tE,resolve as nE,sep as Ou}from"node:path";var co="mcp__plugin_context-mode_context-mode__",Ci=Object.freeze(["Bash","PowerShell"]),ad="PowerShell",ld="Bash",ud=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],Ni="mcp__",yi="__",dd={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function fd(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(Ni))return e;let n=e.slice(Ni.length),o=n.indexOf(yi);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+yi.length)}function xd(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return ki(e).text;if(typeof e=="object"&&e!==null){let t=e;if(typeof t.stdout=="string"||typeof t.stderr=="string"){let n=typeof t.stdout=="string"?t.stdout:"",o=typeof t.stderr=="string"?t.stderr:"";return o===""?n:n===""?o:n+`
|
|
4
|
-
`+o}}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=
|
|
2
|
+
var Xe=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode","omp"];var te="context-mode",Nt=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function L(e,t){if(t==="")return e;let n=e;for(let o of Nt)n=n.split(o).join(t+o);return n}var ue=16384;var Hr=2048;var Fr=640,Pn="</context_mode_state>",Mn=1048576,vr=65536,Mr=4096,Vu="CTX_REPLACE_TRIGGER_BYTES";function Ju(e){if(e===void 0||e.trim()==="")return Mr;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Mr}var jr=Ju(process.env[Vu]),Ye=Object.freeze(["Read","view"]),Gr=Object.freeze(["offset","limit","view_range"]),Br=96,Wr=256,Xr=48;function Kr(e,t,n,o="",r=""){let s=r===""?[e]:[e,r];return o+"ctx_search({queries:["+s.map(i=>JSON.stringify(i)).join(",")+"], source:"+JSON.stringify(t)+"}) searches the whole output ("+n+" B)."}function Yr(e,t,n){return"The full output ("+t+" B) is stored as "+e+"; above is the best-matching part."+(n?" Read the file with offset and limit for other lines.":"")}function qr(e,t,n,o){return" Or run: node "+wn(e)+" "+t+" "+wn(n)+" "+wn(o)}function wn(e){return"'"+e.split("'").join("'\\''")+"'"}var zr=3,de=4096;var Un=85,Hn=340,Fn=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var Vr=.7,Jr=.7,$r=.3,vn=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]),Qr='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var $u=6e5;var M=5e3,yt="-wal",It="-shm",Zr=".tmp",es=["EACCES","EPERM","ENOSYS","ENOTSUP","EOPNOTSUPP"],ts=".publish",ns=["EEXIST","EPERM"],os=5,rs=255,ss=11,is=26;var B=5e3;var Ct=0;var cs=16,qe=6;var kt="projects",as="context.db";var jn=".git",Gn="worktree ",Bn="gitdir: ",ls="commondir",us="HEAD",Dt="--workspace-folder",ng=Object.freeze(["shell","powershell","javascript","typescript","python"]),ds=Object.freeze(["sh","bash","zsh","dash","ksh","fish"]);var fs=80;var og=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var xs="search.mjs",ps="claude-code";var rg=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),ze="24.15.0",_s="~/.context-mode",Ve="CONTEXT_MODE_DATA_DIR";var Es="CONTEXT_MODE_REQUIRE_SECURITY",gs=".claude",Je="agents",fe=".md",ms="synced",Lt="plugins",hs="installed_plugins.json",Re=":",Ss="@";var sg=Object.freeze(["local","project"]),ig=Object.freeze({local:0,project:1,user:2,managed:2}),Wn="---",bs="tools",Os="disallowedTools",Ae="mcp__",Ne="__",Ts="mcp_",Rs="_-.:",Ur=10;function Qu(e){if(e===void 0||e.trim()==="")return Ur;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:Ur}var cg=Qu(process.env.CTX_MCP_HINT_EVERY);var W=32;var As=Object.freeze([".agents","skills"]),Xn="context-mode: ",Ns=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),ys=" sends its body into the conversation.",Is="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",Cs="Tool: ",ks="state what you need",Ds="ctx_execute",Ls=Object.freeze(["ctx_index","ctx_search"]),$e="Blocked by security policy: matches deny pattern ",wt="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",Pt="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",Kn="hook-errors.log";var ws=Object.freeze(["tool_name","toolName","tool"]),Ps=Object.freeze(["hook_event_name","hookEventName","type"]),Ms=Object.freeze(["tool_input","toolArgs","input","args"]),Us=Object.freeze(["cwd","directory"]),Hs=Object.freeze(["pretooluse","beforetool","tool_call","execute.before","tool.execute.before"]),Fs="CM_HOOK_FAULT",ag=Object.freeze(["decode","project","policy","store","encode"]),Qe=Object.freeze({shell:Object.freeze(["Bash","bash","shell"]),read:Object.freeze(["Read","read_file"]),grep:Object.freeze(["Grep","grep_search"]),fetch:Object.freeze(["WebFetch","web_fetch","fetch"])});function vs(e,t){return`${Xn}the hook failed (${e}). Fix: run ${t}ctx_doctor.`}var Yn=Object.freeze({read:"Read the file in parts with offset and limit, or process it with ctx_execute(language, code); only what you print comes back.",shell:"Run the command with ctx_execute(language, code) or ctx_batch instead; only the part that matches your intent comes back.",grep:"Search with ctx_execute(language, code), or index the files with ctx_index and query them with ctx_search.",fetch:"Index the URL with ctx_index and query it with ctx_search."});var lg=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),ug=Object.freeze(["status"]),dg=Object.freeze(["--version","-v"]),fg=Object.freeze(["cp","mv","rm"]),xg=Object.freeze(["-v","--verbose"]),w=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),js="{prefix}",Gs=", then ",Bs="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",Ws=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),Xs=Object.freeze(["curl","wget"]),Ks=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),Ys=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),qs="-D",zs=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),Ze="fetch(",Vs="'\"`",Js="http",$s=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),Qs=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),Zs=Object.freeze(["head","tail"]),qn=Object.freeze(["-n","-c","--lines","--bytes"]),Mt="sed",ei=Object.freeze(["-n","--quiet","--silent"]),ti="jq",xe=Object.freeze(["file_path","absolute_path","path","filePath"]),ye="filePaths",zn=Object.freeze({png:{exts:[".png"],sig:[{at:0,bytes:[137,80,78,71,13,10,26,10]}]},jpeg:{exts:[".jpg",".jpeg"],sig:[{at:0,bytes:[255,216,255]}]},gif:{exts:[".gif"],sig:[{at:0,bytes:[71,73,70,56]}]},webp:{exts:[".webp"],sig:[{at:0,bytes:[82,73,70,70]},{at:8,bytes:[87,69,66,80]}]},pdf:{exts:[".pdf"],sig:[{at:0,bytes:[37,80,68,70,45]}]}}),Vn=12,Ke=Object.freeze(["png","jpeg","gif","webp"]),At=Object.freeze([...Ke,"pdf"]),ni=Object.freeze({"claude-code":At,gemini:At,qwen:At,opencode:At,pi:Ke,omp:Ke,vscode:Ke,zcode:Ke,"copilot-cli":[],codex:[],kiro:[]}),Ut="ctx_",oi="Bash",ri=Object.freeze(["Write","Edit"]),si=Object.freeze(["file_path","path"]),Jn="Exit code ",et="resume-hint",ii="compact-state",$n="pending-compact",Ht="pending_compact:",ci="1",tt=2048,Qn=5,ai=340,Zn="compacted:",li="recall_units_seen:",ui=8,Ft=64,di=64,fi="recall_seen:",eo="<context_mode_recall>",to="</context_mode_recall>",xi="recall",no="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",pi="subagent:",_i="run.mjs",Ei="node",gi=`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.`,vt="--agent",mi=1e3;var pg=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var _g=Object.freeze(["Ready. Your savings show up here after the first tool call.","Large outputs from ctx_execute, ctx_batch and ctx_index stay in the","sandbox, and only the short answer goes to the chat."]),Eg=Object.freeze([["index","Content indexed"],["edit","File edits"],["toolerr","Issues kept"],["decision","Your decisions"],["cmd","Other tool calls"],["prompt","Your prompts"]]),gg=Object.freeze(["ctx_resume brings back your last task, files changed and open issues","after a compact or a restart; ctx_search finds indexed content by words."]);var mg=Object.freeze([["sandbox","\u2588","sandbox run"],["index","\u2593","index + search"],["redirect","\u2592","hook sent to sandbox"],["replace","\u2591","hook cut down"]]),hg=Object.freeze(["ctx_index","ctx_search"]);var Sg=Object.freeze(["session","source","project"]);var jt="decision";var oo="AskUserQuestion",hi="answers",Gt="option",Si=" | ",Zu="https://github.com/mksglu/context-mode.git";var bg=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10","D11"]),Og=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 nt=256;var ed="ctx_doctor:report";var Tg=`ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(ed)}})`;var Rg=Object.freeze(["--tags","--refs"]),td="v*";var Ag=`git ls-remote --tags --refs ${Zu} "${td}"`;var Ng=`nvm install ${ze.split(".")[0]}, or install it from https://nodejs.org`;var yg=Object.freeze(["MCP entry","hook entries","hook timeout"]);var k=Object.freeze({"claude-code":[".claude"],codex:[".codex"],gemini:[".gemini"],qwen:[".qwen"],"copilot-cli":[".copilot"],vscode:[".vscode"],kiro:[".kiro"],zcode:[".zcode"],pi:[".pi"],opencode:[".config","opencode"],omp:[".omp"]});var Ig=Object.freeze(["upgrade","uninstall"]);var Cg=Object.freeze(["clone","--depth","1","--branch"]),kg=Object.freeze(["rev-parse","HEAD"]);var Dg=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),Lg=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var wg=Object.freeze(["shell","bash","sh"]),Pg=Object.freeze([["..","bin","bash.exe"],["..","..","bin","bash.exe"]]);var bi="tool-results",Oi=16*1024*1024;var Mg=Object.freeze(["doctor-env.ts","doctor-config.ts","doctor-hook.ts","doctor-db.ts","doctor-heal.ts","verify-sums.ts","plugin-swap.ts","host-write.ts","v1-remove.ts","uninstall.ts"]);var le=e=>Object.freeze(e),Ug=Object.freeze([le({id:"antigravity",name:"Antigravity",clientNames:["antigravity","antigravity-client","antigravity-cli","agy"],envVars:["ANTIGRAVITY_CLI_ALIAS"],pluginPaths:[[".gemini","config","plugins"],[".gemini","antigravity","plugins"],[".gemini","antigravity-cli","plugins"],[".gemini","antigravity-ide","plugins"]],configDirs:[".gemini/antigravity",".gemini/antigravity-cli",".gemini/config"],binaries:["agy"],source:"v1.0.169:src/adapters/client-map.ts:15-17; detect.ts:156,481-483; #1340"}),le({id:"cursor",name:"Cursor",clientNames:["cursor-vscode"],envVars:["CURSOR_TRACE_ID","CURSOR_CLI","CURSOR_CWD"],pluginPaths:[],configDirs:[".cursor"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:18; detect.ts:163-165,584"}),le({id:"openclaw",name:"OpenClaw",clientNames:[],envVars:[],pluginPaths:[],configDirs:[".openclaw"],binaries:[],source:"v1.0.169:src/adapters/detect.ts:252,575 (the runtime sets no env var)"}),le({id:"kimi",name:"Kimi Code",clientNames:["kimi-code","kimi"],envVars:[],pluginPaths:[],configDirs:[".kimi-code"],binaries:["kimi"],source:"v1.0.169:src/adapters/client-map.ts:42-44; detect.ts:567; adapters/kimi/index.ts:127"}),le({id:"kilo",name:"Kilo Code",clientNames:["kilo code"],envVars:["KILO","KILO_PID"],pluginPaths:[],configDirs:[".config/kilo"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:28; detect.ts:170-171,592"}),le({id:"zed",name:"Zed",clientNames:["zed"],envVars:["ZED_SESSION_ID","ZED_TERM"],pluginPaths:[],configDirs:[".config/zed"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:38-39; detect.ts:189-190,616"}),le({id:"jetbrains-copilot",name:"JetBrains Copilot",clientNames:["jetbrains client","intellij idea","pycharm"],envVars:["IDEA_INITIAL_DIRECTORY"],pluginPaths:[],configDirs:[".config/JetBrains"],binaries:[],source:"v1.0.169:src/adapters/client-map.ts:23-25; detect.ts:213,600"})]);var Hg=Object.freeze({"claude-code":{root:"plugin",file:["hooks","claude-code.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},codex:{root:"home",file:[".codex","hooks.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},gemini:{root:"plugin",file:["hooks","hooks.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!1},qwen:{root:"plugin",file:["hooks","qwen.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},"copilot-cli":{root:"home",file:[".copilot","hooks","context-mode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeoutSec",matcher:!1},vscode:{root:"home",file:[".copilot","hooks","context-mode-vscode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeout",matcher:!1},kiro:{root:"home",file:[".kiro","hooks","context-mode.json"],key:["hooks"],shape:"kiro",timeoutKey:"timeout",matcher:!1},zcode:{root:"home",file:[".zcode","cli","config.json"],key:["hooks","events"],shape:"zcode",timeoutKey:"timeoutMs",matcher:!0},pi:null,opencode:null,omp:null}),Fg=Object.freeze(["PreToolUse","PostToolUse"]);var vg=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var jg=Object.freeze(["features","hooks"]);var Gg=Object.freeze(["",yt,It]);var nd=Object.freeze({"claude-code":"claude plugin marketplace update context-mode && claude plugin update context-mode@context-mode",codex:"codex plugin marketplace upgrade context-mode",gemini:"gemini extensions update context-mode",qwen:"qwen extensions update context-mode",pi:"pi update --extensions",omp:"omp plugin upgrade context-mode",opencode:"opencode plugin update","copilot-cli":"npm i -g context-mode && context-mode setup --agents copilot-cli",vscode:"npm i -g context-mode && context-mode setup --agents vscode",kiro:"npm i -g context-mode && context-mode setup --agents kiro",zcode:"npm i -g context-mode && context-mode setup --agents zcode"});var Bg=Object.freeze(["afteragentresponse.mjs","aftermodel.mjs","aftertool.mjs","agentspawn.mjs","beforeagent.mjs","beforetool.mjs","posttooluse.mjs","precompact.mjs","precompress.mjs","pretooluse.mjs","sessionend.mjs","sessionstart.mjs","stop.mjs","userpromptsubmit.mjs"]);var Wg=Object.freeze(["hooks","codex"]),Xg=Object.freeze(["pretooluse.mjs","posttooluse.mjs","sessionstart.mjs","precompact.mjs","userpromptsubmit.mjs","stop.mjs"]);var Kg=Object.freeze([".mjs",".sh"]);var od="npm:context-mode";var Bt="CLAUDE_CONFIG_DIR";var Ti="CODEX_HOME",Ri="COPILOT_HOME",Ai="GEMINI_CLI_HOME",Ni="KIRO_HOME",yi="OPENCODE_CONFIG_DIR",ro="APPDATA",Wt=Object.freeze(["Code","User"]),Xt="XDG_CONFIG_HOME";var rd="mcp.json",Yg=Object.freeze(["agents","default.json"]);var qg=Object.freeze(["steering","KIRO.md"]),Ii="agent",zg=Object.freeze(["opencode.jsonc","opencode.json"]);var sd=`${te}@`,id="@",Vg=`${sd}latest`,Jg=`${od}${id}latest`;var $g=Object.freeze(["content","platform.json"]);var Ci="custom",ki="PI_CODING_AGENT_DIR";var cd=Object.freeze(["/","\\"]),ad="${/}",Qg=Object.freeze([...cd,ad]),P=Object.freeze({hook:"old context-mode hook entry: command contains context-mode and an old script name or context-mode hook",cacheHealHook:"old context-mode cache-heal SessionStart hook entry",cacheHealFile:"old context-mode cache-heal script file",statusLine:"old context-mode statusLine (context-mode statusline): report only, never removed",mcpEntry:"old context-mode MCP entry mcpServers.context-mode",codexHook:"old context-mode Codex hook entry: context-mode hook codex or hooks/codex/<event>.mjs",codexToml:"old context-mode config.toml [mcp_servers.context-mode*] section",hookFile:"old context-mode hook file context-mode.json (runs context-mode hook)",vscodeMcp:"old context-mode MCP entry servers.context-mode in .vscode/mcp.json: report only, never removed",kiroHook:"old Kiro hook entry: command contains context-mode and an old script name or context-mode hook",kiroAgentFile:"old context-mode Kiro agent file agents/*.json with name context-mode",kiroSteering:"old context-mode Kiro steering doc .kiro/steering/KIRO.md: manual review, report only, never removed",piNpm:"old context-mode Pi package npm:context-mode",opencodePlugin:"old context-mode OpenCode plugin spec context-mode",piGit:"old context-mode Pi entry git:github.com/mksglu/context-mode@release: ctx_upgrade replaces it with npm:context-mode@latest",opencodeGit:"old context-mode OpenCode entry git+https://github.com/mksglu/context-mode.git#release: ctx_upgrade replaces it with context-mode@latest",zcodeHook:"old context-mode ZCode hook entry: command contains context-mode hook",dataDir:"old context-mode data dir <agent home>/context-mode/",dataDirShared:"old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",dataRoot:"old context-mode content under ~/.context-mode/",tmpFile:"old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep",projectLink:"context-mode path in the project reached through a link: report only, upgrade keeps it as is and never follows a link"}),Zg=Object.freeze([P.statusLine,P.vscodeMcp,P.dataDirShared,P.tmpFile,P.kiroSteering,P.piGit,P.opencodeGit,P.projectLink]),em=Object.freeze([P.dataDir,P.dataRoot]);var tm=te+"_";var nm=Object.freeze(["opencode","plugin.js"]);var ld=Object.freeze(["features","mcp"]),ud="omit_tools_from",dd=Object.freeze(["deferred"]),fd="default_tools_approval_mode",xd="approve",om=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",te],fields:{[ud]:dd,[fd]:xd}},vscode:{file:[rd],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:$u},also:[[ld,!0]]}});var rm=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])}),pd="Environment: ";var _d="Docs: ";var Ed="Report file: ",gd="File it: ",md="Or open: ",hd="Rules: ",Sd=" --",sm=Object.freeze([pd,_d,Ed,gd,Sd.trim(),md,hd]),Di="mksglu/context-mode",bd="agent-report.yml",im=`https://github.com/${Di}/blob/main/.github/AGENT_ISSUE.md`,cm=Object.freeze(['Search for the same problem first: `gh issue list -R mksglu/context-mode --state all --search "<check id or error>"`. When one matches, add your facts there as a comment.',"File one bug per issue.","Call the `ctx_doctor` tool and paste its full output unchanged in the `ctx-report` field.","Give the versions: context-mode, the agent, the OS and arch, and Node.","Write numbered repro steps that start from a fresh project (`mktemp -d`) and the agent's own install command.","Give the exact command and its exact output in a fenced code block.","Say what you expected and what happened instead.","Name the source file and line when you found the cause.","Replace every secret with `<masked>` and the home folder with `~` before you send."]);var am=Object.freeze(["Summary","ctx-report","What happened","Hook errors","Journal rows","Agent config","Expected","Steps","Environment"]);var lm=Object.freeze(["CODEX_HOME","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_ROOT","COPILOT_HOME","KIRO_HOME","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","XDG_CONFIG_HOME","SHELL"]),um=Object.freeze(["node","git","sh"]),dm=Object.freeze(["token","secret","password","apikey","api_key","authorization","bearer"]);var fm=Object.freeze({"claude-code":["claude plugin marketplace add mksglu/context-mode","claude plugin install context-mode@context-mode"],codex:["codex plugin marketplace add mksglu/context-mode","codex plugin add context-mode@context-mode"],gemini:["gemini extensions install https://github.com/mksglu/context-mode"],qwen:["qwen extensions install https://github.com/mksglu/context-mode:context-mode"],opencode:["opencode plugin add context-mode"],pi:["pi install npm:context-mode"],omp:["omp plugin install context-mode"],"copilot-cli":["npm i -g context-mode","context-mode setup --agents copilot-cli"],vscode:["npm i -g context-mode","context-mode setup --agents vscode"],kiro:["npm i -g context-mode","context-mode setup --agents kiro"],zcode:["zcode plugins marketplace add mksglu/context-mode","zcode plugins install context-mode@context-mode"]}),xm=`https://github.com/${Di}/issues/new?template=${bd}`;import{dirname as Uu,join as wr,relative as _E,resolve as Hu,sep as wu}from"node:path";var so="mcp__plugin_context-mode_context-mode__",Mi=Object.freeze(["Bash","PowerShell"]),Od="PowerShell",Td="Bash",Rd=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],Li="mcp__",wi="__",Ad={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function Nd(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(Li))return e;let n=e.slice(Li.length),o=n.indexOf(wi);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+wi.length)}function yd(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return Ui(e).text;if(typeof e=="object"&&e!==null){let t=e;if(typeof t.stdout=="string"||typeof t.stderr=="string"){let n=typeof t.stdout=="string"?t.stdout:"",o=typeof t.stderr=="string"?t.stderr:"";return o===""?n:n===""?o:n+`
|
|
4
|
+
`+o}}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=io(e);if(t!==null)return t.text}return JSON.stringify(e)}function io(e){let t=e.file;return e.type==="text"&&typeof t=="object"&&t!==null&&typeof t.content=="string"?{text:t.content,put:(n,o)=>({...n,file:Id(n.file,o)})}:kd(e)?{text:e.content,put:(n,o)=>({...n,content:o})}:Array.isArray(e.filenames)&&e.filenames.every(n=>typeof n=="string")?{text:e.filenames.join(`
|
|
5
5
|
`),put:(n,o)=>({...n,filenames:o.split(`
|
|
6
|
-
`)})}:typeof e.result=="string"?{text:e.result,put:(n,o)=>({...n,result:o})}:null}function
|
|
6
|
+
`)})}:typeof e.result=="string"?{text:e.result,put:(n,o)=>({...n,result:o})}:null}function Id(e,t){let n=typeof e.startLine=="number"?e.startLine:1,o=String(e.content).split(`
|
|
7
7
|
`),r=typeof e.numLines=="number"?e.numLines:o.length,s=t.split(`
|
|
8
|
-
`),i=
|
|
9
|
-
`),startLine:n+i.at,numLines:c.length}}function
|
|
10
|
-
`),keep:n}}function
|
|
11
|
-
`+t.reason});case"replace":return n&&e.event==="PostToolUse"?o({updatedToolOutput:
|
|
12
|
-
`;function A(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var
|
|
13
|
-
\r\f\v`;function
|
|
14
|
-
`+t.reason}),exitCode:0}:Kt;case"replace":return e.event!=="PostToolUse"?Kt:{stdout:JSON.stringify({decision:"deny",reason:
|
|
15
|
-
`+t.reason}),exitCode:0};case"replace":return e.event!=="PostToolUse"?qt:{stdout:JSON.stringify({modifiedResult:{resultType:
|
|
16
|
-
`+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var
|
|
17
|
-
`+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function
|
|
18
|
-
`+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}}var
|
|
19
|
-
`,
|
|
20
|
-
`,
|
|
21
|
-
|
|
22
|
-
\r;&|()<>`,
|
|
23
|
-
\r`,
|
|
24
|
-
`,s),u=l<0?e.n:l,d=e.s.slice(s,u);if(d.endsWith("\r")&&(d=d.slice(0,-1)),s=l<0?e.n:l+1,(i.strip?d.trim():d)===i.tag){a=!0;break}}if(o!==null&&r!==null&&r.push(o.length),
|
|
25
|
-
`||f==="\r"){let S=c;c+=i.startsWith(
|
|
26
|
-
`&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(No,c)||i.startsWith(wc,c)){let S=on(e,c+No.length,!0,o+1,null,null);K(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}let p=Wf(i,c);if(p!==null){K(r,"io",i.slice(c,p.end),c,p.end),u=p.op===Mf||p.op===Nc?p.op===Nc:null,c=p.end;continue}if(i.startsWith(Ie,c)&&Io(i.charAt(c+Ie.length))){let S=Bf(e,c,o);if(S>0){K(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}if(i.startsWith(ot,c)){let S=Do(i,c);if(S>0){K(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let g=Df.find(S=>i.startsWith(S,c));if(g!==void 0){if(n&&g==="("&&a++,n&&g===")"){if(a>0)a--;else if(l===0)return c+1}K(r,"op",g,c,c+g.length),c+=g.length,u=null;continue}if(f==="$"&&x==="("||f==="`"){let S=f==="`"?ke(e,c):rt(e,c,o);if(Uc(i.charAt(S))){K(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let E=c;c=Xf(e,c,o);let h=i.slice(E,c);K(r,"word",h,E,c),u!==null&&(d.push({tag:De(h),strip:u}),u=null),n&&h===jf&&l++,n&&h===Gf&&l>0&&l--}return d.length>0&&Ce(e,"unterminated-heredoc"),e.n}function Fc(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return on(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function De(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=M;continue}if(r==="'"){let s=e.indexOf("'",n+1),i=s<0?o:s;t+=e.slice(n+1,i),n=i+1;continue}if(r==="$"&&e.charAt(n+1)==="'"){let s=n+Pc.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=M;continue}t+=e.charAt(s),s++}n=s+1;continue}if(r==='"'){let s=n+1;for(;s<o&&e.charAt(s)!=='"';){let i=e.charAt(s+1);if(e.charAt(s)==="\\"&&i!==""&&vf.includes(i)){t+=i,s+=M;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function rn(e){let t={s:e,n:e.length,end:"complete"},n=[],o=!1,r=0;for(;r<t.n;){let s=e.charAt(r),i=e.charAt(r+1);if(s==="\\"){r+=M;continue}if(!o&&s==="'"){r=nn(t,r);continue}if(!o&&s==="$"&&i==="'"){r=Hc(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Lc.length;continue}let c=e.startsWith(No,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(wc,r))){let a=r+1;if(s==="$"&&e.startsWith(ot,a)&&Do(e,a)>0){r=a+ot.length;continue}let l=on(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=ke(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 sn(e){let t=e.charAt(0);if(!(Dc(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(!(Dc(o)||yo(o)||o==="_"))return!1}return!1}var Bc=[";","&","&&","||"],Wc=["|","|&"],st="(",it=")",Xc=";;",wo=["(",")"],Yf="!";function U(e,t){for(let n of t)e.push(n)}var b=Object.freeze({group:"{",groupEnd:"}",if:"if",then:"then",elif:"elif",else:"else",fi:"fi",while:"while",until:"until",for:"for",in:"in",do:"do",done:"done",case:"case",esac:"esac",function:"function",coproc:"coproc",select:"select"}),Kc=[],qf="[[",zf="((",Yc=[">",">>",">|","&>","&>>",">&"],Vf=[...Yc,"<","<>","<<<","<<","<<-"],Jf=["","1"],qc=["-","/dev/stdout","/dev/stderr"],an="-",ct="--",at="=",$f="/",Qf=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),cn=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),Lo="-c",Po="--bytes",Zf="c",e0="--count",xe=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],te=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,D=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,Mo=e=>e!==""&&e>="0"&&e<="9",t0=e=>Mo(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function Uo(e){let t=e.lastIndexOf($f);return t>=0&&t<e.length-1?e.slice(t+1):e}function Ho(e,t){let n=Qf[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===ct)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+at))s=r.slice(n.long.length+at.length);else if(r.startsWith(an)&&!r.startsWith(ct)){let i=r.indexOf(n.short,an.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&&!qc.includes(s))return!0}return!1}function n0(e){if(e==="")return!1;for(let t of e)if(!Mo(t))return!1;return!0}function o0(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===Lo||n===Po?o=e[t+1]:n.startsWith(Po+at)?o=n.slice(Po.length+at.length):n.startsWith(Lo)&&!n.startsWith(ct)&&(o=n.slice(Lo.length)),o!==void 0)return n0(o)&&Number(o)<=le}return!1}function r0(e){for(let t of e){if(t===ct)return!1;if(t===e0||t.startsWith(an)&&!t.startsWith(ct)&&t.includes(Zf))return!0}return!1}function vc(e){if(!e.startsWith(P.fieldSep))return!1;for(let t of e.slice(P.fieldSep.length).split(P.fieldSep)){if(t==="")return!1;for(let n of t)if(!t0(n))return!1}return!0}function s0(e){let t=e.trim();if(t===P.identity||t===P.length)return!0;let n=t.indexOf(P.pipeLength.charAt(0));if(n<0)return vc(t);let o=t.slice(0,n).trim(),r=P.pipeLength.slice(1).trim();return(o===P.identity||vc(o))&&t.slice(n+1).trim()===r}function i0(e){let t=e.argv0.toLowerCase();if(t===cn.wc)return!0;if(t===cn.head)return o0(e.args);if(t===cn.grep)return r0(e.args);if(t===cn.jq){let n=e.args.filter(o=>!o.startsWith(an));return n.length===1&&s0(n[0])}return!1}function Fo(e){return rn(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function zc(e,t,n){return n<=t?[]:Fo(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function Vc(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function c0(e){let t=0;for(;Mo(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function Jc(e){let t=c0(e.toks[e.i].text);if(e.i++,!Vf.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,Yc.includes(t.op)&&Jf.includes(t.fd)&&!qc.includes(De(n.text)))}function $c(e){let t=!1;for(;O(e)?.kind==="io";)t=Jc(e)||t;return t}function Qc(e){for(;O(e)?.kind==="op"&&Bc.includes(O(e)?.text??"");)e.i++}function Le(e,t){if(e.depth++,e.depth>B)return e.err="nesting-too-deep",xe();let n=t();if(e.depth--,$c(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function Zc(e){if(Qc(e),!D(O(e),b.do))return[];e.i++;let t=Y(e,[b.done]);return D(O(e),b.done)&&e.i++,t}function a0(e){e.i++;let t=Y(e,[b.then]);for(;e.err===null;){let n=O(e);if(D(n,b.then)||D(n,b.else)){e.i++,U(t,Y(e,[b.elif,b.else,b.fi]));continue}if(D(n,b.elif)){e.i++,U(t,Y(e,[b.then]));continue}D(n,b.fi)&&e.i++;break}return t}function l0(e){e.i++;let t=Y(e,[b.do]);return U(t,Zc(e)),t}function u0(e){e.i++;let t=[],n=O(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,D(O(e),b.in)){e.i++;let o=e.i;for(;(O(e)?.kind==="word"||O(e)?.kind==="unhandled")&&!D(O(e),b.do);)e.i++;U(t,zc(e,o,e.i))}return U(t,Zc(e)),t}function d0(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,U(t,zc(e,e.i-1,e.i))),D(O(e),b.in)&&e.i++;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)||o.kind==="op"&&(Bc.includes(o.text)||o.text===Xc)){e.i++;continue}if(D(o,b.esac)){e.i++;break}for(te(o,st)&&e.i++;e.i<e.toks.length&&!te(O(e),it);){let s=e.toks[e.i];if(s.kind==="op"&&!Wc.includes(s.text))break;e.i++}if(!te(O(e),it))break;e.i++;let r=Y(e,[b.esac]);Vc(r,b.case),U(t,r)}return t}function jc(e,t){Qc(e);let n=ea(e);return Vc(n.cmds,t),{cmds:n.cmds,simple:null}}function Gc(e,t){return wo.every((n,o)=>te(e.toks[t+o],n))}function f0(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=Jc(e)||o;continue}if(n.length===0&&l.kind==="word"&&sn(l.text)){e.i++;let u=O(e);if(l.text.endsWith(at)&&u!==void 0&&te(u,st)&&u.start===l.end){let d=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,te(f,st)&&d++,te(f,it)&&--d===0)break}}continue}n.push(l),e.i++}if(e.i===t)return xe();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:Fo(r),simple:null};let s=l=>l.kind==="word"?De(l.text):l.text,i=Uo(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||Ho(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function ea(e){let t=O(e);if(t===void 0)return xe();if(t.kind==="op")return t.text!==st?xe():Le(e,()=>{e.i++;let n=Y(e,Kc);return te(O(e),it)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(qf)||t.text.startsWith(zf)))return e.i++,$c(e),{cmds:Fo(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return Le(e,()=>{e.i++;let n=Y(e,[b.groupEnd]);return D(O(e),b.groupEnd)&&e.i++,n});case b.if:return Le(e,()=>a0(e));case b.while:case b.until:return Le(e,()=>l0(e));case b.for:return Le(e,()=>u0(e));case b.case:return Le(e,()=>d0(e));case b.coproc:return e.err="coproc",xe();case b.select:return e.err="select",xe();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=De(n.text),e.i++),Gc(e,e.i)&&(e.i+=wo.length),jc(e,o)}default:if(Gc(e,e.i+1))return e.i+=wo.length+1,jc(e,De(t.text))}return f0(e)}function x0(e){D(O(e),Yf)&&e.i++;let t=[],n=xe();for(;e.err===null;){n=ea(e),U(t,n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&Wc.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&i0(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function Y(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===it||o.text===Xc)return n;if(o.text!==st){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;U(n,x0(e)),e.i===r&&e.err===null&&e.i++}return n}function Pe(e){let t=Fc(e);if(t.end==="unterminated-quote")return{ok:!1,construct:"unterminated-quote"};if(t.end==="unterminated-heredoc")return{ok:!1,construct:"unterminated-heredoc"};if(t.end==="too-deep")return{ok:!1,construct:"nesting-too-deep"};let n={toks:t.tokens,src:e,bodies:new Set(t.heredocBodies),i:0,depth:0,err:null},o=[];for(;n.i<n.toks.length&&n.err===null;)U(o,Y(n,Kc)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as ta}from"node:path";var un="'",we='"',dn="`",p0=" \r",ut="([{",Bo=")]}",vo=` \r
|
|
27
|
-
|;>`,
|
|
8
|
+
`),i=Cd(o,s);if(i===null)return{...e,content:t,startLine:n+r,numLines:s.length};let c=s.slice(0,i.length);return i.length<s.length&&c.push(s[s.length-1]),{...e,content:c.join(`
|
|
9
|
+
`),startLine:n+i.at,numLines:c.length}}function Cd(e,t){let n=null;for(let o=0;o<e.length;o++){if(e[o]!==t[0])continue;let r=1;for(;r<t.length&&o+r<e.length&&e[o+r]===t[r];)r++;if((n===null||r>n.length)&&(n={at:o,length:r}),r===t.length)break}return n}function Pi(e){let t=e;return typeof t.stdout=="string"||typeof t.stderr=="string"}function kd(e){let t=e;return(t.mode==="content"||t.mode==="count")&&typeof t.content=="string"}function Ui(e){let t=[],n=!1;for(let o of e){let r=typeof o=="object"&&o!==null?o:{};r.type==="text"&&typeof r.text=="string"?t.push(r.text):n=!0}return{text:t.join(`
|
|
10
|
+
`),keep:n}}function Dd(e){let t=yd(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)&&Pi(e)&&(o.shape=e),typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Pi(e)&&(io(e)!==null?o.shape=e:o.keep=!0),Array.isArray(e)&&(o.blocks=!0,Ui(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 pe(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=Rd.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:Nd(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=Dd(r.tool_response)),i}function Ld(e,t){let n=e.result?.shape;if(e.tool?.canonicalName==="Bash"){let{persistedOutputPath:r,persistedOutputSize:s,...i}=n??{};return{interrupted:!1,...i,stdout:t,stderr:""}}let o=n===void 0?null:io(n);return n!==void 0&&o!==null?o.put(n,t):e.result?.blocks===!0?[{type:"text",text:t}]:t}function X(e,t,n){let o=r=>({stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e.event,...r}}),exitCode:0});switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return o({additionalContext:t.text});case"deny":return o({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
11
|
+
`+t.reason});case"replace":return n&&e.event==="PostToolUse"?o({updatedToolOutput:Ld(e,t.output)}):{stdout:"",exitCode:0}}}var wd={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function Pd(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 Md(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 wd[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function Hi(e){Md(e);let t=pe(e,"claude-code",so,Ad);if(t.tool!==void 0&&t.tool.name===Od&&(t.tool.canonicalName=Td),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"+Pd(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function Fi(e,t,n){return X(e,t,!0)}var ao="mcp__context_mode__",Hd={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"},co="Stop",Fd={stdout:"",exitCode:0};function vi(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===co){let t=e;return{event:co,agent:"codex",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")}}return pe(e,"codex",ao,Hd)}function ji(e,t,n){return e.event===co?Fd:X(e,t,!1)}var Yt="mcp_context-mode_",Gi={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},Bi={startup:"startup",resume:"resume",clear:"clear"},jd=["SessionStart","UserPromptSubmit","PostToolUse"],Gd=["UserPromptSubmit","PreToolUse"],Kt={stdout:"",exitCode:0},Bd=`the tool ran and succeeded; context-mode indexed its full output, and this is the part that answers the call:
|
|
12
|
+
`;function A(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var Wi={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function Wd(e,t){if(e.startsWith(Yt))return e.slice(Yt.length);if(Object.hasOwn(Wi,e))return Wi[e];if(typeof t!="object"||t===null)return e;let n=t,o=A(n,"server_name"),r=A(n,"tool_name");return typeof o!="string"||typeof r!="string"?e:"mcp:"+o+":"+r}function Xd(e){if(!Array.isArray(e)||e.length===0)return;let t=[];for(let n of e){if(typeof n=="string"){t.push(n);continue}if(typeof n!="object"||n===null)return;let o=A(n,"text");if(typeof o!="string")return;t.push(o)}return t.join("")}function Kd(e){let t=typeof e=="object"&&e!==null?e:void 0,n=t===void 0?void 0:A(t,"llmContent"),o=e===void 0?"":typeof e=="string"?e:typeof n=="string"?n:Xd(n)??JSON.stringify(e),r=t===void 0?void 0:A(t,"error"),s={isError:r!=null,bytes:Buffer.byteLength(o),text:o};return Yd(n)&&(s.keep=!0),s}function Yd(e){return(Array.isArray(e)?e:[e]).some(n=>typeof n=="object"&&n!==null&&(Object.hasOwn(n,"inlineData")||Object.hasOwn(n,"fileData")))}var qd=["https://","http://"],zd=`.,;:!?)]}>'"`,Vd=`
|
|
13
|
+
\r\f\v`;function Jd(e){let t=[],n="";for(let o of e)Vd.includes(o)?(n!==""&&t.push(n),n=""):n+=o;return n!==""&&t.push(n),t}function $d(e){if(typeof e=="string")for(let t of Jd(e)){let n=t.toLowerCase(),o=qd.map(s=>n.indexOf(s)).filter(s=>s>=0).sort((s,i)=>s-i)[0];if(o===void 0)continue;let r=t.slice(o);for(;r.length>0&&zd.includes(r[r.length-1]);)r=r.slice(0,-1);return r}}function Qd(e,t){if(e==="web_fetch"&&A(t,"url")===void 0){let n=$d(A(t,"prompt"));return n===void 0?t:{...t,url:n}}if(e==="read_many_files"&&A(t,"file_path")===void 0){let n=A(t,"include"),o=Array.isArray(n)?n.filter(r=>typeof r=="string"):[];return o.length===0?t:{...t,file_path:o.join(" ")}}return t}function Xi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("gemini: hook payload is not a JSON object");let t=e,n=A(t,"hook_event_name"),o=typeof n=="string"&&Object.hasOwn(Gi,n)?Gi[n]:void 0;if(o===void 0)throw new Error("gemini: unknown hook event "+String(n));let r={event:o,agent:"gemini",sessionId:String(A(t,"session_id")??""),cwd:String(A(t,"cwd")??"")},s=A(t,"source");o==="SessionStart"&&typeof s=="string"&&Object.hasOwn(Bi,s)&&(r.source=Bi[s]);let i=A(t,"prompt");if(o==="UserPromptSubmit"&&typeof i=="string"&&(r.prompt=i),o==="PreToolUse"||o==="PostToolUse"){let c=String(A(t,"tool_name")??""),a=A(t,"tool_input");r.tool={name:c,canonicalName:Wd(c,A(t,"mcp_context")),input:Qd(c,typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{})}}return o==="PostToolUse"&&(r.result=Kd(A(t,"tool_response"))),r}function Ki(e,t,n){switch(t.kind){case"allow":return Kt;case"hint":return jd.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:Kt;case"deny":return Gd.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
14
|
+
`+t.reason}),exitCode:0}:Kt;case"replace":return e.event!=="PostToolUse"?Kt:{stdout:JSON.stringify({decision:"deny",reason:Bd+t.output}),exitCode:0}}}var lo="mcp__context-mode__",ef={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Yi={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},tf="PostToolUseFailure";function qi(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===tf,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=pe(n,"qwen",lo,ef);if(o.tool!==void 0&&Object.hasOwn(Yi,o.tool.name)&&(o.tool.canonicalName=Yi[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 zi(e,t,n){return X(e,t,!1)}var zt="context-mode-",of={sessionStart:{event:"SessionStart",casing:"camel",failure:!1},userPromptSubmitted:{event:"UserPromptSubmit",casing:"camel",failure:!1},preToolUse:{event:"PreToolUse",casing:"camel",failure:!1},postToolUse:{event:"PostToolUse",casing:"camel",failure:!1},postToolUseFailure:{event:"PostToolUse",casing:"camel",failure:!0},SessionStart:{event:"SessionStart",casing:"snake",failure:!1},UserPromptSubmit:{event:"UserPromptSubmit",casing:"snake",failure:!1},PreToolUse:{event:"PreToolUse",casing:"snake",failure:!1},PostToolUse:{event:"PostToolUse",casing:"snake",failure:!1},PostToolUseFailure:{event:"PostToolUse",casing:"snake",failure:!0}},Vi={startup:"startup",resume:"resume",new:"startup"},rf={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"}},Qi="success";function Vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var uo=Object.freeze(["bash","powershell"]),Ji=Object.fromEntries(uo.map(e=>[e,"Bash"]));function sf(e){return e.startsWith(zt)?e.slice(zt.length):Object.hasOwn(Ji,e)?Ji[e]:e}var $i=e=>typeof e=="number"&&Number.isFinite(e);function cf(e,t){let n=t.view_range;if(e!=="view"||!Array.isArray(n)||!$i(n[0]))return t;let o={...t,offset:n[0]};return $i(n[1])&&n[1]>=n[0]&&(o.limit=n[1]-n[0]+1),o}function af(e){if(Vt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return Vt(t)?t:{}}catch{return{}}}var lf={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function uf(e,t,n){let o=lf[t],r=Vt(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==Qi,bytes:Buffer.byteLength(s),text:s}}var df=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function ff(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:df.find(([t])=>Object.hasOwn(e,t))?.[1]}function Zi(e){if(!Vt(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=ff(e),n=typeof t=="string"?of[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=rf[n.casing],r=n.event,s={event:r,agent:"copilot-cli",sessionId:String(e[o.session]??""),cwd:String(e.cwd??"")};if(r==="SessionStart"&&typeof e.source=="string"&&Vi[e.source]!==void 0&&(s.source=Vi[e.source]),r==="UserPromptSubmit"&&typeof e.prompt=="string"&&(s.prompt=e.prompt),r==="PreToolUse"||r==="PostToolUse"){let i=String(e[o.tool]??""),c={name:i,canonicalName:sf(i),input:cf(i,af(e[o.args]))};s.tool=c}return r==="PostToolUse"&&(s.result=uf(e[o.result],n.casing,n.failure)),s}var qt={stdout:"",exitCode:0};function ec(e,t,n){switch(t.kind){case"allow":return qt;case"hint":return e.event==="PostToolUse"?qt:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?qt:{stdout:JSON.stringify({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
15
|
+
`+t.reason}),exitCode:0};case"replace":return e.event!=="PostToolUse"?qt:{stdout:JSON.stringify({modifiedResult:{resultType:Qi,textResultForLlm:t.output}}),exitCode:0}}}var Jt="mcp_context-mode_",ic=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],tc="mcp_",nc="_",pf="new",fo=Object.freeze(["run_in_terminal","runTerminalCommand","bash","powershell"]),Qt=Object.freeze(["read_file","view"]),xo=Object.freeze(["fetch_webpage","web_fetch"]),oc=Object.fromEntries([...fo.map(e=>[e,"Bash"]),...Qt.map(e=>[e,"Read"]),...xo.map(e=>[e,"WebFetch"])]);function cc(e){if(e.startsWith(Jt))return e.slice(Jt.length);if(Object.hasOwn(oc,e))return oc[e];if(!e.startsWith(tc))return e;let t=e.slice(tc.length),n=t.indexOf(nc);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+nc.length)}var ot=e=>typeof e=="number"&&Number.isFinite(e);function ac(e,t,n){if(t==="Read"&&Qt.includes(e)){let o={...n};if(e==="read_file")typeof n.filePath=="string"&&(o.file_path=n.filePath),ot(n.startLine)&&(o.offset=n.startLine),ot(n.startLine)&&ot(n.endLine)&&n.endLine>=n.startLine&&(o.limit=n.endLine-n.startLine+1);else if(Array.isArray(n.view_range)&&ot(n.view_range[0])){o.offset=n.view_range[0];let r=n.view_range[1];ot(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 _f(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:typeof e=="object"&&e!==null&&e.is_error===!0,bytes:Buffer.byteLength(t),text:t}}var Ef={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},gf=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],rc={new:"startup",startup:"startup",resume:"resume"},mf="success";function $t(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hf(e){if($t(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return $t(t)?t:{}}catch{return{}}}function Sf(e){let t=$t(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==mf,bytes:Buffer.byteLength(n),text:n}}function sc(e,t){let n=typeof t=="string"?Ef[t]??ic.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"&&rc[e.source]!==void 0&&(o.source=rc[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??""),s=cc(r);o.tool={name:r,canonicalName:s,input:ac(r,s,hf(e.toolArgs))}}return n==="PostToolUse"&&(o.result=Sf(e.toolResult)),o}function lc(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 sc(t,t.hookEventName);if(t.hook_event_name===void 0){let r=gf.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return sc(t,r)}let n=ic.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===pf&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=$t(t.tool_input)?t.tool_input:{},i=cc(r);o.tool={name:r,canonicalName:i,input:ac(r,i,s)}}return n==="PostToolUse"&&(o.result=_f(t.tool_response)),o}function uc(e,t,n){return X(e,t,!1)}var Zt="mcp_context_mode_",dc="mcp_context-mode_",fc={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},Of="prompt",Tf="USER_PROMPT",xc="mcp_",po=Object.freeze(["execute_bash","execute_pwsh","shell"]),pc=Object.fromEntries(po.map(e=>[e,"Bash"])),_c="_",Ec={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function Rf(e){if(e.startsWith(Zt))return e.slice(Zt.length);if(e.startsWith(dc))return e.slice(dc.length);if(Object.hasOwn(pc,e))return pc[e];if(!e.startsWith(xc))return e;let t=e.slice(xc.length),n=t.indexOf(_c);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+_c.length)}function Af(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function gc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("kiro: hook payload is not a JSON object");let t=e,n=typeof t.hook_event_name=="string"?t.hook_event_name:"",o=Object.prototype.hasOwnProperty.call(fc,n)?fc[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"&&Ec[t.source]!==void 0&&(r.source=Ec[t.source]),o==="UserPromptSubmit"){let s=t[Of],i=typeof s=="string"?s:process.env[Tf];i!==void 0&&(r.prompt=i)}if(o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool_name??""),i=typeof t.tool_input=="object"&&t.tool_input!==null&&!Array.isArray(t.tool_input)?t.tool_input:{};r.tool={name:s,canonicalName:Rf(s),input:i}}return o==="PostToolUse"&&(r.result=Af(t.tool_response)),r}function mc(e,t,n){if(e.event==="UserPromptSubmit")return{stdout:t.kind==="hint"?t.text:"",exitCode:0};switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:t.text,exitCode:0};case"deny":return{stdout:"",stderr:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
16
|
+
`+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var _o="mcp__context-mode__",hc="mcp__plugin_context-mode_context-mode__",yf={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},If={hook_event_name:"hookEventName",session_id:"sessionId"},Cf="PostToolUseFailure";function Sc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("zcode: hook payload is not a JSON object");let t={...e};for(let[i,c]of Object.entries(If))t[i]===void 0&&(t[i]=t[c]);let n=t.hook_event_name===Cf;n&&(t.hook_event_name="PostToolUse");let r=(typeof t.tool_name=="string"?t.tool_name:"").startsWith(hc)?hc:_o,s=pe(t,"zcode",r,yf);if(n){let i=typeof t.error=="string"?t.error:t.error===void 0?"":JSON.stringify(t.error);s.result={isError:!0,bytes:Buffer.byteLength(i),text:i}}return s}function bc(e,t,n){return X(e,t,!1)}var Eo="",Oc={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},Tc={bash:"Bash",read:"Read",edit:"Edit",write:"Write"};function Df(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Lf(e){let t=e.content===void 0?"":typeof e.content=="string"?e.content:JSON.stringify(e.content),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),e.keep===!0&&(n.keep=!0),n}function Rc(e){return{...go(e),agent:"omp"}}function go(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(Oc,n)?Oc[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(Tc,s)?Tc[s]:s,input:Df(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=Lf(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function wf(e,t){switch(t?.kind){case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
17
|
+
`+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function mo(e,t,n){let o=wf(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:Ci,content:o.stdout,timestamp:Date.now()}}function ho(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var Ic="",Ac=te+"_",Nc={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},So="bash",bo="read",Mf=Object.freeze([So,"shell"]),yc={webfetch:"WebFetch",[bo]:"Read",...Object.fromEntries(Mf.map(e=>[e,"Bash"]))};function Oo(e){return e.startsWith(Ac)?e.slice(Ac.length):Object.prototype.hasOwnProperty.call(yc,e)?yc[e]:e}function Uf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Hf(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 Cc(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(Nc,n)?Nc[n]:void 0;if(o===void 0)throw new Error("opencode: unknown hook event "+String(t.type));let r={event:o,agent:"opencode",sessionId:String(t.sessionID??""),cwd:String(t.directory??"")};if(typeof t.agentID=="string"&&t.agentID!==""&&(r.agentId=t.agentID,r.agentType=t.agentID),Array.isArray(t.agentTools)&&(r.agentTools=t.agentTools.filter(s=>typeof s=="string")),o==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool??"");r.tool={name:s,canonicalName:Oo(s),input:Uf(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=Hf(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function kc(e,t,n){switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
18
|
+
`+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}}var rt={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},Dc={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},vf={...Dc,shell:[...Mi]},jf=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:so,nativeTools:vf,execReadOnlyHint:!1,eventMap:rt,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:B,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"skills"},decode:Hi,encode:Fi},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:ao,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:rt,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:B,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:vi,encode:ji},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:Yt,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:B,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:Xi,encode:Ki},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:lo,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:rt,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:B,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:qi,encode:zi},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:zt,nativeTools:{shell:[...uo]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:B,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:Zi,encode:ec},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:Jt,nativeTools:{shell:[...fo],read:[...Qt],webfetch:[...xo]},execReadOnlyHint:!1,eventMap:{...rt,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:B,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:lc,encode:uc},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:Zt,nativeTools:{shell:[...po]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:B,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:gc,encode:mc},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:_o,nativeTools:Dc,execReadOnlyHint:!1,eventMap:rt,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:B,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:Sc,encode:bc},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:Eo,nativeTools:{shell:["bash","powershell"],read:["read"]},execReadOnlyHint:!1,eventMap:{SessionStart:"session_start",UserPromptSubmit:"input",PreToolUse:"tool_call",PostToolUse:"tool_result"},compactDelivery:"pi-flag",compactSummary:"none",hookTimeoutMs:Ct,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:go,encode:mo,checkPermission:ho},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:Ic,nativeTools:{shell:[So],read:[bo]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:Ct,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:Cc,encode:kc,toCanonicalTool:Oo},{id:"omp",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:Eo,nativeTools:{shell:["bash","powershell"],read:["read"]},execReadOnlyHint:!1,eventMap:{SessionStart:"session_start",UserPromptSubmit:"input",PreToolUse:"tool_call",PostToolUse:"tool_result"},compactDelivery:"pi-flag",compactSummary:"none",hookTimeoutMs:Ct,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"omp/index.js"},skillChannel:{kind:"package",path:"skills"},decode:Rc,encode:mo,checkPermission:ho}]),Gf=new Map(jf.map(e=>[e.id,e])),Bf=new Set(["claude-code","gemini","copilot-cli","pi","opencode","omp"]);function Ie(e){return Bf.has(e.id)}var Wf=new Set(["claude-code","copilot-cli","pi","omp"]);function To(e){return Wf.has(e.id)&&Ie(e)}var Xf=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode","kiro"]);function en(e){return Xf.has(e.id)}function K(e){return Gf.get(e)}import{resolve as Et}from"node:path";var Kf=["&&","||",";;","|&",";","|","&","(",")"],Yf=["&>>","&>"],qf=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],zf="&",Vf="<<",Lc="<<-",Jf=";",wc=`\r
|
|
19
|
+
`,Pc=`\\
|
|
20
|
+
`,Mc=`\\\r
|
|
21
|
+
`,$f="$(",Fc="${",vc="$'",st="((",Uc="))",Ce="[[",tn="]]",Ro="<(",jc=">(",U=2,Gc=`
|
|
22
|
+
\r;&|()<>`,Qf=`
|
|
23
|
+
\r`,Zf='$`"\\\n',e0="case",t0="esac";function ke(e,t){e.end==="complete"&&(e.end=t)}function Ao(e){return e!==""&&e>="0"&&e<="9"}function Hc(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function Bc(e){return e===""||Gc.includes(e)}function No(e){return e!==""&&Qf.includes(e)}function Y(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function nn(e,t){let n=e.s.indexOf("'",t+1);return n<0?(ke(e,"unterminated-quote"),e.n):n+1}function Wc(e,t){let n=t+vc.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=U;continue}if(o==="'")return n+1;n++}return ke(e,"unterminated-quote"),e.n}function yo(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+=U;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=it(e,o,n);continue}if(r==="$"&&s==="{"){o=Io(e,o,n);continue}if(r==="`"){o=De(e,o);continue}o++}return ke(e,"unterminated-quote"),e.n}function De(e,t){let n=t+1;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=U;continue}if(o==="`")return n+1;n++}return e.n}function Io(e,t,n){let o=t+Fc.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=U;continue}if(s==="'"){o=nn(e,o);continue}if(s==='"'){o=yo(e,o,n);continue}if(s==="$"&&i==="("){o=it(e,o,n);continue}if(s==="`"){o=De(e,o);continue}if(s==="{"&&r++,s==="}"){if(r===0)return o+1;r--}o++}return e.n}function Co(e,t){let n=0,o=t+st.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(Uc,o)?o+Uc.length:-1;n--}o++}return-1}function it(e,t,n){let o=t+$f.length-1;if(e.s.startsWith(st,o)){let r=Co(e.s,o);if(r>0)return r}return on(e,o+1,!0,n+1,null,null)}function n0(e,t,n){let o=t+Ce.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=U;continue}if(s==="'"){o=nn(e,o);continue}if(s==='"'){o=yo(e,o,n);continue}if(s==="$"&&i==="("){o=it(e,o,n);continue}if(s==="$"&&i==="{"){o=Io(e,o,n);continue}if(s==="`"){o=De(e,o);continue}let c=No(e.s.charAt(o-1));if(c&&e.s.startsWith(tn,o)&&Bc(e.s.charAt(o+tn.length))){if(r===0)return o+tn.length;r--,o+=tn.length;continue}if(c&&e.s.startsWith(Ce,o)&&No(e.s.charAt(o+Ce.length))){r++,o+=Ce.length;continue}o++}return-1}function o0(e,t){let n=t;for(;Ao(e.charAt(n));)n++;if(n===t){for(let o of Yf)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of qf){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(zf))if(e.charAt(r)==="-")r++;else for(;Ao(e.charAt(r));)r++;return{end:r,op:o}}return null}function r0(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(Gc.includes(r))break;if(r==="\\"){o+=U;continue}if(r==="'"){o=nn(e,o);continue}if(r==='"'){o=yo(e,o,n);continue}if(r==="$"&&s==="'"){o=Wc(e,o);continue}if(r==="$"&&s==="("){o=it(e,o,n);continue}if(r==="$"&&s==="{"){o=Io(e,o,n);continue}if(r==="`"){o=De(e,o);continue}o++}return Math.min(o,e.n)}function s0(e,t,n,o,r){let s=t;for(let i of n){let c=s,a=!1;for(;s<e.n;){let l=e.s.indexOf(`
|
|
24
|
+
`,s),u=l<0?e.n:l,d=e.s.slice(s,u);if(d.endsWith("\r")&&(d=d.slice(0,-1)),s=l<0?e.n:l+1,(i.strip?d.trim():d)===i.tag){a=!0;break}}if(o!==null&&r!==null&&r.push(o.length),Y(o,"unhandled",e.s.slice(c,s),c,s),!a)return ke(e,"unterminated-heredoc"),e.n}return n.length=0,s}function on(e,t,n,o,r,s){if(o>W)return ke(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(Pc,c)){c+=Pc.length;continue}if(i.startsWith(Mc,c)){c+=Mc.length;continue}if(f===`
|
|
25
|
+
`||f==="\r"){let S=c;c+=i.startsWith(wc,c)?wc.length:1,Y(r,"op",Jf,S,c),u=null,d.length>0&&(c=s0(e,c,d,r,s));continue}if(f==="#"){for(;c<e.n&&i.charAt(c)!==`
|
|
26
|
+
`&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(Ro,c)||i.startsWith(jc,c)){let S=on(e,c+Ro.length,!0,o+1,null,null);Y(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}let p=o0(i,c);if(p!==null){Y(r,"io",i.slice(c,p.end),c,p.end),u=p.op===Vf||p.op===Lc?p.op===Lc:null,c=p.end;continue}if(i.startsWith(Ce,c)&&No(i.charAt(c+Ce.length))){let S=n0(e,c,o);if(S>0){Y(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}if(i.startsWith(st,c)){let S=Co(i,c);if(S>0){Y(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let g=Kf.find(S=>i.startsWith(S,c));if(g!==void 0){if(n&&g==="("&&a++,n&&g===")"){if(a>0)a--;else if(l===0)return c+1}Y(r,"op",g,c,c+g.length),c+=g.length,u=null;continue}if(f==="$"&&x==="("||f==="`"){let S=f==="`"?De(e,c):it(e,c,o);if(Bc(i.charAt(S))){Y(r,"unhandled",i.slice(c,S),c,S),c=S,u=null;continue}}let E=c;c=r0(e,c,o);let h=i.slice(E,c);Y(r,"word",h,E,c),u!==null&&(d.push({tag:Le(h),strip:u}),u=null),n&&h===e0&&l++,n&&h===t0&&l>0&&l--}return d.length>0&&ke(e,"unterminated-heredoc"),e.n}function Xc(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return on(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function Le(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=U;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+vc.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=U;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!==""&&Zf.includes(i)){t+=i,s+=U;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function rn(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+=U;continue}if(!o&&s==="'"){r=nn(t,r);continue}if(!o&&s==="$"&&i==="'"){r=Wc(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Fc.length;continue}let c=e.startsWith(Ro,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(jc,r))){let a=r+1;if(s==="$"&&e.startsWith(st,a)&&Co(e,a)>0){r=a+st.length;continue}let l=on(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=De(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 sn(e){let t=e.charAt(0);if(!(Hc(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(!(Hc(o)||Ao(o)||o==="_"))return!1}return!1}var zc=[";","&","&&","||"],Vc=["|","|&"],ct="(",at=")",Jc=";;",Lo=["(",")"],i0="!";function H(e,t){for(let n of t)e.push(n)}var b=Object.freeze({group:"{",groupEnd:"}",if:"if",then:"then",elif:"elif",else:"else",fi:"fi",while:"while",until:"until",for:"for",in:"in",do:"do",done:"done",case:"case",esac:"esac",function:"function",coproc:"coproc",select:"select"}),$c=[],c0="[[",a0="((",Qc=[">",">>",">|","&>","&>>",">&"],l0=[...Qc,"<","<>","<<<","<<","<<-"],u0=["","1"],Zc=["-","/dev/stdout","/dev/stderr"],an="-",lt="--",ut="=",d0="/",f0=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),cn=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),ko="-c",Do="--bytes",x0="c",p0="--count",_e=()=>({cmds:[],simple:null}),O=(e,t=0)=>e.toks[e.i+t],ne=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,D=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,wo=e=>e!==""&&e>="0"&&e<="9",_0=e=>wo(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function Po(e){let t=e.lastIndexOf(d0);return t>=0&&t<e.length-1?e.slice(t+1):e}function Mo(e,t){let n=f0[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===lt)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+ut))s=r.slice(n.long.length+ut.length);else if(r.startsWith(an)&&!r.startsWith(lt)){let i=r.indexOf(n.short,an.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&&!Zc.includes(s))return!0}return!1}function E0(e){if(e==="")return!1;for(let t of e)if(!wo(t))return!1;return!0}function g0(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===ko||n===Do?o=e[t+1]:n.startsWith(Do+ut)?o=n.slice(Do.length+ut.length):n.startsWith(ko)&&!n.startsWith(lt)&&(o=n.slice(ko.length)),o!==void 0)return E0(o)&&Number(o)<=ue}return!1}function m0(e){for(let t of e){if(t===lt)return!1;if(t===p0||t.startsWith(an)&&!t.startsWith(lt)&&t.includes(x0))return!0}return!1}function Kc(e){if(!e.startsWith(w.fieldSep))return!1;for(let t of e.slice(w.fieldSep.length).split(w.fieldSep)){if(t==="")return!1;for(let n of t)if(!_0(n))return!1}return!0}function h0(e){let t=e.trim();if(t===w.identity||t===w.length)return!0;let n=t.indexOf(w.pipeLength.charAt(0));if(n<0)return Kc(t);let o=t.slice(0,n).trim(),r=w.pipeLength.slice(1).trim();return(o===w.identity||Kc(o))&&t.slice(n+1).trim()===r}function S0(e){let t=e.argv0.toLowerCase();if(t===cn.wc)return!0;if(t===cn.head)return g0(e.args);if(t===cn.grep)return m0(e.args);if(t===cn.jq){let n=e.args.filter(o=>!o.startsWith(an));return n.length===1&&h0(n[0])}return!1}function Uo(e){return rn(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function ea(e,t,n){return n<=t?[]:Uo(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function ta(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function b0(e){let t=0;for(;wo(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function na(e){let t=b0(e.toks[e.i].text);if(e.i++,!l0.includes(t.op))return!1;let n=O(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,Qc.includes(t.op)&&u0.includes(t.fd)&&!Zc.includes(Le(n.text)))}function oa(e){let t=!1;for(;O(e)?.kind==="io";)t=na(e)||t;return t}function ra(e){for(;O(e)?.kind==="op"&&zc.includes(O(e)?.text??"");)e.i++}function we(e,t){if(e.depth++,e.depth>W)return e.err="nesting-too-deep",_e();let n=t();if(e.depth--,oa(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function sa(e){if(ra(e),!D(O(e),b.do))return[];e.i++;let t=q(e,[b.done]);return D(O(e),b.done)&&e.i++,t}function O0(e){e.i++;let t=q(e,[b.then]);for(;e.err===null;){let n=O(e);if(D(n,b.then)||D(n,b.else)){e.i++,H(t,q(e,[b.elif,b.else,b.fi]));continue}if(D(n,b.elif)){e.i++,H(t,q(e,[b.then]));continue}D(n,b.fi)&&e.i++;break}return t}function T0(e){e.i++;let t=q(e,[b.do]);return H(t,sa(e)),t}function R0(e){e.i++;let t=[],n=O(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,D(O(e),b.in)){e.i++;let o=e.i;for(;(O(e)?.kind==="word"||O(e)?.kind==="unhandled")&&!D(O(e),b.do);)e.i++;H(t,ea(e,o,e.i))}return H(t,sa(e)),t}function A0(e){e.i++;let t=[],n=O(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,H(t,ea(e,e.i-1,e.i))),D(O(e),b.in)&&e.i++;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)||o.kind==="op"&&(zc.includes(o.text)||o.text===Jc)){e.i++;continue}if(D(o,b.esac)){e.i++;break}for(ne(o,ct)&&e.i++;e.i<e.toks.length&&!ne(O(e),at);){let s=e.toks[e.i];if(s.kind==="op"&&!Vc.includes(s.text))break;e.i++}if(!ne(O(e),at))break;e.i++;let r=q(e,[b.esac]);ta(r,b.case),H(t,r)}return t}function Yc(e,t){ra(e);let n=ia(e);return ta(n.cmds,t),{cmds:n.cmds,simple:null}}function qc(e,t){return Lo.every((n,o)=>ne(e.toks[t+o],n))}function N0(e){let t=e.i,n=[],o=!1;for(;e.i<e.toks.length;){let l=e.toks[e.i];if(l.kind==="op")break;if(l.kind==="io"){o=na(e)||o;continue}if(n.length===0&&l.kind==="word"&&sn(l.text)){e.i++;let u=O(e);if(l.text.endsWith(ut)&&u!==void 0&&ne(u,ct)&&u.start===l.end){let d=0;for(;e.i<e.toks.length;){let f=e.toks[e.i];if(e.i++,ne(f,ct)&&d++,ne(f,at)&&--d===0)break}}continue}n.push(l),e.i++}if(e.i===t)return _e();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:Uo(r),simple:null};let s=l=>l.kind==="word"?Le(l.text):l.text,i=Po(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||Mo(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function ia(e){let t=O(e);if(t===void 0)return _e();if(t.kind==="op")return t.text!==ct?_e():we(e,()=>{e.i++;let n=q(e,$c);return ne(O(e),at)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(c0)||t.text.startsWith(a0)))return e.i++,oa(e),{cmds:Uo(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return we(e,()=>{e.i++;let n=q(e,[b.groupEnd]);return D(O(e),b.groupEnd)&&e.i++,n});case b.if:return we(e,()=>O0(e));case b.while:case b.until:return we(e,()=>T0(e));case b.for:return we(e,()=>R0(e));case b.case:return we(e,()=>A0(e));case b.coproc:return e.err="coproc",_e();case b.select:return e.err="select",_e();case b.function:{e.i++;let n=O(e),o="";return n?.kind==="word"&&(o=Le(n.text),e.i++),qc(e,e.i)&&(e.i+=Lo.length),Yc(e,o)}default:if(qc(e,e.i+1))return e.i+=Lo.length+1,Yc(e,Le(t.text))}return N0(e)}function y0(e){D(O(e),i0)&&e.i++;let t=[],n=_e();for(;e.err===null;){n=ia(e),H(t,n.cmds);let o=O(e);if(o!==void 0&&o.kind==="op"&&Vc.includes(o.text)){for(let r of n.cmds)r.pipesOut=!0;e.i++;continue}break}if(n.simple!==null&&S0(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function q(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===at||o.text===Jc)return n;if(o.text!==ct){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;H(n,y0(e)),e.i===r&&e.err===null&&e.i++}return n}function Pe(e){let t=Xc(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;)H(o,q(n,$c)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{resolve as ca}from"node:path";var un="'",Me='"',dn="`",I0=" \r",ft="([{",jo=")]}",Ho=` \r
|
|
27
|
+
|;>`,ua="*",aa="1",Fo="::",ln=Fo.length,C0=ln;function fn(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===dn){o++;continue}if(r===n){if(e.charAt(o+1)===n){o++;continue}return o}}return-1}function k0(e,t){let n="";for(let o=0;o<e.length;o++){let r=e.charAt(o);if(t===Me&&r===dn&&o+1<e.length){n+=e.charAt(++o);continue}r===t&&e.charAt(o+1)===t&&o++,n+=r}return n}function dt(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===un||r===Me){let s=fn(e,o);if(s<0)return-1;o=s;continue}if(r===dn){o++;continue}if(ft.includes(r))n++;else if(jo.includes(r)&&--n===0)return o}return-1}function D0(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e.charAt(o);if(r===un||r===Me){let s=fn(e,o);if(s<0)return e.length;o=s;continue}if(ft.includes(r))n++;else if(jo.includes(r))n--;else if(n<=0&&Ho.includes(r))return o}return e.length}function L0(e){let t=[],n=0,o=0;for(let r=0;r<e.length;r++){let s=e.charAt(r);if(s===un||s===Me){let i=fn(e,r);if(i<0)break;r=i;continue}ft.includes(s)?n++:jo.includes(s)?n--:s===","&&n===0&&(t.push(e.slice(o,r)),o=r+1)}return t.push(e.slice(o)),t}var w0=e=>e!==""&&(e===ua||[...e].every(t=>t>="0"&&t<="9")),la=()=>({words:[],toFile:!1,chained:!1});function da(e){let t=[],n=[],o=la(),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=la()},d=()=>{u(),n.length>0&&t.push(n),n=[]},f=(p,g)=>{r+=p,s=!0,g&&(i=!1)},x=0;for(;x<a;){let p=e.charAt(x),g=e.charAt(x+1);if(p===un||p===Me){let E=fn(e,x);f(k0(e.slice(x+1,E<0?a:E),p),!0),x=E<0?a:E+1}else if(p===dn)g!==`
|
|
28
28
|
`&&g!==""&&f(g,!1),x+=ln;else if(p===`
|
|
29
|
-
`)d(),x++;else if(
|
|
30
|
-
`;)x++;else if(p===">"){let E=
|
|
31
|
-
`,
|
|
32
|
-
`;function xn(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(
|
|
33
|
-
`).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Wn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Wn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=
|
|
34
|
-
\r`,hx=Object.freeze({tool:va});function Sx(e,t){if(t!=="claude-code")return[];let n=H(process.env),o=process.env[Bt],r=o!==void 0&&o!==""?o:n===null?null:z(process.env,n),s=[$o(e,Da,Ex),$o(e,Da,La)];return r===null?s:[...s,$o(r,La)]}function Fa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bx(e){let t;try{t=xn(xx(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Fa(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Fa(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 ja(e,t){let n=[];for(let o of Sx(e,t)){let r=bx(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function Zo(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 er(e,t,n,o){let r=t.length,s=o,i=new Uint8Array(r+1);for(let c=e.length-1;c>=0;c--){let a=e[c];s===o&&(s=Uint8Array.from(o));let l=0;for(let d=r;d>=0;d--){let f=d<r,x=f?t[d]:"";switch(a.t){case"lit":i[d]=f&&x===a.c?s[d+1]:0;break;case"any1":i[d]=f&&!(n&&x==="/")?s[d+1]:0;break;case"star":i[d]=s[d]||(f&&!(n&&x==="/")?i[d+1]:0);break;case"globstar":i[d]=s[d]||(f?i[d+1]:0);break;case"globstarDir":f&&x==="/"&&s[d+1]&&(l=1),i[d]=s[d]||l;break}}let u=i;i=s,s=u}return s}function dt(e,t,n){let o=Zo(e,n),r=o[0];if(r!==void 0&&r.t==="lit"&&t[0]!==r.c)return!1;let s=new Uint8Array(t.length+1);return s[t.length]=1,er(o,t,n,s)[0]===1}function Ga(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 Ba(e,t){let n=t.length,o=new Uint8Array(n+1);if(o[n]=1,!e.endsWith(Pa))return er(Zo(e,!1),t,!1,o);for(let r=0;r<n;r++)mx.includes(t[r])&&(o[r]=1);return er(Zo(e.slice(0,e.length-Pa.length),!1),t,!1,o)}function Ox(e,t){return Ba(e,t)[0]===1}function Wa(e,t,n){for(let o of t){let r=Ga(o);if(r===null||r.tool!==va)continue;let s=Ba(r.glob,e);for(let i=0;i<=e.length;i++)if(n[i]===1&&s[i]===1)return o}return null}var Tx=/^[A-Za-z]:(?=\/)/;function ft(e){return Qo==="/"?e:e.split(Qo).join("/")}function Rx(e,t,n){if(e.startsWith(Ua)){if(n===void 0)return!1;let r=_x(n,t);return r===""||r===Ha||r.startsWith(Ha+Qo)||px(r)?!1:dt(e.slice(Ua.length),ft(r),!0)}let o=ft(t);if(e.startsWith(wa)){let r=ft(e.slice(wa.length-1));return dt(r,o,!0)||dt(r,o.replace(Tx,""),!0)}if(e.startsWith(Ma)){let r=H(process.env);return r!==null&&dt(ft(r)+e.slice(Ma.length-1),o,!0)}return dt(ft(e),o,!0)}function He(e,t,n=hx){for(let o of t){let r=Ga(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===gx?Rx(r.glob,e,n.projectDir):Ox(r.glob,e))return o}return null}var jm=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),Xa='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.',Ka=`context-mode: {size}-byte file, over the one-read limit. Read "{path}" in parts with offset and limit, or sed -n '1,200p'.`;var Ya="{size}",qa="{path}";function za(e,t,n=""){return L(Xa,n).split(Ya).join(String(t)).split(qa).join(e)}function Va(e,t){return Ka.split(Ya).join(String(t)).split(qa).join(e)}import{extname as Ix,join as tr,resolve as Cx}from"node:path";import{dirname as Ja,isAbsolute as Za,join as qm,relative as zm,resolve as el,sep as tl}from"node:path";var{lstatSync:Km,realpathSync:Ax}=process.getBuiltinModule("node:fs");function xt(e){try{return Ax.native(e)}catch{return}}function I(e){return e.split(tl).filter(t=>t!=="")}function nl(e,t){let n=xt(e),o=xt(t);if(n===void 0||o===void 0)return!1;let r=I(n),s=I(o);if(s.length<r.length)return!1;for(let i=0;i<r.length;i+=1)if(r[i]!==s[i])return!1;return!0}var $a=new Map;function Nx(e){let t=$a.get(e);if(t!==void 0)return t;let n=xt(e);return n!==void 0&&$a.set(e,n),n}function Fe(e,t){if(e.length===0)return!1;let n=xt(t);if(n===void 0)return!1;let o=I(n);return e.some(r=>{let s=Nx(r);if(s===void 0)return!1;let i=I(s);return o.length>=i.length&&i.every((c,a)=>c===o[a])})}function ol(e,t){return(Za(t)?I(t):[...I(e),...I(t)]).includes("..")}var Qa=new Map;function yx(e){let t=Qa.get(e);return t===void 0&&(t=I(el(e)),Qa.set(e,t)),t}function rl(e,t){if(e.length===0)return!1;let n=I(t);if(n.includes(".."))return!1;let o=tl==="/"&&Za(t)?n.filter(r=>r!=="."):I(el(t));return e.some(r=>{let s=yx(r);return o.length>=s.length&&s.every((i,c)=>i===o[c])})}function sl(e){let t=e.map(xt).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=I(n).length;for(let s of t){let i=I(s),c=I(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;I(r).length>o&&Ja(r)!==r;)r=Ja(r);return r}function kx(e,t){let n=H(t);if(n===null)return[];let o=tr(n,...bs);return[...e==="claude-code"?[z(t,n)]:e==="codex"?[pa(t,n)]:e==="gemini"?[Ea(t,n)]:e==="copilot-cli"?[_a(t,n)]:e==="kiro"?[ga(t,n)]:e==="opencode"?[ma(t,n)]:e==="pi"?[ha(t,n)]:e==="vscode"?[tr(n,...k.vscode),Sa(t,n)]:[tr(n,...k[e])],o]}function ve(e,t,n,o=process.env){if(Ix(n).toLowerCase()!==de)return!1;let r=kx(e,o),s=Cx(t,n);return!ol(t,n)&&rl(r,s)||Fe(r,s)}import{extname as wx}from"node:path";var{closeSync:Dx,openSync:Lx,readSync:Px}=process.getBuiltinModule("node:fs");function Mx(e){let t=null;try{t=Lx(e,"r");let n=Buffer.alloc(Vn),o=Px(t,n,0,Vn,0);return n.subarray(0,o)}catch{return null}finally{t!==null&&Dx(t)}}function gn(e,t){let n=Qs[e]??[];if(n.length===0)return!1;let o=wx(t).toLowerCase(),r=n.filter(i=>zn[i].exts.includes(o));if(r.length===0)return!1;let s=Mx(t);return s===null?!1:r.some(i=>zn[i].sig.every(c=>c.bytes.every((a,l)=>s[c.at+l]===a)))}var{statSync:Ux}=process.getBuiltinModule("node:fs"),dl="Bash",or="Read",Hx="WebFetch",Fx="ctx_execute",vx="ctx_batch",fl="shell",jx="1",ne="-",rr="--",Gx="=",Bx=".",il=",",nr="p",Wx=["-e","--expression"],cl=".exe",Xx=";&|(`\n\r",me=Object.freeze({kind:"allow"}),Ee=e=>({kind:"deny",reason:e}),ge=e=>typeof e=="string"?e:void 0,al=e=>e!=null,V=(e,t)=>e.includes(t);function xl(e,t,n,o=e.cwd){let r=e.tool;if(r===void 0)return me;let s=r.canonicalName,i=r.input,c;if(n===null){if(process.env[fs]===jx)return Ee(L(Pt,t.toolNamePrefix));process.stderr.write(Fs+`
|
|
35
|
-
`),c=[]}else c=n;let a=
|
|
36
|
-
`)}function
|
|
37
|
-
`),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function
|
|
38
|
-
`).filter(r=>r!=="")}function
|
|
39
|
-
PRAGMA busy_timeout = ${
|
|
29
|
+
`)d(),x++;else if(I0.includes(p))l(),x++;else if(p===";")d(),x++;else if(p==="|")g==="|"?(d(),x+=ln):(u(),x++);else if(p==="&")g==="&"?(d(),x+=ln):((s||o.words.length>0)&&f(p,!1),x++);else if(p==="#"&&!s)for(;x<a&&e.charAt(x)!==`
|
|
30
|
+
`;)x++;else if(p===">"){let E=aa;s&&i&&w0(r)?(E=r,r="",s=!1):s&&l();let h=x+1;if(e.charAt(h)===">"&&h++,e.charAt(h)==="&")for(h++;h<a&&!Ho.includes(e.charAt(h));)h++;else c=E===aa||E===ua?"file":"skip";x=h}else if(p==="("&&s&&i&&r.includes(Fo)){let E=dt(e,x),h=e.slice(x+1,E<0?a:E);l();for(let S of h.trim()===""?[]:L0(h)){let _=da(S)[0]?.[0]?.words[0];o.words.push(_??S.trim())}x=E<0?a:E+1,x<a&&!Ho.includes(e.charAt(x))&&(o.chained=!0,x=D0(e,x))}else if(p==="["&&!s&&e.startsWith(Fo,dt(e,x)+1)&&dt(e,x)>=0){let E=dt(e,x);f(e.slice(x,E+1),!1),x=E+1}else if(ft.includes(p)&&(p!=="["||!s)||(p==="$"||p==="@")&&ft.includes(g)&&g!=="["){let E=p==="$"||p==="@"?x+1:x,h=dt(e,E);f(e.slice(x,h<0?a:h+1),!0),x=h<0?a:h+1}else f(p,!1),x++}return d(),t}var P0=["get-content","gc","cat","type"],M0=["[io.file]::","[system.io.file]::"],U0=["readalltext","readalllines","readallbytes","readlines"],Go=["path","literalpath"],fa=["totalcount","head","first","tail","last"],xa=[...Go,...fa,"encoding","readcount","delimiter","filter","include","exclude","stream","credential"],H0=["raw","wait","force","asbytestream"],F0=[...xa,...H0],v0=["out-string","write-output","echo","write","out-host","write-host","out-default","tee-object"],j0=["cd","chdir","sl","set-location","pushd","push-location"],G0=["powershell","powershell.exe","pwsh","pwsh.exe"],B0=["cmd","cmd.exe"],W0=["/c","/k","/r"],X0="command",Ee="-";function vo(e){let t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return(t>=0&&t<e.length-1?e.slice(t+1):e).toLowerCase()}function Bo(e,t){let n=e.slice(Ee.length),o=n.indexOf(":"),r=(o<0?n:n.slice(0,o)).toLowerCase(),s=o<0?void 0:n.slice(o+1);if(r==="")return{full:void 0,inline:s};if(t.includes(r))return{full:r,inline:s};let i=t.filter(c=>c.startsWith(r));return{full:i.length===1?i[0]:void 0,inline:s}}function K0(e){if(e.length===0)return null;let t=vo(e[0]);if(!P0.includes(t)){let r=e[0].toLowerCase(),s=M0.find(i=>r.startsWith(i));return s===void 0||!U0.includes(r.slice(s.length))||e.length<C0?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(Ee)||s.length===Ee.length){n.push(s);continue}let i=Bo(s,F0);if(i.full===void 0||!xa.includes(i.full))continue;let c=i.inline??e[++r];if(c===void 0)return null;Go.includes(i.full)&&n.push(c),fa.includes(i.full)&&(o=!0)}return n.length===1?{file:n[0],bounded:o}:null}function Y0(e,t){if(G0.includes(e)){for(let n=1;n<t.length;n++){let o=t[n];if(!o.startsWith(Ee)||o.length===Ee.length)continue;let r=Bo(o,[X0]);if(r.full!==void 0)return[...r.inline===void 0?[]:[r.inline],...t.slice(n+1)].join(" ")}return null}if(B0.includes(e)){for(let n=1;n<t.length;n++)if(W0.includes(t[n].toLowerCase()))return t.slice(n+1).join(" ")}return null}function q0(e){for(let t=1;t<e.length;t++){let n=e[t];if(n.toLowerCase()==="/d")continue;if(!n.startsWith(Ee)||n.length===Ee.length)return n;let o=Bo(n,Go);if(o.full!==void 0)return o.inline??e[t+1]??null}return null}function pa(e,t,n,o){let r=t;for(let s of da(e)){let i=s[0];if(i.words.length===0)continue;let c=vo(i.words[0]);if(s.length===1&&j0.includes(c)){let d=q0(i.words);d!==null&&(r=ca(r,d));continue}let a=n<W?Y0(c,i.words):null;if(a!==null){pa(a,r,n+1,o);continue}if(i.toFile||i.chained)continue;let l=K0(i.words);if(l===null||l.bounded)continue;let u=!0;for(let d=1;d<s.length;d++)if(s[d].toFile||!v0.includes(vo(s[d].words[0]??""))){u=!1;break}u&&o.push(ca(r,l.file))}}function _a(e,t){let n=[];return pa(e,t,0,n),n}import{join as Ue}from"node:path";var Ea=`\r
|
|
31
|
+
`,z0=`
|
|
32
|
+
`;function xn(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(Ea)<0?t:t.split(Ea).join(z0)}import{basename as Q0,dirname as Z0,join as z,posix as ma,resolve as ex,win32 as ha}from"node:path";var V0=Object.freeze({NODE_TOO_OLD:"Context Mode needs Node 24.15.0 or newer; you have <v>. Fix: nvm install 24, or install it from https://nodejs.org.",NO_SQLITE:"node:sqlite failed to load. Fix: run ctx_doctor.",DB_GONE:"context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",NO_PROJECT:"Project source <kind> is missing. Fix: run ctx_doctor.",UNKNOWN_FIELD:'Unknown field "<f>". Fix: use "queries".',TIMEOUT:"Timed out after <ms> ms. Fix: pass background: true.",NO_GIT_BASH:"Git Bash not found. Fix: install Git for Windows.",NO_RUNTIME:"No <lang> runtime on PATH. Fix: install it or pick another language.",FETCH_FAILED:"Fetch failed: <code>. Fix: check the URL or proxy.",SSRF:"Blocked private address <host>. Fix: use a public URL.",OUTSIDE_ROOT:"Path <p> is outside the project. Fix: use a path inside <root>.",INVALID_ARGS:"Invalid argument <field>. Fix: <action>.",ONE_OF_INPUT:"Pass exactly one of <names>. Fix: drop the extra field.",SPAWN_FAILED:"Failed to start the process: <detail>. Fix: check the command and PATH.",DB_CORRUPT:"context.db failed integrity_check. Fix: run ctx_doctor.",SCHEMA_STALE:"context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.",NO_GIT_DIR:"No git repository at <path>. Fix: run context-mode inside a git repository.",NO_HOME:"Env var <name> is not set. Fix: set <name> to your home directory.",PLUGIN_ROOT_MISSING:"Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.",BUNDLE_HASH_MISMATCH:"Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.",CONFIG_PARSE_FAILED:"<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade."});function J0(e,t){let n=V0[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(J0(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{existsSync:Hm,mkdirSync:$0,readFileSync:Fm,readdirSync:vm,realpathSync:ga}=process.getBuiltinModule("node:fs");function F(e,t=process.platform){let n=o=>o!==void 0&&o!=="";return t==="win32"?n(e.USERPROFILE)?e.USERPROFILE:n(e.HOMEDRIVE)&&n(e.HOMEPATH)?e.HOMEDRIVE+e.HOMEPATH:n(e.HOME)?e.HOME:null:n(e.HOME)?e.HOME:n(e.USERPROFILE)?e.USERPROFILE:null}function Sa(e,t){let n=e[Ti];return n!==void 0&&n!==""?n:z(t,...k.codex)}function ba(e,t){let n=e[Ri];return n!==void 0&&n!==""?n:z(t,...k["copilot-cli"])}function Oa(e,t){let n=e[Ai];return z(n!==void 0&&n!==""?n:t,...k.gemini)}function Ta(e,t,n=process.platform){let o=n==="win32"?ha:ma,r=o.join(t,...k.kiro),s=e[Ni]?.trim();if(s===void 0||s===""||!o.isAbsolute(s)||n==="win32"&&o.parse(s).root.length<2)return r;let i=o.resolve(s),c=n===process.platform?tx:u=>u,a=c(i);if(o.parse(a).root===a)return r;let l=o.relative(a,c(o.resolve(t)));return!o.isAbsolute(l)&&l.split(o.sep)[0]!==".."?r:i}function tx(e){let t=[];for(let n=e;;)try{return z(ga.native(n),...t.reverse())}catch{let o=Z0(n);if(o===n)return e;t.push(Q0(n)),n=o}}function V(e,t){let n=e[Bt];return n!==void 0&&n!==""?n:z(t,...k["claude-code"])}function Ra(e,t){let n=e[yi];if(n!==void 0&&n!=="")return n;let o=e[Xt];return o!==void 0&&o!==""?z(o,k.opencode[k.opencode.length-1]):z(t,...k.opencode)}function Aa(e,t){let n=e[ki];return n!==void 0&&n!==""?n:z(t,...k.pi,Ii)}function Na(e,t,n=process.platform){let o=s=>s!==void 0&&s!=="",r=n==="win32"?ha:ma;return n==="win32"?r.join(o(e[ro])?e[ro]:r.join(t,"AppData","Roaming"),...Wt):n==="darwin"?r.join(t,"Library","Application Support",...Wt):r.join(o(e[Xt])?e[Xt]:r.join(t,".config"),...Wt)}function nx(e,t=process.platform){let n=F(e,t);if(n!==null)return n;throw new R("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function pn(e,t){let n=e[Ve];return n!==void 0&&n!==""?ex(n):z(t,_s.slice(1))}function ya(e){let t=e[Ve],n=pn(e,t!==void 0&&t!==""?"":nx(e));return $0(n,{recursive:!0}),ga.native(n)}var{readFileSync:wa,readdirSync:ox}=process.getBuiltinModule("node:fs"),Ia=Object.freeze(["Agent","Artifact","ArtifactComments","ArtifactData","ArtifactCheck","ExitPlanMode","Edit","Write","NotebookEdit"]),Ca=Object.freeze({"general-purpose":{tools:null,disallowed:[]},fork:{tools:null,disallowed:[]},claude:{tools:null,disallowed:[]},Explore:{tools:null,disallowed:[...Ia]},Plan:{tools:null,disallowed:[...Ia]},"claude-code-guide":{tools:["Glob","Grep","Read","WebFetch","WebSearch"],disallowed:[]},"statusline-setup":{tools:["Read","Edit"],disallowed:[]},"web-fetch":{tools:["WebFetch"],disallowed:[]}}),rx="claude-code";function He(e){return e.agentId!==void 0&&e.agentId!==""}function Xo(e,t){if(t===null)return"C";let n=K(e.agent),o=new Set(t);for(let r of Nt)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function Ko(e,t){if(!He(e))return null;let n=K(e.agent);if(t.manifestTools!==void 0)return La(t.manifestTools.map(a=>Wo(n,a)));let o=e.agentType??"",r=sx(o,t)??ix(e.agent,o);if(r===null)return null;let s=xx(n),i=r.tools===null?s:r.tools.map(a=>Wo(n,a)).flatMap(a=>[a,...s.filter(l=>_x(a,l))]),c=r.disallowed.map(a=>Wo(n,a));return La(i.filter(a=>!c.some(l=>Ex(l,a))))}function sx(e,t){if(!cx(e))return null;let n=ax(t.env);if(e.indexOf(Re)>=0){if(n!==null){let s=lx(V(t.env,n),e);if(s!==null)return s}}else{let s=_n(Ue(t.projectDir,gs,Je,e+fe));if(s!==null)return s;if(n!==null){let i=_n(Ue(V(t.env,n),Je,e+fe));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 ix(e,t){if(e!==rx||!Object.prototype.hasOwnProperty.call(Ca,t))return null;let n=Ca[t];return{tools:n.tools,disallowed:[...n.disallowed]}}function cx(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(Re))if(t===""||t==="."||t==="..")return!1;return!0}function ax(e){return F(e)}function lx(e,t){let n=t.indexOf(Re),o=t.slice(0,n),r=t.slice(n+Re.length);return r.indexOf(Re)>=0?null:ux(e,o,r)??dx(e,o,r)}function ux(e,t,n){let o;try{o=JSON.parse(xn(wa(Ue(e,Lt,hs),"utf8")))}catch{return null}let r=o?.plugins;if(r===null||typeof r!="object")return null;for(let s of Object.keys(r)){let i=s.indexOf(Ss);if((i<0?s:s.slice(0,i))!==t)continue;let c=r[s];if(Array.isArray(c))for(let a of c){let l=a?.installPath;if(typeof l!="string"||l==="")continue;let u=_n(Ue(l,Je,n+fe));if(u!==null)return u}}return null}function dx(e,t,n){let o=Ue(e,Lt,ms),r;try{r=ox(o).sort()}catch{return null}for(let s of r){if(s.startsWith("."))continue;let i=_n(Ue(o,s,t,Je,n+fe));if(i!==null)return i}return null}function _n(e){let t;try{t=wa(e,"utf8")}catch{return null}return fx(t)}function fx(e){let t=e.split(`
|
|
33
|
+
`).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Wn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Wn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=ka(o,bs),s=ka(o,Os);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function ka(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(Da(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>Da(s.trim())).filter(s=>s!=="")}return null}function Da(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function xx(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...Nt.map(n=>e.toolNamePrefix+n)]}function Wo(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(Ts)?px(o):o}function px(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||Rs.indexOf(n)>=0;t+=o?n:"_"}return t}function _x(e,t){if(!e.startsWith(Ae))return!1;let n=Ne+"*",o=e.slice(Ae.length,e.endsWith(n)?-n.length:e.length);return o===""||o.indexOf("*")>=0||o.indexOf(Ne)>=0?!1:t.startsWith(Ae+o+Ne)}function Ex(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(Ae)){let n=e.slice(Ae.length);if(n!==""&&n.indexOf(Ne)<0)return t.startsWith(e+Ne)}return!1}function La(e){return[...new Set(e.filter(t=>t!==""))]}var J="",Pa=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:J,subcommands:[]},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:J,subcommands:[]},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:J,subcommands:[]},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:J,subcommands:[]},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:J,subcommands:[]},command:{valueShorts:J,valueLongs:[],assignments:!1,duration:!1,refuseShorts:"vV",subcommands:[]},xargs:{valueShorts:"aEdILnPs",valueLongs:["--arg-file","--delimiter","--max-args","--max-procs","--max-chars"],assignments:!1,duration:!1,refuseShorts:J,subcommands:[]},rtk:{valueShorts:J,valueLongs:[],assignments:!1,duration:!1,refuseShorts:J,subcommands:["proxy","bypass"]}}),gx=["bash","sh","zsh"],mx="c",hx=" -c",Sx=["-o","+o","-O","+O"],En="-",bx="+",Yo="--",Ox="smhd",Tx=".",Ma=e=>e!==""&&e>="0"&&e<="9";function Rx(e){if(e===""||!Ma(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(Ma(n)||n===Tx))return t===e.length-1&&Ox.includes(n)}return!0}function Ax(e,t){let n=0;if(e.subcommands.length>0){if(t.length===0||!e.subcommands.includes(t[0]))return null;n=1}for(;n<t.length;){let o=t[n];if(o===Yo){n++;break}if(e.assignments&&sn(o)){n++;continue}if(o.startsWith(Yo)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(En)&&o.length>En.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=En.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||!Rx(t[n]))return null;n++}return n<t.length?t.slice(n):null}function Nx(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(Yo)){if(o.startsWith(En)||o.startsWith(bx)){o.includes(mx)&&(t=!0),Sx.includes(o)&&n++;continue}return t?o:null}}return null}function Ua(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function qo(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let a=s.toLowerCase();if(gx.includes(a)){let d=Nx(i),f=d!==null&&n<W?Pe(d):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=Ua(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,qo(p,[...r,a+hx],n+1,o)}return}let l=Object.hasOwn(Pa,a)?Pa[a]:void 0,u=l===void 0?null:Ax(l,i);if(u===null)break;r.push(a),s=Po(u[0]),i=u.slice(1),c=c||Mo(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=W))for(let a of rn(e.raw)){let l=Pe(a.body);if(l.ok)for(let u of l.commands)qo(Ua(u,e),[...t,a.wrapper],n+1,o)}}function zo(e){let t=[];for(let n of e)qo(n,[],0,t);return t}import{isAbsolute as Ix,join as Vo,relative as Cx,sep as Jo}from"node:path";var{readFileSync:yx}=process.getBuiltinModule("node:fs"),Ha=".claude",kx="settings.local.json",Fa="settings.json",Ka="Bash",Dx="Read",va=":*",ja="//",Ga="~/",Ba="./",Wa="..",Lx=`
|
|
34
|
+
\r`,wx=Object.freeze({tool:Ka});function Px(e,t){if(t!=="claude-code")return[];let n=F(process.env),o=process.env[Bt],r=o!==void 0&&o!==""?o:n===null?null:V(process.env,n),s=[Vo(e,Ha,kx),Vo(e,Ha,Fa)];return r===null?s:[...s,Vo(r,Fa)]}function Xa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mx(e){let t;try{t=xn(yx(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Xa(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Xa(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 Ya(e,t){let n=[];for(let o of Px(e,t)){let r=Mx(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function $o(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 Qo(e,t,n,o){let r=t.length,s=o,i=new Uint8Array(r+1);for(let c=e.length-1;c>=0;c--){let a=e[c];s===o&&(s=Uint8Array.from(o));let l=0;for(let d=r;d>=0;d--){let f=d<r,x=f?t[d]:"";switch(a.t){case"lit":i[d]=f&&x===a.c?s[d+1]:0;break;case"any1":i[d]=f&&!(n&&x==="/")?s[d+1]:0;break;case"star":i[d]=s[d]||(f&&!(n&&x==="/")?i[d+1]:0);break;case"globstar":i[d]=s[d]||(f?i[d+1]:0);break;case"globstarDir":f&&x==="/"&&s[d+1]&&(l=1),i[d]=s[d]||l;break}}let u=i;i=s,s=u}return s}function xt(e,t,n){let o=$o(e,n),r=o[0];if(r!==void 0&&r.t==="lit"&&t[0]!==r.c)return!1;let s=new Uint8Array(t.length+1);return s[t.length]=1,Qo(o,t,n,s)[0]===1}function qa(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 za(e,t){let n=t.length,o=new Uint8Array(n+1);if(o[n]=1,!e.endsWith(va))return Qo($o(e,!1),t,!1,o);for(let r=0;r<n;r++)Lx.includes(t[r])&&(o[r]=1);return Qo($o(e.slice(0,e.length-va.length),!1),t,!1,o)}function Ux(e,t){return za(e,t)[0]===1}function Va(e,t,n){for(let o of t){let r=qa(o);if(r===null||r.tool!==Ka)continue;let s=za(r.glob,e);for(let i=0;i<=e.length;i++)if(n[i]===1&&s[i]===1)return o}return null}var Hx=/^[A-Za-z]:(?=\/)/;function pt(e){return Jo==="/"?e:e.split(Jo).join("/")}function Fx(e,t,n){if(e.startsWith(Ba)){if(n===void 0)return!1;let r=Cx(n,t);return r===""||r===Wa||r.startsWith(Wa+Jo)||Ix(r)?!1:xt(e.slice(Ba.length),pt(r),!0)}let o=pt(t);if(e.startsWith(ja)){let r=pt(e.slice(ja.length-1));return xt(r,o,!0)||xt(r,o.replace(Hx,""),!0)}if(e.startsWith(Ga)){let r=F(process.env);return r!==null&&xt(pt(r)+e.slice(Ga.length-1),o,!0)}return xt(pt(e),o,!0)}function Fe(e,t,n=wx){for(let o of t){let r=qa(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===Dx?Fx(r.glob,e,n.projectDir):Ux(r.glob,e))return o}return null}var sh=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),Ja='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.',$a=`context-mode: {size}-byte file, over the one-read limit. Read "{path}" in parts with offset and limit, or sed -n '1,200p'.`;var Qa="{size}",Za="{path}";function el(e,t,n=""){return L(Ja,n).split(Qa).join(String(t)).split(Za).join(e)}function tl(e,t){return $a.split(Qa).join(String(t)).split(Za).join(e)}import{extname as Bx,join as Zo,resolve as Wx}from"node:path";import{dirname as nl,isAbsolute as sl,join as fh,relative as xh,resolve as il,sep as cl}from"node:path";var{lstatSync:uh,realpathSync:vx}=process.getBuiltinModule("node:fs");function _t(e){try{return vx.native(e)}catch{return}}function I(e){return e.split(cl).filter(t=>t!=="")}function al(e,t){let n=_t(e),o=_t(t);if(n===void 0||o===void 0)return!1;let r=I(n),s=I(o);if(s.length<r.length)return!1;for(let i=0;i<r.length;i+=1)if(r[i]!==s[i])return!1;return!0}var ol=new Map;function jx(e){let t=ol.get(e);if(t!==void 0)return t;let n=_t(e);return n!==void 0&&ol.set(e,n),n}function ve(e,t){if(e.length===0)return!1;let n=_t(t);if(n===void 0)return!1;let o=I(n);return e.some(r=>{let s=jx(r);if(s===void 0)return!1;let i=I(s);return o.length>=i.length&&i.every((c,a)=>c===o[a])})}function ll(e,t){return(sl(t)?I(t):[...I(e),...I(t)]).includes("..")}var rl=new Map;function Gx(e){let t=rl.get(e);return t===void 0&&(t=I(il(e)),rl.set(e,t)),t}function ul(e,t){if(e.length===0)return!1;let n=I(t);if(n.includes(".."))return!1;let o=cl==="/"&&sl(t)?n.filter(r=>r!=="."):I(il(t));return e.some(r=>{let s=Gx(r);return o.length>=s.length&&s.every((i,c)=>i===o[c])})}function dl(e){let t=e.map(_t).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=I(n).length;for(let s of t){let i=I(s),c=I(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;I(r).length>o&&nl(r)!==r;)r=nl(r);return r}function Xx(e,t){let n=F(t);if(n===null)return[];let o=Zo(n,...As);return[...e==="claude-code"?[V(t,n)]:e==="codex"?[Sa(t,n)]:e==="gemini"?[Oa(t,n)]:e==="copilot-cli"?[ba(t,n)]:e==="kiro"?[Ta(t,n)]:e==="opencode"?[Ra(t,n)]:e==="pi"?[Aa(t,n)]:e==="vscode"?[Zo(n,...k.vscode),Na(t,n)]:[Zo(n,...k[e])],o]}function je(e,t,n,o=process.env){if(Bx(n).toLowerCase()!==fe)return!1;let r=Xx(e,o),s=Wx(t,n);return!ll(t,n)&&ul(r,s)||ve(r,s)}import{extname as zx}from"node:path";var{closeSync:Kx,openSync:Yx,readSync:qx}=process.getBuiltinModule("node:fs");function Vx(e){let t=null;try{t=Yx(e,"r");let n=Buffer.alloc(Vn),o=qx(t,n,0,Vn,0);return n.subarray(0,o)}catch{return null}finally{t!==null&&Kx(t)}}function gn(e,t){let n=ni[e]??[];if(n.length===0)return!1;let o=zx(t).toLowerCase(),r=n.filter(i=>zn[i].exts.includes(o));if(r.length===0)return!1;let s=Vx(t);return s===null?!1:r.some(i=>zn[i].sig.every(c=>c.bytes.every((a,l)=>s[c.at+l]===a)))}var{statSync:Jx}=process.getBuiltinModule("node:fs"),gl="Bash",tr="Read",$x="WebFetch",Qx="ctx_execute",Zx="ctx_batch",ml="shell",ep="1",oe="-",nr="--",tp="=",np=".",fl=",",er="p",op=["-e","--expression"],xl=".exe",rp=";&|(`\n\r",he=Object.freeze({kind:"allow"}),ge=e=>({kind:"deny",reason:e}),me=e=>typeof e=="string"?e:void 0,pl=e=>e!=null,$=(e,t)=>e.includes(t);function hl(e,t,n,o=e.cwd){let r=e.tool;if(r===void 0)return he;let s=r.canonicalName,i=r.input,c;if(n===null){if(process.env[Es]===ep)return ge(L(wt,t.toolNamePrefix));process.stderr.write(Bs+`
|
|
35
|
+
`),c=[]}else c=n;let a=ip(s,i,e.cwd,c);return a!==null?ge($e+a):s===$x?up(i,t):s===gl?dp(e,t,i,c,o):s===tr?mp(e,t,i,o):he}function Sl(e,t,n,o){let r=e==="webfetch",s=r?Ls.map(c=>n.toolNamePrefix+c).join(Gs):n.toolNamePrefix+Ds,i=JSON.stringify(r?{url:t}:{language:ml,code:t,intent:o??ks});return[Xn+Ns[e]+ys,Is,Cs+s,i].join(`
|
|
36
|
+
`)}function sp(e){for(let t of xe){let n=me(e[t]);if(n!==void 0&&n!=="")return n}}function bl(e){let t=sp(e),n=Array.isArray(e[ye])?e[ye].filter(o=>typeof o=="string"&&o!==""):[];return t===void 0?n:[t,...n]}function ip(e,t,n,o){if(o.length===0)return null;let r=s=>Fe(Et(n,s),o,{tool:tr,projectDir:n});if(e===gl){let s=me(t.command);return s===void 0?null:Fe(s,o)}if(e===tr){for(let s of bl(t)){let i=r(s);if(i!==null)return i}return null}if(e===Qx){let s=me(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=me(t.code);return cp(t.language)&&c!==void 0?_l(c,o):null}if(e===Zx&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?_l(s,o):null;if(i!==null)return i}return null}function cp(e){if(typeof e!="string")return!1;let t=e.toLowerCase(),n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return n>=0&&(t=t.slice(n+1)),t.endsWith(xl)&&(t=t.slice(0,t.length-xl.length)),t===ml||$(ds,t)}function _l(e,t){let n=Fe(e,t);if(n!==null)return n;let o=Pe(e);if(!o.ok)return Tl(e,t);for(let r of zo(o.commands)){let s=Ol(r,t);if(s!==null)return s}return null}function Ol(e,t){return t.length===0?null:Fe([e.argv0,...e.args].join(" "),t)??Fe(e.raw,t)}function Tl(e,t){if(t.length===0)return null;let n=new Uint8Array(e.length+1),o=!1;for(let r=0;r<=e.length;r++)(r===0||rp.includes(e.charAt(r-1)))&&(o=!0),o&&(r===e.length||e.charAt(r).trim()!=="")&&(n[r]=1,o=!1);return Va(e,t,n)}function ap(e,t){return Tl(e,t)!==null}function lp(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return Ws.some(n=>t===n||t.endsWith(np+n))}function up(e,t){let n=me(e.url)??"";return lp(n)?he:ge(Sl("webfetch",n,t))}function dp(e,t,n,o,r){let s=me(n.command)??"",i=Pe(s);if(!i.ok)return ap(s,o)?ge(L(Pt,t.toolNamePrefix)):El(e,s,t,r)??he;let c=zo(i.commands);for(let a of c){let l=Ol(a,o);if(l!==null)return ge($e+l)}if(!Ie(t)||He(e))for(let a of c){let l=fp(a);if(l!==null)return ge(Sl(l,s,t,me(n.description)))}return hp(e,c,t,r)??El(e,s,t,r)??he}function fp(e){let t=e.argv0.toLowerCase();return $(Xs,t)&&xp(t,e)?"curl":_p(e.raw)?"http":$(zs,t)?"build":null}function xp(e,t){return t.redirectsToFile?!pp(e,t.args):!t.endsInBoundedSink}function pp(e,t){let n=Ks[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===nr)break;if($(Ys,s)||s===qs&&t[r+1]===oe)return!1;(s===n.long||s.startsWith(oe)&&!s.startsWith(nr)&&s.includes(n.short,oe.length))&&(o=!0)}return o}function _p(e){let t=e.toLowerCase();for(let n of $s)if(t.includes(n))return!0;for(let n=t.indexOf(Ze);n>=0;n=t.indexOf(Ze,n+1)){let o=t.charAt(n+Ze.length);if(o!==""&&Vs.includes(o)&&t.startsWith(Js,n+Ze.length+o.length))return!0}return!1}var Ep="cd";function or(e){try{let t=Jx(e);return t.isFile()?t.size:-1}catch{return-1}}function rr(e,t,n,o,r,s){let i=Et(n,o);return r<=ue||je(e.agent,n,o)?null:ge(gp(s,i)?el(i,r,t.toolNamePrefix):tl(i,r))}function gp(e,t){if(typeof e=="string")return ve([e],t);if(ve([e.worktree],t))return!0;try{return ve([e.containmentRoot],t)}catch{return!1}}function mp(e,t,n,o){if(!pl(n.offset)&&!pl(n.limit))for(let r of bl(n)){let s=Et(e.cwd,r),i=or(s);if(i>ue&&!gn(e.agent,s)){let c=rr(e,t,e.cwd,r,i,o);if(c!==null)return c}}return he}function hp(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&To(n))return null;let r=e.cwd,s=null;for(let i of t){let c=i.argv0.toLowerCase();if(c===Ep&&i.args.length===1&&i.insideConstruct===void 0&&(r=Et(r,i.args[0])),i.redirectsToFile||i.endsInBoundedSink||i.pipesOut===!0||i.insideConstruct!==void 0||!$(Qs,c))continue;let a=Op(c,i.args);if(a===null)continue;if(a.bounded){s=he;continue}let l=Et(r,a.file),u=rr(e,n,r,a.file,or(l),o);if(u!==null)return u}return s}function El(e,t,n,o){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&To(n))return null;for(let r of _a(t,e.cwd)){let s=rr(e,n,e.cwd,r,or(r),o);if(s!==null)return s}return null}var mn=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function Sp(e){if($(qn,e))return 1;for(let t of qn)if(t.startsWith(nr)?e.startsWith(t+tp):e.startsWith(t))return 0;return e.startsWith(oe)&&mn(e.slice(oe.length))?0:-1}function bp(e){if(e===er)return"all";if(!e.endsWith(er))return null;let t=e.slice(0,e.length-er.length),n=t.indexOf(fl);return(n<0?mn(t):mn(t.slice(0,n))&&mn(t.slice(n+fl.length)))?"range":null}function Op(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if($(Zs,e)){let a=Sp(c);if(a>=0){o=!0,i+=a;continue}}if(e===Mt&&$(ei,c)){r=!0;continue}if(e===Mt&&$(op,c)){s=t[i+1],i++;continue}c.startsWith(oe)&&c!==oe||n.push(c)}if(e===Mt){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:bp(s);if(i===null)return null;o=i==="range"}return e===ti&&n.shift()!==w.identity?null:n.length===1&&n[0]!==oe?{file:n[0],bounded:o}:null}import{basename as Ip,dirname as hn,join as mt,resolve as Nl}from"node:path";var Tp=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]),Rp=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],v=(e,t)=>e>>>t|e<<32-t;function Rl(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=Rp.slice(),i=new Uint32Array(64);for(let c=0;c<o;c+=64){for(let E=0;E<16;E++)i[E]=r.readUInt32BE(c+E*4);for(let E=16;E<64;E++){let h=v(i[E-15],7)^v(i[E-15],18)^i[E-15]>>>3,S=v(i[E-2],17)^v(i[E-2],19)^i[E-2]>>>10;i[E]=i[E-16]+h+i[E-7]+S>>>0}let[a,l,u,d,f,x,p,g]=s;for(let E=0;E<64;E++){let h=g+(v(f,6)^v(f,11)^v(f,25))+(f&x^~f&p)+Tp[E]+i[E]>>>0,S=(v(a,2)^v(a,13)^v(a,22))+(a&l^a&u^l&u)>>>0;g=p,p=x,x=f,f=d+h>>>0,d=u,u=l,l=a,a=h+S>>>0}s[0]=s[0]+a>>>0,s[1]=s[1]+l>>>0,s[2]=s[2]+u>>>0,s[3]=s[3]+d>>>0,s[4]=s[4]+f>>>0,s[5]=s[5]+x>>>0,s[6]=s[6]+p>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:Ap,readFileSync:Np,realpathSync:Al,statSync:yp}=process.getBuiltinModule("node:fs");function Cp(e){switch(e){case"claude-code":return"env:CLAUDE_PROJECT_DIR";case"codex":case"copilot-cli":case"kiro":return"arg:--agent+cwd";case"vscode":return"arg:workspaceFolder";case"gemini":case"qwen":case"zcode":case"opencode":return"spawn-cwd";case"pi":case"omp":return"pi:ctx.cwd"}}function gt(e){return e===void 0||e===""?void 0:e}function kp(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return gt(t.env.CLAUDE_PROJECT_DIR)??gt(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return gt(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(Dt);return n<0?void 0:gt(t.argv[n+1])}case"pi:ctx.cwd":return gt(t.piCwd)}}function Dp(e){let t;try{t=Al.native(e)}catch{throw new R("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=Lp(mt(t,jn));if(o!==null){let s=yl(mt(o,ls));return{commonDir:Al.native(s===null?o:Nl(o,s)),worktree:t,start:n}}let r=hn(t);if(r===t)return{commonDir:null,start:n};t=r}}function Lp(e){let t;try{if(yp(e).isDirectory())t=e;else{let n=yl(e);if(n===null||!n.startsWith(Bn))return null;t=Nl(hn(e),n.slice(Bn.length))}}catch{return null}return Ap(mt(t,us))?t:null}function yl(e){let t;try{t=Np(e,"utf8")}catch{return null}let n=t.indexOf(`
|
|
37
|
+
`),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function wp(e,t){let{spawnSync:n}=process.getBuiltinModule("node:child_process"),o=n("git",t,{cwd:e,shell:!1,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});if(o.error!==void 0||o.status!==0)throw new R("NO_GIT_DIR",{path:e});return o.stdout.split(`
|
|
38
|
+
`).filter(r=>r!=="")}function Pp(e,t){let n=Ip(t)===jn?hn(t):t,o=wp(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(Gn)).map(r=>r.slice(Gn.length));return dl([hn(n),...o])}function Il(e,t){let n=Cp(e),o=kp(n,t);if(o===void 0)throw new R("NO_PROJECT",{kind:n});let r=Dp(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??=Rl(i).slice(0,cs),a},get projectDir(){return l??=mt(ya(process.env),kt,this.projectKey),l},get dbPath(){return mt(this.projectDir,as)},worktree:c,get containmentRoot(){return u??=s??Pp(o,i),u},agent:e,source:n}}var Sn=qe,Mp=`
|
|
39
|
+
PRAGMA busy_timeout = ${M};
|
|
40
40
|
PRAGMA journal_mode = WAL;
|
|
41
|
-
`,bn="tokenize = 'porter unicode61 remove_diacritics 2'",
|
|
41
|
+
`,bn="tokenize = 'porter unicode61 remove_diacritics 2'",Up="tokenize = 'unicode61 remove_diacritics 2'",Hp=`
|
|
42
42
|
CREATE TABLE IF NOT EXISTS events (
|
|
43
43
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
44
44
|
session_id TEXT NOT NULL,
|
|
@@ -83,16 +83,16 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
|
|
|
83
83
|
agent UNINDEXED,
|
|
84
84
|
ord UNINDEXED,
|
|
85
85
|
body,
|
|
86
|
-
${
|
|
86
|
+
${Up}
|
|
87
87
|
);
|
|
88
88
|
|
|
89
89
|
CREATE TABLE IF NOT EXISTS meta (
|
|
90
90
|
key TEXT PRIMARY KEY,
|
|
91
91
|
value TEXT NOT NULL
|
|
92
92
|
);
|
|
93
|
-
`,
|
|
93
|
+
`,Fp=`
|
|
94
94
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_events_cost_session_turn ON events(session_id, turn) WHERE kind = 'cost';
|
|
95
|
-
`,
|
|
95
|
+
`,vp=`
|
|
96
96
|
CREATE VIRTUAL TABLE chunks_v3 USING fts5(
|
|
97
97
|
source_id UNINDEXED,
|
|
98
98
|
session_id UNINDEXED,
|
|
@@ -107,7 +107,7 @@ INSERT INTO chunks_v3(rowid, source_id, session_id, worktree, agent, ord, body,
|
|
|
107
107
|
SELECT rowid, source_id, session_id, worktree, agent, ord, body, '' FROM chunks;
|
|
108
108
|
DROP TABLE chunks;
|
|
109
109
|
ALTER TABLE chunks_v3 RENAME TO chunks;
|
|
110
|
-
`,
|
|
110
|
+
`,jp=`
|
|
111
111
|
CREATE VIRTUAL TABLE chunks_tri USING fts5(
|
|
112
112
|
body,
|
|
113
113
|
title,
|
|
@@ -116,7 +116,7 @@ CREATE VIRTUAL TABLE chunks_tri USING fts5(
|
|
|
116
116
|
);
|
|
117
117
|
INSERT INTO chunks_tri(rowid, body, title) SELECT rowid, body, title FROM chunks;
|
|
118
118
|
CREATE VIRTUAL TABLE chunks_vocab USING fts5vocab(chunks, 'row');
|
|
119
|
-
`,
|
|
119
|
+
`,Gp=`
|
|
120
120
|
CREATE VIRTUAL TABLE line_units USING fts5(
|
|
121
121
|
body,
|
|
122
122
|
source_id UNINDEXED,
|
|
@@ -124,16 +124,16 @@ CREATE VIRTUAL TABLE line_units USING fts5(
|
|
|
124
124
|
ord UNINDEXED,
|
|
125
125
|
${bn}
|
|
126
126
|
);
|
|
127
|
-
`,
|
|
127
|
+
`,Bp=`
|
|
128
128
|
UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
|
|
129
|
-
`,Cp=[{version:1,sql:Tp},{version:2,sql:Rp},{version:3,sql:Ap},{version:4,sql:Np},{version:5,sql:yp},{version:6,sql:Ip}];function cr(e,t){if(t!==Sn){if(t>Sn)throw new R("SCHEMA_STALE",{found:t,want:Sn});e.exec(bp),e.exec("BEGIN IMMEDIATE");try{for(let n of Cp)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${Sn}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}function Tl(e,t,n={}){if(("bun"in n?n.bun:process.versions.bun)===void 0)return new e.DatabaseSync(t,{timeout:ee,readOnly:!0});let r=new e.DatabaseSync(t,{timeout:ee});return n.queryOnly!==!1&&r.exec("PRAGMA query_only = ON"),r}var{existsSync:gt,linkSync:kp,mkdirSync:Dp,rmSync:Lp}=process.getBuiltinModule("node:fs");function Rl(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function Pp(e,t){let n=Rl(e),o=Rl(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 wp(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&es;return n===ts||n===ns}async function Mp(){try{return await import("node:sqlite")}catch{throw new R("NO_SQLITE")}}function ar(e){return e.prepare("PRAGMA user_version").get().user_version}function Up(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+Zr;try{let r=new e.DatabaseSync(o,{timeout:ee});try{cr(r,ar(r))}finally{r.close()}try{kp(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",yt,It])Lp(o+r,{force:!0})}}function Al(e,t){let n=null;try{return gt(t)||Up(e,t),n=new e.DatabaseSync(t,{timeout:ee}),cr(n,ar(n)),n}catch(o){throw n&&n.close(),o}}function Hp(e,t){let n=Tl(e,t);try{let o=ar(n);if(o!==Ke)throw new R("SCHEMA_STALE",{found:o,want:Ke});return n}catch(o){throw n.close(),o}}async function y(e,t){if(Pp(process.version,Ye))throw new R("NODE_TOO_OLD",{v:process.version});let n=await Mp();Dp(e.projectDir,{recursive:!0});let o=e.dbPath;if((gt(o+yt)||gt(o+It))&&!gt(o))throw new R("DB_GONE");try{let s;return t?.readOnly===!0?(gt(o)||Al(n,o).close(),s=Hp(n,o)):s=Al(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw wp(s)?new R("DB_CORRUPT"):s}}function v(e,t){e.raw.exec("BEGIN IMMEDIATE");try{let n=t(e);return e.raw.exec("COMMIT"),n}catch(n){throw e.raw.isTransaction&&e.raw.exec("ROLLBACK"),n}}function Nl(e,t){return e.raw.isTransaction?t(e):v(e,t)}function oe(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function J(e,t,n){Nl(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function On(e,t){return Nl(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var yl="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",Fp="INSERT INTO "+yl,vp="INSERT OR IGNORE INTO "+yl,jp="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function Tn(e,t){return v(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?vp:Fp).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(jp).get(t.session_id,t.turn).seq})}function Il(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 lr(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 Cl(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 kl(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 Dl(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function Ll(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var ur=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 Gp(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=ur.length/2-1;for(;t<=n;){let o=t+n>>1,r=ur[2*o],s=ur[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function Bp(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 je(e){return Bp(e,t=>!Gp(t))}var Wp=`
|
|
129
|
+
`,Wp=[{version:1,sql:Hp},{version:2,sql:Fp},{version:3,sql:vp},{version:4,sql:jp},{version:5,sql:Gp},{version:6,sql:Bp}];function sr(e,t){if(t!==Sn){if(t>Sn)throw new R("SCHEMA_STALE",{found:t,want:Sn});e.exec(Mp),e.exec("BEGIN IMMEDIATE");try{for(let n of Wp)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${Sn}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}function Cl(e,t,n={}){if(("bun"in n?n.bun:process.versions.bun)===void 0)return new e.DatabaseSync(t,{timeout:M,readOnly:!0});let r=new e.DatabaseSync(t,{timeout:M});return n.queryOnly!==!1&&r.exec("PRAGMA query_only = ON"),r}var{existsSync:Se,linkSync:Xp,mkdirSync:Ll,renameSync:Kp,rmSync:ir,statSync:Yp}=process.getBuiltinModule("node:fs");function kl(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function qp(e,t){let n=kl(e),o=kl(t);for(let r=0;r<o.length;r+=1){let s=n[r]??0;if(s!==o[r])return s<o[r]}return!1}function zp(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&rs;return n===ss||n===is}async function Vp(){try{return await import("node:sqlite")}catch{throw new R("NO_SQLITE")}}function cr(e){return e.prepare("PRAGMA user_version").get().user_version}function wl(e){return e.code??""}function Jp(e,t){let n=t+ts,o=Date.now();for(;;){if(Se(t))return;try{Ll(n)}catch(r){if(!ns.includes(wl(r)))throw r;if(Date.now()-o<M){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,os);continue}let s=Yp(n,{throwIfNoEntry:!1});throw s!==void 0&&s.mtimeMs<o&&ir(n,{recursive:!0,force:!0}),new Error(`context.db was not published within ${M} ms: ${n} was held; open again`)}try{Se(t)||Kp(e,t)}finally{ir(n,{recursive:!0,force:!0})}return}}function $p(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+Zr;try{let r=new e.DatabaseSync(o,{timeout:M});try{sr(r,cr(r))}finally{r.close()}try{Xp(o,t)}catch(s){let i=wl(s);if(es.includes(i))Jp(o,t);else if(i!=="EEXIST")throw s}}finally{for(let r of["",yt,It])ir(o+r,{force:!0})}}function Dl(e,t){let n=null;try{return Se(t)||$p(e,t),n=new e.DatabaseSync(t,{timeout:M}),sr(n,cr(n)),n}catch(o){throw n&&n.close(),o}}function Qp(e,t){let n=Cl(e,t);try{let o=cr(n);if(o!==qe)throw new R("SCHEMA_STALE",{found:o,want:qe});return n}catch(o){throw n.close(),o}}async function y(e,t){if(qp(process.version,ze))throw new R("NODE_TOO_OLD",{v:process.version});let n=await Vp();Ll(e.projectDir,{recursive:!0});let o=e.dbPath;if((Se(o+yt)||Se(o+It))&&!Se(o))throw new R("DB_GONE");try{let s;return t?.readOnly===!0?(Se(o)||Dl(n,o).close(),s=Qp(n,o)):s=Dl(n,o),{raw:s,projectKey:e.projectKey,path:o,...t?.readOnly===!0?{readOnly:!0}:{}}}catch(s){throw zp(s)?new R("DB_CORRUPT"):s}}function j(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 Pl(e,t){return e.raw.isTransaction?t(e):j(e,t)}function re(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function Q(e,t,n){Pl(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function On(e,t){return Pl(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var Ml="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",Zp="INSERT INTO "+Ml,e_="INSERT OR IGNORE INTO "+Ml,t_="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function Tn(e,t){return j(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?e_:Zp).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(t_).get(t.session_id,t.turn).seq})}function Ul(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 ar(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 Hl(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 Fl(e,t,n,o,r=Number.MAX_SAFE_INTEGER){return t===""?[]:e.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND ((session_id = ? AND seq <= ?) OR (worktree = ? AND session_id <> ?)) ORDER BY seq DESC LIMIT ?").all(t,r,n,t,o)}function vl(e){let t=e.raw.prepare("SELECT COALESCE(MAX(seq), 0) AS n FROM events").get();return Number(t.n)}function jl(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function Gl(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}function Bl(e,t){return e.raw.prepare("SELECT MAX(seq) AS m FROM events WHERE session_id = ?").get(t)?.m??0}var lr=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 n_(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=lr.length/2-1;for(;t<=n;){let o=t+n>>1,r=lr[2*o],s=lr[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function o_(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 o_(e,t=>!n_(t))}var r_=`
|
|
130
130
|
INSERT INTO sources(session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts)
|
|
131
131
|
VALUES (:session_id, :worktree, :agent, :kind, :label, :bytes_total, :chunk_count, :created_ts, :created_at, :created_ts)
|
|
132
|
-
RETURNING id`,
|
|
133
|
-
INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
132
|
+
RETURNING id`,s_=`
|
|
133
|
+
INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,Xl=1,Wl=" (raw)",Kl=`AND (:source IS NOT NULL OR substr(s.label, -${Wl.length}) <> '${Wl}')`,Yl=`
|
|
134
134
|
SELECT chunks.rowid AS rid, chunks.source_id AS source_id, chunks.session_id AS session_id,
|
|
135
135
|
chunks.worktree AS worktree, chunks.ord AS ord, s.created_ts AS created_ts,
|
|
136
|
-
bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${
|
|
136
|
+
bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${Xl}) AS bm,
|
|
137
137
|
(chunks.rowid IN (SELECT rowid FROM chunks WHERE chunks MATCH :all)) AS full
|
|
138
138
|
FROM chunks JOIN sources s ON s.id = chunks.source_id
|
|
139
139
|
WHERE chunks MATCH :match
|
|
@@ -141,9 +141,9 @@ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VAL
|
|
|
141
141
|
AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
|
|
142
142
|
AND (:source IS NULL OR s.label = :source)
|
|
143
143
|
AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
|
|
144
|
-
${
|
|
145
|
-
ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,
|
|
146
|
-
WITH m AS (${
|
|
144
|
+
${Kl}`,ql=`
|
|
145
|
+
ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,bS=`
|
|
146
|
+
WITH m AS (${Yl}
|
|
147
147
|
), r AS (
|
|
148
148
|
SELECT *,
|
|
149
149
|
ROW_NUMBER() OVER (ORDER BY full DESC, bm ASC, source_id DESC, ord ASC) AS rank_a,
|
|
@@ -151,11 +151,11 @@ WITH m AS (${Ul}
|
|
|
151
151
|
FROM m
|
|
152
152
|
)
|
|
153
153
|
SELECT rid, source_id, session_id, worktree, ord, full, 1.0 / (:k + rank_a) + 1.0 / (:k + rank_b) AS score
|
|
154
|
-
FROM r${
|
|
155
|
-
WITH m AS (${
|
|
154
|
+
FROM r${ql}`,OS=`
|
|
155
|
+
WITH m AS (${Yl}
|
|
156
156
|
)
|
|
157
157
|
SELECT rid, source_id, session_id, worktree, ord, full, -bm AS score
|
|
158
|
-
FROM m${
|
|
158
|
+
FROM m${ql}`;var TS=`
|
|
159
159
|
SELECT t.rowid AS rid, c.source_id AS source_id, c.session_id AS session_id, c.worktree AS worktree, c.ord AS ord
|
|
160
160
|
FROM chunks_tri t JOIN chunks c ON c.rowid = t.rowid JOIN sources s ON s.id = c.source_id
|
|
161
161
|
WHERE chunks_tri MATCH :match
|
|
@@ -163,10 +163,10 @@ WHERE chunks_tri MATCH :match
|
|
|
163
163
|
AND (:scope <> 'worktree' OR c.worktree = :worktree)
|
|
164
164
|
AND (:source IS NULL OR s.label = :source)
|
|
165
165
|
AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
|
|
166
|
-
${
|
|
167
|
-
ORDER BY bm25(chunks_tri, 1.0, ${
|
|
166
|
+
${Kl}
|
|
167
|
+
ORDER BY bm25(chunks_tri, 1.0, ${Xl}) ASC, c.source_id DESC, c.ord ASC`;var i_="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",c_="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function zl(e,t,n){let o=ur(e,t,n);return Jl(e,o,t,n),o}function ur(e,t,n){let o=0;for(let r of n)o+=r.bytes;return j(e,r=>{let s=r.raw.prepare(r_).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 Vl(e,t,n,o,r){try{Jl(e,t,n,o),fr(e,t,n.sessionId,r)}catch(s){throw j(e,i=>{a_(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function Jl(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>Mn&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)j(e,a=>{let l=a.raw.prepare(s_),u=a.raw.prepare(i_);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 a_(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(c_+" 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 dr(e){let t=[],n="";for(let o of e)o.trim()===""||o==="\0"?(n!==""&&t.push(n),n=""):n+=o==='"'?'""':o;return n!==""&&t.push(n),t.map(o=>`"${o}"*`).join(" ")}function l_(e){return[...new Set(dr(e).split(" ").filter(n=>n!==""))].join(" OR ")}var $l=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 u_(e){let t=[...new Set(dr(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!$l.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var Rn=`
|
|
168
168
|
AND (:scope <> 'session' OR session_id = :session_id)
|
|
169
|
-
AND (:scope <> 'worktree' OR worktree = :worktree)`,
|
|
169
|
+
AND (:scope <> 'worktree' OR worktree = :worktree)`,RS=`
|
|
170
170
|
WITH e AS (
|
|
171
171
|
SELECT seq, kind, key, path, body, created_at FROM events
|
|
172
172
|
WHERE created_at > :after${Rn}
|
|
@@ -174,7 +174,7 @@ WITH e AS (
|
|
|
174
174
|
)
|
|
175
175
|
SELECT seq, kind, key, path, body, created_at FROM e
|
|
176
176
|
WHERE created_at <= IFNULL((SELECT created_at FROM e ORDER BY created_at, seq LIMIT 1 OFFSET :off), created_at)
|
|
177
|
-
ORDER BY created_at ASC, seq ASC`,
|
|
177
|
+
ORDER BY created_at ASC, seq ASC`,AS=`
|
|
178
178
|
WITH s AS (
|
|
179
179
|
SELECT id, label, created_ts FROM sources
|
|
180
180
|
WHERE created_ts > :after${Rn}
|
|
@@ -183,43 +183,43 @@ WITH s AS (
|
|
|
183
183
|
)
|
|
184
184
|
SELECT id, label, created_ts FROM s
|
|
185
185
|
WHERE created_ts <= IFNULL((SELECT created_ts FROM s ORDER BY created_ts, id LIMIT 1 OFFSET :off), created_ts)
|
|
186
|
-
ORDER BY created_ts ASC, id ASC`;var
|
|
186
|
+
ORDER BY created_ts ASC, id ASC`;var NS=`
|
|
187
187
|
SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${Rn} AND (:source IS NULL OR kind = :source))
|
|
188
188
|
OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${Rn} AND (:source IS NULL OR label = :source)
|
|
189
|
-
AND label <> :reserved) AS more`;var
|
|
190
|
-
`),n=[],o=[],r=
|
|
191
|
-
`)}),n.push({indent:c,line:i,bytes:a})}return o}function
|
|
192
|
-
`);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function
|
|
193
|
-
`+e.body}function
|
|
194
|
-
`)}function
|
|
195
|
-
`),seqs:l.map(f=>f.seq),...u.length>0?{units:u.map(
|
|
196
|
-
`)}var
|
|
189
|
+
AND label <> :reserved) AS more`;var d_=`CREATE VIRTUAL TABLE r USING fts5(body, ${bn}, content='')`,f_="INSERT INTO r(rowid, body) VALUES (?, ?)",x_="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function Z(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?l_(t):dr(t);if(r===""||e.length===0)return o;let s=process.getBuiltinModule("node:sqlite");if(s===void 0)throw new R("NO_SQLITE");let i=new s.DatabaseSync(":memory:");try{i.exec(d_);let c=i.prepare(f_);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(x_).all(r))o[Number(a.id)-1]=-a.bm;return o}finally{i.close()}}var p_="s";function Ql(e){return p_+e.toString(36)}function fr(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<=Mn);)i+=o[s].body.length,s++;let c=r;j(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 Zl(e){let t=new Set,n=new Set,o=s=>{n.size<Ft&&n.add(s),$l.has(s.toLowerCase())||t.add(s)},r="";for(let s of e){if(t.size>=Ft)break;s.trim()===""||s==="\0"?(r!==""&&o(r),r=""):r+=s}return r!==""&&t.size<Ft&&o(r),[...t.size>0?t:n].join(" ")}function eu(e){let t=e.raw.prepare("SELECT COALESCE(MAX(id), 0) AS n FROM sources").get();return Number(t.n)}function tu(e,t,n,o,r=Number.MAX_SAFE_INTEGER){let s=u_(n).join(" OR ");return s===""||t===""?[]:e.raw.prepare("SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? AND s.id <= ? ORDER BY bm25(line_units) LIMIT ?").all(s,t,r,o).map(c=>({sourceId:Number(c.source_id),ord:Number(c.ord),label:c.label,body:c.body,score:c.score}))}function __(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function xr(e){let t=e.split(`
|
|
190
|
+
`),n=[],o=[],r=ui*Buffer.byteLength(e,"utf8");for(let s=0;s<t.length;s++){let i=t[s].endsWith("\r")?t[s].slice(0,-1):t[s],c=__(i);if(c===i.length)continue;for(;n.length>0&&n[n.length-1].indent>=c;)n.pop();let a=Buffer.byteLength(i,"utf8"),l=a,u=n.length;for(;u>0;){let d=n[u-1].bytes+1;if(l+d>tt||l-a+d>r)break;l+=d,u--}r-=l-a,o.push({ord:s,body:[...n.slice(u).map(d=>d.line),i].join(`
|
|
191
|
+
`)}),n.push({indent:c,line:i,bytes:a})}return o}function pr(e){let t=e.indexOf(`
|
|
192
|
+
`);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 ht(e){return e.length>Un?e.slice(e.length-Un):e}function E_(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function nu(e,t){if(!t)return E_();let n=e.filter(_=>_.session_id===t).sort((_,m)=>_.seq-m.seq),o=n.filter(_=>_.kind==="prompt"),r=o.length>0?o[o.length-1]:void 0,s=r===void 0?null:Be("last_request",r,"now: "+pr(r.body),1,null),i=o.slice(0,o.length-1).map(_=>Be("earlier_requests",_,"asked #"+_.seq+": "+pr(_.body),1,null)),c=new Map,a=new Map;for(let _ of n)if(!(_.kind!=="cmd"&&_.kind!=="toolerr"||_.key===null)){if(_.ok===1){a.set(_.key,_.seq);continue}c.set(_.key,{row:_,count:(c.get(_.key)?.count??0)+1})}let l=[];for(let[_,m]of c)(a.get(_)??0)>m.row.seq||l.push(Be("open_errors",m.row,"error #"+m.row.seq+" "+(m.row.tool??"")+": "+_,m.count,_));l.sort((_,m)=>_.seq-m.seq);let u=new Map;for(let _ of n)_.kind!=="edit"||_.path===null||u.set(_.path,{row:_,count:(u.get(_.path)?.count??0)+1});let d=[];for(let[_,m]of u){let T=Be("changed_files",m.row,"edited "+_+" x"+m.count,m.count,_);d.push({...T,editCount:m.count})}d.sort((_,m)=>_.seq-m.seq);let f=new Map;for(let _ of n){if(_.kind!=="decision"||_.body==="")continue;let m=_.key??_.body;f.set(m,{row:_,count:(f.get(m)?.count??0)+1})}let x=[];for(let[_,m]of f)x.push(Be("decisions",m.row,"decided #"+m.row.seq+": "+pr(m.row.body),m.count,_));x.sort((_,m)=>_.seq-m.seq);let p=n.filter(_=>_.kind==="index").map(_=>Be("indexed_sources",_,"indexed "+(_.key??""),1,_.key)),g={lastRequest:s,openErrors:ht(l),changedFiles:ht(d),decisions:ht(x),earlierRequests:ht(i),indexedSources:ht(p)},E=[...g.openErrors,...g.changedFiles,...g.decisions,...g.earlierRequests,...g.indexedSources],h=E.length+(s===null?0:1);if(h<=Hn)return g;let S=new Set(E.map(_=>_.seq).sort((_,m)=>_-m).slice(0,h-Hn));return{lastRequest:s,openErrors:g.openErrors.filter(_=>!S.has(_.seq)),changedFiles:g.changedFiles.filter(_=>!S.has(_.seq)),decisions:g.decisions.filter(_=>!S.has(_.seq)),earlierRequests:g.earlierRequests.filter(_=>!S.has(_.seq)),indexedSources:g.indexedSources.filter(_=>!S.has(_.seq))}}function g_(e){if(!Object.hasOwn(Fn,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=vn[Math.min(t,vn.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(Fn[e.section]*n*o/mi)}function m_(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 ou(e,t){return e.map(n=>({...n,score:g_({section:m_(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function iu(e){return e.sourceId+":"+e.ord}function Nn(e){return"@"+e.label+" line "+(e.ord+1)+`:
|
|
193
|
+
`+e.body}function h_(e){return new Set(Ge(e.toLowerCase()))}function S_(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 Er(e,t,n){let o=e.filter(l=>!t.has(iu(l))&&l.score>=Qn);if(o.length===0)return[];let r=Math.max(...o.map(l=>l.score)),s=o.map(l=>h_(l.body)),i=[],c=new Set(o.map((l,u)=>u)),a=0;for(;c.size>0;){let l=-1,u=-1/0;for(let f of c){let x=0;for(let g of i)x=Math.max(x,S_(s[f],s[g]));let p=Jr*(o[f].score/r)-$r*x;p>u&&(u=p,l=f)}c.delete(l);let d=An(Nn(o[l]))+1;a+d>n||(a+=d,i.push(l))}return i.map(l=>o[l])}var ru={text:"",seqs:[]};function An(e){return Buffer.byteLength(e,"utf8")}function _r(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
|
|
194
|
+
`)}function su(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+_r(e)}function cu(e,t,n,o=[],r=new Set){if(t.trim()==="")return ru;let s=e.filter(f=>!n.has(f.seq)&&f.kind!=="cost"&&!(f.kind==="prompt"&&f.body===t)&&_r(f)!==""),i=s.length===0?[]:Z(s.map(_r),t,"any"),c=s.map((f,x)=>({r:f,score:i[x]})).filter(f=>f.score>=Qn).sort((f,x)=>x.score-f.score||x.r.seq-f.r.seq),a=An(eo)+1+An(to),l=[];for(let{r:f}of c){let x=An(su(f))+1;a+x>tt||(a+=x,l.push(f))}let u=Er(o,r,tt-a);if(l.length===0&&u.length===0)return ru;l.sort((f,x)=>f.seq-x.seq);let d=[...l.map(su),...u.map(Nn)];return{text:[eo,...d,to].join(`
|
|
195
|
+
`),seqs:l.map(f=>f.seq),...u.length>0?{units:u.map(iu)}:{}}}function se(e){return Buffer.byteLength(e,"utf8")}function gr(e,t){return e.bytes>Fr?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function mr(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function au(e,t,n,o=""){let r;for(let m of e)(r===void 0||m.seq>r.seq)&&(r=m);let s=r===void 0?"":r.session_id,i=r===void 0||s===""?0:r.seq,c=nu(e,s),a=`<context_mode_state session="${s}" upto="${i}">`,l=se(mr([],o)),u=Hr-(se(a)+1+l+1+se(Pn)),d=0,f=c.lastRequest===null?null:gr(c.lastRequest,o);f!==null&&(d+=se(f)+1);let x=ou([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),p=new Map,g=[],E=[];for(;x.length>0;){let m=0,T=-1/0;for(let Oe=0;Oe<x.length;Oe++){let Te=x[Oe],Ln=Te.score*Vr**(p.get(Te.section)??0)/Te.bytes;(Ln>T||Ln===T&&Te.seq>x[m].seq)&&(m=Oe,T=Ln)}let C=x.splice(m,1)[0],ae=se(gr(C,o))+1;d+ae<=u?(d+=ae,g.push(C),p.set(C.section,(p.get(C.section)??0)+1)):E.push(C)}let h=[a];f!==null&&h.push(f);for(let m of["open_errors","changed_files","decisions","earlier_requests","indexed_sources"])for(let T of g.filter(C=>C.section===m).sort((C,ae)=>C.seq-ae.seq))h.push(gr(T,o));if(n!==void 0){for(let m of n.sources){let T=se(m)+1;d+T>u||(d+=T,h.push(m))}for(let m of Er(n.units,new Set,u-d)){let T=Nn(m);d+=se(T)+1,h.push(T)}}let S=[],_=new Set;for(let m of E.sort((T,C)=>T.seq-C.seq))if(!(m.query===null||_.has(m.query))){if(se(mr([...S,m.query],o))-l>u-d)break;S.push(m.query),_.add(m.query)}return h.push(mr(S,o),Pn),h.join(`
|
|
196
|
+
`)}var b_=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),O_=new Set(["script","style"]),T_=new TextEncoder;function yn(e,t,n=de){let o=N_(e);if(o.length===0)return[];let r=Math.max(4,Math.min(de,Math.floor(n)));if(t==="md")return R_(o,r,r<de);let s=t==="html"?k_(o):hr(o,!1);return Sr(o,s,t!=="text",r,r<de)}function R_(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 Sr(e,i,!0,t,n))c(l.text,l.bytes);i=[]}};for(let l of hr(e,!0)){if(l.heading!==void 0){for(a();r.length>0&&r[r.length-1].level>=l.heading.level;)r.pop();r.push(l.heading),s=r.map(u=>u.text).join(" > ")}if(l.fence!==void 0&&ie(e.slice(l.start,l.end))>t){let u=A_(e,l,l.fence,t);if(u!==void 0){a();for(let d of u)c(d,ie(d));continue}}i.push(l)}return a(),o}function A_(e,t,n,o){let r=e.slice(t.start,n.openEnd),s=n.closeStart>=0?e.slice(n.closeStart,t.end):n.fence,i=n.closeStart>=0?Math.max(n.openEnd+1,n.closeStart-1):t.end,c=e.slice(Math.min(n.openEnd+1,i),i),a=o-ie(r)-ie(s)-2;if(!(a<16||c.length===0))return Sr(c,hr(c,!1),!0,a,!0).map(l=>r+`
|
|
197
197
|
`+l.text+`
|
|
198
|
-
`+s)}function
|
|
198
|
+
`+s)}function N_(e){let t=e.split(`\r
|
|
199
199
|
`).join(`
|
|
200
|
-
`);return t.startsWith("\uFEFF")?t.slice(1):t}function
|
|
201
|
-
`,d),x=f<0?e.length:f,p=e.slice(d,x);if(i!=="")u(d,x,!1),
|
|
202
|
-
`||e===" "||e==="\f"||e==="\r"}function
|
|
203
|
-
`,p.end-1):-1;if(g>f){let E=
|
|
204
|
-
`,f),h=E<0||E>=d.end?d.end:E+1,S=
|
|
205
|
-
`,
|
|
206
|
-
`,
|
|
207
|
-
`&&n!=="\r"&&n!==" ")return n}return""}function
|
|
208
|
-
`);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<
|
|
209
|
-
`)}}function In(e,t,n){
|
|
210
|
-
ref: #`+n}}function
|
|
200
|
+
`);return t.startsWith("\uFEFF")?t.slice(1):t}function hr(e,t){let n=[],o=-1,r=-1,s=!1,i="",c,a,l=()=>{if(o>=0){let f={start:o,end:r};c!==void 0&&(f.heading=c),a!==void 0&&(f.fence=a),n.push(f)}o=-1,c=void 0,a=void 0},u=(f,x,p)=>{o<0&&(o=f),r=x,s=p},d=0;for(;d<=e.length;){let f=e.indexOf(`
|
|
201
|
+
`,d),x=f<0?e.length:f,p=e.slice(d,x);if(i!=="")u(d,x,!1),C_(p,i)&&(i="",t&&a!==void 0&&(a.closeStart=d,l()));else if(p.length===0)l();else{let g=t?I_(p):"",E=t&&g===""?y_(p):void 0,h=t&&g===""&&E===void 0&&p.includes("|");t&&o>=0&&(h!==s||g!==""||E!==void 0)&&l(),u(d,x,h),i=g,g!==""&&(a={fence:g,openEnd:x,closeStart:-1}),E!==void 0&&(c=E,l())}d=x+1}return l(),n}function y_(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 I_(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 C_(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 k_(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{uu(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=D_(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||b_.has(c.name))){if(O_.has(c.name)){s=L_(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return uu(t,e,r,e.length),t}function fu(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function xu(e){return fu(e)||e>="0"&&e<="9"||e==="-"||e===":"}function D_(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!fu(e[n]))return;let r=n;for(;n<e.length&&xu(e[n]);)n+=1;let s=e.slice(r,n).toLowerCase(),i="";for(;n<e.length;){let c=e[n];if(i!=="")c===i&&(i="");else if(c==='"'||c==="'")i=c;else if(c===">")break;n+=1}if(!(n>=e.length))return{name:s,close:o,selfClose:e[n-1]==="/",end:n+1}}function L_(e,t,n){let o=e.indexOf("</",t);for(;o>=0;){let r=o+2+n.length;if(e.slice(o+2,r).toLowerCase()===n&&(r>=e.length||!xu(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function lu(e){return e===" "||e===`
|
|
202
|
+
`||e===" "||e==="\f"||e==="\r"}function uu(e,t,n,o){let r=n,s=o;for(;r<s&&lu(t[r]);)r+=1;for(;s>r&&lu(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function ie(e){return Buffer.byteLength(e,"utf8")}function du(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=T_.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function Sr(e,t,n,o,r){let s=[],i=new Uint8Array(o),c,a,l=0,u=(d,f,x)=>{s.push({ord:s.length,text:e.slice(d,f),bytes:x})};for(let d of t){if(a!==void 0&&!n&&(u(a.start,a.end,l),a=void 0),a!==void 0){let p=ie(e.slice(a.end,d.end));if(l+p<=o){a.end=d.end,l+=p;continue}u(a.start,a.end,l),a=void 0}let f=d.start,x=ie(e.slice(d.start,d.end));for(;x>o;){let p=du(e,f,d.end,i),g=r?e.lastIndexOf(`
|
|
203
|
+
`,p.end-1):-1;if(g>f){let E=ie(e.slice(f,g+1));u(f,g+1,E),f=g+1,x-=E;continue}if(r){let E=e.indexOf(`
|
|
204
|
+
`,f),h=E<0||E>=d.end?d.end:E+1,S=ie(e.slice(f,h));if(S<=de){u(f,h,S),f=h,x-=S;continue}c??=new Uint8Array(de);let _=du(e,f,h,c);u(f,_.end,_.written),f=_.end,x-=_.written;continue}u(f,p.end,p.written),f=p.end,x-=p.written}f>=d.end||(a={start:f,end:d.end},l=x)}return a!==void 0&&u(a.start,a.end,l),s}var w_=`
|
|
205
|
+
`,P_=1;function pu(e,t,n,o,r){return M_(e,t,n,o,r)}function M_(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(f=>f.text),i=r===void 0?Z(s,t):Z(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?P_: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(w_),more:u?br(t,o):null}}function br(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+(Buffer.byteLength(e,"utf8")>nt?"...":JSON.stringify(e))+"]"+n+"})"}var _u=20,G=2,Eu=9,gu=8,U_=.9,H_=.5,F_=64,v_=2,j_=4,Or=`
|
|
206
|
+
`,G_="(absent)",ee=e=>Buffer.byteLength(e,"utf8");function mu(e,t,n){let o=X_(e,t)??q_(e,t)??J_(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):Z(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?ee(Or):0,d=o.units[l].render(n-c-u);d===null||c+u+ee(d)>n||(i.push({pos:o.units[l].pos,text:d}),c+=u+ee(d))}if(i.length===0)return null;i.sort((l,u)=>l.pos-u.pos);let a=i.map(l=>l.text);return c+ee(Or)+ee(o.header)<=n&&a.unshift(o.header),a.join(Or)}function B_(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
|
|
207
|
+
`&&n!=="\r"&&n!==" ")return n}return""}function W_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hu(e,t,n){if(n.size<2||n.size>gu)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=G+1)return o[0][1]<U_*e||e-o[0][1]>G?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>G),s=o.filter(([,i])=>i<=G);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function Su(e){if(B_(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<_u||!t.every(W_))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 bu=(e,t)=>e+" objects {"+t.join(",")+"}";function X_(e,t){let n=Su(e);if(n===null)return null;let{objs:o,keys:r}=n,s=new Map;for(let l of r){let u=new Map,d=new Map,f=!0;for(let x=0;x<o.length&&f;x++){let p=l in o[x]?o[x][l]:void 0;if(typeof p=="object"&&p!==null){f=!1;break}let g=p===void 0?G_:JSON.stringify(p);d.set(g,(d.get(g)??0)+1);let E=u.get(g)??[];if(E.length<=G&&E.push(x),u.set(g,E),d.size>gu)break}if(f)for(let x of hu(o.length,u,d))s.set(x,[...s.get(x)??[],l])}if(s.size===0||s.size>Eu)return null;let i=Z(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=>Ou(l,o[l],u,c,d)}));return{header:bu(o.length,r)+", "+s.size+" rare:",units:a}}function Ou(e,t,n,o,r){let s="["+e+"] ",i=K_(t,n,o,r-ee(s));return i===null?null:s+i}function K_(e,t,n,o){let r=JSON.stringify(e);if(ee(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=ee(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 Y_(e,t){let n=Z(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function q_(e,t){let n=Su(e);if(n===null)return null;let{objs:o,keys:r}=n,s=Y_(r,t),i=new Map,c=0;for(let l of r){if(!s.has(l)||c>=v_||!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=>Ou(l,o[l],[u],s,d)}));return{header:bu(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:a,direct:!0}}function z_(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function V_(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 J_(e){let t=e.split(`
|
|
208
|
+
`);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<_u)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=>z_(p)?"<*>":p),d=u.length+" "+(u[0]??""),f=n.get(d)??[],x;for(let p of f)if(V_(p.tpl,u)>=H_){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>F_)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<=G&&x.lines.push(a);for(let p=0;p<x.pos.length;p++){let g=x.pos[p];if(g===null)continue;g.totals.set(l[p],(g.totals.get(l[p])??0)+1);let E=g.counts.get(l[p])??[];E.length<=G&&E.push(a),g.counts.set(l[p],E),g.totals.size>G+1&&(x.pos[p]=null)}}let r=o.filter(a=>a.count>G);if(r.length===0||r.length>j_||r.some(a=>a.tpl.every(l=>l==="<*>")))return null;let s=new Set(o.filter(a=>a.count<=G).flatMap(a=>a.lines));for(let a of r)for(let l of a.pos)if(l!==null)for(let u of hu(a.count,l.counts,l.totals))s.add(u);if(s.size===0||s.size>Eu)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=>ee(l)<=u?l:null}});return{header:i,units:c}}function $_(e,t,n,o,r,s,i,c=yn(s,i)){return{sourceId:zl(e,{projectKey:t.projectKey,sessionId:n,worktree:t.worktree,agent:t.agent,kind:o,label:r,bytes:Buffer.byteLength(s,"utf8"),chunkCount:c.length,createdAt:Date.now()},c),chunks:c.length}}function Tr(e,t,n,o,r,s,i){return $_(e,t,n,"content",o,r,s,i)}async function Q_(e,t){try{let n=await y(e);Tn(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
|
|
209
|
+
`)}}function In(e,t,n){Q_(e,n)}function Tu(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,zr).map(i=>i[0]).join(" ")}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Z_(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(Si):""}function eE(e){return Array.isArray(e)?e.filter(St).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):St(e)?Object.entries(e):[]}function Au(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!St(t))return[];let n=[];for(let[o,r]of eE(t[hi])){let s=Z_(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function Nu(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!St(o)||!Array.isArray(o.options)))for(let r of o.options)St(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function Ru(e){return e.trim().toLowerCase()}function yu(e,t,n){let o=Ru(e);if(o==="")return null;let r=t.find(s=>Ru(s)===o);return r===void 0?null:{key:Gt,body:"A: "+r+`
|
|
210
|
+
ref: #`+n}}function tE(e,t){return"hint:"+e+":"+t}function nE(e,t){return re(e,t)!==null?!1:(Q(e,t,"1"),!0)}function oE(e,t,n){let o=re(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return Q(e,t,String(r)),(r-1)%n===0}function Cn(e,t,n,o){if(t==="")return!1;let r=tE(t,n),s=i=>o===void 0?nE(i,r):oE(i,r,o);return e.raw.isTransaction?s(e):j(e,s)}import{join as Ar,resolve as Iu}from"node:path";var Rr=process.getBuiltinModule("node:fs");function Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kn(e,t){for(let n of t)if(typeof e[n]=="string")return e[n];return""}function rE(e){for(let t of Ms){let n=e[t];if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}if(Nr(n))return n}return{}}function sE(e){return e.HOME??e.USERPROFILE??""}function iE(e){let t=e[Ve];if(t!==void 0&&t!=="")return Ar(pn(e,""),Kn);let n=sE(e);return n===""?"":Ar(pn(e,n),Kn)}function ku(e){let t=Nr(e)?e.code:void 0;return typeof t=="string"&&t!==""?t:e instanceof Error?e.name:"Error"}function We(e,t,n,o){try{let r=iE(e);if(r==="")return;Rr.mkdirSync(Ar(r,".."),{recursive:!0});let s=JSON.stringify({ts:new Date().toISOString(),agent:t,stage:n,label:ku(o),message:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack??"":""});Rr.appendFileSync(r,s+`
|
|
211
211
|
`)}catch{process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
|
|
212
|
-
`)}}var
|
|
213
|
-
`+
|
|
214
|
-
`),
|
|
215
|
-
`)},s=(u,d,f)=>(r(u,d,f),
|
|
216
|
-
`)}let a,l={};try{
|
|
217
|
-
`)})}function
|
|
218
|
-
`)})}function
|
|
219
|
-
`),n=t<0?e:e.slice(0,t);if(!n.startsWith(Jn))return null;let o=0,r=0;for(let s of n.slice(Jn.length)){let i=s.charCodeAt(0)-
|
|
220
|
-
`+t}function
|
|
221
|
-
`+t)-1-Buffer.byteLength(e))}function
|
|
222
|
-
`);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,
|
|
223
|
-
`)})}function
|
|
224
|
-
`)}function
|
|
225
|
-
`);try{return
|
|
212
|
+
`)}}var Cu=!1;function bt(e,t){if(!(Cu||e[Fs]!==t))throw Cu=!0,new Error("injected fault at "+t)}function Du(e){let t=(e.startsWith("v")?e.slice(1):e).split("."),n=ze.split(".");for(let o=0;o<n.length;o++){let r=Number(t[o]??0)||0,s=Number(n[o]);if(r!==s)return r<s}return!1}function ce(e,t){return e!==void 0&&e.some(n=>n.toLowerCase()===t)}function cE(e,t){let n=t.toLowerCase();return ce(e.nativeTools.shell,n)||ce(Qe.shell,n)?"shell":ce(e.nativeTools.read,n)||ce(Qe.read,n)?"read":ce(e.nativeTools.grep,n)||ce(Qe.grep,n)?"grep":ce(e.nativeTools.webfetch,n)||ce(Qe.fetch,n)?"fetch":null}function aE(e,t){let n=t.toLowerCase();return Hs.includes(n)||(e.eventMap.PreToolUse??"").toLowerCase()===n}function lE(e){try{let t=Rr.statSync(e);return t.isFile()&&t.size>ue}catch{return!1}}function uE(e,t,n){if((t.offset??null)!==null||(t.limit??null)!==null)return!1;let o=Array.isArray(t[ye])?t[ye].filter(r=>typeof r=="string"):[];return[kn(t,xe),...o].some(r=>r!==""&&lE(Iu(n,r))&&!gn(e,Iu(n,r))&&!je(e,n,r))}function be(e){try{return K(e).encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},{kind:"allow"})}catch{return{stdout:"",exitCode:0}}}function Ot(e,t,n,o=""){let r=K(e);try{if(!Nr(t)||!aE(r,kn(t,Ps)))return be(e);let s=kn(t,ws);if(s===""||s.includes(Ut))return be(e);let i=cE(r,s);if(i===null)return be(e);let c=kn(t,Us)||o;if(i==="read"&&!uE(e,rE(t),c))return be(e);let a=i==="read"?Yn.read:Yn[i],l=L(a,r.toolNamePrefix)+`
|
|
213
|
+
`+vs(ku(n),r.toolNamePrefix);return r.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:c,turn:0},{kind:"deny",reason:l})}catch{return{stdout:"",exitCode:0}}}var{read:dE,writeSync:fE}=process.getBuiltinModule("node:fs"),Lu=65536;function xE(e){let t=Buffer.allocUnsafe(Lu);return new Promise(n=>{let o=()=>{dE(0,t,0,Lu,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 yr(){let e=[];if(!await xE(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function Ir(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=fE(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{lstatSync:Mu,readFileSync:pE}=process.getBuiltinModule("node:fs"),N={kind:"allow"},EE={stdout:"",exitCode:0},gE=48;function mE(e){return Xe.includes(e)}function Tt(e){return e instanceof Error?e.message:String(e)}function Rt(e){return typeof e=="string"?e:""}async function Fu(e,t,n){if(!mE(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
|
|
214
|
+
`),EE;let o=K(e),r=(u,d,f)=>{We(n,e,u,d),process.stderr.write(f??"hooks: "+u+" failed: "+Tt(d)+`
|
|
215
|
+
`)},s=(u,d,f)=>(r(u,d,f),Ot(e,t,d));if(Du(process.version)){let u=new R("NODE_TOO_OLD",{v:process.version});return o.installMode==="in-process"?s("node",u):(r("node",u),be(e))}let i;try{bt(n,"decode"),i=o.decode(t)}catch(u){return s("decode",u)}if(i.event==="Stop")return o.encode(i,N);let c;try{bt(n,"project");let u=e==="vscode"?[Dt,i.cwd]:process.argv;c=Il(e,{env:n,argv:u,cwd:i.cwd,piCwd:K(e).projectSource==="pi:ctx.cwd"?i.cwd:void 0})}catch(u){return s("project",u,"hooks: no project: "+String(u.code??"ERROR")+" "+Tt(u)+`
|
|
216
|
+
`)}let a,l={};try{bt(n,"policy"),a=await hE(i,o,c,n,l)}catch(u){return s("store",u)}try{bt(n,"encode");let u=o.encode(i,a);return l.run?.(!0),u}catch(u){return l.run?.(!1),s("encode",u)}}function hE(e,t,n,o,r){switch(e.event){case"SessionStart":return SE(e,t,n);case"UserPromptSubmit":return bE(e,t,n);case"PreToolUse":return kE(e,t,n,o);case"PostToolUse":return ME(e,t,n,o,r);case"PreCompact":return $E(e,t,n);case"Usage":return QE(e,n)}return Promise.resolve(N)}function vu(e,t){return e.split(js).join(t.toolNamePrefix)}function Dr(e,t,n){return n.compactSummary==="host"?L(Qr,n.toolNamePrefix):au(ar(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function SE(e,t,n){if(e.source==="compact"&&en(t)&&ju(await y(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await y(n),s=ii+":"+Bl(r,e.sessionId);return Cn(r,e.sessionId,s)?{kind:"hint",text:Dr(r,e,t),onceKey:s}:N}let o=await y(n);return t.compactDelivery==="opencode-cache"&&On(o,Ht+e.sessionId)!==null?{kind:"hint",text:Dr(o,e,t),onceKey:$n}:Cn(o,e.sessionId,et)?{kind:"hint",text:vu(no,t),onceKey:et}:N}async function bE(e,t,n){let o=e.prompt??"",r=await OE(e,t,n);if(In(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}),IE(e,n,o),t.compactDelivery==="pending-flag"){let s=await y(n);if(On(s,Ht+e.sessionId)!==null)return{kind:"hint",text:Dr(s,e,t),onceKey:$n}}return r!==null?r:NE(e,t,n,o)}async function OE(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await y(n);return Gl(o,e.sessionId)||!Cn(o,e.sessionId,et)||!jl(o,n.worktree,e.agent)?null:{kind:"hint",text:vu(no,t),onceKey:et}}function ju(e,t){t!==""&&Q(e,Zn+t,JSON.stringify({seq:vl(e),source:eu(e)}))}function TE(e){let t={seq:Number.MAX_SAFE_INTEGER,source:Number.MAX_SAFE_INTEGER};try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return t;let{seq:o,source:r}=n;return{seq:typeof o=="number"?o:t.seq,source:typeof r=="number"?r:t.source}}catch{return t}}function RE(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function AE(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 NE(e,t,n,o){if(!en(t)||e.sessionId==="")return N;let r=await y(n),s=re(r,Zn+e.sessionId);if(s===null)return N;let i=TE(s),c=fi+e.sessionId,a=RE(re(r,c)),l=li+e.sessionId,u=AE(re(r,l)),d=tu(r,e.sessionId,Zl(o),di,i.source),f=Fl(r,e.sessionId,n.worktree,ai,i.seq),x=cu(f,o,new Set(a),d,new Set(u));return x.text===""?N:(x.seqs.length>0&&Q(r,c,JSON.stringify([...a,...x.seqs])),x.units!==void 0&&Q(r,l,JSON.stringify([...u,...x.units])),{kind:"hint",text:x.text,onceKey:xi})}function Gu(e){return jt+":"+Gt+":"+e}function yE(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 IE(e,t,n){if(e.sessionId==="")return;let o=Gu(e.sessionId);y(t).then(r=>{if(re(r,o)===null)return;let s=On(r,o),i=s===null?null:yE(s);if(i===null)return;let c=yu(n,i.labels,i.seq);c!==null&&Bu(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+Tt(r)+`
|
|
217
|
+
`)})}function Bu(e,t,n,o){for(let r of o)Tn(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:oo,key:r.key,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(r.body),body:r.body,turn:t.turn??0,sandbox_bytes:0,returned_bytes:0}),Tr(e,n,t.sessionId,jt,r.body,"text")}function CE(e,t,n,o){let r=Au(o),s=r.length===0?Nu(n.input):[];r.length===0&&s.length===0||y(t).then(i=>{if(r.length>0)return Bu(i,e,t,r);let c=ar(i,e.sessionId,"prompt"),a=c[c.length-1];a===void 0||e.sessionId===""||Q(i,Gu(e.sessionId),JSON.stringify({seq:a.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+Tt(i)+`
|
|
218
|
+
`)})}function Wu(e,t,n){let o={projectDir:t.worktree,env:n};return e.agentTools!==void 0&&(o.manifestTools=e.agentTools),o}async function kE(e,t,n,o){let r=Ya(n.worktree,e.agent),s=hl(e,t,r,n),i=s;if(s.kind==="deny"&&He(e)&&!Xu(s.reason,t)){let c=Ko(e,Wu(e,n,o)),a=Xo(e,c),l=e.tool,u=c!==null||(e.agentType??"")!==""&&Ie(t);a==="B"&&l!==void 0&&Pr(l,t)?i=DE(e,t,s,r):a!=="A"&&u&&(i=N)}return i}function Pr(e,t){return e.canonicalName===oi||t.nativeTools.shell.includes(e.name)}function Xu(e,t){return e.startsWith($e)||e===L(wt,t.toolNamePrefix)||e===L(Pt,t.toolNamePrefix)}function Cr(e){return Buffer.from(e,"utf8").toString("base64url")}function DE(e,t,n,o){let r=e.tool;if(r===void 0||!Pr(r,t)||Xu(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+wr(Uu(process.argv[1]??""),_i)+'"',c=[Ei,i,Cr(s),Cr(JSON.stringify(o??[])),Cr(Rt(r.input.description))].join(" ");return{kind:"deny",reason:gi,rewritten:c}}function LE(e,t,n){return n?"toolerr":ri.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":Pr(e,t)?"cmd":null}function Lr(e){if(Array.isArray(e))return"["+e.map(Lr).join(",")+"]";if(typeof e=="object"&&e!==null){let t=e;return"{"+Object.keys(t).filter(o=>t[o]!==void 0).sort().map(o=>JSON.stringify(o)+":"+Lr(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function wE(e){let t=e.indexOf(`
|
|
219
|
+
`),n=t<0?e:e.slice(0,t);if(!n.startsWith(Jn))return null;let o=0,r=0;for(let s of n.slice(Jn.length)){let i=s.charCodeAt(0)-gE;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function PE(e){for(let t of si)if(typeof e[t]=="string")return e[t];return null}async function ME(e,t,n,o,r){let s=e.tool;if(s===void 0||s.canonicalName.startsWith(Ut))return N;let i=e.result??{isError:!1,bytes:0},c=qE(i,e.sessionId,o);i.persistedPath!==void 0&&(i.bytes=Buffer.byteLength(c)),s.canonicalName===oo&&CE(e,n,s,c);let a=LE(s,t,i.isError),l=f=>{if(a===null)return;let x=a==="cmd"?Ul(s.canonicalName,Rt(s.input.command)):a==="toolerr"?s.canonicalName+":"+Lr(s.input):null;In(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:a,tool:s.canonicalName,key:x,path:PE(s.input),ok:i.isError?0:1,exit_code:wE(c),bytes:i.bytes,body:c,turn:e.turn??0,sandbox_bytes:i.bytes,returned_bytes:f})},u;try{u=await HE(e,t,n,o,s,i,c)}catch(f){throw l(i.bytes),f}let d=u;return r.run=f=>l(f&&d.kind==="replace"?Buffer.byteLength(d.output):i.bytes),u}function UE(e,t,n){if(!Ye.includes(t.canonicalName))return!1;let o=xe.map(r=>t.input[r]).find(r=>typeof r=="string"&&r!=="");return o!==void 0&&je(e.agent,e.cwd,o,n)}async function HE(e,t,n,o,r,s,i){if(s.bytes<=jr||vE(r)||jE(e,r)||UE(e,r,o)||s.keep===!0||!Ie(t))return N;let c,a={ctx:!0,shell:!0,read:!1};if(He(e)){let T=Ko(e,Wu(e,n,o)),C=Xo(e,T),ae=Oe=>T!==null&&Oe.some(Te=>T.includes(Te));if(a={ctx:C==="A",shell:ae(t.nativeTools.shell),read:Ye.includes(r.canonicalName)&&ae(t.nativeTools.read??[])},T!==null&&!a.ctx&&!a.shell&&!a.read)return N;c=pi+r.canonicalName+":"+(r.callId??String(e.turn??0))}else c=VE(r,e);let l=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url,r.name].map(Rt).find(T=>T.trim()!=="")??r.canonicalName,u=yn(i,"text",Xr),d=await y(n),f;s.bytes<=vr?(f=Tr(d,n,e.sessionId,c,i,"text",u).sourceId,fr(d,f,e.sessionId,xr(i))):(f=ur(d,Yu(n,e.sessionId,c),u),JE(n,e.sessionId,f,c,i,u));let x=Ql(f),p=await zE(n,e.sessionId),g=p.trim()===""?void 0:l+" "+p,E=a.ctx?Kr(l,x,s.bytes,t.toolNamePrefix,Tu(l,p,i)):Yr(x,s.bytes,a.read),h=KE(E,br(l,c)),S=E+(a.shell&&e.agent===ps?FE(x,l,n):""),_=mu(i,g??l,Wr);if(_!==null)return{kind:"replace",output:Pu(_,S)};let m=pu(u,l,h,c,g);return{kind:"replace",output:m.more!==null?Pu(m.text,S):m.text}}function FE(e,t,n){let o=Buffer.byteLength(t,"utf8")>nt?"":t;return qr(wr(Uu(process.argv[1]??""),xs),e,o,n.worktree)}function vE(e){return Ye.includes(e.canonicalName)&&Gr.some(t=>e.input[t]!==void 0&&e.input[t]!==null)}function jE(e,t){if(e.agent!=="omp"||!Ye.includes(t.canonicalName))return!1;let n=xe.map(o=>t.input[o]).find(o=>typeof o=="string"&&o!=="");if(n===void 0||!GE(n))return!1;try{return Mu(Hu(e.cwd,n),{throwIfNoEntry:!1})===void 0}catch{return!1}}function GE(e){let t=e.lastIndexOf(":"),n=e.slice(t+1);if(n.toLowerCase()==="raw"&&(t=e.lastIndexOf(":",t-1),n=e.slice(t+1,e.length-4)),t<=0||!BE(n))return!1;let o=e.slice(0,t);return o.toLowerCase().endsWith(":raw")&&(o=o.slice(0,-4)),o.length>1||!XE(o)}function BE(e){return e!==""&&e.split(",").every(WE)}function WE(e){if(e.startsWith("-"))return kr(e.slice(1));let t=0;for(;t<e.length&&Ku(e[t]);)t++;if(t===0)return!1;if(t===e.length)return!0;let n=e[t],o=e.slice(t+1);return n==="-"&&(o===""||kr(o))||n==="+"&&kr(o)}function kr(e){if(e==="")return!1;for(let t of e)if(!Ku(t))return!1;return!0}function Ku(e){return e>="0"&&e<="9"}function XE(e){let t=e.toLowerCase();return t.length===1&&t>="a"&&t<="z"}function Pu(e,t){return e===""?t:e+`
|
|
220
|
+
`+t}function KE(e,t){return Math.max(0,Br+Buffer.byteLength(`
|
|
221
|
+
`+t)-1-Buffer.byteLength(e))}function YE(e,t,n){if(t===""||t.includes(wu)||t.includes("/"))return!1;let o=wr(V(n,F(n)??""),kt),r=_E(o,Hu(e)).split(wu);if(r.length!==4||r.includes("..")||r.includes("")||r[1]!==t||r[2]!==bi)return!1;let s=Mu(e);return s.isFile()&&s.size<=Oi&&al(o,e)}function qE(e,t,n){let o=e.text??"";if(e.persistedPath===void 0)return o;try{return YE(e.persistedPath,t,n)?pE(e.persistedPath,"utf8"):(We(n,"claude-code","persisted-output",new Error("persisted output path is outside this session's tool-results dir or too large; kept the head")),o)}catch{return o}}async function zE(e,t){try{return Hl(await y(e),t)}catch{return""}}function VE(e,t){let n=Rt(e.input.command)??Rt(e.input.file_path)??"",o=n.indexOf(`
|
|
222
|
+
`);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,fs)+"#"+(e.callId??String(t.turn??0))}function JE(e,t,n,o,r,s){y(e).then(i=>{Vl(i,n,Yu(e,t,o),s,xr(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+Tt(i)+`
|
|
223
|
+
`)})}function Yu(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function $E(e,t,n){let o=await y(n);return Q(o,Ht+e.sessionId,ci),en(t)&&ju(o,e.sessionId),N}function QE(e,t){return In(t,e.sessionId,{session_id:e.sessionId,worktree:t.worktree,agent:e.agent,kind:"cost",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:0,body:"",turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),Promise.resolve(N)}var zu={stdout:"",exitCode:0};function ZE(e){return Xe.includes(e)}function Dn(e){process.exitCode=e.exitCode,e.stdout!==""&&Ir(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
|
|
224
|
+
`)}function qu(e,t,n,o,r){process.stderr.write("hooks: "+n+" failed: "+(o instanceof Error?o.message:String(o))+`
|
|
225
|
+
`);try{return We(r,e,n,o),Ot(e,t,o)}catch{return zu}}async function eg(e,t){let n=e.indexOf(vt),o=n>=0?e[n+1]??"":"";if(!ZE(o))return console.error("hooks: unknown "+vt+" "+JSON.stringify(o)+". Fix: pass "+vt+" with one of "+Xe.join(", ")+"."),Dn(zu);let r;try{r=JSON.parse(await yr())}catch(s){return Dn(qu(o,void 0,"stdin",s,t))}try{return Dn(await Fu(o,r,t))}catch(s){return Dn(qu(o,r,"load",s,t))}}eg(process.argv.slice(2),process.env);export{eg as main};
|