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