@tokmizer/plugin 0.9.63 → 0.9.65

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.
Files changed (37) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/README.md +9 -8
  4. package/dist/bin/tkr-agent-hook.js +9 -9
  5. package/dist/bin/tkr-codex-hook.js +68 -68
  6. package/dist/bin/tkr-copilot-hook.js +8 -8
  7. package/dist/bin/tkr-crush-hook.js +8 -8
  8. package/dist/bin/tkr-cursor-hook.js +8 -8
  9. package/dist/bin/tkr-daemon.js +120 -116
  10. package/dist/bin/tkr-droid-hook.js +8 -8
  11. package/dist/bin/tkr-exec +75 -71
  12. package/dist/bin/tkr-exec.js +75 -71
  13. package/dist/bin/tkr-gemini-hook.js +8 -8
  14. package/dist/bin/tkr-grok-hook.js +8 -8
  15. package/dist/bin/tkr-junie-hook.js +8 -8
  16. package/dist/bin/tkr-processor.js +94 -90
  17. package/dist/bin/tkr-qwen-hook.js +8 -8
  18. package/dist/bin/tkr-shim.js +75 -73
  19. package/dist/bin/tkr-trae-hook.js +8 -8
  20. package/dist/bin/tkr-zcode-hook.js +8 -8
  21. package/dist/bin/tkr.js +230 -230
  22. package/dist/hooks-host/post-tool-use.js +86 -82
  23. package/dist/hooks-host/pre-tool-use.js +9 -9
  24. package/dist/hooks-host/reducer-stop.js +24 -24
  25. package/dist/hooks-host/session-recap.js +1 -1
  26. package/dist/index.js +84 -84
  27. package/dist/native/manifest.json +12 -12
  28. package/dist/native/single.json +12 -12
  29. package/dist/native/tkr-exec-darwin-arm64 +0 -0
  30. package/dist/native/tkr-exec-darwin-x64 +0 -0
  31. package/dist/native/tkr-exec-linux-arm64 +0 -0
  32. package/dist/native/tkr-exec-linux-x64 +0 -0
  33. package/dist/native/tkr-exec-win32-arm64.exe +0 -0
  34. package/dist/native/tkr-exec-win32-x64.exe +0 -0
  35. package/hooks/on-session-start.mjs +16 -5
  36. package/package.json +8 -8
  37. package/scripts/install-mac-linux.sh +1 -1
@@ -1,12 +1,12 @@
1
1
  import { createRequire as __tkrCreateRequire } from "node:module"; const require = __tkrCreateRequire(import.meta.url);
2
- function R(t=5e3){return new Promise(e=>{let n=[],r=process.stdin,o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("data",i),r.pause(),r.unref?.(),e(Buffer.concat(n).toString("utf8")))},i=u=>{n.push(Buffer.isBuffer(u)?u:Buffer.from(u))},c=setTimeout(s,t);r.on("data",i).once("end",s).once("error",s),r.resume()})}import{realpathSync as gt}from"node:fs";import{fileURLToPath as ne,pathToFileURL as re}from"node:url";var ht=null;function kt(t,e,n){if(n!==void 0&&ht===n)return!0;if(ht!==null||!t)return!1;if(e===re(t).href)return!0;try{return gt(t)===gt(ne(e))}catch{return!1}}import{appendFileSync as ae,chmodSync as fe,mkdirSync as de,existsSync as pe,readFileSync as Ar,rmSync as Rr}from"node:fs";import{dirname as me,join as ge}from"node:path";import oe from"node:os";import{join as se}from"node:path";function $(){return process.env.TOKMIZER_HOME||se(oe.homedir(),".tokmizer")}import{readFileSync as ie,renameSync as ce,statSync as ue,writeFileSync as le}from"node:fs";function _t(t,e,n){try{if(ue(t).size<=e)return;let r=ie(t,"utf8").split(`
3
- `).filter(c=>c.trim()!==""),o=[],s=0;for(let c=r.length-1;c>=0;c-=1){let u=r[c],l=Buffer.byteLength(u)+1;if(s+l>n)break;o.push(u),s+=l}o.reverse();let i=`${t}.tmp-${process.pid}`;le(i,o.length?`${o.join(`
2
+ function R(t=5e3){return new Promise(e=>{let n=[],r=process.stdin,o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("data",i),r.pause(),r.unref?.(),e(Buffer.concat(n).toString("utf8")))},i=u=>{n.push(Buffer.isBuffer(u)?u:Buffer.from(u))},c=setTimeout(s,t);r.on("data",i).once("end",s).once("error",s),r.resume()})}import{realpathSync as ht}from"node:fs";import{fileURLToPath as re,pathToFileURL as oe}from"node:url";var kt=null;function _t(t,e,n){if(n!==void 0&&kt===n)return!0;if(kt!==null||!t)return!1;if(e===oe(t).href)return!0;try{return ht(t)===ht(re(e))}catch{return!1}}import{appendFileSync as fe,chmodSync as de,mkdirSync as pe,existsSync as me,readFileSync as Pr,rmSync as Hr}from"node:fs";import{dirname as ge,join as he}from"node:path";import se from"node:os";import{join as ie}from"node:path";function A(){return process.env.TOKMIZER_HOME||ie(se.homedir(),".tokmizer")}import{readFileSync as ce,renameSync as ue,statSync as le,writeFileSync as ae}from"node:fs";function bt(t,e,n){try{if(le(t).size<=e)return;let r=ce(t,"utf8").split(`
3
+ `).filter(c=>c.trim()!==""),o=[],s=0;for(let c=r.length-1;c>=0;c-=1){let u=r[c],l=Buffer.byteLength(u)+1;if(s+l>n)break;o.push(u),s+=l}o.reverse();let i=`${t}.tmp-${process.pid}`;ae(i,o.length?`${o.join(`
4
4
  `)}
5
- `:"",{mode:384}),ce(i,t)}catch{}}var he="usage.jsonl";var bt=2*1024*1024;function ke(){return ge($(),he)}function h(t,e,n=ke()){try{let r=me(n);pe(r)||de(r,{recursive:!0,mode:448});let o=t.replace(/[^A-Za-z0-9._-]/g,"").slice(0,64)||"unknown";ae(n,`{"t":${Math.floor(Date.now()/1e3)},"s":"${o}","o":${e?1:0}}
6
- `,{mode:384}),fe(n,384),_t(n,bt,bt/2)}catch{}}import{rmSync as _e,statSync as be}from"node:fs";import{join as we}from"node:path";function wt(){return we($(),"fail-open")}var Se=24*36e5;function S(t=Date.now()){try{if(t-be(wt()).mtimeMs<Se)return!0;_e(wt(),{force:!0})}catch{}return!1}import{existsSync as W,readFileSync as ot,readdirSync as st}from"node:fs";import{homedir as C}from"node:os";import{fileURLToPath as en}from"node:url";import{dirname as It,join as f,resolve as nn}from"node:path";function z(){return!1}import{execFileSync as ze}from"node:child_process";import{mkdirSync as Je,readFileSync as vt,renameSync as Be,statSync as We,writeFileSync as Ge}from"node:fs";import{join as Ot}from"node:path";import{closeSync as ye,openSync as xe,readSync as $e,readdirSync as Ee,readFileSync as ve,statSync as xt}from"node:fs";import{homedir as Oe}from"node:os";import{isAbsolute as Ae,join as J,resolve as Re}from"node:path";var Te=/^[A-Za-z0-9._+@%:,/-]+$/,Ce=new Set(["7f454c46","feedface","feedfacf","cefaedfe","cffaedfe","cafebabe","bebafeca"]),Pe=32,He=4*1024*1024;function et(t){let e;try{e=xe(t,"r");let n=Buffer.alloc(4),r=$e(e,n,0,4,0);return r>=2&&n[0]===35&&n[1]===33?"#!":r===4?n.toString("hex"):null}catch{return null}finally{e!==void 0&&ye(e)}}function F(t,e=process.platform){try{let n=xt(t);if(!n.isFile())return!1;if(e==="win32")return!0;if((n.mode&73)===0)return!1;let r=et(t);return r==="#!"||r!==null&&Ce.has(r)}catch{return!1}}function Ne(t){if(/\.[A-Za-z0-9]+$/.test(t))return[t];let e=(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);return[t,...e.map(n=>t+n.toLowerCase())]}function T(t,e,n,r=process.platform){if(!Te.test(t))return!1;let o=r==="win32";if(t.includes("/"))return F(Re(e??process.cwd(),t),r);if(!n)return!1;let s=o?Ne(t):[t];for(let i of n.split(o?";":":"))if(!(!i||!Ae(i))){for(let c of s)if(F(J(i,c),r))return!0}return!1}var Ie=/^eval \$'([^\s'()=]+) \(\) /,Le=/^([^\s'"()=]+) \(\) \{$/,je=/^alias -- ([^\s=]+)=(.*)$/,Fe=/^# (?:Shell Options|Aliases|Shopt|Check for |Shadow )/,De=/^export PATH=(.*)$/,Me=/^(?:--colou?r(?:=\S+)?|-G)$/;function yt(t){return t.length>=2&&t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/'\\''/g,"'"):t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function Ue(t,e){let n="";for(let r of t.split(`
7
- `)){let o=De.exec(r);if(o&&n!=="# Functions"){let s=yt(o[1].trim());/[$`\\]/.test(s)||e.paths.push(s);continue}if(r.startsWith("# ")&&(n!=="# Functions"||Fe.test(r))){n=r;continue}if(n==="# Functions"){let s=Ie.exec(r)??Le.exec(r);s&&e.functions.add(s[1])}else if(n==="# Aliases"){let s=je.exec(r);s&&e.aliases.set(s[1],yt(s[2].trim()))}}}function tt(t){return t?.code==="ENOENT"}function $t(t){let e={functions:new Set,aliases:new Map,paths:[],uncertain:!1},n=J(t||J(Oe(),".claude"),"shell-snapshots"),r=[];try{for(let o of Ee(n)){if(!o.startsWith("snapshot-")||!o.endsWith(".sh"))continue;let s=J(n,o);try{let i=xt(s);i.isFile()&&r.push({path:s,mtime:i.mtimeMs,size:i.size})}catch(i){tt(i)||(e.uncertain=!0)}}}catch(o){return tt(o)||(e.uncertain=!0),e}r=r.sort((o,s)=>s.mtime-o.mtime).slice(0,Pe);for(let o of r)try{if(o.size>He)throw new Error("snapshot too large");Ue(ve(o.path,"utf8"),e)}catch(s){tt(s)||(e.uncertain=!0)}return e}function Et(t,e){if(e.uncertain||e.functions.has(t))return!0;let n=e.aliases.get(t);if(n===void 0)return!1;let r=n.trim().split(/\s+/);return r[0]!==t||!r.slice(1).every(o=>Me.test(o))}var Ze="exec-probe.json",Ke=6e4;function qe(){return Ot($(),Ze)}function Ye(t){try{let e=JSON.parse(vt(t,"utf8"));if(e==null||typeof e!="object")return null;let n=e;return typeof n.key!="string"||typeof n.ok!="boolean"?null:{key:n.key,ok:n.ok,at:typeof n.at=="number"?n.at:0,skipped:typeof n.skipped=="number"&&n.skipped>=0?n.skipped:0}}catch{return null}}function Ve(t,e){try{Je(Ot(t,".."),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;Ge(n,JSON.stringify(e),{mode:384}),Be(n,t)}catch{}}function Xe(t){try{return ze(t,["--native-check"],{encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"],windowsHide:!0}).startsWith("tokmizer-native ")}catch{return!1}}function Qe(t,e){try{let r=vt(t,"utf8").split(`
8
- `,1)[0].slice(2).trim().split(/\s+/),o=r[0]??"";return o==="/usr/bin/env"?T(r[1]??"",void 0,e):F(o)}catch{return!1}}function tn(t,e,n){try{let r=We(t);return[t,r.size,r.mtimeMs,r.ino,r.mode,e?n??"":""].join("|")}catch{return`${t}|missing`}}function nt(t,e=process.platform,n=process.env.PATH,r=qe(),o=Date.now()){let s=e!=="win32"&&et(t)==="#!",i=tn(t,s,n),c=Ye(r);if(c?.key===i&&(c.ok||o-c.at<Ke))return c.ok;let u=F(t,e)&&(s?Qe(t,n):Xe(t));return Ve(r,{key:i,ok:u,at:o,skipped:(c?.skipped??0)+(u?0:1)}),u}var rn=new Set(["tkr","tkr-exec","token","claude","cd","export","source","echo","mkdir","rm","mv","cp","chmod","ln","true","false",":","test","[","exit","return","nohup","sudo","doas","env"]),on=new Set(["for","while","until","if","then","else","elif","fi","do","done","case","esac","select","function","time","coproc","in","!","[[","]]","{","}",".","declare","typeset","local","readonly","unset","set","shift","trap","wait","read","eval","exec","break","continue","pushd","popd","dirs","alias","unalias","hash","ulimit","umask","getopts","let","shopt","builtin","command","compgen","complete","disown","suspend","jobs","fg","bg","kill","history","fc","bind","enable","caller","type","printf","pwd","times","logout","mapfile","readarray","help","which","print","whence","where","autoload","zmodload","setopt","unsetopt","emulate","noglob","rehash","functions","bindkey","zle","vared","sched","limit","unlimit","zstyle","zparseopts","ttyctl"]),At=new Set(["sh","bash","zsh","dash","ksh","fish","python","python3","python2","node","ruby","perl","php","awk","sed","deno","bun"]),Rt="(?:dev|start|serve|watch|preview)",sn=new RegExp(`^(?:\\S*/)?(?:bun\\s+(?:install|i|add|remove|rm|update|outdated|audit|test|build|pm|x)(?:\\s|$)|bun\\s+run\\s+(?!${Rt}(?:\\s|$))[A-Za-z0-9:_-]+(?:\\s|$)|deno\\s+(?:test|lint|fmt|check|compile|install|info|doc|bench|outdated)(?:\\s|$)|deno\\s+task\\s+(?!${Rt}(?:\\s|$))[A-Za-z0-9:_-]+(?:\\s|$)|php\\s+-l(?:\\s|$)|php\\s+(?:\\S*/)?(?:phpunit|pest|paratest|phpstan|pint|ecs|php-cs-fixer|psalm|rector|run-tests\\.php)(?:\\s|$)|php\\s+artisan\\s+(?!(?:serve|tinker|queue:work|queue:listen|horizon|octane:start|reverb:start|schedule:work|pail|dev)(?:\\s|$))\\S)`),cn=/(?:^|\s)--watch(?:\s|=|$)/;function un(t){return sn.test(t)&&!cn.test(t)}var ln=/^((?:\S*\/)?(sh|bash|zsh|dash|ksh|fish)\s+(-[elux]*c[elux]*)\s+)(['"])/,an=/[()$]|(?:^|[;&|\n]\s*)(?:and|or|not|begin|end|if|else|switch|case|while|for|function|return)(?:\s|;|$)/,Lt=3;function jt(t){let e=ln.exec(t);if(!e)return null;let n=e[2]==="fish";if(n&&e[3]!=="-c")return null;let r=e[4],o=e[1].length+1,s=t.indexOf(r,o);if(s<=o)return null;let i=t.slice(s+1);if(i&&!/^\s/.test(i))return null;let c=t.slice(o,s);return r==='"'&&/[$`\\!]/.test(c)||n&&an.test(c)?null:{script:c,start:o,end:s,quote:r}}var fn=new Set(["cd","export","set","unset","source",".","true",":","pushd","popd"]);function dn(t){return Z(t).filter(n=>{if(n.kind!=="cmd"||n.unsafe)return!1;let r=Dt(n.text);return r!==""&&!fn.has(r)&&!it.test(r)}).length>1}function pn(t,e,n,r,o){if(n>=Lt)return null;let s=jt(t);if(!s)return null;let{script:i,start:c,end:u,quote:l}=s,a=[],d=Ut(i,e,n+1,r,v=>a.push(v));if(d===i||l==='"'&&/["$`]/.test(d))return null;let _=l==="'"?d.replace(/'/g,"'\\''"):d,g=`${t.slice(0,c)}${_}${t.slice(u)}`,w=dn(i);if(o)for(let v of w?[t,...a]:a)o(v);return w?`${e} ${g}`:g}var Tt=/(?:^|\s)(?:--follow|-[0-9a-zA-Z]*f[a-zA-Z]*)(?:\s|=|$)/,mn=new Set(["docker","podman","kubectl","nerdctl","docker-compose","stern","flyctl"]);function gn(t,e){let n=G(e);return n==="tail"||n==="journalctl"?Tt.test(t):n==="stern"?!0:mn.has(n)?/\blogs?\b/.test(t)&&Tt.test(t):!1}var it=/^[A-Za-z_][A-Za-z0-9_]*\+?=/,hn=/^[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/,kn=/(?:^|[;&|\n({])\s*[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/;function G(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Ft(t){let e=new Array(t.length).fill(!1),n=[],r=0;for(;r<t.length;){let o=t[r],s=t[r+1],i=n[n.length-1];if(i==="'"){o==="'"&&n.pop(),r+=1;continue}if(o==="\\"){if(s===void 0)return null;r+=2;continue}if(i==="$'"){o==="'"&&n.pop(),r+=1;continue}if(o==="$"&&(s==="("||s==="{")){n.push(s==="("?")":"}"),r+=2;continue}if(o==="`"){i==="`"?n.pop():n.push("`"),r+=1;continue}if(i==='"'){o==='"'&&n.pop(),r+=1;continue}if(o==="$"&&s==="'"){n.push("$'"),r+=2;continue}if(o==="'"||o==='"'){n.push(o),r+=1;continue}if(o==="("||o==="{"&&i==="}"){n.push(o==="("?")":"}"),r+=1;continue}if(o===i){n.pop(),r+=1;continue}if(o===")"&&i===void 0)return null;e[r]=i===void 0,r+=1}return n.length===0?e:null}function Ct(t){let e=Ft(t);if(!e)return!0;for(let n=0;n<t.length;n++)if(e[n]&&t[n]===">")return!0;return!1}function Z(t){let e=Ft(t);if(!e)return[{kind:"cmd",text:t,unsafe:!0}];let n=[],r="",o=0,s=()=>{r.length>0&&(n.push({kind:"cmd",text:r}),r="")},i=(c,u)=>{s(),n.push({kind:"sep",text:c}),o+=u};for(;o<t.length;){let c=t[o],u=t[o+1];if(e[o]){if(c===">"&&u==="|"){r+=">|",o+=2;continue}if(c==="&"&&u==="&"){i("&&",2);continue}if(c==="&"&&u!==">"){let l=r.replace(/\s+$/,""),a=l[l.length-1];if(a!==">"&&a!=="<"&&a!=="&"){i("&",1);continue}}if(c==="|"&&u==="|"){i("||",2);continue}if(c==="|"&&u==="&"){i("|&",2);continue}if(c===";"&&u===";"){let l=t[o+2]==="&";i(l?";;&":";;",l?3:2);continue}if(c===";"||c===`
9
- `||c==="|"){i(c,1);continue}}r+=c,o+=1}return s(),n}function Dt(t){return t.trim().split(/\s+/)[0]??""}function k(t,e=process.platform){try{let n=It(en(import.meta.url)),r=e==="win32",o=t&&t!=="claude-code"&&t!=="codex"&&!r?`TOKMIZER_HOST=${t} `:"";if(r&&(!t||t==="claude-code")){let c=f(n,"..","bin","tkr-exec.exe");if(W(c))return nt(c,e)?`'${c.replace(/\\/g,"/").replace(/'/g,"'\\''")}'`:null}let s=f(n,"..","bin","tkr-exec");if(!r&&W(s))return nt(s,e)?`${o}'${s.replace(/'/g,"'\\''")}'`:null;if(z()){let c=r?process.execPath.replace(/\\/g,"/"):process.execPath;return`${o}'${c.replace(/'/g,"'\\''")}' exec`}let i=f(n,"..","bin","tkr-exec.js");return W(i)?`${o}node '${i.replace(/'/g,"'\\''")}'`:null}catch{return null}}function Mt(t,e="tkr-exec",n=()=>!0,r){return Ut(t,e,0,n,r)}function Ut(t,e,n,r,o){if(t.includes("<<")||kn.test(t))return t;let s=Z(t),i=[];for(let c=0;c<s.length;c++){let u=s[c];if(u.kind==="sep"||u.unsafe){i.push(u.text);continue}let l=u.text.trim();if(!l){i.push(u.text);continue}let a=Dt(l),d=s[c+1],_=d?.kind==="sep"&&(d.text==="|"||d.text==="|&"),g=d?.kind==="sep"&&d.text==="&",w=!_&&!g&&!Ct(u.text)&&!u.text.includes("<(")&&!u.text.includes(">(")?pn(l,e,n,r,o):null;if(w!==null){i.push(`${u.text.match(/^\s*/)?.[0]??""}${w}${u.text.match(/\s*$/)?.[0]??""}`);continue}if(l===e||l.startsWith(e)&&/^\s/.test(l.slice(e.length))||rn.has(a)||on.has(a)||(At.has(a)||At.has(G(a)))&&!un(l)||it.test(a)||a.startsWith("(")||a.startsWith("#")||a.startsWith("<")||a.startsWith(">")||hn.test(l)||gn(l,a)||a.endsWith(")")||_||g||Ct(u.text)||u.text.includes("<(")||u.text.includes(">(")||a==="node"&&l.includes("tkr-exec.js")||!r(a)){i.push(u.text);continue}let v=u.text.match(/^\s*/)?.[0]??"",b=u.text.match(/\s*$/)?.[0]??"";o?.(l),i.push(`${v}${e} ${l}${b}`)}return i.join("")}var _n=new Set(["command","workdir","timeout_ms","yield_time_ms","max_output_tokens","shell","login","tty","description"]),bn=new Set(["cd","cat","head","tail","ls","tree","find","grep","rg","wc","nl","sort","cut","diff","stat","file","du","df","ps","jq","yq","pwd","which"]),wn=new Set(["log","diff","show","status","blame","ls-files","rev-parse","describe","shortlog"]),Sn={find:/^-(?:delete|exec|execdir|ok|okdir|fprint|fls)/,sort:/^(?:-[^-]*o|--output|--compress-program)/,rg:/^(?:--pre|-[^-]*z|--search-zip)/,yq:/^(?:-[^-]*[is]|--inplace|--split-exp)/,file:/^(?:-C|--compile)/,tree:/^(?:-o|--output|-R$|-H$)/,git:/^(?:--output|--ext-diff|--textconv|-c$|--exec-path|--git-dir|--work-tree)/,eslint:/^--fix/},B=["test","run test","run build","run lint","run typecheck"],yn={npm:new Set(B),pnpm:new Set([...B,"build","lint","typecheck"]),yarn:new Set([...B,"build","lint","typecheck"]),bun:new Set(B),cargo:new Set(["test","build","check","clippy"]),go:new Set(["test","build","vet"]),mvn:new Set(["test","compile","verify"]),gradle:new Set(["test","build","check"]),dotnet:new Set(["test","build"])},xn=new Set(["pytest","tsc","vitest","jest","eslint","mypy"]);function zt(t,e,n=0){if(/\$|`|<\(|>\(|\\\r?\n/.test(t)||/>/.test(t.replace(/2>&1|[12]?>\s*\/dev\/null/g,"")))return!1;for(let r of Z(t)){if(r.kind==="sep")continue;if(r.unsafe)return!1;let o=n<Lt?jt(r.text.trim()):null;if(o){if(!zt(o.script,e,n+1))return!1;continue}let s=r.text.trim().split(/\s+/).filter(Boolean).map(l=>l.replace(/['"\\]/g,""));if(s.length===0)continue;if(s.some(l=>it.test(l)))return!1;let i=G(s[0]);if(i!==s[0])return!1;let c=Sn[i];if(c&&s.slice(1).some(l=>c.test(l)))return!1;if((i==="git"?wn.has(s[1]??""):bn.has(i))||e&&xn.has(i))continue;let u=e?yn[i]:void 0;if(!(u&&(u.has(s[1]??"")||s[1]==="run"&&u.has(`run ${s[2]??""}`))))return!1}return!0}function ct(t,e,n=k(e),r=h,o=q(),s=process.env.PATH){if(!m(t)||t.tool_name!=="Bash")return null;let i=t.tool_input;if(!m(i)||i.run_in_background)return null;let c=i.command;if(typeof c!="string"||!c||e==="codex"&&Object.keys(i).some(w=>!_n.has(w)))return null;let u=typeof t.cwd=="string"&&t.cwd?t.cwd:i.workdir,l=typeof u=="string"&&u?u:void 0,a=typeof t.session_id=="string"&&t.session_id?t.session_id:"unknown",d=typeof t.permission_mode=="string"?t.permission_mode:void 0,_=qt(c,{host:e,sessionId:a,cwd:l,claudeDirs:o,pathEnv:s,permissionMode:d},n,r);if(!_)return null;let g={...i,command:_.command};return JSON.stringify({hookSpecificOutput:e==="codex"?{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:g}:_.allowedBy?{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Tokmizer: allowed by your rule ${_.allowedBy}`,updatedInput:g}:{hookEventName:"PreToolUse",updatedInput:g}})}function $n(t,e){if(!W(t))return"missing";try{let n=ot(t,"utf8");return JSON.parse(e?Jt(n):n)}catch{return"unreadable"}}function Jt(t){let e="",n=!1;for(let r=0;r<t.length;r++){let o=t[r];if(n){e+=o,o==="\\"?e+=t[++r]??"":o==='"'&&(n=!1);continue}if(o==='"')n=!0,e+=o;else if(o==="/"&&t[r+1]==="/"){for(;r<t.length&&t[r]!==`
5
+ `:"",{mode:384}),ue(i,t)}catch{}}var ke="usage.jsonl";var wt=2*1024*1024;function _e(){return he(A(),ke)}function k(t,e,n=_e()){try{let r=ge(n);me(r)||pe(r,{recursive:!0,mode:448});let o=t.replace(/[^A-Za-z0-9._-]/g,"").slice(0,64)||"unknown";fe(n,`{"t":${Math.floor(Date.now()/1e3)},"s":"${o}","o":${e?1:0}}
6
+ `,{mode:384}),de(n,384),bt(n,wt,wt/2)}catch{}}import{rmSync as be,statSync as we}from"node:fs";import{join as Se}from"node:path";function St(){return Se(A(),"fail-open")}var ye=24*36e5;function w(t=Date.now()){try{if(t-we(St()).mtimeMs<ye)return!0;be(St(),{force:!0})}catch{}return!1}import{spawnSync as nn}from"node:child_process";import{existsSync as W,readFileSync as ot,readdirSync as st}from"node:fs";import{homedir as C}from"node:os";import{fileURLToPath as rn}from"node:url";import{dirname as Lt,join as f,resolve as on}from"node:path";function J(){return!1}import{execFileSync as ze}from"node:child_process";import{mkdirSync as Be,readFileSync as vt,renameSync as We,statSync as Ge,writeFileSync as Ze}from"node:fs";import{join as Ot}from"node:path";import{closeSync as xe,openSync as $e,readSync as Ae,readdirSync as Ee,readFileSync as ve,statSync as $t}from"node:fs";import{homedir as Oe}from"node:os";import{isAbsolute as Re,join as z,resolve as Te}from"node:path";var Ce=/^[A-Za-z0-9._+@%:,/-]+$/,Pe=new Set(["7f454c46","feedface","feedfacf","cefaedfe","cffaedfe","cafebabe","bebafeca"]),He=32,Ne=4*1024*1024;function et(t){let e;try{e=$e(t,"r");let n=Buffer.alloc(4),r=Ae(e,n,0,4,0);return r>=2&&n[0]===35&&n[1]===33?"#!":r===4?n.toString("hex"):null}catch{return null}finally{e!==void 0&&xe(e)}}function F(t,e=process.platform){try{let n=$t(t);if(!n.isFile())return!1;if(e==="win32")return!0;if((n.mode&73)===0)return!1;let r=et(t);return r==="#!"||r!==null&&Pe.has(r)}catch{return!1}}function Ie(t){if(/\.[A-Za-z0-9]+$/.test(t))return[t];let e=(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);return[t,...e.map(n=>t+n.toLowerCase())]}function T(t,e,n,r=process.platform){if(!Ce.test(t))return!1;let o=r==="win32";if(t.includes("/"))return F(Te(e??process.cwd(),t),r);if(!n)return!1;let s=o?Ie(t):[t];for(let i of n.split(o?";":":"))if(!(!i||!Re(i))){for(let c of s)if(F(z(i,c),r))return!0}return!1}var Le=/^eval \$'([^\s'()=]+) \(\) /,je=/^([^\s'"()=]+) \(\) \{$/,Fe=/^alias -- ([^\s=]+)=(.*)$/,De=/^# (?:Shell Options|Aliases|Shopt|Check for |Shadow )/,Me=/^export PATH=(.*)$/,Ue=/^(?:--colou?r(?:=\S+)?|-G)$/;function xt(t){return t.length>=2&&t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/'\\''/g,"'"):t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function Je(t,e){let n="";for(let r of t.split(`
7
+ `)){let o=Me.exec(r);if(o&&n!=="# Functions"){let s=xt(o[1].trim());/[$`\\]/.test(s)||e.paths.push(s);continue}if(r.startsWith("# ")&&(n!=="# Functions"||De.test(r))){n=r;continue}if(n==="# Functions"){let s=Le.exec(r)??je.exec(r);s&&e.functions.add(s[1])}else if(n==="# Aliases"){let s=Fe.exec(r);s&&e.aliases.set(s[1],xt(s[2].trim()))}}}function tt(t){return t?.code==="ENOENT"}function At(t){let e={functions:new Set,aliases:new Map,paths:[],uncertain:!1},n=z(t||z(Oe(),".claude"),"shell-snapshots"),r=[];try{for(let o of Ee(n)){if(!o.startsWith("snapshot-")||!o.endsWith(".sh"))continue;let s=z(n,o);try{let i=$t(s);i.isFile()&&r.push({path:s,mtime:i.mtimeMs,size:i.size})}catch(i){tt(i)||(e.uncertain=!0)}}}catch(o){return tt(o)||(e.uncertain=!0),e}r=r.sort((o,s)=>s.mtime-o.mtime).slice(0,He);for(let o of r)try{if(o.size>Ne)throw new Error("snapshot too large");Je(ve(o.path,"utf8"),e)}catch(s){tt(s)||(e.uncertain=!0)}return e}function Et(t,e){if(e.uncertain||e.functions.has(t))return!0;let n=e.aliases.get(t);if(n===void 0)return!1;let r=n.trim().split(/\s+/);return r[0]!==t||!r.slice(1).every(o=>Ue.test(o))}var Ke="exec-probe.json",qe=6e4;function Ye(){return Ot(A(),Ke)}function Ve(t){try{let e=JSON.parse(vt(t,"utf8"));if(e==null||typeof e!="object")return null;let n=e;return typeof n.key!="string"||typeof n.ok!="boolean"?null:{key:n.key,ok:n.ok,at:typeof n.at=="number"?n.at:0,skipped:typeof n.skipped=="number"&&n.skipped>=0?n.skipped:0}}catch{return null}}function Xe(t,e){try{Be(Ot(t,".."),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;Ze(n,JSON.stringify(e),{mode:384}),We(n,t)}catch{}}function Qe(t){try{return ze(t,["--native-check"],{encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"],windowsHide:!0}).startsWith("tokmizer-native ")}catch{return!1}}function tn(t,e){try{let r=vt(t,"utf8").split(`
8
+ `,1)[0].slice(2).trim().split(/\s+/),o=r[0]??"";return o==="/usr/bin/env"?T(r[1]??"",void 0,e):F(o)}catch{return!1}}function en(t,e,n){try{let r=Ge(t);return[t,r.size,r.mtimeMs,r.ino,r.mode,e?n??"":""].join("|")}catch{return`${t}|missing`}}function nt(t,e=process.platform,n=process.env.PATH,r=Ye(),o=Date.now()){let s=e!=="win32"&&et(t)==="#!",i=en(t,s,n),c=Ve(r);if(c?.key===i&&(c.ok||o-c.at<qe))return c.ok;let u=F(t,e)&&(s?tn(t,n):Qe(t));return Xe(r,{key:i,ok:u,at:o,skipped:(c?.skipped??0)+(u?0:1)}),u}var sn=new Set(["tkr","tkr-exec","token","claude","cd","export","source","echo","mkdir","rm","mv","cp","chmod","ln","true","false",":","test","[","exit","return","nohup","sudo","doas","env"]),cn=new Set(["for","while","until","if","then","else","elif","fi","do","done","case","esac","select","function","time","coproc","in","!","[[","]]","{","}",".","declare","typeset","local","readonly","unset","set","shift","trap","wait","read","eval","exec","break","continue","pushd","popd","dirs","alias","unalias","hash","ulimit","umask","getopts","let","shopt","builtin","command","compgen","complete","disown","suspend","jobs","fg","bg","kill","history","fc","bind","enable","caller","type","printf","pwd","times","logout","mapfile","readarray","help","which","print","whence","where","autoload","zmodload","setopt","unsetopt","emulate","noglob","rehash","functions","bindkey","zle","vared","sched","limit","unlimit","zstyle","zparseopts","ttyctl"]),Rt=new Set(["sh","bash","zsh","dash","ksh","fish","python","python3","python2","node","ruby","perl","php","awk","sed","deno","bun"]),Tt="(?:dev|start|serve|watch|preview)",un=new RegExp(`^(?:\\S*/)?(?:bun\\s+(?:install|i|add|remove|rm|update|outdated|audit|test|build|pm|x)(?:\\s|$)|bun\\s+run\\s+(?!${Tt}(?:\\s|$))[A-Za-z0-9:_-]+(?:\\s|$)|deno\\s+(?:test|lint|fmt|check|compile|install|info|doc|bench|outdated)(?:\\s|$)|deno\\s+task\\s+(?!${Tt}(?:\\s|$))[A-Za-z0-9:_-]+(?:\\s|$)|php\\s+-l(?:\\s|$)|php\\s+(?:\\S*/)?(?:phpunit|pest|paratest|phpstan|pint|ecs|php-cs-fixer|psalm|rector|run-tests\\.php)(?:\\s|$)|php\\s+artisan\\s+(?!(?:serve|tinker|queue:work|queue:listen|horizon|octane:start|reverb:start|schedule:work|pail|dev)(?:\\s|$))\\S)`),ln=/(?:^|\s)--watch(?:\s|=|$)/;function an(t){return un.test(t)&&!ln.test(t)}var fn=/^((?:\S*\/)?(sh|bash|zsh|dash|ksh|fish)\s+(-[elux]*c[elux]*)\s+)(['"])/,dn=/[()$]|(?:^|[;&|\n]\s*)(?:and|or|not|begin|end|if|else|switch|case|while|for|function|return)(?:\s|;|$)/,jt=3;function Ft(t){let e=fn.exec(t);if(!e)return null;let n=e[2]==="fish";if(n&&e[3]!=="-c")return null;let r=e[4],o=e[1].length+1,s=t.indexOf(r,o);if(s<=o)return null;let i=t.slice(s+1);if(i&&!/^\s/.test(i))return null;let c=t.slice(o,s);return r==='"'&&/[$`\\!]/.test(c)||n&&dn.test(c)?null:{script:c,start:o,end:s,quote:r}}var pn=new Set(["cd","export","set","unset","source",".","true",":","pushd","popd"]);function mn(t){return Z(t).filter(n=>{if(n.kind!=="cmd"||n.unsafe)return!1;let r=Mt(n.text);return r!==""&&!pn.has(r)&&!it.test(r)}).length>1}function gn(t,e,n,r,o){if(n>=jt)return null;let s=Ft(t);if(!s)return null;let{script:i,start:c,end:u,quote:l}=s,a=[],d=Jt(i,e,n+1,r,S=>a.push(S));if(d===i||l==='"'&&/["$`]/.test(d))return null;let x=l==="'"?d.replace(/'/g,"'\\''"):d,m=`${t.slice(0,c)}${x}${t.slice(u)}`,h=mn(i);if(o)for(let S of h?[t,...a]:a)o(S);return h?`${e} ${m}`:m}var Ct=/(?:^|\s)(?:--follow|-[0-9a-zA-Z]*f[a-zA-Z]*)(?:\s|=|$)/,hn=new Set(["docker","podman","kubectl","nerdctl","docker-compose","stern","flyctl"]);function kn(t,e){let n=G(e);return n==="tail"||n==="journalctl"?Ct.test(t):n==="stern"?!0:hn.has(n)?/\blogs?\b/.test(t)&&Ct.test(t):!1}var it=/^[A-Za-z_][A-Za-z0-9_]*\+?=/,_n=/^[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/,bn=/(?:^|[;&|\n({])\s*[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/;function G(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Dt(t){let e=new Array(t.length).fill(!1),n=[],r=0;for(;r<t.length;){let o=t[r],s=t[r+1],i=n[n.length-1];if(i==="'"){o==="'"&&n.pop(),r+=1;continue}if(o==="\\"){if(s===void 0)return null;r+=2;continue}if(i==="$'"){o==="'"&&n.pop(),r+=1;continue}if(o==="$"&&(s==="("||s==="{")){n.push(s==="("?")":"}"),r+=2;continue}if(o==="`"){i==="`"?n.pop():n.push("`"),r+=1;continue}if(i==='"'){o==='"'&&n.pop(),r+=1;continue}if(o==="$"&&s==="'"){n.push("$'"),r+=2;continue}if(o==="'"||o==='"'){n.push(o),r+=1;continue}if(o==="("||o==="{"&&i==="}"){n.push(o==="("?")":"}"),r+=1;continue}if(o===i){n.pop(),r+=1;continue}if(o===")"&&i===void 0)return null;e[r]=i===void 0,r+=1}return n.length===0?e:null}function Pt(t){let e=Dt(t);if(!e)return!0;for(let n=0;n<t.length;n++)if(e[n]&&t[n]===">")return!0;return!1}function Z(t){let e=Dt(t);if(!e)return[{kind:"cmd",text:t,unsafe:!0}];let n=[],r="",o=0,s=()=>{r.length>0&&(n.push({kind:"cmd",text:r}),r="")},i=(c,u)=>{s(),n.push({kind:"sep",text:c}),o+=u};for(;o<t.length;){let c=t[o],u=t[o+1];if(e[o]){if(c===">"&&u==="|"){r+=">|",o+=2;continue}if(c==="&"&&u==="&"){i("&&",2);continue}if(c==="&"&&u!==">"){let l=r.replace(/\s+$/,""),a=l[l.length-1];if(a!==">"&&a!=="<"&&a!=="&"){i("&",1);continue}}if(c==="|"&&u==="|"){i("||",2);continue}if(c==="|"&&u==="&"){i("|&",2);continue}if(c===";"&&u===";"){let l=t[o+2]==="&";i(l?";;&":";;",l?3:2);continue}if(c===";"||c===`
9
+ `||c==="|"){i(c,1);continue}}r+=c,o+=1}return s(),n}function Mt(t){return t.trim().split(/\s+/)[0]??""}function _(t,e=process.platform){try{let n=Lt(rn(import.meta.url)),r=e==="win32",o=t&&t!=="claude-code"&&t!=="codex"&&!r?`TOKMIZER_HOST=${t} `:"";if(r&&(!t||t==="claude-code")){let c=f(n,"..","bin","tkr-exec.exe");if(W(c))return nt(c,e)?`'${c.replace(/\\/g,"/").replace(/'/g,"'\\''")}'`:null}let s=f(n,"..","bin","tkr-exec");if(!r&&W(s))return nt(s,e)?`${o}'${s.replace(/'/g,"'\\''")}'`:null;if(J()){let c=r?process.execPath.replace(/\\/g,"/"):process.execPath;return`${o}'${c.replace(/'/g,"'\\''")}' exec`}let i=f(n,"..","bin","tkr-exec.js");return W(i)?`${o}node '${i.replace(/'/g,"'\\''")}'`:null}catch{return null}}function Ut(t,e="tkr-exec",n=()=>!0,r){return Jt(t,e,0,n,r)}function Jt(t,e,n,r,o){if(t.includes("<<")||bn.test(t))return t;let s=Z(t),i=[];for(let c=0;c<s.length;c++){let u=s[c];if(u.kind==="sep"||u.unsafe){i.push(u.text);continue}let l=u.text.trim();if(!l){i.push(u.text);continue}let a=Mt(l),d=s[c+1],x=d?.kind==="sep"&&(d.text==="|"||d.text==="|&"),m=d?.kind==="sep"&&d.text==="&",h=!x&&!m&&!Pt(u.text)&&!u.text.includes("<(")&&!u.text.includes(">(")?gn(l,e,n,r,o):null;if(h!==null){i.push(`${u.text.match(/^\s*/)?.[0]??""}${h}${u.text.match(/\s*$/)?.[0]??""}`);continue}if(l===e||l.startsWith(e)&&/^\s/.test(l.slice(e.length))||sn.has(a)||cn.has(a)||(Rt.has(a)||Rt.has(G(a)))&&!an(l)||it.test(a)||a.startsWith("(")||a.startsWith("#")||a.startsWith("<")||a.startsWith(">")||_n.test(l)||kn(l,a)||a.endsWith(")")||x||m||Pt(u.text)||u.text.includes("<(")||u.text.includes(">(")||a==="node"&&l.includes("tkr-exec.js")||!r(a)){i.push(u.text);continue}let S=u.text.match(/^\s*/)?.[0]??"",b=u.text.match(/\s*$/)?.[0]??"";o?.(l),i.push(`${S}${e} ${l}${b}`)}return i.join("")}var wn=new Set(["command","workdir","timeout_ms","yield_time_ms","max_output_tokens","shell","login","tty","description"]),Sn=new Set(["cd","cat","head","tail","ls","tree","find","grep","rg","wc","nl","sort","cut","diff","stat","file","du","df","ps","jq","yq","pwd","which"]),yn=new Set(["log","diff","show","status","blame","ls-files","rev-parse","describe","shortlog"]),xn={find:/^-(?:delete|exec|execdir|ok|okdir|fprint|fls)/,sort:/^(?:-[^-]*o|--output|--compress-program)/,rg:/^(?:--pre|-[^-]*z|--search-zip)/,yq:/^(?:-[^-]*[is]|--inplace|--split-exp)/,file:/^(?:-C|--compile)/,tree:/^(?:-o|--output|-R$|-H$)/,git:/^(?:--output|--ext-diff|--textconv|-c$|--exec-path|--git-dir|--work-tree)/,eslint:/^--fix/},B=["test","run test","run build","run lint","run typecheck"],$n={npm:new Set(B),pnpm:new Set([...B,"build","lint","typecheck"]),yarn:new Set([...B,"build","lint","typecheck"]),bun:new Set(B),cargo:new Set(["test","build","check","clippy"]),go:new Set(["test","build","vet"]),mvn:new Set(["test","compile","verify"]),gradle:new Set(["test","build","check"]),dotnet:new Set(["test","build"])},An=new Set(["pytest","tsc","vitest","jest","eslint","mypy"]);function zt(t,e,n=0){if(/\$|`|<\(|>\(|\\\r?\n/.test(t)||/>/.test(t.replace(/2>&1|[12]?>\s*\/dev\/null/g,"")))return!1;for(let r of Z(t)){if(r.kind==="sep")continue;if(r.unsafe)return!1;let o=n<jt?Ft(r.text.trim()):null;if(o){if(!zt(o.script,e,n+1))return!1;continue}let s=r.text.trim().split(/\s+/).filter(Boolean).map(l=>l.replace(/['"\\]/g,""));if(s.length===0)continue;if(s.some(l=>it.test(l)))return!1;let i=G(s[0]);if(i!==s[0])return!1;let c=xn[i];if(c&&s.slice(1).some(l=>c.test(l)))return!1;if((i==="git"?yn.has(s[1]??""):Sn.has(i))||e&&An.has(i))continue;let u=e?$n[i]:void 0;if(!(u&&(u.has(s[1]??"")||s[1]==="run"&&u.has(`run ${s[2]??""}`))))return!1}return!0}function ct(t,e,n=_(e),r=k,o=q(),s=process.env.PATH,i=ut){if(!g(t)||t.tool_name!=="Bash"||e==="claude-code"&&vn(i()))return null;let c=t.tool_input;if(!g(c)||c.run_in_background)return null;let u=c.command;if(typeof u!="string"||!u||e==="codex"&&Object.keys(c).some(S=>!wn.has(S)))return null;let l=typeof t.cwd=="string"&&t.cwd?t.cwd:c.workdir,a=typeof l=="string"&&l?l:void 0,d=typeof t.session_id=="string"&&t.session_id?t.session_id:"unknown",x=typeof t.permission_mode=="string"?t.permission_mode:void 0,m=Yt(u,{host:e,sessionId:d,cwd:a,claudeDirs:o,pathEnv:s,permissionMode:x},n,r);if(!m)return null;let h={...c,command:m.command};return JSON.stringify({hookSpecificOutput:e==="codex"?{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:h}:m.allowedBy?{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Tokmizer: allowed by your rule ${m.allowedBy}`,updatedInput:h}:{hookEventName:"PreToolUse",updatedInput:h}})}var En=/(?:^|\s)--(?:disallowedTools|disallowed-tools|settings|setting-sources)(?:[=\s]|$)/;function ut(t=process.env,e=process.platform){let n=Number(t.CLAUDE_PID)||process.ppid;if(e==="win32"||!Number.isInteger(n)||n<=1)return null;try{let r=nn("ps",["-ww","-o","args=","-p",String(n)],{encoding:"utf8",timeout:2e3});return r.status===0&&r.stdout.trim()?r.stdout:null}catch{return null}}function vn(t){return t===null||En.test(t)}function On(t,e){if(!W(t))return"missing";try{let n=ot(t,"utf8");return JSON.parse(e?Bt(n):n)}catch{return"unreadable"}}function Bt(t){let e="",n=!1;for(let r=0;r<t.length;r++){let o=t[r];if(n){e+=o,o==="\\"?e+=t[++r]??"":o==='"'&&(n=!1);continue}if(o==='"')n=!0,e+=o;else if(o==="/"&&t[r+1]==="/"){for(;r<t.length&&t[r]!==`
10
10
  `;)r++;e+=`
11
- `}else if(o==="/"&&t[r+1]==="*"){if(r=t.indexOf("*/",r+2),r===-1)return"";r+=1}else e+=o}return e.replace(/,(\s*[}\]])/g,"$1")}function K(t){let e=[],n=nn(t);for(;;){e.push(n);let r=It(n);if(r===n)return e;n=r}}function En(){let t=process.platform==="darwin"?"/Library/Application Support/ClaudeCode":process.platform==="win32"?"C:\\Program Files\\ClaudeCode":"/etc/claude-code",e=[f(t,"managed-settings.json")];try{for(let n of st(f(t,"managed-settings.d")))n.endsWith(".json")&&e.push(f(t,"managed-settings.d",n))}catch{return e}return e}function M(t,e,n,r){let o=[];for(let s of t){let i=$n(s,e);if(i!=="missing"&&(i==="unreadable"||!m(i)||!n(i,o)))return"unreadable"}return{matchers:o,complete:r}}function D(t){return t===void 0?[]:Array.isArray(t)?t.filter(e=>typeof e=="string"):null}function q(){return{projectDir:process.env.CLAUDE_PROJECT_DIR,configDir:process.env.CLAUDE_CONFIG_DIR}}function vn(t,e){let n=b=>[f(b,"settings.json"),f(b,"settings.local.json")],r=b=>n(f(b,".claude")),o=f(C(),".claude"),s=e.configDir||o,i=[[En(),"managed"],[[f(s,"settings.json")],"loaded"],[[f(s,"settings.local.json")],"loadedLocal"],[e.configDir?n(o):[],"extra"],[e.projectDir?r(e.projectDir):[],"project"],[K(t).flatMap(r),"extra"]],c=[],u={managed:[],loaded:[],loadedLocal:[],project:[],extra:[]},l={managed:!1,loaded:!1,loadedLocal:!1,project:!1,extra:!1},a=!1,d="managed",_=(b,Q)=>{let x=b.permissions;if(d==="managed"&&(b.allowManagedPermissionRulesOnly===!0||m(x)&&x.allowManagedPermissionRulesOnly===!0)&&(a=!0),x===void 0)return!0;if(!m(x))return!1;for(let ft of["deny","ask","allow"]){let dt=D(x[ft]);if(!dt)return!1;for(let pt of dt){let A=/^\s*Bash\s*(?:\(([\s\S]*)\))?\s*$/.exec(pt);if(A)if(ft!=="allow")Q.push(O((A[1]??"*").replace(/:\*$/," *")));else if(A[1]===void 0||A[1].trim()==="*")l[d]=!0;else{c.push(O(A[1].replace(/:\*$/," *")));let mt=Dn(A[1]);mt&&u[d].push({rule:pt.trim(),matches:mt})}}}return!0},g=[];for(let[b,Q]of i){d=Q;let x=M(b,!1,_,!0);if(x==="unreadable")return"unreadable";g.push(...x.matchers)}let w=l.managed||(l.loaded||l.loadedLocal)&&!a,v=[...u.managed,...a?[]:u.loaded];return{matchers:[...g,...w?[]:c],complete:!0,allow:c,allowsEverything:w,guards:g,trustedAllow:v}}function On(t){let e=[f(C(),".cursor","cli-config.json"),...K(t).map(n=>f(n,".cursor","cli.json"))];return M(e,!0,(n,r)=>{let o=n.permissions;if(o===void 0)return!0;if(!m(o))return!1;let s=D(o.deny);if(!s)return!1;for(let i of s){let c=/^\s*Shell\s*(?:\(([\s\S]*)\))?\s*$/.exec(i);if(!c)continue;let u=c[1]??"*",l=u.indexOf(":");r.push(O(l===-1?`${u} *`:`${u.slice(0,l)} ${u.slice(l+1)}`))}return!0},!1)}function An(){return process.platform==="darwin"?"/Library/Application Support/GeminiCli":process.platform==="win32"?"C:\\ProgramData\\gemini-cli":"/etc/gemini-cli"}var Bt=/^\s*(?:run_shell_command|ShellTool)\s*(?:\(([\s\S]*)\))?\s*$/;function Rn(t,e){let n=t.tools;if(n!==void 0&&!m(n))return!1;let r=[D(t.excludeTools),D(m(n)?n.exclude:void 0)];for(let o of r){if(!o)return!1;for(let s of o){let i=Bt.exec(s);i&&e.push(O(i[1]===void 0?"*":`${i[1]}*`))}}return!0}function Pt(t){try{return JSON.parse(t)}catch{return null}}function Tn(t){let e=t.trim();if(e.startsWith('"""')||e.startsWith("'''"))return null;if(e.startsWith("[")){if(!/\]\s*(?:#.*)?$/.test(e))return null;let n=[];for(let r of e.matchAll(/"((?:\\.|[^"\\])*)"|'([^']*)'/g)){let o=r[2]??Pt(`"${r[1]}"`);if(o===null)return null;n.push(o)}return n}if(e.startsWith('"')){let n=/^"((?:\\.|[^"\\])*)"/.exec(e);return n?Pt(`"${n[1]}"`):null}if(e.startsWith("'")){let n=/^'([^']*)'/.exec(e);return n?n[1]:null}return e.replace(/\s*#.*$/,"")}function Cn(t,e){for(let n of t.split(/^\s*\[\[\s*rule\s*\]\]\s*$/m).slice(1)){let r={};for(let u of n.split(/\r?\n/)){if(/^\s*\[/.test(u))break;let l=/^\s*([A-Za-z_]+)\s*=\s*(.*)$/.exec(u);if(!l)continue;let a=Tn(l[2]);if(a===null)return!1;r[l[1]]=a}let o=r.decision;if(o!=="deny"&&o!=="ask_user"||!(r.toolName===void 0?["*"]:[r.toolName].flat()).some(u=>u==="*"||Bt.test(u)))continue;let i=r.commandPrefix===void 0?[]:[r.commandPrefix].flat(),c=[r.commandRegex,r.argsPattern].flat().filter(u=>typeof u=="string");if(i.length===0&&c.length===0){e.push(()=>!0);continue}for(let u of i)e.push(O(`${u}*`));for(let u of c){let l;try{l=new RegExp(u)}catch{return!1}e.push(a=>l.test(JSON.stringify({command:a}))||ut(l,a))}}return!0}function Ht(t){try{return st(t).filter(e=>e.endsWith(".toml")).map(e=>f(t,e))}catch{return[]}}function Pn(t){let e=An(),n=[f(e,"system-defaults.json"),f(e,"settings.json"),process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,process.env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH,f(C(),".gemini","settings.json"),...K(t).map(o=>f(o,".gemini","settings.json"))].filter(o=>!!o),r=M(n,!0,Rn,!1);if(r==="unreadable")return r;for(let o of[...Ht(f(C(),".gemini","policies")),...Ht(f(e,"policies"))]){let s;try{s=ot(o,"utf8")}catch{return"unreadable"}if(!Cn(s,r.matchers))return"unreadable"}return r}function rt(t,e){if(t===void 0)return!0;if(typeof t=="string")return t!=="allow"&&e.push(()=>!0),!0;if(!m(t))return!1;for(let n of["bash","shell","*"]){let r=t[n];if(r!==void 0){if(typeof r=="string"){r!=="allow"&&e.push(()=>!0);continue}if(!m(r))return!1;for(let[o,s]of Object.entries(r))s!=="allow"&&e.push(O(o.replace(/\?/g,"*")))}}return!0}function Nt(t,e){if(t.permissions!==void 0||!rt(t.permission,e))return!1;for(let n of["agent","agents","mode"]){let r=t[n];if(r!==void 0){if(!m(r))return!1;for(let o of Object.values(r))if(m(o)&&(o.permissions!==void 0||!rt(o.permission,e)))return!1}}return!0}function Hn(t){for(let e of t)for(let n of["agent","agents","mode","modes"]){let r;try{r=st(f(e,n))}catch{continue}for(let o of r)try{if(o.endsWith(".md")&&/permission/i.test(ot(f(e,n,o),"utf8")))return!0}catch{return!0}}return!1}function Nn(t){let e=f(process.env.XDG_CONFIG_HOME||f(C(),".config"),"opencode"),n=K(t),r=[e,...n.map(c=>f(c,".opencode"))];if(Hn(r))return"unreadable";let o=["opencode.json","opencode.jsonc","config.json"],s=[...o.map(c=>f(e,c)),process.env.OPENCODE_CONFIG,...n.flatMap(c=>[...o.slice(0,2).map(u=>f(c,u)),...o.slice(0,2).map(u=>f(c,".opencode",u))])].filter(c=>!!c),i=M(s,!0,Nt,!0);if(i==="unreadable")return i;for(let c of[process.env.OPENCODE_CONFIG_CONTENT,process.env.OPENCODE_PERMISSION]){if(!c)continue;let u;try{u=JSON.parse(Jt(c))}catch{return"unreadable"}if(!(c===process.env.OPENCODE_PERMISSION?rt(u,i.matchers):m(u)&&Nt(u,i.matchers)))return"unreadable"}return i}function In(){return M([f(C(),".gemini","antigravity-cli","settings.json")],!0,(t,e)=>{let n=t.permissions;if(n===void 0)return!0;if(!m(n))return!1;for(let r of["deny","ask"]){let o=D(n[r]);if(!o)return!1;for(let s of o){let i=/^\s*command\s*\(([\s\S]*)\)\s*$/.exec(s);if(!i)continue;let c=i[1].trim();if(!c.startsWith("regex:")){e.push(O(c==="*"?"*":`${c} *`));continue}let u;try{u=new RegExp(c.slice(6))}catch{return!1}e.push(l=>ut(u,l))}}return!0},!1)}function m(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Wt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ln(t){let e=t.trim().replace(/\s+/g," "),n=e.endsWith(" *")&&e.length>2,r=(n?e.slice(0,-2):e).split("*").map(Wt).join("[\\s\\S]*");return new RegExp(`^${r}${n?"(?: [\\s\\S]*)?":""}(?= |$)`)}var jn=512;function Fn(t){let e=t.replace(/['"\\]/g,"").split(/[\s;&|(){}<>`$]+/).filter(Boolean);return[e,e.map(G)]}function ut(t,e){if(t.test(e)||t.test(e.trim().replace(/\s+/g," ")))return!0;for(let n of Fn(e)){if(n.length>jn)return!0;for(let r=0;r<n.length;r++)if(t.test(n.slice(r).join(" ")))return!0}return!1}function O(t){let e=Ln(t);return n=>ut(e,n)}function Dn(t){let e=t.trim().replace(/:\*$/," *"),n=e.endsWith(" *"),r=n?e.slice(0,-2):e;if(!r||r.includes("*")||/\s\s|[^\S ]|^ | $/.test(r))return null;let o=new RegExp(`^${Wt(r)}${n?"(?: [\\s\\S]*)?":""}$`);return s=>o.test(s)}var Mn={"claude-code":vn,cursor:On,"gemini-cli":Pn,opencode:Nn,antigravity:In},Un=new Set(["codex"]),Gt=/(?:^|[\s=:/~])\.(?:git|claude|vscode|idea|husky)(?=[/\s;|&)]|$)|(?:^|[\s=:/~])\.(?:bashrc|bash_profile|bash_login|bash_logout|profile|zshrc|zprofile|zshenv|zlogin|zlogout|gitconfig|gitmodules|ripgreprc|mcp\.json)(?![A-Za-z0-9_])/;function zn(t,e,n){let r=Mn[t];return r?r(e??process.cwd(),n):{matchers:[],complete:!1}}function Jn(t,e,n){return t==="unreadable"||Gt.test(e.replace(/['"\\]/g,""))||t.matchers.some(r=>r(e))?!1:t.complete||zt(e,!Un.has(n))}var Zt=new Set(["default","acceptEdits","dontAsk"]);function Kt(t,e){return e.host!=="claude-code"||e.permissionMode==="bypassPermissions"?!0:t!=="unreadable"&&t.allowsEverything===!0&&Zt.has(e.permissionMode??"")}function Bn(t,e){let n="pathEnv"in t?t.pathEnv:process.env.PATH,r;return o=>t.host!=="claude-code"?T(o,t.cwd,n):(r??=$t(e.configDir),!T(o,t.cwd,n)&&!r.paths.some(s=>T(o,t.cwd,s))?!1:o.includes("/")||!Et(o,r))}var Wn=/^[^\s;&|<>()$`\\{}*?[\]~#!]+(?: [^\s;&|<>()$`\\{}*?[\]~#!]+)*$/;function Gn(t,e,n){return n.host!=="claude-code"||t==="unreadable"||Kt(t,n)||!Zt.has(n.permissionMode??"")||!Wn.test(e)||Gt.test(e.replace(/['"]/g,""))||(t.guards??[]).some(r=>r(e))?null:(t.trustedAllow??[]).find(r=>r.matches(e))?.rule??null}function qt(t,e,n,r){if(!n||/["\\$`;&|<>(){}]|'\\''/.test(n))return null;let o=e.claudeDirs??q(),s=zn(e.host,e.cwd,o),i=Gn(s,t,e),c=i||Jn(s,t,e.host)?Mt(t,n,Bn(e,o)):t;return c!==t&&s!=="unreadable"&&(i?(s.guards??[]).some(u=>u(c)):s.matchers.some(u=>u(c))||(s.allow??[]).some(u=>u(c)&&!u(t)))&&(c=t),r(e.sessionId,c!==t),c===t?null:i?{command:c,allowedBy:i}:Kt(s,e)?{command:c}:null}function E(t,e,n,r){return qt(t,e,n,r)?.command??null}function p(t,e){let n=t[e];return typeof n=="string"&&n?n:null}function U(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Zn(t){return p(t,"prompt_id")||p(t,"scratchpad_dir")?!0:U(t.effort)}function Kn(t){return p(t,"tool_use_id")?.startsWith("toolu_")===!0||/^claude/i.test(p(t,"model")??"")}var qn=new Set(["BeforeTool","AfterTool","BeforeAgent","AfterAgent","BeforeModel","AfterModel","BeforeToolSelection"]),Yn=new Set(["preToolUse","postToolUse","beforeShellExecution","afterShellExecution","beforeSubmitPrompt","sessionStart","sessionEnd","stop"]),Vn=new Set(["pre_tool","post_tool"]),Xn=new Set(["before_tool_call","after_tool_call"]),Qn=new Set(["runTerminalCommand","run_in_terminal"]),tr=[["codex",t=>p(t,"turn_id")!==null],["claude-code",Zn],["cursor",t=>p(t,"cursor_version")!==null||p(t,"generation_id")!==null||p(t,"conversation_id")!==null||Array.isArray(t.workspace_roots)||Yn.has(p(t,"hook_event_name")??"")],["gemini-cli",t=>qn.has(p(t,"hook_event_name")??"")],["qwen-code",t=>t.hook_event_name==="PreToolUse"&&t.tool_name==="run_shell_command"],["vibe",t=>Vn.has(p(t,"hook_event_name")??"")],["antigravity",t=>U(t.toolCall)],["copilot",t=>p(t,"toolName")!==null&&"toolArgs"in t||Qn.has(p(t,"tool_name")??"")],["grok",t=>t.toolName==="run_terminal_command"||t.tool_name==="run_terminal_command"||U(t.toolInput)&&!("toolArgs"in t)],["droid",t=>t.tool_name==="Execute"],["trae",t=>t.tool_name==="RunCommand"],["crush",t=>t.hook_event_name===void 0&&p(t,"event")!==null&&!Xn.has(p(t,"event"))]],er=new Set(["codex","antigravity"]);function nr(t){return U(t)?tr.filter(([,e])=>e(t)).map(([e])=>e):[]}function Yt(t,e){if(!U(t))return null;let n=nr(t);return n.length>1?null:n.length===1?n[0]:Kn(t)&&er.has(e)?"claude-code":e==="codex"?null:e}var lt=JSON.stringify({permission:"allow"});function Vt(t,e=k("cursor"),n=h){if(t.tool_name!=="Shell")return lt;let r=t.tool_input??{},o=r.command;if(typeof o!="string"||!o)return lt;let s=typeof r.working_directory=="string"?r.working_directory:void 0,i=E(o,{host:"cursor",sessionId:t.conversation_id??"unknown",cwd:s},S()?null:e,n);return i?JSON.stringify({permission:"allow",updated_input:{...r,command:i}}):lt}var Y="{}";function Xt(t,e=k("gemini-cli"),n=h){if(t.hook_event_name!=="BeforeTool"||t.tool_name!=="run_shell_command")return Y;let r=t.tool_input??{};if(r.is_background)return Y;let o=r.command;if(typeof o!="string"||!o)return Y;let s=typeof t.cwd=="string"?t.cwd:void 0,i=E(o,{host:"gemini-cli",sessionId:t.session_id??"unknown",cwd:s},S()?null:e,n);return i?JSON.stringify({hookSpecificOutput:{tool_input:{command:i}}}):Y}function H(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Bo=String.raw`(?:'(?:(?:[^']|'\\'')*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?'|"(?:[^"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?"|(?:[^\s'"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?)`;function N(t,e,n="unknown",r=k(e),o=h){return t?E(t,{host:e,sessionId:n},S()?null:r,o):null}var or=new Set(["bash","file_system.bash"]),at=JSON.stringify({decision:"allow"});function Qt(t,e=(n,r)=>N(n,"vibe",r)){if(!H(t)||t.hook_event_name!=="pre_tool"||typeof t.tool_name!="string"||!or.has(t.tool_name))return"";let n=t.tool_input;if(!H(n)||typeof n.command!="string"||!n.command)return"";let r=e(n.command,typeof t.session_id=="string"?t.session_id:"unknown");return r?JSON.stringify({hook_specific_output:{tool_input:{...n,command:r}}}):""}function te(t,e=(n,r)=>N(n,"antigravity",r)){if(!H(t)||!H(t.toolCall)||t.toolCall.name!=="run_command")return at;let n=t.toolCall.args;if(!H(n)||typeof n.CommandLine!="string"||!n.CommandLine)return at;let r=e(n.CommandLine,typeof t.conversationId=="string"?t.conversationId:"unknown");return r?JSON.stringify({decision:"allow",overwrite:{CommandLine:r}}):at}var y="{}",sr=new Set(["runTerminalCommand","run_in_terminal","Bash","bash"]),ir=["run_in_background","is_background","isBackground"];function V(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function cr(t){let e=t.session_id??t.sessionId;return typeof e=="string"&&e?e:"unknown"}function ur(t,e){let n=t.cwd??e.cwd??e.workdir??e.working_directory;return typeof n=="string"&&n?n:void 0}function X(t,e,n,r,o){if(!V(e)||ir.some(i=>e[i]===!0))return null;let s=e.command;return typeof s!="string"||!s?null:E(s,{host:t,sessionId:cr(n),cwd:ur(n,e)},S()?null:r,o)}function L(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...t,command:e}}})}function lr(t){if(V(t))return t;if(typeof t!="string")return null;try{let e=JSON.parse(t);return V(e)?e:null}catch{return null}}function ar(t,e,n){if(typeof t.tool_name=="string"){if(!sr.has(t.tool_name))return y;let s=t.tool_input,i=X("copilot",s,t,e,n);return i?L(s,i):y}if(t.toolName!=="bash")return y;let r=lr(t.toolArgs),o=X("copilot",r,t,e,n);return o?JSON.stringify({modifiedArgs:{...r,command:o}}):y}function I(t,e,n){return(r,o,s)=>{if(r.tool_name!==e)return y;let i=r.tool_input,c=X(t,i,r,o,s);return c?n(i,c):y}}var fr=new Set(["run_terminal_command","Bash","bash"]);function dr(t,e,n){let r=t.toolName??t.tool_name;if(typeof r!="string"||!fr.has(r))return y;let o=t.toolInput??t.tool_input,s=X("grok",o,t,e,n);return s?L(o,s):y}var pr={copilot:ar,droid:I("droid","Execute",L),trae:I("trae","RunCommand",L),"qwen-code":I("qwen-code","run_shell_command",L),crush:I("crush","bash",(t,e)=>JSON.stringify({updated_input:{command:e}})),junie:I("junie","Bash",(t,e)=>JSON.stringify({updatedInput:{...t,command:e}})),zcode:I("zcode","Bash",L),grok:dr};function ee(t,e,n=k(t),r=h){return V(e)?pr[t](e,n,r):y}function j(t){return S()?null:k(t)}function mr(t,e,n={}){let r=n.recordUsage??h;switch(t){case"claude-code":case"codex":return e.hook_event_name!==void 0&&e.hook_event_name!=="PreToolUse"?"":ct(e,t,j(t),r,n.claudeDirs??q(),n.pathEnv??process.env.PATH)??"";case"cursor":return Vt(e,j(t),r);case"gemini-cli":return Xt(e,j(t),r);case"vibe":return Qt(e,(o,s)=>N(o,"vibe",s,j(t),r));case"antigravity":return te(e,(o,s)=>N(o,"antigravity",s,j(t),r));default:return ee(t,e,j(t),r)}}function P(t,e,n={}){let r=Yt(t,e);return r?mr(r,t,n):n.fallback??""}function gr(t){let e;try{e=JSON.parse(t)}catch{return""}return P(e,"claude-code")}async function hr(){let t=await R(),e=t?gr(t):"";e&&process.stdout.write(e)}var kr=process.argv[1]??"";kt(kr,import.meta.url,"pre-tool-use")&&hr().catch(t=>{process.stderr.write(`tkr pre-tool-use: ${t.message}
12
- `),process.exit(0)});export{ct as buildPreToolUseOutput,k as execInvocation,gr as preToolUseResponse,Mt as rewrite,Z as splitTopLevel};
11
+ `}else if(o==="/"&&t[r+1]==="*"){if(r=t.indexOf("*/",r+2),r===-1)return"";r+=1}else e+=o}return e.replace(/,(\s*[}\]])/g,"$1")}function K(t){let e=[],n=on(t);for(;;){e.push(n);let r=Lt(n);if(r===n)return e;n=r}}function Rn(){let t=process.platform==="darwin"?"/Library/Application Support/ClaudeCode":process.platform==="win32"?"C:\\Program Files\\ClaudeCode":"/etc/claude-code",e=[f(t,"managed-settings.json")];try{for(let n of st(f(t,"managed-settings.d")))n.endsWith(".json")&&e.push(f(t,"managed-settings.d",n))}catch{return e}return e}function M(t,e,n,r){let o=[];for(let s of t){let i=On(s,e);if(i!=="missing"&&(i==="unreadable"||!g(i)||!n(i,o)))return"unreadable"}return{matchers:o,complete:r}}function D(t){return t===void 0?[]:Array.isArray(t)?t.filter(e=>typeof e=="string"):null}function q(){return{projectDir:process.env.CLAUDE_PROJECT_DIR,configDir:process.env.CLAUDE_CONFIG_DIR}}function Tn(t,e){let n=b=>[f(b,"settings.json"),f(b,"settings.local.json")],r=b=>n(f(b,".claude")),o=f(C(),".claude"),s=e.configDir||o,i=[[Rn(),"managed"],[[f(s,"settings.json")],"loaded"],[[f(s,"settings.local.json")],"loadedLocal"],[e.configDir?n(o):[],"extra"],[e.projectDir?r(e.projectDir):[],"project"],[K(t).flatMap(r),"extra"]],c=[],u={managed:[],loaded:[],loadedLocal:[],project:[],extra:[]},l={managed:!1,loaded:!1,loadedLocal:!1,project:!1,extra:!1},a=!1,d="managed",x=(b,Q)=>{let $=b.permissions;if(d==="managed"&&(b.allowManagedPermissionRulesOnly===!0||g($)&&$.allowManagedPermissionRulesOnly===!0)&&(a=!0),$===void 0)return!0;if(!g($))return!1;for(let dt of["deny","ask","allow"]){let pt=D($[dt]);if(!pt)return!1;for(let mt of pt){let O=/^\s*Bash\s*(?:\(([\s\S]*)\))?\s*$/.exec(mt);if(O)if(dt!=="allow")Q.push(v((O[1]??"*").replace(/:\*$/," *")));else if(O[1]===void 0||O[1].trim()==="*")l[d]=!0;else{c.push(v(O[1].replace(/:\*$/," *")));let gt=zn(O[1]);gt&&u[d].push({rule:mt.trim(),matches:gt})}}}return!0},m=[];for(let[b,Q]of i){d=Q;let $=M(b,!1,x,!0);if($==="unreadable")return"unreadable";m.push(...$.matchers)}let h=l.managed||(l.loaded||l.loadedLocal)&&!a,S=[...u.managed,...a?[]:u.loaded];return{matchers:[...m,...h?[]:c],complete:!0,allow:c,allowsEverything:h,guards:m,trustedAllow:S}}function Cn(t){let e=[f(C(),".cursor","cli-config.json"),...K(t).map(n=>f(n,".cursor","cli.json"))];return M(e,!0,(n,r)=>{let o=n.permissions;if(o===void 0)return!0;if(!g(o))return!1;let s=D(o.deny);if(!s)return!1;for(let i of s){let c=/^\s*Shell\s*(?:\(([\s\S]*)\))?\s*$/.exec(i);if(!c)continue;let u=c[1]??"*",l=u.indexOf(":");r.push(v(l===-1?`${u} *`:`${u.slice(0,l)} ${u.slice(l+1)}`))}return!0},!1)}function Pn(){return process.platform==="darwin"?"/Library/Application Support/GeminiCli":process.platform==="win32"?"C:\\ProgramData\\gemini-cli":"/etc/gemini-cli"}var Wt=/^\s*(?:run_shell_command|ShellTool)\s*(?:\(([\s\S]*)\))?\s*$/;function Hn(t,e){let n=t.tools;if(n!==void 0&&!g(n))return!1;let r=[D(t.excludeTools),D(g(n)?n.exclude:void 0)];for(let o of r){if(!o)return!1;for(let s of o){let i=Wt.exec(s);i&&e.push(v(i[1]===void 0?"*":`${i[1]}*`))}}return!0}function Ht(t){try{return JSON.parse(t)}catch{return null}}function Nn(t){let e=t.trim();if(e.startsWith('"""')||e.startsWith("'''"))return null;if(e.startsWith("[")){if(!/\]\s*(?:#.*)?$/.test(e))return null;let n=[];for(let r of e.matchAll(/"((?:\\.|[^"\\])*)"|'([^']*)'/g)){let o=r[2]??Ht(`"${r[1]}"`);if(o===null)return null;n.push(o)}return n}if(e.startsWith('"')){let n=/^"((?:\\.|[^"\\])*)"/.exec(e);return n?Ht(`"${n[1]}"`):null}if(e.startsWith("'")){let n=/^'([^']*)'/.exec(e);return n?n[1]:null}return e.replace(/\s*#.*$/,"")}function In(t,e){for(let n of t.split(/^\s*\[\[\s*rule\s*\]\]\s*$/m).slice(1)){let r={};for(let u of n.split(/\r?\n/)){if(/^\s*\[/.test(u))break;let l=/^\s*([A-Za-z_]+)\s*=\s*(.*)$/.exec(u);if(!l)continue;let a=Nn(l[2]);if(a===null)return!1;r[l[1]]=a}let o=r.decision;if(o!=="deny"&&o!=="ask_user"||!(r.toolName===void 0?["*"]:[r.toolName].flat()).some(u=>u==="*"||Wt.test(u)))continue;let i=r.commandPrefix===void 0?[]:[r.commandPrefix].flat(),c=[r.commandRegex,r.argsPattern].flat().filter(u=>typeof u=="string");if(i.length===0&&c.length===0){e.push(()=>!0);continue}for(let u of i)e.push(v(`${u}*`));for(let u of c){let l;try{l=new RegExp(u)}catch{return!1}e.push(a=>l.test(JSON.stringify({command:a}))||lt(l,a))}}return!0}function Nt(t){try{return st(t).filter(e=>e.endsWith(".toml")).map(e=>f(t,e))}catch{return[]}}function Ln(t){let e=Pn(),n=[f(e,"system-defaults.json"),f(e,"settings.json"),process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,process.env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH,f(C(),".gemini","settings.json"),...K(t).map(o=>f(o,".gemini","settings.json"))].filter(o=>!!o),r=M(n,!0,Hn,!1);if(r==="unreadable")return r;for(let o of[...Nt(f(C(),".gemini","policies")),...Nt(f(e,"policies"))]){let s;try{s=ot(o,"utf8")}catch{return"unreadable"}if(!In(s,r.matchers))return"unreadable"}return r}function rt(t,e){if(t===void 0)return!0;if(typeof t=="string")return t!=="allow"&&e.push(()=>!0),!0;if(!g(t))return!1;for(let n of["bash","shell","*"]){let r=t[n];if(r!==void 0){if(typeof r=="string"){r!=="allow"&&e.push(()=>!0);continue}if(!g(r))return!1;for(let[o,s]of Object.entries(r))s!=="allow"&&e.push(v(o.replace(/\?/g,"*")))}}return!0}function It(t,e){if(t.permissions!==void 0||!rt(t.permission,e))return!1;for(let n of["agent","agents","mode"]){let r=t[n];if(r!==void 0){if(!g(r))return!1;for(let o of Object.values(r))if(g(o)&&(o.permissions!==void 0||!rt(o.permission,e)))return!1}}return!0}function jn(t){for(let e of t)for(let n of["agent","agents","mode","modes"]){let r;try{r=st(f(e,n))}catch{continue}for(let o of r)try{if(o.endsWith(".md")&&/permission/i.test(ot(f(e,n,o),"utf8")))return!0}catch{return!0}}return!1}function Fn(t){let e=f(process.env.XDG_CONFIG_HOME||f(C(),".config"),"opencode"),n=K(t),r=[e,...n.map(c=>f(c,".opencode"))];if(jn(r))return"unreadable";let o=["opencode.json","opencode.jsonc","config.json"],s=[...o.map(c=>f(e,c)),process.env.OPENCODE_CONFIG,...n.flatMap(c=>[...o.slice(0,2).map(u=>f(c,u)),...o.slice(0,2).map(u=>f(c,".opencode",u))])].filter(c=>!!c),i=M(s,!0,It,!0);if(i==="unreadable")return i;for(let c of[process.env.OPENCODE_CONFIG_CONTENT,process.env.OPENCODE_PERMISSION]){if(!c)continue;let u;try{u=JSON.parse(Bt(c))}catch{return"unreadable"}if(!(c===process.env.OPENCODE_PERMISSION?rt(u,i.matchers):g(u)&&It(u,i.matchers)))return"unreadable"}return i}function Dn(){return M([f(C(),".gemini","antigravity-cli","settings.json")],!0,(t,e)=>{let n=t.permissions;if(n===void 0)return!0;if(!g(n))return!1;for(let r of["deny","ask"]){let o=D(n[r]);if(!o)return!1;for(let s of o){let i=/^\s*command\s*\(([\s\S]*)\)\s*$/.exec(s);if(!i)continue;let c=i[1].trim();if(!c.startsWith("regex:")){e.push(v(c==="*"?"*":`${c} *`));continue}let u;try{u=new RegExp(c.slice(6))}catch{return!1}e.push(l=>lt(u,l))}}return!0},!1)}function g(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Gt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mn(t){let e=t.trim().replace(/\s+/g," "),n=e.endsWith(" *")&&e.length>2,r=(n?e.slice(0,-2):e).split("*").map(Gt).join("[\\s\\S]*");return new RegExp(`^${r}${n?"(?: [\\s\\S]*)?":""}(?= |$)`)}var Un=512;function Jn(t){let e=t.replace(/['"\\]/g,"").split(/[\s;&|(){}<>`$]+/).filter(Boolean);return[e,e.map(G)]}function lt(t,e){if(t.test(e)||t.test(e.trim().replace(/\s+/g," ")))return!0;for(let n of Jn(e)){if(n.length>Un)return!0;for(let r=0;r<n.length;r++)if(t.test(n.slice(r).join(" ")))return!0}return!1}function v(t){let e=Mn(t);return n=>lt(e,n)}function zn(t){let e=t.trim().replace(/:\*$/," *"),n=e.endsWith(" *"),r=n?e.slice(0,-2):e;if(!r||r.includes("*")||/\s\s|[^\S ]|^ | $/.test(r))return null;let o=new RegExp(`^${Gt(r)}${n?"(?: [\\s\\S]*)?":""}$`);return s=>o.test(s)}var Bn={"claude-code":Tn,cursor:Cn,"gemini-cli":Ln,opencode:Fn,antigravity:Dn},Wn=new Set(["codex"]),Zt=/(?:^|[\s=:/~])\.(?:git|claude|vscode|idea|husky)(?=[/\s;|&)]|$)|(?:^|[\s=:/~])\.(?:bashrc|bash_profile|bash_login|bash_logout|profile|zshrc|zprofile|zshenv|zlogin|zlogout|gitconfig|gitmodules|ripgreprc|mcp\.json)(?![A-Za-z0-9_])/;function Gn(t,e,n){let r=Bn[t];return r?r(e??process.cwd(),n):{matchers:[],complete:!1}}function Zn(t,e,n){return t==="unreadable"||Zt.test(e.replace(/['"\\]/g,""))||t.matchers.some(r=>r(e))?!1:t.complete||zt(e,!Wn.has(n))}var Kt=new Set(["default","acceptEdits","dontAsk"]);function qt(t,e){return e.host!=="claude-code"||e.permissionMode==="bypassPermissions"?!0:t!=="unreadable"&&t.allowsEverything===!0&&Kt.has(e.permissionMode??"")}function Kn(t,e){let n="pathEnv"in t?t.pathEnv:process.env.PATH,r;return o=>t.host!=="claude-code"?T(o,t.cwd,n):(r??=At(e.configDir),!T(o,t.cwd,n)&&!r.paths.some(s=>T(o,t.cwd,s))?!1:o.includes("/")||!Et(o,r))}var qn=/^[^\s;&|<>()$`\\{}*?[\]~#!]+(?: [^\s;&|<>()$`\\{}*?[\]~#!]+)*$/;function Yn(t,e,n){return n.host!=="claude-code"||t==="unreadable"||qt(t,n)||!Kt.has(n.permissionMode??"")||!qn.test(e)||Zt.test(e.replace(/['"]/g,""))||(t.guards??[]).some(r=>r(e))?null:(t.trustedAllow??[]).find(r=>r.matches(e))?.rule??null}function Yt(t,e,n,r){if(!n||/["\\$`;&|<>(){}]|'\\''/.test(n))return null;let o=e.claudeDirs??q(),s=Gn(e.host,e.cwd,o),i=Yn(s,t,e),c=i||Zn(s,t,e.host)?Ut(t,n,Kn(e,o)):t;return c!==t&&s!=="unreadable"&&(i?(s.guards??[]).some(u=>u(c)):s.matchers.some(u=>u(c))||(s.allow??[]).some(u=>u(c)&&!u(t)))&&(c=t),r(e.sessionId,c!==t),c===t?null:i?{command:c,allowedBy:i}:qt(s,e)?{command:c}:null}function E(t,e,n,r){return Yt(t,e,n,r)?.command??null}function p(t,e){let n=t[e];return typeof n=="string"&&n?n:null}function U(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Vn(t){return p(t,"prompt_id")||p(t,"scratchpad_dir")?!0:U(t.effort)}function Xn(t){return p(t,"tool_use_id")?.startsWith("toolu_")===!0||/^claude/i.test(p(t,"model")??"")}var Qn=new Set(["BeforeTool","AfterTool","BeforeAgent","AfterAgent","BeforeModel","AfterModel","BeforeToolSelection"]),tr=new Set(["preToolUse","postToolUse","beforeShellExecution","afterShellExecution","beforeSubmitPrompt","sessionStart","sessionEnd","stop"]),er=new Set(["pre_tool","post_tool"]),nr=new Set(["before_tool_call","after_tool_call"]),rr=new Set(["runTerminalCommand","run_in_terminal"]),or=[["codex",t=>p(t,"turn_id")!==null],["claude-code",Vn],["cursor",t=>p(t,"cursor_version")!==null||p(t,"generation_id")!==null||p(t,"conversation_id")!==null||Array.isArray(t.workspace_roots)||tr.has(p(t,"hook_event_name")??"")],["gemini-cli",t=>Qn.has(p(t,"hook_event_name")??"")],["qwen-code",t=>t.hook_event_name==="PreToolUse"&&t.tool_name==="run_shell_command"],["vibe",t=>er.has(p(t,"hook_event_name")??"")],["antigravity",t=>U(t.toolCall)],["copilot",t=>p(t,"toolName")!==null&&"toolArgs"in t||rr.has(p(t,"tool_name")??"")],["grok",t=>t.toolName==="run_terminal_command"||t.tool_name==="run_terminal_command"||U(t.toolInput)&&!("toolArgs"in t)],["droid",t=>t.tool_name==="Execute"],["trae",t=>t.tool_name==="RunCommand"],["crush",t=>t.hook_event_name===void 0&&p(t,"event")!==null&&!nr.has(p(t,"event"))]],sr=new Set(["codex","antigravity"]);function ir(t){return U(t)?or.filter(([,e])=>e(t)).map(([e])=>e):[]}function Vt(t,e){if(!U(t))return null;let n=ir(t);return n.length>1?null:n.length===1?n[0]:Xn(t)&&sr.has(e)?"claude-code":e==="codex"?null:e}var at=JSON.stringify({permission:"allow"});function Xt(t,e=_("cursor"),n=k){if(t.tool_name!=="Shell")return at;let r=t.tool_input??{},o=r.command;if(typeof o!="string"||!o)return at;let s=typeof r.working_directory=="string"?r.working_directory:void 0,i=E(o,{host:"cursor",sessionId:t.conversation_id??"unknown",cwd:s},w()?null:e,n);return i?JSON.stringify({permission:"allow",updated_input:{...r,command:i}}):at}var Y="{}";function Qt(t,e=_("gemini-cli"),n=k){if(t.hook_event_name!=="BeforeTool"||t.tool_name!=="run_shell_command")return Y;let r=t.tool_input??{};if(r.is_background)return Y;let o=r.command;if(typeof o!="string"||!o)return Y;let s=typeof t.cwd=="string"?t.cwd:void 0,i=E(o,{host:"gemini-cli",sessionId:t.session_id??"unknown",cwd:s},w()?null:e,n);return i?JSON.stringify({hookSpecificOutput:{tool_input:{command:i}}}):Y}function H(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var qo=String.raw`(?:'(?:(?:[^']|'\\'')*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?'|"(?:[^"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?"|(?:[^\s'"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?)`;function N(t,e,n="unknown",r=_(e),o=k){return t?E(t,{host:e,sessionId:n},w()?null:r,o):null}var ur=new Set(["bash","file_system.bash"]),ft=JSON.stringify({decision:"allow"});function te(t,e=(n,r)=>N(n,"vibe",r)){if(!H(t)||t.hook_event_name!=="pre_tool"||typeof t.tool_name!="string"||!ur.has(t.tool_name))return"";let n=t.tool_input;if(!H(n)||typeof n.command!="string"||!n.command)return"";let r=e(n.command,typeof t.session_id=="string"?t.session_id:"unknown");return r?JSON.stringify({hook_specific_output:{tool_input:{...n,command:r}}}):""}function ee(t,e=(n,r)=>N(n,"antigravity",r)){if(!H(t)||!H(t.toolCall)||t.toolCall.name!=="run_command")return ft;let n=t.toolCall.args;if(!H(n)||typeof n.CommandLine!="string"||!n.CommandLine)return ft;let r=e(n.CommandLine,typeof t.conversationId=="string"?t.conversationId:"unknown");return r?JSON.stringify({decision:"allow",overwrite:{CommandLine:r}}):ft}var y="{}",lr=new Set(["runTerminalCommand","run_in_terminal","Bash","bash"]),ar=["run_in_background","is_background","isBackground"];function V(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function fr(t){let e=t.session_id??t.sessionId;return typeof e=="string"&&e?e:"unknown"}function dr(t,e){let n=t.cwd??e.cwd??e.workdir??e.working_directory;return typeof n=="string"&&n?n:void 0}function X(t,e,n,r,o){if(!V(e)||ar.some(i=>e[i]===!0))return null;let s=e.command;return typeof s!="string"||!s?null:E(s,{host:t,sessionId:fr(n),cwd:dr(n,e)},w()?null:r,o)}function L(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...t,command:e}}})}function pr(t){if(V(t))return t;if(typeof t!="string")return null;try{let e=JSON.parse(t);return V(e)?e:null}catch{return null}}function mr(t,e,n){if(typeof t.tool_name=="string"){if(!lr.has(t.tool_name))return y;let s=t.tool_input,i=X("copilot",s,t,e,n);return i?L(s,i):y}if(t.toolName!=="bash")return y;let r=pr(t.toolArgs),o=X("copilot",r,t,e,n);return o?JSON.stringify({modifiedArgs:{...r,command:o}}):y}function I(t,e,n){return(r,o,s)=>{if(r.tool_name!==e)return y;let i=r.tool_input,c=X(t,i,r,o,s);return c?n(i,c):y}}var gr=new Set(["run_terminal_command","Bash","bash"]);function hr(t,e,n){let r=t.toolName??t.tool_name;if(typeof r!="string"||!gr.has(r))return y;let o=t.toolInput??t.tool_input,s=X("grok",o,t,e,n);return s?L(o,s):y}var kr={copilot:mr,droid:I("droid","Execute",L),trae:I("trae","RunCommand",L),"qwen-code":I("qwen-code","run_shell_command",L),crush:I("crush","bash",(t,e)=>JSON.stringify({updated_input:{command:e}})),junie:I("junie","Bash",(t,e)=>JSON.stringify({updatedInput:{...t,command:e}})),zcode:I("zcode","Bash",L),grok:hr};function ne(t,e,n=_(t),r=k){return V(e)?kr[t](e,n,r):y}function j(t){return w()?null:_(t)}function _r(t,e,n={}){let r=n.recordUsage??k;switch(t){case"claude-code":case"codex":return e.hook_event_name!==void 0&&e.hook_event_name!=="PreToolUse"?"":ct(e,t,j(t),r,n.claudeDirs??q(),n.pathEnv??process.env.PATH,n.launchArgs??ut)??"";case"cursor":return Xt(e,j(t),r);case"gemini-cli":return Qt(e,j(t),r);case"vibe":return te(e,(o,s)=>N(o,"vibe",s,j(t),r));case"antigravity":return ee(e,(o,s)=>N(o,"antigravity",s,j(t),r));default:return ne(t,e,j(t),r)}}function P(t,e,n={}){let r=Vt(t,e);return r?_r(r,t,n):n.fallback??""}function br(t){let e;try{e=JSON.parse(t)}catch{return""}return P(e,"claude-code")}async function wr(){let t=await R(),e=t?br(t):"";e&&process.stdout.write(e)}var Sr=process.argv[1]??"";_t(Sr,import.meta.url,"pre-tool-use")&&wr().catch(t=>{process.stderr.write(`tkr pre-tool-use: ${t.message}
12
+ `),process.exit(0)});export{ct as buildPreToolUseOutput,_ as execInvocation,br as preToolUseResponse,Ut as rewrite,Z as splitTopLevel};