@tokmizer/plugin 0.9.64 → 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.
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +5 -4
- package/dist/bin/tkr-agent-hook.js +9 -9
- package/dist/bin/tkr-codex-hook.js +68 -68
- package/dist/bin/tkr-copilot-hook.js +8 -8
- package/dist/bin/tkr-crush-hook.js +8 -8
- package/dist/bin/tkr-cursor-hook.js +8 -8
- package/dist/bin/tkr-daemon.js +119 -117
- package/dist/bin/tkr-droid-hook.js +8 -8
- package/dist/bin/tkr-exec +75 -73
- package/dist/bin/tkr-exec.js +75 -73
- package/dist/bin/tkr-gemini-hook.js +8 -8
- package/dist/bin/tkr-grok-hook.js +8 -8
- package/dist/bin/tkr-junie-hook.js +8 -8
- package/dist/bin/tkr-processor.js +92 -90
- package/dist/bin/tkr-qwen-hook.js +8 -8
- package/dist/bin/tkr-shim.js +77 -75
- package/dist/bin/tkr-trae-hook.js +8 -8
- package/dist/bin/tkr-zcode-hook.js +8 -8
- package/dist/bin/tkr.js +228 -228
- package/dist/hooks-host/post-tool-use.js +85 -83
- package/dist/hooks-host/pre-tool-use.js +9 -9
- package/dist/hooks-host/reducer-stop.js +24 -24
- package/dist/hooks-host/session-recap.js +1 -1
- package/dist/index.js +84 -84
- package/dist/native/manifest.json +12 -12
- package/dist/native/single.json +12 -12
- package/dist/native/tkr-exec-darwin-arm64 +0 -0
- package/dist/native/tkr-exec-darwin-x64 +0 -0
- package/dist/native/tkr-exec-linux-arm64 +0 -0
- package/dist/native/tkr-exec-linux-x64 +0 -0
- package/dist/native/tkr-exec-win32-arm64.exe +0 -0
- package/dist/native/tkr-exec-win32-x64.exe +0 -0
- package/package.json +8 -8
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __tkrCreateRequire } from "node:module"; const require = __tkrCreateRequire(import.meta.url);
|
|
3
|
-
function L(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{appendFileSync as
|
|
4
|
-
`).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}`;
|
|
3
|
+
function L(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{appendFileSync as ie,chmodSync as ce,mkdirSync as ue,existsSync as le,readFileSync as xr,rmSync as $r}from"node:fs";import{dirname as ae,join as fe}from"node:path";import te from"node:os";import{join as ee}from"node:path";function A(){return process.env.TOKMIZER_HOME||ee(te.homedir(),".tokmizer")}import{readFileSync as ne,renameSync as re,statSync as oe,writeFileSync as se}from"node:fs";function gt(t,e,n){try{if(oe(t).size<=e)return;let r=ne(t,"utf8").split(`
|
|
4
|
+
`).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}`;se(i,o.length?`${o.join(`
|
|
5
5
|
`)}
|
|
6
|
-
`:"",{mode:384}),
|
|
7
|
-
`,{mode:384}),
|
|
8
|
-
`)){let o=
|
|
9
|
-
`,1)[0].slice(2).trim().split(/\s+/),o=r[0]??"";return o==="/usr/bin/env"?R(r[1]??"",void 0,e):j(o)}catch{return!1}}function
|
|
10
|
-
`||c==="|"){i(c,1);continue}}r+=c,o+=1}return s(),n}function
|
|
6
|
+
`:"",{mode:384}),re(i,t)}catch{}}var de="usage.jsonl";var ht=2*1024*1024;function pe(){return fe(A(),de)}function _(t,e,n=pe()){try{let r=ae(n);le(r)||ue(r,{recursive:!0,mode:448});let o=t.replace(/[^A-Za-z0-9._-]/g,"").slice(0,64)||"unknown";ie(n,`{"t":${Math.floor(Date.now()/1e3)},"s":"${o}","o":${e?1:0}}
|
|
7
|
+
`,{mode:384}),ce(n,384),gt(n,ht,ht/2)}catch{}}import{spawnSync as Ze}from"node:child_process";import{existsSync as G,readFileSync as rt,readdirSync as ot}from"node:fs";import{homedir as T}from"node:os";import{fileURLToPath as Ke}from"node:url";import{dirname as Ct,join as f,resolve as qe}from"node:path";function z(){return!1}import{execFileSync as Ne}from"node:child_process";import{mkdirSync as Ie,readFileSync as yt,renameSync as Le,statSync as je,writeFileSync as Fe}from"node:fs";import{join as xt}from"node:path";import{closeSync as me,openSync as ge,readSync as he,readdirSync as ke,readFileSync as _e,statSync as bt}from"node:fs";import{homedir as be}from"node:os";import{isAbsolute as Se,join as B,resolve as we}from"node:path";var ye=/^[A-Za-z0-9._+@%:,/-]+$/,xe=new Set(["7f454c46","feedface","feedfacf","cefaedfe","cffaedfe","cafebabe","bebafeca"]),$e=32,Ae=4*1024*1024;function tt(t){let e;try{e=ge(t,"r");let n=Buffer.alloc(4),r=he(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&&me(e)}}function j(t,e=process.platform){try{let n=bt(t);if(!n.isFile())return!1;if(e==="win32")return!0;if((n.mode&73)===0)return!1;let r=tt(t);return r==="#!"||r!==null&&xe.has(r)}catch{return!1}}function Ee(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 R(t,e,n,r=process.platform){if(!ye.test(t))return!1;let o=r==="win32";if(t.includes("/"))return j(we(e??process.cwd(),t),r);if(!n)return!1;let s=o?Ee(t):[t];for(let i of n.split(o?";":":"))if(!(!i||!Se(i))){for(let c of s)if(j(B(i,c),r))return!0}return!1}var ve=/^eval \$'([^\s'()=]+) \(\) /,Oe=/^([^\s'"()=]+) \(\) \{$/,Re=/^alias -- ([^\s=]+)=(.*)$/,Te=/^# (?:Shell Options|Aliases|Shopt|Check for |Shadow )/,Ce=/^export PATH=(.*)$/,Pe=/^(?:--colou?r(?:=\S+)?|-G)$/;function _t(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 He(t,e){let n="";for(let r of t.split(`
|
|
8
|
+
`)){let o=Ce.exec(r);if(o&&n!=="# Functions"){let s=_t(o[1].trim());/[$`\\]/.test(s)||e.paths.push(s);continue}if(r.startsWith("# ")&&(n!=="# Functions"||Te.test(r))){n=r;continue}if(n==="# Functions"){let s=ve.exec(r)??Oe.exec(r);s&&e.functions.add(s[1])}else if(n==="# Aliases"){let s=Re.exec(r);s&&e.aliases.set(s[1],_t(s[2].trim()))}}}function Q(t){return t?.code==="ENOENT"}function St(t){let e={functions:new Set,aliases:new Map,paths:[],uncertain:!1},n=B(t||B(be(),".claude"),"shell-snapshots"),r=[];try{for(let o of ke(n)){if(!o.startsWith("snapshot-")||!o.endsWith(".sh"))continue;let s=B(n,o);try{let i=bt(s);i.isFile()&&r.push({path:s,mtime:i.mtimeMs,size:i.size})}catch(i){Q(i)||(e.uncertain=!0)}}}catch(o){return Q(o)||(e.uncertain=!0),e}r=r.sort((o,s)=>s.mtime-o.mtime).slice(0,$e);for(let o of r)try{if(o.size>Ae)throw new Error("snapshot too large");He(_e(o.path,"utf8"),e)}catch(s){Q(s)||(e.uncertain=!0)}return e}function wt(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=>Pe.test(o))}var De="exec-probe.json",Me=6e4;function Ue(){return xt(A(),De)}function Je(t){try{let e=JSON.parse(yt(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 ze(t,e){try{Ie(xt(t,".."),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;Fe(n,JSON.stringify(e),{mode:384}),Le(n,t)}catch{}}function Be(t){try{return Ne(t,["--native-check"],{encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"],windowsHide:!0}).startsWith("tokmizer-native ")}catch{return!1}}function We(t,e){try{let r=yt(t,"utf8").split(`
|
|
9
|
+
`,1)[0].slice(2).trim().split(/\s+/),o=r[0]??"";return o==="/usr/bin/env"?R(r[1]??"",void 0,e):j(o)}catch{return!1}}function Ge(t,e,n){try{let r=je(t);return[t,r.size,r.mtimeMs,r.ino,r.mode,e?n??"":""].join("|")}catch{return`${t}|missing`}}function et(t,e=process.platform,n=process.env.PATH,r=Ue(),o=Date.now()){let s=e!=="win32"&&tt(t)==="#!",i=Ge(t,s,n),c=Je(r);if(c?.key===i&&(c.ok||o-c.at<Me))return c.ok;let u=j(t,e)&&(s?We(t,n):Be(t));return ze(r,{key:i,ok:u,at:o,skipped:(c?.skipped??0)+(u?0:1)}),u}var Ye=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"]),Ve=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"]),$t=new Set(["sh","bash","zsh","dash","ksh","fish","python","python3","python2","node","ruby","perl","php","awk","sed","deno","bun"]),At="(?:dev|start|serve|watch|preview)",Xe=new RegExp(`^(?:\\S*/)?(?:bun\\s+(?:install|i|add|remove|rm|update|outdated|audit|test|build|pm|x)(?:\\s|$)|bun\\s+run\\s+(?!${At}(?:\\s|$))[A-Za-z0-9:_-]+(?:\\s|$)|deno\\s+(?:test|lint|fmt|check|compile|install|info|doc|bench|outdated)(?:\\s|$)|deno\\s+task\\s+(?!${At}(?:\\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)`),Qe=/(?:^|\s)--watch(?:\s|=|$)/;function tn(t){return Xe.test(t)&&!Qe.test(t)}var en=/^((?:\S*\/)?(sh|bash|zsh|dash|ksh|fish)\s+(-[elux]*c[elux]*)\s+)(['"])/,nn=/[()$]|(?:^|[;&|\n]\s*)(?:and|or|not|begin|end|if|else|switch|case|while|for|function|return)(?:\s|;|$)/,Pt=3;function Ht(t){let e=en.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&&nn.test(c)?null:{script:c,start:o,end:s,quote:r}}var rn=new Set(["cd","export","set","unset","source",".","true",":","pushd","popd"]);function on(t){return it(t).filter(n=>{if(n.kind!=="cmd"||n.unsafe)return!1;let r=It(n.text);return r!==""&&!rn.has(r)&&!st.test(r)}).length>1}function sn(t,e,n,r,o){if(n>=Pt)return null;let s=Ht(t);if(!s)return null;let{script:i,start:c,end:u,quote:l}=s,a=[],d=Lt(i,e,n+1,r,y=>a.push(y));if(d===i||l==='"'&&/["$`]/.test(d))return null;let x=l==="'"?d.replace(/'/g,"'\\''"):d,g=`${t.slice(0,c)}${x}${t.slice(u)}`,k=on(i);if(o)for(let y of k?[t,...a]:a)o(y);return k?`${e} ${g}`:g}var Et=/(?:^|\s)(?:--follow|-[0-9a-zA-Z]*f[a-zA-Z]*)(?:\s|=|$)/,cn=new Set(["docker","podman","kubectl","nerdctl","docker-compose","stern","flyctl"]);function un(t,e){let n=Z(e);return n==="tail"||n==="journalctl"?Et.test(t):n==="stern"?!0:cn.has(n)?/\blogs?\b/.test(t)&&Et.test(t):!1}var st=/^[A-Za-z_][A-Za-z0-9_]*\+?=/,ln=/^[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/,an=/(?:^|[;&|\n({])\s*[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/;function Z(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Nt(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 vt(t){let e=Nt(t);if(!e)return!0;for(let n=0;n<t.length;n++)if(e[n]&&t[n]===">")return!0;return!1}function it(t){let e=Nt(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===`
|
|
10
|
+
`||c==="|"){i(c,1);continue}}r+=c,o+=1}return s(),n}function It(t){return t.trim().split(/\s+/)[0]??""}function S(t,e=process.platform){try{let n=Ct(Ke(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(G(c))return et(c,e)?`'${c.replace(/\\/g,"/").replace(/'/g,"'\\''")}'`:null}let s=f(n,"..","bin","tkr-exec");if(!r&&G(s))return et(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 G(i)?`${o}node '${i.replace(/'/g,"'\\''")}'`:null}catch{return null}}function fn(t,e="tkr-exec",n=()=>!0,r){return Lt(t,e,0,n,r)}function Lt(t,e,n,r,o){if(t.includes("<<")||an.test(t))return t;let s=it(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=It(l),d=s[c+1],x=d?.kind==="sep"&&(d.text==="|"||d.text==="|&"),g=d?.kind==="sep"&&d.text==="&",k=!x&&!g&&!vt(u.text)&&!u.text.includes("<(")&&!u.text.includes(">(")?sn(l,e,n,r,o):null;if(k!==null){i.push(`${u.text.match(/^\s*/)?.[0]??""}${k}${u.text.match(/\s*$/)?.[0]??""}`);continue}if(l===e||l.startsWith(e)&&/^\s/.test(l.slice(e.length))||Ye.has(a)||Ve.has(a)||($t.has(a)||$t.has(Z(a)))&&!tn(l)||st.test(a)||a.startsWith("(")||a.startsWith("#")||a.startsWith("<")||a.startsWith(">")||ln.test(l)||un(l,a)||a.endsWith(")")||x||g||vt(u.text)||u.text.includes("<(")||u.text.includes(">(")||a==="node"&&l.includes("tkr-exec.js")||!r(a)){i.push(u.text);continue}let y=u.text.match(/^\s*/)?.[0]??"",b=u.text.match(/\s*$/)?.[0]??"";o?.(l),i.push(`${y}${e} ${l}${b}`)}return i.join("")}var dn=new Set(["command","workdir","timeout_ms","yield_time_ms","max_output_tokens","shell","login","tty","description"]),pn=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"]),mn=new Set(["log","diff","show","status","blame","ls-files","rev-parse","describe","shortlog"]),gn={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/},W=["test","run test","run build","run lint","run typecheck"],hn={npm:new Set(W),pnpm:new Set([...W,"build","lint","typecheck"]),yarn:new Set([...W,"build","lint","typecheck"]),bun:new Set(W),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"])},kn=new Set(["pytest","tsc","vitest","jest","eslint","mypy"]);function jt(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 it(t)){if(r.kind==="sep")continue;if(r.unsafe)return!1;let o=n<Pt?Ht(r.text.trim()):null;if(o){if(!jt(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=>st.test(l)))return!1;let i=Z(s[0]);if(i!==s[0])return!1;let c=gn[i];if(c&&s.slice(1).some(l=>c.test(l)))return!1;if((i==="git"?mn.has(s[1]??""):pn.has(i))||e&&kn.has(i))continue;let u=e?hn[i]:void 0;if(!(u&&(u.has(s[1]??"")||s[1]==="run"&&u.has(`run ${s[2]??""}`))))return!1}return!0}function Ft(t,e,n=S(e),r=_,o=q(),s=process.env.PATH,i=ct){if(!h(t)||t.tool_name!=="Bash"||e==="claude-code"&&bn(i()))return null;let c=t.tool_input;if(!h(c)||c.run_in_background)return null;let u=c.command;if(typeof u!="string"||!u||e==="codex"&&Object.keys(c).some(y=>!dn.has(y)))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,g=Wt(u,{host:e,sessionId:d,cwd:a,claudeDirs:o,pathEnv:s,permissionMode:x},n,r);if(!g)return null;let k={...c,command:g.command};return JSON.stringify({hookSpecificOutput:e==="codex"?{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:k}:g.allowedBy?{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Tokmizer: allowed by your rule ${g.allowedBy}`,updatedInput:k}:{hookEventName:"PreToolUse",updatedInput:k}})}var _n=/(?:^|\s)--(?:disallowedTools|disallowed-tools|settings|setting-sources)(?:[=\s]|$)/;function ct(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=Ze("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 bn(t){return t===null||_n.test(t)}function Sn(t,e){if(!G(t))return"missing";try{let n=rt(t,"utf8");return JSON.parse(e?Dt(n):n)}catch{return"unreadable"}}function Dt(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]!==`
|
|
11
11
|
`;)r++;e+=`
|
|
12
|
-
`}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=Ze(t);for(;;){e.push(n);let r=Tt(n);if(r===n)return e;n=r}}function kn(){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 ot(f(t,"managed-settings.d")))n.endsWith(".json")&&e.push(f(t,"managed-settings.d",n))}catch{return e}return e}function D(t,e,n,r){let o=[];for(let s of t){let i=hn(s,e);if(i!=="missing"&&(i==="unreadable"||!g(i)||!n(i,o)))return"unreadable"}return{matchers:o,complete:r}}function F(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 _n(t,e){let n=b=>[f(b,"settings.json"),f(b,"settings.local.json")],r=b=>n(f(b,".claude")),o=f(T(),".claude"),s=e.configDir||o,i=[[kn(),"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,X)=>{let x=b.permissions;if(d==="managed"&&(b.allowManagedPermissionRulesOnly===!0||g(x)&&x.allowManagedPermissionRulesOnly===!0)&&(a=!0),x===void 0)return!0;if(!g(x))return!1;for(let at of["deny","ask","allow"]){let ft=F(x[at]);if(!ft)return!1;for(let dt of ft){let v=/^\s*Bash\s*(?:\(([\s\S]*)\))?\s*$/.exec(dt);if(v)if(at!=="allow")X.push(O((v[1]??"*").replace(/:\*$/," *")));else if(v[1]===void 0||v[1].trim()==="*")l[d]=!0;else{c.push(O(v[1].replace(/:\*$/," *")));let pt=Cn(v[1]);pt&&u[d].push({rule:dt.trim(),matches:pt})}}}return!0},h=[];for(let[b,X]of i){d=X;let x=D(b,!1,_,!0);if(x==="unreadable")return"unreadable";h.push(...x.matchers)}let w=l.managed||(l.loaded||l.loadedLocal)&&!a,E=[...u.managed,...a?[]:u.loaded];return{matchers:[...h,...w?[]:c],complete:!0,allow:c,allowsEverything:w,guards:h,trustedAllow:E}}function bn(t){let e=[f(T(),".cursor","cli-config.json"),...K(t).map(n=>f(n,".cursor","cli.json"))];return D(e,!0,(n,r)=>{let o=n.permissions;if(o===void 0)return!0;if(!g(o))return!1;let s=F(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 Sn(){return process.platform==="darwin"?"/Library/Application Support/GeminiCli":process.platform==="win32"?"C:\\ProgramData\\gemini-cli":"/etc/gemini-cli"}var Dt=/^\s*(?:run_shell_command|ShellTool)\s*(?:\(([\s\S]*)\))?\s*$/;function wn(t,e){let n=t.tools;if(n!==void 0&&!g(n))return!1;let r=[F(t.excludeTools),F(g(n)?n.exclude:void 0)];for(let o of r){if(!o)return!1;for(let s of o){let i=Dt.exec(s);i&&e.push(O(i[1]===void 0?"*":`${i[1]}*`))}}return!0}function Ot(t){try{return JSON.parse(t)}catch{return null}}function yn(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]??Ot(`"${r[1]}"`);if(o===null)return null;n.push(o)}return n}if(e.startsWith('"')){let n=/^"((?:\\.|[^"\\])*)"/.exec(e);return n?Ot(`"${n[1]}"`):null}if(e.startsWith("'")){let n=/^'([^']*)'/.exec(e);return n?n[1]:null}return e.replace(/\s*#.*$/,"")}function xn(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=yn(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==="*"||Dt.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}))||ct(l,a))}}return!0}function vt(t){try{return ot(t).filter(e=>e.endsWith(".toml")).map(e=>f(t,e))}catch{return[]}}function $n(t){let e=Sn(),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(T(),".gemini","settings.json"),...K(t).map(o=>f(o,".gemini","settings.json"))].filter(o=>!!o),r=D(n,!0,wn,!1);if(r==="unreadable")return r;for(let o of[...vt(f(T(),".gemini","policies")),...vt(f(e,"policies"))]){let s;try{s=rt(o,"utf8")}catch{return"unreadable"}if(!xn(s,r.matchers))return"unreadable"}return r}function nt(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(O(o.replace(/\?/g,"*")))}}return!0}function Rt(t,e){if(t.permissions!==void 0||!nt(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||!nt(o.permission,e)))return!1}}return!0}function An(t){for(let e of t)for(let n of["agent","agents","mode","modes"]){let r;try{r=ot(f(e,n))}catch{continue}for(let o of r)try{if(o.endsWith(".md")&&/permission/i.test(rt(f(e,n,o),"utf8")))return!0}catch{return!0}}return!1}function En(t){let e=f(process.env.XDG_CONFIG_HOME||f(T(),".config"),"opencode"),n=K(t),r=[e,...n.map(c=>f(c,".opencode"))];if(An(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=D(s,!0,Rt,!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(Ft(c))}catch{return"unreadable"}if(!(c===process.env.OPENCODE_PERMISSION?nt(u,i.matchers):g(u)&&Rt(u,i.matchers)))return"unreadable"}return i}function On(){return D([f(T(),".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=F(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=>ct(u,l))}}return!0},!1)}function g(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Mt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vn(t){let e=t.trim().replace(/\s+/g," "),n=e.endsWith(" *")&&e.length>2,r=(n?e.slice(0,-2):e).split("*").map(Mt).join("[\\s\\S]*");return new RegExp(`^${r}${n?"(?: [\\s\\S]*)?":""}(?= |$)`)}var Rn=512;function Tn(t){let e=t.replace(/['"\\]/g,"").split(/[\s;&|(){}<>`$]+/).filter(Boolean);return[e,e.map(Z)]}function ct(t,e){if(t.test(e)||t.test(e.trim().replace(/\s+/g," ")))return!0;for(let n of Tn(e)){if(n.length>Rn)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=vn(t);return n=>ct(e,n)}function Cn(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(`^${Mt(r)}${n?"(?: [\\s\\S]*)?":""}$`);return s=>o.test(s)}var Pn={"claude-code":_n,cursor:bn,"gemini-cli":$n,opencode:En,antigravity:On},Hn=new Set(["codex"]),Ut=/(?:^|[\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 Nn(t,e,n){let r=Pn[t];return r?r(e??process.cwd(),n):{matchers:[],complete:!1}}function In(t,e,n){return t==="unreadable"||Ut.test(e.replace(/['"\\]/g,""))||t.matchers.some(r=>r(e))?!1:t.complete||Lt(e,!Hn.has(n))}var zt=new Set(["default","acceptEdits","dontAsk"]);function Jt(t,e){return e.host!=="claude-code"||e.permissionMode==="bypassPermissions"?!0:t!=="unreadable"&&t.allowsEverything===!0&&zt.has(e.permissionMode??"")}function Ln(t,e){let n="pathEnv"in t?t.pathEnv:process.env.PATH,r;return o=>t.host!=="claude-code"?R(o,t.cwd,n):(r??=bt(e.configDir),!R(o,t.cwd,n)&&!r.paths.some(s=>R(o,t.cwd,s))?!1:o.includes("/")||!St(o,r))}var jn=/^[^\s;&|<>()$`\\{}*?[\]~#!]+(?: [^\s;&|<>()$`\\{}*?[\]~#!]+)*$/;function Fn(t,e,n){return n.host!=="claude-code"||t==="unreadable"||Jt(t,n)||!zt.has(n.permissionMode??"")||!jn.test(e)||Ut.test(e.replace(/['"]/g,""))||(t.guards??[]).some(r=>r(e))?null:(t.trustedAllow??[]).find(r=>r.matches(e))?.rule??null}function Bt(t,e,n,r){if(!n||/["\\$`;&|<>(){}]|'\\''/.test(n))return null;let o=e.claudeDirs??q(),s=Nn(e.host,e.cwd,o),i=Fn(s,t,e),c=i||In(s,t,e.host)?ln(t,n,Ln(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}:Jt(s,e)?{command:c}:null}function A(t,e,n,r){return Bt(t,e,n,r)?.command??null}import{rmSync as Dn,statSync as Mn}from"node:fs";import{join as Un}from"node:path";function Wt(){return Un($(),"fail-open")}var zn=24*36e5;function y(t=Date.now()){try{if(t-Mn(Wt()).mtimeMs<zn)return!0;Dn(Wt(),{force:!0})}catch{}return!1}function p(t,e){let n=t[e];return typeof n=="string"&&n?n:null}function M(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Jn(t){return p(t,"prompt_id")||p(t,"scratchpad_dir")?!0:M(t.effort)}function Bn(t){return p(t,"tool_use_id")?.startsWith("toolu_")===!0||/^claude/i.test(p(t,"model")??"")}var Wn=new Set(["BeforeTool","AfterTool","BeforeAgent","AfterAgent","BeforeModel","AfterModel","BeforeToolSelection"]),Gn=new Set(["preToolUse","postToolUse","beforeShellExecution","afterShellExecution","beforeSubmitPrompt","sessionStart","sessionEnd","stop"]),Zn=new Set(["pre_tool","post_tool"]),Kn=new Set(["before_tool_call","after_tool_call"]),qn=new Set(["runTerminalCommand","run_in_terminal"]),Yn=[["codex",t=>p(t,"turn_id")!==null],["claude-code",Jn],["cursor",t=>p(t,"cursor_version")!==null||p(t,"generation_id")!==null||p(t,"conversation_id")!==null||Array.isArray(t.workspace_roots)||Gn.has(p(t,"hook_event_name")??"")],["gemini-cli",t=>Wn.has(p(t,"hook_event_name")??"")],["qwen-code",t=>t.hook_event_name==="PreToolUse"&&t.tool_name==="run_shell_command"],["vibe",t=>Zn.has(p(t,"hook_event_name")??"")],["antigravity",t=>M(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"||M(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&&!Kn.has(p(t,"event"))]],Vn=new Set(["codex","antigravity"]);function Xn(t){return M(t)?Yn.filter(([,e])=>e(t)).map(([e])=>e):[]}function Gt(t,e){if(!M(t))return null;let n=Xn(t);return n.length>1?null:n.length===1?n[0]:Bn(t)&&Vn.has(e)?"claude-code":e==="codex"?null:e}var ut=JSON.stringify({permission:"allow"});function Zt(t,e=S("cursor"),n=k){if(t.tool_name!=="Shell")return ut;let r=t.tool_input??{},o=r.command;if(typeof o!="string"||!o)return ut;let s=typeof r.working_directory=="string"?r.working_directory:void 0,i=A(o,{host:"cursor",sessionId:t.conversation_id??"unknown",cwd:s},y()?null:e,n);return i?JSON.stringify({permission:"allow",updated_input:{...r,command:i}}):ut}var Y="{}";function Kt(t,e=S("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=A(o,{host:"gemini-cli",sessionId:t.session_id??"unknown",cwd:s},y()?null:e,n);return i?JSON.stringify({hookSpecificOutput:{tool_input:{command:i}}}):Y}function C(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Io=String.raw`(?:'(?:(?:[^']|'\\'')*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?'|"(?:[^"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?"|(?:[^\s'"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?)`;function P(t,e,n="unknown",r=S(e),o=k){return t?A(t,{host:e,sessionId:n},y()?null:r,o):null}var tr=new Set(["bash","file_system.bash"]),lt=JSON.stringify({decision:"allow"});function qt(t,e=(n,r)=>P(n,"vibe",r)){if(!C(t)||t.hook_event_name!=="pre_tool"||typeof t.tool_name!="string"||!tr.has(t.tool_name))return"";let n=t.tool_input;if(!C(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 Yt(t,e=(n,r)=>P(n,"antigravity",r)){if(!C(t)||!C(t.toolCall)||t.toolCall.name!=="run_command")return lt;let n=t.toolCall.args;if(!C(n)||typeof n.CommandLine!="string"||!n.CommandLine)return lt;let r=e(n.CommandLine,typeof t.conversationId=="string"?t.conversationId:"unknown");return r?JSON.stringify({decision:"allow",overwrite:{CommandLine:r}}):lt}function H(t){return y()?null:S(t)}function er(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"?"":jt(e,t,H(t),r,n.claudeDirs??q(),n.pathEnv??process.env.PATH)??"";case"cursor":return Zt(e,H(t),r);case"gemini-cli":return Kt(e,H(t),r);case"vibe":return qt(e,(o,s)=>P(o,"vibe",s,H(t),r));case"antigravity":return Yt(e,(o,s)=>P(o,"antigravity",s,H(t),r));default:return Vt(t,e,H(t),r)}}function U(t,e,n={}){let r=Gt(t,e);return r?er(r,t,n):n.fallback??""}var m="{}",nr=new Set(["runTerminalCommand","run_in_terminal","Bash","bash"]),rr=["run_in_background","is_background","isBackground"];function z(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function or(t){let e=t.session_id??t.sessionId;return typeof e=="string"&&e?e:"unknown"}function sr(t,e){let n=t.cwd??e.cwd??e.workdir??e.working_directory;return typeof n=="string"&&n?n:void 0}function V(t,e,n,r,o){if(!z(e)||rr.some(i=>e[i]===!0))return null;let s=e.command;return typeof s!="string"||!s?null:A(s,{host:t,sessionId:or(n),cwd:sr(n,e)},y()?null:r,o)}function I(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...t,command:e}}})}function ir(t){if(z(t))return t;if(typeof t!="string")return null;try{let e=JSON.parse(t);return z(e)?e:null}catch{return null}}function cr(t,e,n){if(typeof t.tool_name=="string"){if(!nr.has(t.tool_name))return m;let s=t.tool_input,i=V("copilot",s,t,e,n);return i?I(s,i):m}if(t.toolName!=="bash")return m;let r=ir(t.toolArgs),o=V("copilot",r,t,e,n);return o?JSON.stringify({modifiedArgs:{...r,command:o}}):m}function N(t,e,n){return(r,o,s)=>{if(r.tool_name!==e)return m;let i=r.tool_input,c=V(t,i,r,o,s);return c?n(i,c):m}}var ur=new Set(["run_terminal_command","Bash","bash"]);function lr(t,e,n){let r=t.toolName??t.tool_name;if(typeof r!="string"||!ur.has(r))return m;let o=t.toolInput??t.tool_input,s=V("grok",o,t,e,n);return s?I(o,s):m}var ar={copilot:cr,droid:N("droid","Execute",I),trae:N("trae","RunCommand",I),"qwen-code":N("qwen-code","run_shell_command",I),crush:N("crush","bash",(t,e)=>JSON.stringify({updated_input:{command:e}})),junie:N("junie","Bash",(t,e)=>JSON.stringify({updatedInput:{...t,command:e}})),zcode:N("zcode","Bash",I),grok:lr};function Vt(t,e,n=S(t),r=k){return z(e)?ar[t](e,n,r):m}function fr(t,e){if(!e)return m;let n;try{n=JSON.parse(e.replace(/^/,""))}catch{return m}return z(n)?U(n,t,{fallback:m}):m}async function Xt(t){process.stdout.write(fr(t,await L()))}Xt("copilot").catch(t=>{process.stderr.write(`tkr-copilot-hook: ${t.message}
|
|
12
|
+
`}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=qe(t);for(;;){e.push(n);let r=Ct(n);if(r===n)return e;n=r}}function wn(){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 ot(f(t,"managed-settings.d")))n.endsWith(".json")&&e.push(f(t,"managed-settings.d",n))}catch{return e}return e}function D(t,e,n,r){let o=[];for(let s of t){let i=Sn(s,e);if(i!=="missing"&&(i==="unreadable"||!h(i)||!n(i,o)))return"unreadable"}return{matchers:o,complete:r}}function F(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 yn(t,e){let n=b=>[f(b,"settings.json"),f(b,"settings.local.json")],r=b=>n(f(b,".claude")),o=f(T(),".claude"),s=e.configDir||o,i=[[wn(),"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,X)=>{let $=b.permissions;if(d==="managed"&&(b.allowManagedPermissionRulesOnly===!0||h($)&&$.allowManagedPermissionRulesOnly===!0)&&(a=!0),$===void 0)return!0;if(!h($))return!1;for(let ft of["deny","ask","allow"]){let dt=F($[ft]);if(!dt)return!1;for(let pt of dt){let O=/^\s*Bash\s*(?:\(([\s\S]*)\))?\s*$/.exec(pt);if(O)if(ft!=="allow")X.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 mt=In(O[1]);mt&&u[d].push({rule:pt.trim(),matches:mt})}}}return!0},g=[];for(let[b,X]of i){d=X;let $=D(b,!1,x,!0);if($==="unreadable")return"unreadable";g.push(...$.matchers)}let k=l.managed||(l.loaded||l.loadedLocal)&&!a,y=[...u.managed,...a?[]:u.loaded];return{matchers:[...g,...k?[]:c],complete:!0,allow:c,allowsEverything:k,guards:g,trustedAllow:y}}function xn(t){let e=[f(T(),".cursor","cli-config.json"),...K(t).map(n=>f(n,".cursor","cli.json"))];return D(e,!0,(n,r)=>{let o=n.permissions;if(o===void 0)return!0;if(!h(o))return!1;let s=F(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 $n(){return process.platform==="darwin"?"/Library/Application Support/GeminiCli":process.platform==="win32"?"C:\\ProgramData\\gemini-cli":"/etc/gemini-cli"}var Mt=/^\s*(?:run_shell_command|ShellTool)\s*(?:\(([\s\S]*)\))?\s*$/;function An(t,e){let n=t.tools;if(n!==void 0&&!h(n))return!1;let r=[F(t.excludeTools),F(h(n)?n.exclude:void 0)];for(let o of r){if(!o)return!1;for(let s of o){let i=Mt.exec(s);i&&e.push(v(i[1]===void 0?"*":`${i[1]}*`))}}return!0}function Ot(t){try{return JSON.parse(t)}catch{return null}}function En(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]??Ot(`"${r[1]}"`);if(o===null)return null;n.push(o)}return n}if(e.startsWith('"')){let n=/^"((?:\\.|[^"\\])*)"/.exec(e);return n?Ot(`"${n[1]}"`):null}if(e.startsWith("'")){let n=/^'([^']*)'/.exec(e);return n?n[1]:null}return e.replace(/\s*#.*$/,"")}function vn(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=En(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==="*"||Mt.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}))||ut(l,a))}}return!0}function Rt(t){try{return ot(t).filter(e=>e.endsWith(".toml")).map(e=>f(t,e))}catch{return[]}}function On(t){let e=$n(),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(T(),".gemini","settings.json"),...K(t).map(o=>f(o,".gemini","settings.json"))].filter(o=>!!o),r=D(n,!0,An,!1);if(r==="unreadable")return r;for(let o of[...Rt(f(T(),".gemini","policies")),...Rt(f(e,"policies"))]){let s;try{s=rt(o,"utf8")}catch{return"unreadable"}if(!vn(s,r.matchers))return"unreadable"}return r}function nt(t,e){if(t===void 0)return!0;if(typeof t=="string")return t!=="allow"&&e.push(()=>!0),!0;if(!h(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(!h(r))return!1;for(let[o,s]of Object.entries(r))s!=="allow"&&e.push(v(o.replace(/\?/g,"*")))}}return!0}function Tt(t,e){if(t.permissions!==void 0||!nt(t.permission,e))return!1;for(let n of["agent","agents","mode"]){let r=t[n];if(r!==void 0){if(!h(r))return!1;for(let o of Object.values(r))if(h(o)&&(o.permissions!==void 0||!nt(o.permission,e)))return!1}}return!0}function Rn(t){for(let e of t)for(let n of["agent","agents","mode","modes"]){let r;try{r=ot(f(e,n))}catch{continue}for(let o of r)try{if(o.endsWith(".md")&&/permission/i.test(rt(f(e,n,o),"utf8")))return!0}catch{return!0}}return!1}function Tn(t){let e=f(process.env.XDG_CONFIG_HOME||f(T(),".config"),"opencode"),n=K(t),r=[e,...n.map(c=>f(c,".opencode"))];if(Rn(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=D(s,!0,Tt,!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(Dt(c))}catch{return"unreadable"}if(!(c===process.env.OPENCODE_PERMISSION?nt(u,i.matchers):h(u)&&Tt(u,i.matchers)))return"unreadable"}return i}function Cn(){return D([f(T(),".gemini","antigravity-cli","settings.json")],!0,(t,e)=>{let n=t.permissions;if(n===void 0)return!0;if(!h(n))return!1;for(let r of["deny","ask"]){let o=F(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=>ut(u,l))}}return!0},!1)}function h(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Ut(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pn(t){let e=t.trim().replace(/\s+/g," "),n=e.endsWith(" *")&&e.length>2,r=(n?e.slice(0,-2):e).split("*").map(Ut).join("[\\s\\S]*");return new RegExp(`^${r}${n?"(?: [\\s\\S]*)?":""}(?= |$)`)}var Hn=512;function Nn(t){let e=t.replace(/['"\\]/g,"").split(/[\s;&|(){}<>`$]+/).filter(Boolean);return[e,e.map(Z)]}function ut(t,e){if(t.test(e)||t.test(e.trim().replace(/\s+/g," ")))return!0;for(let n of Nn(e)){if(n.length>Hn)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=Pn(t);return n=>ut(e,n)}function In(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(`^${Ut(r)}${n?"(?: [\\s\\S]*)?":""}$`);return s=>o.test(s)}var Ln={"claude-code":yn,cursor:xn,"gemini-cli":On,opencode:Tn,antigravity:Cn},jn=new Set(["codex"]),Jt=/(?:^|[\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 Fn(t,e,n){let r=Ln[t];return r?r(e??process.cwd(),n):{matchers:[],complete:!1}}function Dn(t,e,n){return t==="unreadable"||Jt.test(e.replace(/['"\\]/g,""))||t.matchers.some(r=>r(e))?!1:t.complete||jt(e,!jn.has(n))}var zt=new Set(["default","acceptEdits","dontAsk"]);function Bt(t,e){return e.host!=="claude-code"||e.permissionMode==="bypassPermissions"?!0:t!=="unreadable"&&t.allowsEverything===!0&&zt.has(e.permissionMode??"")}function Mn(t,e){let n="pathEnv"in t?t.pathEnv:process.env.PATH,r;return o=>t.host!=="claude-code"?R(o,t.cwd,n):(r??=St(e.configDir),!R(o,t.cwd,n)&&!r.paths.some(s=>R(o,t.cwd,s))?!1:o.includes("/")||!wt(o,r))}var Un=/^[^\s;&|<>()$`\\{}*?[\]~#!]+(?: [^\s;&|<>()$`\\{}*?[\]~#!]+)*$/;function Jn(t,e,n){return n.host!=="claude-code"||t==="unreadable"||Bt(t,n)||!zt.has(n.permissionMode??"")||!Un.test(e)||Jt.test(e.replace(/['"]/g,""))||(t.guards??[]).some(r=>r(e))?null:(t.trustedAllow??[]).find(r=>r.matches(e))?.rule??null}function Wt(t,e,n,r){if(!n||/["\\$`;&|<>(){}]|'\\''/.test(n))return null;let o=e.claudeDirs??q(),s=Fn(e.host,e.cwd,o),i=Jn(s,t,e),c=i||Dn(s,t,e.host)?fn(t,n,Mn(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}:Bt(s,e)?{command:c}:null}function E(t,e,n,r){return Wt(t,e,n,r)?.command??null}import{rmSync as zn,statSync as Bn}from"node:fs";import{join as Wn}from"node:path";function Gt(){return Wn(A(),"fail-open")}var Gn=24*36e5;function w(t=Date.now()){try{if(t-Bn(Gt()).mtimeMs<Gn)return!0;zn(Gt(),{force:!0})}catch{}return!1}function p(t,e){let n=t[e];return typeof n=="string"&&n?n:null}function M(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Zn(t){return p(t,"prompt_id")||p(t,"scratchpad_dir")?!0:M(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=>M(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"||M(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 M(t)?tr.filter(([,e])=>e(t)).map(([e])=>e):[]}function Zt(t,e){if(!M(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 Kt(t,e=S("cursor"),n=_){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},w()?null:e,n);return i?JSON.stringify({permission:"allow",updated_input:{...r,command:i}}):lt}var Y="{}";function qt(t,e=S("gemini-cli"),n=_){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 C(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Mo=String.raw`(?:'(?:(?:[^']|'\\'')*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?'|"(?:[^"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?"|(?:[^\s'"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?)`;function P(t,e,n="unknown",r=S(e),o=_){return t?E(t,{host:e,sessionId:n},w()?null:r,o):null}var or=new Set(["bash","file_system.bash"]),at=JSON.stringify({decision:"allow"});function Yt(t,e=(n,r)=>P(n,"vibe",r)){if(!C(t)||t.hook_event_name!=="pre_tool"||typeof t.tool_name!="string"||!or.has(t.tool_name))return"";let n=t.tool_input;if(!C(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 Vt(t,e=(n,r)=>P(n,"antigravity",r)){if(!C(t)||!C(t.toolCall)||t.toolCall.name!=="run_command")return at;let n=t.toolCall.args;if(!C(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}function H(t){return w()?null:S(t)}function sr(t,e,n={}){let r=n.recordUsage??_;switch(t){case"claude-code":case"codex":return e.hook_event_name!==void 0&&e.hook_event_name!=="PreToolUse"?"":Ft(e,t,H(t),r,n.claudeDirs??q(),n.pathEnv??process.env.PATH,n.launchArgs??ct)??"";case"cursor":return Kt(e,H(t),r);case"gemini-cli":return qt(e,H(t),r);case"vibe":return Yt(e,(o,s)=>P(o,"vibe",s,H(t),r));case"antigravity":return Vt(e,(o,s)=>P(o,"antigravity",s,H(t),r));default:return Xt(t,e,H(t),r)}}function U(t,e,n={}){let r=Zt(t,e);return r?sr(r,t,n):n.fallback??""}var m="{}",ir=new Set(["runTerminalCommand","run_in_terminal","Bash","bash"]),cr=["run_in_background","is_background","isBackground"];function J(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function ur(t){let e=t.session_id??t.sessionId;return typeof e=="string"&&e?e:"unknown"}function lr(t,e){let n=t.cwd??e.cwd??e.workdir??e.working_directory;return typeof n=="string"&&n?n:void 0}function V(t,e,n,r,o){if(!J(e)||cr.some(i=>e[i]===!0))return null;let s=e.command;return typeof s!="string"||!s?null:E(s,{host:t,sessionId:ur(n),cwd:lr(n,e)},w()?null:r,o)}function I(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...t,command:e}}})}function ar(t){if(J(t))return t;if(typeof t!="string")return null;try{let e=JSON.parse(t);return J(e)?e:null}catch{return null}}function fr(t,e,n){if(typeof t.tool_name=="string"){if(!ir.has(t.tool_name))return m;let s=t.tool_input,i=V("copilot",s,t,e,n);return i?I(s,i):m}if(t.toolName!=="bash")return m;let r=ar(t.toolArgs),o=V("copilot",r,t,e,n);return o?JSON.stringify({modifiedArgs:{...r,command:o}}):m}function N(t,e,n){return(r,o,s)=>{if(r.tool_name!==e)return m;let i=r.tool_input,c=V(t,i,r,o,s);return c?n(i,c):m}}var dr=new Set(["run_terminal_command","Bash","bash"]);function pr(t,e,n){let r=t.toolName??t.tool_name;if(typeof r!="string"||!dr.has(r))return m;let o=t.toolInput??t.tool_input,s=V("grok",o,t,e,n);return s?I(o,s):m}var mr={copilot:fr,droid:N("droid","Execute",I),trae:N("trae","RunCommand",I),"qwen-code":N("qwen-code","run_shell_command",I),crush:N("crush","bash",(t,e)=>JSON.stringify({updated_input:{command:e}})),junie:N("junie","Bash",(t,e)=>JSON.stringify({updatedInput:{...t,command:e}})),zcode:N("zcode","Bash",I),grok:pr};function Xt(t,e,n=S(t),r=_){return J(e)?mr[t](e,n,r):m}function gr(t,e){if(!e)return m;let n;try{n=JSON.parse(e.replace(/^/,""))}catch{return m}return J(n)?U(n,t,{fallback:m}):m}async function Qt(t){process.stdout.write(gr(t,await L()))}Qt("copilot").catch(t=>{process.stderr.write(`tkr-copilot-hook: ${t.message}
|
|
13
13
|
`),process.stdout.write(m),process.exit(0)});
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __tkrCreateRequire } from "node:module"; const require = __tkrCreateRequire(import.meta.url);
|
|
3
|
-
function L(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{appendFileSync as
|
|
4
|
-
`).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}`;
|
|
3
|
+
function L(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{appendFileSync as ie,chmodSync as ce,mkdirSync as ue,existsSync as le,readFileSync as xr,rmSync as $r}from"node:fs";import{dirname as ae,join as fe}from"node:path";import te from"node:os";import{join as ee}from"node:path";function A(){return process.env.TOKMIZER_HOME||ee(te.homedir(),".tokmizer")}import{readFileSync as ne,renameSync as re,statSync as oe,writeFileSync as se}from"node:fs";function gt(t,e,n){try{if(oe(t).size<=e)return;let r=ne(t,"utf8").split(`
|
|
4
|
+
`).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}`;se(i,o.length?`${o.join(`
|
|
5
5
|
`)}
|
|
6
|
-
`:"",{mode:384}),
|
|
7
|
-
`,{mode:384}),
|
|
8
|
-
`)){let o=
|
|
9
|
-
`,1)[0].slice(2).trim().split(/\s+/),o=r[0]??"";return o==="/usr/bin/env"?R(r[1]??"",void 0,e):j(o)}catch{return!1}}function
|
|
10
|
-
`||c==="|"){i(c,1);continue}}r+=c,o+=1}return s(),n}function
|
|
6
|
+
`:"",{mode:384}),re(i,t)}catch{}}var de="usage.jsonl";var ht=2*1024*1024;function pe(){return fe(A(),de)}function _(t,e,n=pe()){try{let r=ae(n);le(r)||ue(r,{recursive:!0,mode:448});let o=t.replace(/[^A-Za-z0-9._-]/g,"").slice(0,64)||"unknown";ie(n,`{"t":${Math.floor(Date.now()/1e3)},"s":"${o}","o":${e?1:0}}
|
|
7
|
+
`,{mode:384}),ce(n,384),gt(n,ht,ht/2)}catch{}}import{spawnSync as Ze}from"node:child_process";import{existsSync as G,readFileSync as rt,readdirSync as ot}from"node:fs";import{homedir as T}from"node:os";import{fileURLToPath as Ke}from"node:url";import{dirname as Ct,join as f,resolve as qe}from"node:path";function z(){return!1}import{execFileSync as Ne}from"node:child_process";import{mkdirSync as Ie,readFileSync as yt,renameSync as Le,statSync as je,writeFileSync as Fe}from"node:fs";import{join as xt}from"node:path";import{closeSync as me,openSync as ge,readSync as he,readdirSync as ke,readFileSync as _e,statSync as bt}from"node:fs";import{homedir as be}from"node:os";import{isAbsolute as Se,join as B,resolve as we}from"node:path";var ye=/^[A-Za-z0-9._+@%:,/-]+$/,xe=new Set(["7f454c46","feedface","feedfacf","cefaedfe","cffaedfe","cafebabe","bebafeca"]),$e=32,Ae=4*1024*1024;function tt(t){let e;try{e=ge(t,"r");let n=Buffer.alloc(4),r=he(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&&me(e)}}function j(t,e=process.platform){try{let n=bt(t);if(!n.isFile())return!1;if(e==="win32")return!0;if((n.mode&73)===0)return!1;let r=tt(t);return r==="#!"||r!==null&&xe.has(r)}catch{return!1}}function Ee(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 R(t,e,n,r=process.platform){if(!ye.test(t))return!1;let o=r==="win32";if(t.includes("/"))return j(we(e??process.cwd(),t),r);if(!n)return!1;let s=o?Ee(t):[t];for(let i of n.split(o?";":":"))if(!(!i||!Se(i))){for(let c of s)if(j(B(i,c),r))return!0}return!1}var ve=/^eval \$'([^\s'()=]+) \(\) /,Oe=/^([^\s'"()=]+) \(\) \{$/,Re=/^alias -- ([^\s=]+)=(.*)$/,Te=/^# (?:Shell Options|Aliases|Shopt|Check for |Shadow )/,Ce=/^export PATH=(.*)$/,Pe=/^(?:--colou?r(?:=\S+)?|-G)$/;function _t(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 He(t,e){let n="";for(let r of t.split(`
|
|
8
|
+
`)){let o=Ce.exec(r);if(o&&n!=="# Functions"){let s=_t(o[1].trim());/[$`\\]/.test(s)||e.paths.push(s);continue}if(r.startsWith("# ")&&(n!=="# Functions"||Te.test(r))){n=r;continue}if(n==="# Functions"){let s=ve.exec(r)??Oe.exec(r);s&&e.functions.add(s[1])}else if(n==="# Aliases"){let s=Re.exec(r);s&&e.aliases.set(s[1],_t(s[2].trim()))}}}function Q(t){return t?.code==="ENOENT"}function St(t){let e={functions:new Set,aliases:new Map,paths:[],uncertain:!1},n=B(t||B(be(),".claude"),"shell-snapshots"),r=[];try{for(let o of ke(n)){if(!o.startsWith("snapshot-")||!o.endsWith(".sh"))continue;let s=B(n,o);try{let i=bt(s);i.isFile()&&r.push({path:s,mtime:i.mtimeMs,size:i.size})}catch(i){Q(i)||(e.uncertain=!0)}}}catch(o){return Q(o)||(e.uncertain=!0),e}r=r.sort((o,s)=>s.mtime-o.mtime).slice(0,$e);for(let o of r)try{if(o.size>Ae)throw new Error("snapshot too large");He(_e(o.path,"utf8"),e)}catch(s){Q(s)||(e.uncertain=!0)}return e}function wt(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=>Pe.test(o))}var De="exec-probe.json",Me=6e4;function Ue(){return xt(A(),De)}function Je(t){try{let e=JSON.parse(yt(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 ze(t,e){try{Ie(xt(t,".."),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;Fe(n,JSON.stringify(e),{mode:384}),Le(n,t)}catch{}}function Be(t){try{return Ne(t,["--native-check"],{encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"],windowsHide:!0}).startsWith("tokmizer-native ")}catch{return!1}}function We(t,e){try{let r=yt(t,"utf8").split(`
|
|
9
|
+
`,1)[0].slice(2).trim().split(/\s+/),o=r[0]??"";return o==="/usr/bin/env"?R(r[1]??"",void 0,e):j(o)}catch{return!1}}function Ge(t,e,n){try{let r=je(t);return[t,r.size,r.mtimeMs,r.ino,r.mode,e?n??"":""].join("|")}catch{return`${t}|missing`}}function et(t,e=process.platform,n=process.env.PATH,r=Ue(),o=Date.now()){let s=e!=="win32"&&tt(t)==="#!",i=Ge(t,s,n),c=Je(r);if(c?.key===i&&(c.ok||o-c.at<Me))return c.ok;let u=j(t,e)&&(s?We(t,n):Be(t));return ze(r,{key:i,ok:u,at:o,skipped:(c?.skipped??0)+(u?0:1)}),u}var Ye=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"]),Ve=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"]),$t=new Set(["sh","bash","zsh","dash","ksh","fish","python","python3","python2","node","ruby","perl","php","awk","sed","deno","bun"]),At="(?:dev|start|serve|watch|preview)",Xe=new RegExp(`^(?:\\S*/)?(?:bun\\s+(?:install|i|add|remove|rm|update|outdated|audit|test|build|pm|x)(?:\\s|$)|bun\\s+run\\s+(?!${At}(?:\\s|$))[A-Za-z0-9:_-]+(?:\\s|$)|deno\\s+(?:test|lint|fmt|check|compile|install|info|doc|bench|outdated)(?:\\s|$)|deno\\s+task\\s+(?!${At}(?:\\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)`),Qe=/(?:^|\s)--watch(?:\s|=|$)/;function tn(t){return Xe.test(t)&&!Qe.test(t)}var en=/^((?:\S*\/)?(sh|bash|zsh|dash|ksh|fish)\s+(-[elux]*c[elux]*)\s+)(['"])/,nn=/[()$]|(?:^|[;&|\n]\s*)(?:and|or|not|begin|end|if|else|switch|case|while|for|function|return)(?:\s|;|$)/,Pt=3;function Ht(t){let e=en.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&&nn.test(c)?null:{script:c,start:o,end:s,quote:r}}var rn=new Set(["cd","export","set","unset","source",".","true",":","pushd","popd"]);function on(t){return it(t).filter(n=>{if(n.kind!=="cmd"||n.unsafe)return!1;let r=It(n.text);return r!==""&&!rn.has(r)&&!st.test(r)}).length>1}function sn(t,e,n,r,o){if(n>=Pt)return null;let s=Ht(t);if(!s)return null;let{script:i,start:c,end:u,quote:l}=s,a=[],d=Lt(i,e,n+1,r,y=>a.push(y));if(d===i||l==='"'&&/["$`]/.test(d))return null;let x=l==="'"?d.replace(/'/g,"'\\''"):d,g=`${t.slice(0,c)}${x}${t.slice(u)}`,k=on(i);if(o)for(let y of k?[t,...a]:a)o(y);return k?`${e} ${g}`:g}var Et=/(?:^|\s)(?:--follow|-[0-9a-zA-Z]*f[a-zA-Z]*)(?:\s|=|$)/,cn=new Set(["docker","podman","kubectl","nerdctl","docker-compose","stern","flyctl"]);function un(t,e){let n=Z(e);return n==="tail"||n==="journalctl"?Et.test(t):n==="stern"?!0:cn.has(n)?/\blogs?\b/.test(t)&&Et.test(t):!1}var st=/^[A-Za-z_][A-Za-z0-9_]*\+?=/,ln=/^[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/,an=/(?:^|[;&|\n({])\s*[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/;function Z(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Nt(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 vt(t){let e=Nt(t);if(!e)return!0;for(let n=0;n<t.length;n++)if(e[n]&&t[n]===">")return!0;return!1}function it(t){let e=Nt(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===`
|
|
10
|
+
`||c==="|"){i(c,1);continue}}r+=c,o+=1}return s(),n}function It(t){return t.trim().split(/\s+/)[0]??""}function S(t,e=process.platform){try{let n=Ct(Ke(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(G(c))return et(c,e)?`'${c.replace(/\\/g,"/").replace(/'/g,"'\\''")}'`:null}let s=f(n,"..","bin","tkr-exec");if(!r&&G(s))return et(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 G(i)?`${o}node '${i.replace(/'/g,"'\\''")}'`:null}catch{return null}}function fn(t,e="tkr-exec",n=()=>!0,r){return Lt(t,e,0,n,r)}function Lt(t,e,n,r,o){if(t.includes("<<")||an.test(t))return t;let s=it(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=It(l),d=s[c+1],x=d?.kind==="sep"&&(d.text==="|"||d.text==="|&"),g=d?.kind==="sep"&&d.text==="&",k=!x&&!g&&!vt(u.text)&&!u.text.includes("<(")&&!u.text.includes(">(")?sn(l,e,n,r,o):null;if(k!==null){i.push(`${u.text.match(/^\s*/)?.[0]??""}${k}${u.text.match(/\s*$/)?.[0]??""}`);continue}if(l===e||l.startsWith(e)&&/^\s/.test(l.slice(e.length))||Ye.has(a)||Ve.has(a)||($t.has(a)||$t.has(Z(a)))&&!tn(l)||st.test(a)||a.startsWith("(")||a.startsWith("#")||a.startsWith("<")||a.startsWith(">")||ln.test(l)||un(l,a)||a.endsWith(")")||x||g||vt(u.text)||u.text.includes("<(")||u.text.includes(">(")||a==="node"&&l.includes("tkr-exec.js")||!r(a)){i.push(u.text);continue}let y=u.text.match(/^\s*/)?.[0]??"",b=u.text.match(/\s*$/)?.[0]??"";o?.(l),i.push(`${y}${e} ${l}${b}`)}return i.join("")}var dn=new Set(["command","workdir","timeout_ms","yield_time_ms","max_output_tokens","shell","login","tty","description"]),pn=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"]),mn=new Set(["log","diff","show","status","blame","ls-files","rev-parse","describe","shortlog"]),gn={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/},W=["test","run test","run build","run lint","run typecheck"],hn={npm:new Set(W),pnpm:new Set([...W,"build","lint","typecheck"]),yarn:new Set([...W,"build","lint","typecheck"]),bun:new Set(W),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"])},kn=new Set(["pytest","tsc","vitest","jest","eslint","mypy"]);function jt(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 it(t)){if(r.kind==="sep")continue;if(r.unsafe)return!1;let o=n<Pt?Ht(r.text.trim()):null;if(o){if(!jt(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=>st.test(l)))return!1;let i=Z(s[0]);if(i!==s[0])return!1;let c=gn[i];if(c&&s.slice(1).some(l=>c.test(l)))return!1;if((i==="git"?mn.has(s[1]??""):pn.has(i))||e&&kn.has(i))continue;let u=e?hn[i]:void 0;if(!(u&&(u.has(s[1]??"")||s[1]==="run"&&u.has(`run ${s[2]??""}`))))return!1}return!0}function Ft(t,e,n=S(e),r=_,o=q(),s=process.env.PATH,i=ct){if(!h(t)||t.tool_name!=="Bash"||e==="claude-code"&&bn(i()))return null;let c=t.tool_input;if(!h(c)||c.run_in_background)return null;let u=c.command;if(typeof u!="string"||!u||e==="codex"&&Object.keys(c).some(y=>!dn.has(y)))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,g=Wt(u,{host:e,sessionId:d,cwd:a,claudeDirs:o,pathEnv:s,permissionMode:x},n,r);if(!g)return null;let k={...c,command:g.command};return JSON.stringify({hookSpecificOutput:e==="codex"?{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:k}:g.allowedBy?{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`Tokmizer: allowed by your rule ${g.allowedBy}`,updatedInput:k}:{hookEventName:"PreToolUse",updatedInput:k}})}var _n=/(?:^|\s)--(?:disallowedTools|disallowed-tools|settings|setting-sources)(?:[=\s]|$)/;function ct(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=Ze("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 bn(t){return t===null||_n.test(t)}function Sn(t,e){if(!G(t))return"missing";try{let n=rt(t,"utf8");return JSON.parse(e?Dt(n):n)}catch{return"unreadable"}}function Dt(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]!==`
|
|
11
11
|
`;)r++;e+=`
|
|
12
|
-
`}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=Ze(t);for(;;){e.push(n);let r=Tt(n);if(r===n)return e;n=r}}function kn(){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 ot(f(t,"managed-settings.d")))n.endsWith(".json")&&e.push(f(t,"managed-settings.d",n))}catch{return e}return e}function D(t,e,n,r){let o=[];for(let s of t){let i=hn(s,e);if(i!=="missing"&&(i==="unreadable"||!g(i)||!n(i,o)))return"unreadable"}return{matchers:o,complete:r}}function F(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 _n(t,e){let n=b=>[f(b,"settings.json"),f(b,"settings.local.json")],r=b=>n(f(b,".claude")),o=f(T(),".claude"),s=e.configDir||o,i=[[kn(),"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,X)=>{let x=b.permissions;if(d==="managed"&&(b.allowManagedPermissionRulesOnly===!0||g(x)&&x.allowManagedPermissionRulesOnly===!0)&&(a=!0),x===void 0)return!0;if(!g(x))return!1;for(let at of["deny","ask","allow"]){let ft=F(x[at]);if(!ft)return!1;for(let dt of ft){let v=/^\s*Bash\s*(?:\(([\s\S]*)\))?\s*$/.exec(dt);if(v)if(at!=="allow")X.push(O((v[1]??"*").replace(/:\*$/," *")));else if(v[1]===void 0||v[1].trim()==="*")l[d]=!0;else{c.push(O(v[1].replace(/:\*$/," *")));let pt=Cn(v[1]);pt&&u[d].push({rule:dt.trim(),matches:pt})}}}return!0},h=[];for(let[b,X]of i){d=X;let x=D(b,!1,_,!0);if(x==="unreadable")return"unreadable";h.push(...x.matchers)}let w=l.managed||(l.loaded||l.loadedLocal)&&!a,E=[...u.managed,...a?[]:u.loaded];return{matchers:[...h,...w?[]:c],complete:!0,allow:c,allowsEverything:w,guards:h,trustedAllow:E}}function bn(t){let e=[f(T(),".cursor","cli-config.json"),...K(t).map(n=>f(n,".cursor","cli.json"))];return D(e,!0,(n,r)=>{let o=n.permissions;if(o===void 0)return!0;if(!g(o))return!1;let s=F(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 Sn(){return process.platform==="darwin"?"/Library/Application Support/GeminiCli":process.platform==="win32"?"C:\\ProgramData\\gemini-cli":"/etc/gemini-cli"}var Dt=/^\s*(?:run_shell_command|ShellTool)\s*(?:\(([\s\S]*)\))?\s*$/;function wn(t,e){let n=t.tools;if(n!==void 0&&!g(n))return!1;let r=[F(t.excludeTools),F(g(n)?n.exclude:void 0)];for(let o of r){if(!o)return!1;for(let s of o){let i=Dt.exec(s);i&&e.push(O(i[1]===void 0?"*":`${i[1]}*`))}}return!0}function Ot(t){try{return JSON.parse(t)}catch{return null}}function yn(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]??Ot(`"${r[1]}"`);if(o===null)return null;n.push(o)}return n}if(e.startsWith('"')){let n=/^"((?:\\.|[^"\\])*)"/.exec(e);return n?Ot(`"${n[1]}"`):null}if(e.startsWith("'")){let n=/^'([^']*)'/.exec(e);return n?n[1]:null}return e.replace(/\s*#.*$/,"")}function xn(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=yn(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==="*"||Dt.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}))||ct(l,a))}}return!0}function vt(t){try{return ot(t).filter(e=>e.endsWith(".toml")).map(e=>f(t,e))}catch{return[]}}function $n(t){let e=Sn(),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(T(),".gemini","settings.json"),...K(t).map(o=>f(o,".gemini","settings.json"))].filter(o=>!!o),r=D(n,!0,wn,!1);if(r==="unreadable")return r;for(let o of[...vt(f(T(),".gemini","policies")),...vt(f(e,"policies"))]){let s;try{s=rt(o,"utf8")}catch{return"unreadable"}if(!xn(s,r.matchers))return"unreadable"}return r}function nt(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(O(o.replace(/\?/g,"*")))}}return!0}function Rt(t,e){if(t.permissions!==void 0||!nt(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||!nt(o.permission,e)))return!1}}return!0}function An(t){for(let e of t)for(let n of["agent","agents","mode","modes"]){let r;try{r=ot(f(e,n))}catch{continue}for(let o of r)try{if(o.endsWith(".md")&&/permission/i.test(rt(f(e,n,o),"utf8")))return!0}catch{return!0}}return!1}function En(t){let e=f(process.env.XDG_CONFIG_HOME||f(T(),".config"),"opencode"),n=K(t),r=[e,...n.map(c=>f(c,".opencode"))];if(An(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=D(s,!0,Rt,!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(Ft(c))}catch{return"unreadable"}if(!(c===process.env.OPENCODE_PERMISSION?nt(u,i.matchers):g(u)&&Rt(u,i.matchers)))return"unreadable"}return i}function On(){return D([f(T(),".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=F(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=>ct(u,l))}}return!0},!1)}function g(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Mt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vn(t){let e=t.trim().replace(/\s+/g," "),n=e.endsWith(" *")&&e.length>2,r=(n?e.slice(0,-2):e).split("*").map(Mt).join("[\\s\\S]*");return new RegExp(`^${r}${n?"(?: [\\s\\S]*)?":""}(?= |$)`)}var Rn=512;function Tn(t){let e=t.replace(/['"\\]/g,"").split(/[\s;&|(){}<>`$]+/).filter(Boolean);return[e,e.map(Z)]}function ct(t,e){if(t.test(e)||t.test(e.trim().replace(/\s+/g," ")))return!0;for(let n of Tn(e)){if(n.length>Rn)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=vn(t);return n=>ct(e,n)}function Cn(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(`^${Mt(r)}${n?"(?: [\\s\\S]*)?":""}$`);return s=>o.test(s)}var Pn={"claude-code":_n,cursor:bn,"gemini-cli":$n,opencode:En,antigravity:On},Hn=new Set(["codex"]),Ut=/(?:^|[\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 Nn(t,e,n){let r=Pn[t];return r?r(e??process.cwd(),n):{matchers:[],complete:!1}}function In(t,e,n){return t==="unreadable"||Ut.test(e.replace(/['"\\]/g,""))||t.matchers.some(r=>r(e))?!1:t.complete||Lt(e,!Hn.has(n))}var zt=new Set(["default","acceptEdits","dontAsk"]);function Jt(t,e){return e.host!=="claude-code"||e.permissionMode==="bypassPermissions"?!0:t!=="unreadable"&&t.allowsEverything===!0&&zt.has(e.permissionMode??"")}function Ln(t,e){let n="pathEnv"in t?t.pathEnv:process.env.PATH,r;return o=>t.host!=="claude-code"?R(o,t.cwd,n):(r??=bt(e.configDir),!R(o,t.cwd,n)&&!r.paths.some(s=>R(o,t.cwd,s))?!1:o.includes("/")||!St(o,r))}var jn=/^[^\s;&|<>()$`\\{}*?[\]~#!]+(?: [^\s;&|<>()$`\\{}*?[\]~#!]+)*$/;function Fn(t,e,n){return n.host!=="claude-code"||t==="unreadable"||Jt(t,n)||!zt.has(n.permissionMode??"")||!jn.test(e)||Ut.test(e.replace(/['"]/g,""))||(t.guards??[]).some(r=>r(e))?null:(t.trustedAllow??[]).find(r=>r.matches(e))?.rule??null}function Bt(t,e,n,r){if(!n||/["\\$`;&|<>(){}]|'\\''/.test(n))return null;let o=e.claudeDirs??q(),s=Nn(e.host,e.cwd,o),i=Fn(s,t,e),c=i||In(s,t,e.host)?ln(t,n,Ln(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}:Jt(s,e)?{command:c}:null}function A(t,e,n,r){return Bt(t,e,n,r)?.command??null}import{rmSync as Dn,statSync as Mn}from"node:fs";import{join as Un}from"node:path";function Wt(){return Un($(),"fail-open")}var zn=24*36e5;function y(t=Date.now()){try{if(t-Mn(Wt()).mtimeMs<zn)return!0;Dn(Wt(),{force:!0})}catch{}return!1}function p(t,e){let n=t[e];return typeof n=="string"&&n?n:null}function M(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Jn(t){return p(t,"prompt_id")||p(t,"scratchpad_dir")?!0:M(t.effort)}function Bn(t){return p(t,"tool_use_id")?.startsWith("toolu_")===!0||/^claude/i.test(p(t,"model")??"")}var Wn=new Set(["BeforeTool","AfterTool","BeforeAgent","AfterAgent","BeforeModel","AfterModel","BeforeToolSelection"]),Gn=new Set(["preToolUse","postToolUse","beforeShellExecution","afterShellExecution","beforeSubmitPrompt","sessionStart","sessionEnd","stop"]),Zn=new Set(["pre_tool","post_tool"]),Kn=new Set(["before_tool_call","after_tool_call"]),qn=new Set(["runTerminalCommand","run_in_terminal"]),Yn=[["codex",t=>p(t,"turn_id")!==null],["claude-code",Jn],["cursor",t=>p(t,"cursor_version")!==null||p(t,"generation_id")!==null||p(t,"conversation_id")!==null||Array.isArray(t.workspace_roots)||Gn.has(p(t,"hook_event_name")??"")],["gemini-cli",t=>Wn.has(p(t,"hook_event_name")??"")],["qwen-code",t=>t.hook_event_name==="PreToolUse"&&t.tool_name==="run_shell_command"],["vibe",t=>Zn.has(p(t,"hook_event_name")??"")],["antigravity",t=>M(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"||M(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&&!Kn.has(p(t,"event"))]],Vn=new Set(["codex","antigravity"]);function Xn(t){return M(t)?Yn.filter(([,e])=>e(t)).map(([e])=>e):[]}function Gt(t,e){if(!M(t))return null;let n=Xn(t);return n.length>1?null:n.length===1?n[0]:Bn(t)&&Vn.has(e)?"claude-code":e==="codex"?null:e}var ut=JSON.stringify({permission:"allow"});function Zt(t,e=S("cursor"),n=k){if(t.tool_name!=="Shell")return ut;let r=t.tool_input??{},o=r.command;if(typeof o!="string"||!o)return ut;let s=typeof r.working_directory=="string"?r.working_directory:void 0,i=A(o,{host:"cursor",sessionId:t.conversation_id??"unknown",cwd:s},y()?null:e,n);return i?JSON.stringify({permission:"allow",updated_input:{...r,command:i}}):ut}var Y="{}";function Kt(t,e=S("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=A(o,{host:"gemini-cli",sessionId:t.session_id??"unknown",cwd:s},y()?null:e,n);return i?JSON.stringify({hookSpecificOutput:{tool_input:{command:i}}}):Y}function C(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Io=String.raw`(?:'(?:(?:[^']|'\\'')*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?'|"(?:[^"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?"|(?:[^\s'"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?)`;function P(t,e,n="unknown",r=S(e),o=k){return t?A(t,{host:e,sessionId:n},y()?null:r,o):null}var tr=new Set(["bash","file_system.bash"]),lt=JSON.stringify({decision:"allow"});function qt(t,e=(n,r)=>P(n,"vibe",r)){if(!C(t)||t.hook_event_name!=="pre_tool"||typeof t.tool_name!="string"||!tr.has(t.tool_name))return"";let n=t.tool_input;if(!C(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 Yt(t,e=(n,r)=>P(n,"antigravity",r)){if(!C(t)||!C(t.toolCall)||t.toolCall.name!=="run_command")return lt;let n=t.toolCall.args;if(!C(n)||typeof n.CommandLine!="string"||!n.CommandLine)return lt;let r=e(n.CommandLine,typeof t.conversationId=="string"?t.conversationId:"unknown");return r?JSON.stringify({decision:"allow",overwrite:{CommandLine:r}}):lt}function H(t){return y()?null:S(t)}function er(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"?"":jt(e,t,H(t),r,n.claudeDirs??q(),n.pathEnv??process.env.PATH)??"";case"cursor":return Zt(e,H(t),r);case"gemini-cli":return Kt(e,H(t),r);case"vibe":return qt(e,(o,s)=>P(o,"vibe",s,H(t),r));case"antigravity":return Yt(e,(o,s)=>P(o,"antigravity",s,H(t),r));default:return Vt(t,e,H(t),r)}}function U(t,e,n={}){let r=Gt(t,e);return r?er(r,t,n):n.fallback??""}var m="{}",nr=new Set(["runTerminalCommand","run_in_terminal","Bash","bash"]),rr=["run_in_background","is_background","isBackground"];function z(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function or(t){let e=t.session_id??t.sessionId;return typeof e=="string"&&e?e:"unknown"}function sr(t,e){let n=t.cwd??e.cwd??e.workdir??e.working_directory;return typeof n=="string"&&n?n:void 0}function V(t,e,n,r,o){if(!z(e)||rr.some(i=>e[i]===!0))return null;let s=e.command;return typeof s!="string"||!s?null:A(s,{host:t,sessionId:or(n),cwd:sr(n,e)},y()?null:r,o)}function I(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...t,command:e}}})}function ir(t){if(z(t))return t;if(typeof t!="string")return null;try{let e=JSON.parse(t);return z(e)?e:null}catch{return null}}function cr(t,e,n){if(typeof t.tool_name=="string"){if(!nr.has(t.tool_name))return m;let s=t.tool_input,i=V("copilot",s,t,e,n);return i?I(s,i):m}if(t.toolName!=="bash")return m;let r=ir(t.toolArgs),o=V("copilot",r,t,e,n);return o?JSON.stringify({modifiedArgs:{...r,command:o}}):m}function N(t,e,n){return(r,o,s)=>{if(r.tool_name!==e)return m;let i=r.tool_input,c=V(t,i,r,o,s);return c?n(i,c):m}}var ur=new Set(["run_terminal_command","Bash","bash"]);function lr(t,e,n){let r=t.toolName??t.tool_name;if(typeof r!="string"||!ur.has(r))return m;let o=t.toolInput??t.tool_input,s=V("grok",o,t,e,n);return s?I(o,s):m}var ar={copilot:cr,droid:N("droid","Execute",I),trae:N("trae","RunCommand",I),"qwen-code":N("qwen-code","run_shell_command",I),crush:N("crush","bash",(t,e)=>JSON.stringify({updated_input:{command:e}})),junie:N("junie","Bash",(t,e)=>JSON.stringify({updatedInput:{...t,command:e}})),zcode:N("zcode","Bash",I),grok:lr};function Vt(t,e,n=S(t),r=k){return z(e)?ar[t](e,n,r):m}function fr(t,e){if(!e)return m;let n;try{n=JSON.parse(e.replace(/^/,""))}catch{return m}return z(n)?U(n,t,{fallback:m}):m}async function Xt(t){process.stdout.write(fr(t,await L()))}Xt("crush").catch(t=>{process.stderr.write(`tkr-crush-hook: ${t.message}
|
|
12
|
+
`}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=qe(t);for(;;){e.push(n);let r=Ct(n);if(r===n)return e;n=r}}function wn(){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 ot(f(t,"managed-settings.d")))n.endsWith(".json")&&e.push(f(t,"managed-settings.d",n))}catch{return e}return e}function D(t,e,n,r){let o=[];for(let s of t){let i=Sn(s,e);if(i!=="missing"&&(i==="unreadable"||!h(i)||!n(i,o)))return"unreadable"}return{matchers:o,complete:r}}function F(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 yn(t,e){let n=b=>[f(b,"settings.json"),f(b,"settings.local.json")],r=b=>n(f(b,".claude")),o=f(T(),".claude"),s=e.configDir||o,i=[[wn(),"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,X)=>{let $=b.permissions;if(d==="managed"&&(b.allowManagedPermissionRulesOnly===!0||h($)&&$.allowManagedPermissionRulesOnly===!0)&&(a=!0),$===void 0)return!0;if(!h($))return!1;for(let ft of["deny","ask","allow"]){let dt=F($[ft]);if(!dt)return!1;for(let pt of dt){let O=/^\s*Bash\s*(?:\(([\s\S]*)\))?\s*$/.exec(pt);if(O)if(ft!=="allow")X.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 mt=In(O[1]);mt&&u[d].push({rule:pt.trim(),matches:mt})}}}return!0},g=[];for(let[b,X]of i){d=X;let $=D(b,!1,x,!0);if($==="unreadable")return"unreadable";g.push(...$.matchers)}let k=l.managed||(l.loaded||l.loadedLocal)&&!a,y=[...u.managed,...a?[]:u.loaded];return{matchers:[...g,...k?[]:c],complete:!0,allow:c,allowsEverything:k,guards:g,trustedAllow:y}}function xn(t){let e=[f(T(),".cursor","cli-config.json"),...K(t).map(n=>f(n,".cursor","cli.json"))];return D(e,!0,(n,r)=>{let o=n.permissions;if(o===void 0)return!0;if(!h(o))return!1;let s=F(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 $n(){return process.platform==="darwin"?"/Library/Application Support/GeminiCli":process.platform==="win32"?"C:\\ProgramData\\gemini-cli":"/etc/gemini-cli"}var Mt=/^\s*(?:run_shell_command|ShellTool)\s*(?:\(([\s\S]*)\))?\s*$/;function An(t,e){let n=t.tools;if(n!==void 0&&!h(n))return!1;let r=[F(t.excludeTools),F(h(n)?n.exclude:void 0)];for(let o of r){if(!o)return!1;for(let s of o){let i=Mt.exec(s);i&&e.push(v(i[1]===void 0?"*":`${i[1]}*`))}}return!0}function Ot(t){try{return JSON.parse(t)}catch{return null}}function En(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]??Ot(`"${r[1]}"`);if(o===null)return null;n.push(o)}return n}if(e.startsWith('"')){let n=/^"((?:\\.|[^"\\])*)"/.exec(e);return n?Ot(`"${n[1]}"`):null}if(e.startsWith("'")){let n=/^'([^']*)'/.exec(e);return n?n[1]:null}return e.replace(/\s*#.*$/,"")}function vn(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=En(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==="*"||Mt.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}))||ut(l,a))}}return!0}function Rt(t){try{return ot(t).filter(e=>e.endsWith(".toml")).map(e=>f(t,e))}catch{return[]}}function On(t){let e=$n(),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(T(),".gemini","settings.json"),...K(t).map(o=>f(o,".gemini","settings.json"))].filter(o=>!!o),r=D(n,!0,An,!1);if(r==="unreadable")return r;for(let o of[...Rt(f(T(),".gemini","policies")),...Rt(f(e,"policies"))]){let s;try{s=rt(o,"utf8")}catch{return"unreadable"}if(!vn(s,r.matchers))return"unreadable"}return r}function nt(t,e){if(t===void 0)return!0;if(typeof t=="string")return t!=="allow"&&e.push(()=>!0),!0;if(!h(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(!h(r))return!1;for(let[o,s]of Object.entries(r))s!=="allow"&&e.push(v(o.replace(/\?/g,"*")))}}return!0}function Tt(t,e){if(t.permissions!==void 0||!nt(t.permission,e))return!1;for(let n of["agent","agents","mode"]){let r=t[n];if(r!==void 0){if(!h(r))return!1;for(let o of Object.values(r))if(h(o)&&(o.permissions!==void 0||!nt(o.permission,e)))return!1}}return!0}function Rn(t){for(let e of t)for(let n of["agent","agents","mode","modes"]){let r;try{r=ot(f(e,n))}catch{continue}for(let o of r)try{if(o.endsWith(".md")&&/permission/i.test(rt(f(e,n,o),"utf8")))return!0}catch{return!0}}return!1}function Tn(t){let e=f(process.env.XDG_CONFIG_HOME||f(T(),".config"),"opencode"),n=K(t),r=[e,...n.map(c=>f(c,".opencode"))];if(Rn(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=D(s,!0,Tt,!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(Dt(c))}catch{return"unreadable"}if(!(c===process.env.OPENCODE_PERMISSION?nt(u,i.matchers):h(u)&&Tt(u,i.matchers)))return"unreadable"}return i}function Cn(){return D([f(T(),".gemini","antigravity-cli","settings.json")],!0,(t,e)=>{let n=t.permissions;if(n===void 0)return!0;if(!h(n))return!1;for(let r of["deny","ask"]){let o=F(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=>ut(u,l))}}return!0},!1)}function h(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Ut(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pn(t){let e=t.trim().replace(/\s+/g," "),n=e.endsWith(" *")&&e.length>2,r=(n?e.slice(0,-2):e).split("*").map(Ut).join("[\\s\\S]*");return new RegExp(`^${r}${n?"(?: [\\s\\S]*)?":""}(?= |$)`)}var Hn=512;function Nn(t){let e=t.replace(/['"\\]/g,"").split(/[\s;&|(){}<>`$]+/).filter(Boolean);return[e,e.map(Z)]}function ut(t,e){if(t.test(e)||t.test(e.trim().replace(/\s+/g," ")))return!0;for(let n of Nn(e)){if(n.length>Hn)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=Pn(t);return n=>ut(e,n)}function In(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(`^${Ut(r)}${n?"(?: [\\s\\S]*)?":""}$`);return s=>o.test(s)}var Ln={"claude-code":yn,cursor:xn,"gemini-cli":On,opencode:Tn,antigravity:Cn},jn=new Set(["codex"]),Jt=/(?:^|[\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 Fn(t,e,n){let r=Ln[t];return r?r(e??process.cwd(),n):{matchers:[],complete:!1}}function Dn(t,e,n){return t==="unreadable"||Jt.test(e.replace(/['"\\]/g,""))||t.matchers.some(r=>r(e))?!1:t.complete||jt(e,!jn.has(n))}var zt=new Set(["default","acceptEdits","dontAsk"]);function Bt(t,e){return e.host!=="claude-code"||e.permissionMode==="bypassPermissions"?!0:t!=="unreadable"&&t.allowsEverything===!0&&zt.has(e.permissionMode??"")}function Mn(t,e){let n="pathEnv"in t?t.pathEnv:process.env.PATH,r;return o=>t.host!=="claude-code"?R(o,t.cwd,n):(r??=St(e.configDir),!R(o,t.cwd,n)&&!r.paths.some(s=>R(o,t.cwd,s))?!1:o.includes("/")||!wt(o,r))}var Un=/^[^\s;&|<>()$`\\{}*?[\]~#!]+(?: [^\s;&|<>()$`\\{}*?[\]~#!]+)*$/;function Jn(t,e,n){return n.host!=="claude-code"||t==="unreadable"||Bt(t,n)||!zt.has(n.permissionMode??"")||!Un.test(e)||Jt.test(e.replace(/['"]/g,""))||(t.guards??[]).some(r=>r(e))?null:(t.trustedAllow??[]).find(r=>r.matches(e))?.rule??null}function Wt(t,e,n,r){if(!n||/["\\$`;&|<>(){}]|'\\''/.test(n))return null;let o=e.claudeDirs??q(),s=Fn(e.host,e.cwd,o),i=Jn(s,t,e),c=i||Dn(s,t,e.host)?fn(t,n,Mn(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}:Bt(s,e)?{command:c}:null}function E(t,e,n,r){return Wt(t,e,n,r)?.command??null}import{rmSync as zn,statSync as Bn}from"node:fs";import{join as Wn}from"node:path";function Gt(){return Wn(A(),"fail-open")}var Gn=24*36e5;function w(t=Date.now()){try{if(t-Bn(Gt()).mtimeMs<Gn)return!0;zn(Gt(),{force:!0})}catch{}return!1}function p(t,e){let n=t[e];return typeof n=="string"&&n?n:null}function M(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Zn(t){return p(t,"prompt_id")||p(t,"scratchpad_dir")?!0:M(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=>M(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"||M(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 M(t)?tr.filter(([,e])=>e(t)).map(([e])=>e):[]}function Zt(t,e){if(!M(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 Kt(t,e=S("cursor"),n=_){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},w()?null:e,n);return i?JSON.stringify({permission:"allow",updated_input:{...r,command:i}}):lt}var Y="{}";function qt(t,e=S("gemini-cli"),n=_){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 C(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Mo=String.raw`(?:'(?:(?:[^']|'\\'')*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?'|"(?:[^"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?"|(?:[^\s'"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?)`;function P(t,e,n="unknown",r=S(e),o=_){return t?E(t,{host:e,sessionId:n},w()?null:r,o):null}var or=new Set(["bash","file_system.bash"]),at=JSON.stringify({decision:"allow"});function Yt(t,e=(n,r)=>P(n,"vibe",r)){if(!C(t)||t.hook_event_name!=="pre_tool"||typeof t.tool_name!="string"||!or.has(t.tool_name))return"";let n=t.tool_input;if(!C(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 Vt(t,e=(n,r)=>P(n,"antigravity",r)){if(!C(t)||!C(t.toolCall)||t.toolCall.name!=="run_command")return at;let n=t.toolCall.args;if(!C(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}function H(t){return w()?null:S(t)}function sr(t,e,n={}){let r=n.recordUsage??_;switch(t){case"claude-code":case"codex":return e.hook_event_name!==void 0&&e.hook_event_name!=="PreToolUse"?"":Ft(e,t,H(t),r,n.claudeDirs??q(),n.pathEnv??process.env.PATH,n.launchArgs??ct)??"";case"cursor":return Kt(e,H(t),r);case"gemini-cli":return qt(e,H(t),r);case"vibe":return Yt(e,(o,s)=>P(o,"vibe",s,H(t),r));case"antigravity":return Vt(e,(o,s)=>P(o,"antigravity",s,H(t),r));default:return Xt(t,e,H(t),r)}}function U(t,e,n={}){let r=Zt(t,e);return r?sr(r,t,n):n.fallback??""}var m="{}",ir=new Set(["runTerminalCommand","run_in_terminal","Bash","bash"]),cr=["run_in_background","is_background","isBackground"];function J(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function ur(t){let e=t.session_id??t.sessionId;return typeof e=="string"&&e?e:"unknown"}function lr(t,e){let n=t.cwd??e.cwd??e.workdir??e.working_directory;return typeof n=="string"&&n?n:void 0}function V(t,e,n,r,o){if(!J(e)||cr.some(i=>e[i]===!0))return null;let s=e.command;return typeof s!="string"||!s?null:E(s,{host:t,sessionId:ur(n),cwd:lr(n,e)},w()?null:r,o)}function I(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...t,command:e}}})}function ar(t){if(J(t))return t;if(typeof t!="string")return null;try{let e=JSON.parse(t);return J(e)?e:null}catch{return null}}function fr(t,e,n){if(typeof t.tool_name=="string"){if(!ir.has(t.tool_name))return m;let s=t.tool_input,i=V("copilot",s,t,e,n);return i?I(s,i):m}if(t.toolName!=="bash")return m;let r=ar(t.toolArgs),o=V("copilot",r,t,e,n);return o?JSON.stringify({modifiedArgs:{...r,command:o}}):m}function N(t,e,n){return(r,o,s)=>{if(r.tool_name!==e)return m;let i=r.tool_input,c=V(t,i,r,o,s);return c?n(i,c):m}}var dr=new Set(["run_terminal_command","Bash","bash"]);function pr(t,e,n){let r=t.toolName??t.tool_name;if(typeof r!="string"||!dr.has(r))return m;let o=t.toolInput??t.tool_input,s=V("grok",o,t,e,n);return s?I(o,s):m}var mr={copilot:fr,droid:N("droid","Execute",I),trae:N("trae","RunCommand",I),"qwen-code":N("qwen-code","run_shell_command",I),crush:N("crush","bash",(t,e)=>JSON.stringify({updated_input:{command:e}})),junie:N("junie","Bash",(t,e)=>JSON.stringify({updatedInput:{...t,command:e}})),zcode:N("zcode","Bash",I),grok:pr};function Xt(t,e,n=S(t),r=_){return J(e)?mr[t](e,n,r):m}function gr(t,e){if(!e)return m;let n;try{n=JSON.parse(e.replace(/^/,""))}catch{return m}return J(n)?U(n,t,{fallback:m}):m}async function Qt(t){process.stdout.write(gr(t,await L()))}Qt("crush").catch(t=>{process.stderr.write(`tkr-crush-hook: ${t.message}
|
|
13
13
|
`),process.stdout.write(m),process.exit(0)});
|