@tokmizer/plugin 0.9.62 → 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/README.md +1 -1
- 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 +7 -7
package/README.md
CHANGED
|
@@ -100,7 +100,7 @@ Each command adds one `PreToolUse` hook for the agent's shell tool. It rewrites
|
|
|
100
100
|
|
|
101
101
|
Permission rules stay in force. Agents match their allow, ask and deny rules against the command text, so Tokmizer leaves a command untouched whenever one of your deny or ask rules matches it. Tokmizer reads those rules for Claude Code (`permissions.deny` and `permissions.ask` in user, project, local and managed settings; a command matched by one of your `permissions.allow` rules is left untouched too, so that rule keeps approving it), OpenCode (`permission` in `opencode.json`), Cursor CLI (`permissions.deny`), Gemini CLI (policy files and `tools.exclude`) and Antigravity CLI (`permissions.deny` and `permissions.ask`). For the other agents, and on top of the Cursor, Gemini and Antigravity rules, only inspection, build and test commands (`cat`, `rg`, `git log`, `npm test`, `cargo build` and similar; inspection only for Codex) are routed; anything else, such as `git push` or `rm`, runs exactly as typed. If a settings file cannot be read, nothing is routed. Shell functions, aliases, builtins and anything that is not a program on your `PATH` always run exactly as typed.
|
|
102
102
|
|
|
103
|
-
In Claude Code, a command is rewritten only when that adds no permission prompt: in `bypassPermissions` mode, or when a plain `Bash` allow rule in your user or managed settings applies and the session is in default, `acceptEdits` or `dontAsk` mode. Otherwise it runs exactly as typed, so Claude Code still approves read-only commands such as `ls`, `cat` or `git status` on its own, and Tokmizer shortens the output once the command has succeeded. Claude Code runs that after-command hook only for successful commands, so in this default mode a failing command reaches Claude in full. When commands are rewritten, failing output is shortened too, with its failure details kept.
|
|
103
|
+
In Claude Code, a command is rewritten only when that adds no permission prompt: in `bypassPermissions` mode, or when a plain `Bash` allow rule in your user or managed settings applies and the session is in default, `acceptEdits` or `dontAsk` mode. Otherwise it runs exactly as typed, so Claude Code still approves read-only commands such as `ls`, `cat` or `git status` on its own, and Tokmizer shortens the output once the command has succeeded. Claude Code runs that after-command hook only for successful commands, so in this default mode a failing command reaches Claude in full. A single command typed on its own (no `&&`, `;`, pipe, redirection, `$( )` or wildcard) is also rewritten when one of your own allow rules for it, such as `Bash(pytest:*)` or `Bash(cargo build:*)` in your user or managed settings, applies and no deny or ask rule matches: Tokmizer then gives the approval Claude Code would have given to the command as typed, so no new prompt appears. When commands are rewritten, failing output is shortened too, with its failure details kept.
|
|
104
104
|
|
|
105
105
|
Aider, Cline and Windsurf have no hooks. Start them through Tokmizer, for example `tkr wrap aider`: only that session goes through Tokmizer's command shims. Your own terminals are not changed; `tkr shim global-path on` routes every terminal through the shims by adding a PATH line to your shell profile, and `tkr shim global-path off` removes it.
|
|
106
106
|
|
|
@@ -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()})}function z(){return!1}import ee from"node:os";import{join as ne}from"node:path";function $(){return process.env.TOKMIZER_HOME||ne(ee.homedir(),".tokmizer")}import{rmSync as re,statSync as oe}from"node:fs";import{join as se}from"node:path";function kt(){return se($(),"fail-open")}var ie=24*36e5;function S(t=Date.now()){try{if(t-oe(kt()).mtimeMs<ie)return!0;re(kt(),{force:!0})}catch{}return!1}function E(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var qr=String.raw`(?:'(?:(?:[^']|'\\'')*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?'|"(?:[^"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?"|(?:[^\s'"]*[\\/])?tkr(?:\.(?:exe|cmd|bat|ps1))?)`;import{appendFileSync as de,chmodSync as pe,mkdirSync as me,existsSync as ge,readFileSync as to,rmSync as eo}from"node:fs";import{dirname as he,join as ke}from"node:path";import{readFileSync as ue,renameSync as le,statSync as ae,writeFileSync as fe}from"node:fs";function _t(t,e,n){try{if(ae(t).size<=e)return;let r=ue(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}`;fe(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}),le(i,t)}catch{}}var _e="usage.jsonl";var bt=2*1024*1024;function be(){return ke($(),_e)}function h(t,e,n=be()){try{let r=he(n);ge(r)||me(r,{recursive:!0,mode:448});let o=t.replace(/[^A-Za-z0-9._-]/g,"").slice(0,64)||"unknown";de(n,`{"t":${Math.floor(Date.now()/1e3)},"s":"${o}","o":${e?1:0}}
|
|
7
|
+
`,{mode:384}),pe(n,384),_t(n,bt,bt/2)}catch{}}import{existsSync as W,readFileSync as ot,readdirSync as st}from"node:fs";import{homedir as C}from"node:os";import{fileURLToPath as Qe}from"node:url";import{dirname as Ht,join as f,resolve as tn}from"node:path";import{execFileSync as Me}from"node:child_process";import{mkdirSync as Ue,readFileSync as $t,renameSync as ze,statSync as Je,writeFileSync as Be}from"node:fs";import{join as vt}from"node:path";import{closeSync as we,openSync as Se,readSync as ye,readdirSync as xe,readFileSync as $e,statSync as St}from"node:fs";import{homedir as ve}from"node:os";import{isAbsolute as Ae,join as J,resolve as Ee}from"node:path";var Oe=/^[A-Za-z0-9._+@%:,/-]+$/,Re=new Set(["7f454c46","feedface","feedfacf","cefaedfe","cffaedfe","cafebabe","bebafeca"]),Te=32,Ce=4*1024*1024;function et(t){let e;try{e=Se(t,"r");let n=Buffer.alloc(4),r=ye(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&&we(e)}}function j(t,e=process.platform){try{let n=St(t);if(!n.isFile())return!1;if(e==="win32")return!0;if((n.mode&73)===0)return!1;let r=et(t);return r==="#!"||r!==null&&Re.has(r)}catch{return!1}}function Pe(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(!Oe.test(t))return!1;let o=r==="win32";if(t.includes("/"))return j(Ee(e??process.cwd(),t),r);if(!n)return!1;let s=o?Pe(t):[t];for(let i of n.split(o?";":":"))if(!(!i||!Ae(i))){for(let c of s)if(j(J(i,c),r))return!0}return!1}var He=/^eval \$'([^\s'()=]+) \(\) /,Ne=/^([^\s'"()=]+) \(\) \{$/,Ie=/^alias -- ([^\s=]+)=(.*)$/,Le=/^# (?:Shell Options|Aliases|Shopt|Check for |Shadow )/,je=/^export PATH=(.*)$/,Fe=/^(?:--colou?r(?:=\S+)?|-G)$/;function wt(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 De(t,e){let n="";for(let r of t.split(`
|
|
8
|
+
`)){let o=je.exec(r);if(o&&n!=="# Functions"){let s=wt(o[1].trim());/[$`\\]/.test(s)||e.paths.push(s);continue}if(r.startsWith("# ")&&(n!=="# Functions"||Le.test(r))){n=r;continue}if(n==="# Functions"){let s=He.exec(r)??Ne.exec(r);s&&e.functions.add(s[1])}else if(n==="# Aliases"){let s=Ie.exec(r);s&&e.aliases.set(s[1],wt(s[2].trim()))}}}function tt(t){return t?.code==="ENOENT"}function yt(t){let e={functions:new Set,aliases:new Map,paths:[],uncertain:!1},n=J(t||J(ve(),".claude"),"shell-snapshots"),r=[];try{for(let o of xe(n)){if(!o.startsWith("snapshot-")||!o.endsWith(".sh"))continue;let s=J(n,o);try{let i=St(s);i.isFile()&&r.push({path:s,mtime:i.mtimeMs,size:i.size})}catch(i){tt(i)||(e.uncertain=!0)}}}catch(o){return tt(o)||(e.uncertain=!0),e}r=r.sort((o,s)=>s.mtime-o.mtime).slice(0,Te);for(let o of r)try{if(o.size>Ce)throw new Error("snapshot too large");De($e(o.path,"utf8"),e)}catch(s){tt(s)||(e.uncertain=!0)}return e}function xt(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=>Fe.test(o))}var We="exec-probe.json",Ge=6e4;function Ze(){return vt($(),We)}function Ke(t){try{let e=JSON.parse($t(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 qe(t,e){try{Ue(vt(t,".."),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;Be(n,JSON.stringify(e),{mode:384}),ze(n,t)}catch{}}function Ye(t){try{return Me(t,["--native-check"],{encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"],windowsHide:!0}).startsWith("tokmizer-native ")}catch{return!1}}function Ve(t,e){try{let r=$t(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):j(o)}catch{return!1}}function Xe(t,e,n){try{let r=Je(t);return[t,r.size,r.mtimeMs,r.ino,r.mode,e?n??"":""].join("|")}catch{return`${t}|missing`}}function nt(t,e=process.platform,n=process.env.PATH,r=Ze(),o=Date.now()){let s=e!=="win32"&&et(t)==="#!",i=Xe(t,s,n),c=Ke(r);if(c?.key===i&&(c.ok||o-c.at<Ge))return c.ok;let u=j(t,e)&&(s?Ve(t,n):Ye(t));return qe(r,{key:i,ok:u,at:o,skipped:(c?.skipped??0)+(u?0:1)}),u}var en=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"]),nn=new Set(["for","while","until","if","then","else","elif","fi","do","done","case","esac","select","function","time","coproc","in","!","[[","]]","{","}",".","declare","typeset","local","readonly","unset","set","shift","trap","wait","read","eval","exec","break","continue","pushd","popd","dirs","alias","unalias","hash","ulimit","umask","getopts","let","shopt","builtin","command","compgen","complete","disown","suspend","jobs","fg","bg","kill","history","fc","bind","enable","caller","type","printf","pwd","times","logout","mapfile","readarray","help","which","print","whence","where","autoload","zmodload","setopt","unsetopt","emulate","noglob","rehash","functions","bindkey","zle","vared","sched","limit","unlimit","zstyle","zparseopts","ttyctl"]),At=new Set(["sh","bash","zsh","dash","ksh","fish","python","python3","python2","node","ruby","perl","php","awk","sed","deno","bun"]),Et="(?:dev|start|serve|watch|preview)",rn=new RegExp(`^(?:\\S*/)?(?:bun\\s+(?:install|i|add|remove|rm|update|outdated|audit|test|build|pm|x)(?:\\s|$)|bun\\s+run\\s+(?!${Et}(?:\\s|$))[A-Za-z0-9:_-]+(?:\\s|$)|deno\\s+(?:test|lint|fmt|check|compile|install|info|doc|bench|outdated)(?:\\s|$)|deno\\s+task\\s+(?!${Et}(?:\\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)`),on=/(?:^|\s)--watch(?:\s|=|$)/;function sn(t){return rn.test(t)&&!on.test(t)}var cn=/^((?:\S*\/)?(sh|bash|zsh|dash|ksh|fish)\s+(-[elux]*c[elux]*)\s+)(['"])/,un=/[()$]|(?:^|[;&|\n]\s*)(?:and|or|not|begin|end|if|else|switch|case|while|for|function|return)(?:\s|;|$)/,Nt=3;function It(t){let e=cn.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&&un.test(c)?null:{script:c,start:o,end:s,quote:r}}var ln=new Set(["cd","export","set","unset","source",".","true",":","pushd","popd"]);function an(t){return ct(t).filter(n=>{if(n.kind!=="cmd"||n.unsafe)return!1;let r=jt(n.text);return r!==""&&!ln.has(r)&&!it.test(r)}).length>1}function fn(t,e,n,r,o){if(n>=Nt)return null;let s=It(t);if(!s)return null;let{script:i,start:c,end:u,quote:l}=s,a=[],d=Ft(i,e,n+1,r,A=>a.push(A));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=an(i);if(o)for(let A of w?[t,...a]:a)o(A);return w?`${e} ${g}`:g}var Ot=/(?:^|\s)(?:--follow|-[0-9a-zA-Z]*f[a-zA-Z]*)(?:\s|=|$)/,dn=new Set(["docker","podman","kubectl","nerdctl","docker-compose","stern","flyctl"]);function pn(t,e){let n=G(e);return n==="tail"||n==="journalctl"?Ot.test(t):n==="stern"?!0:dn.has(n)?/\blogs?\b/.test(t)&&Ot.test(t):!1}var it=/^[A-Za-z_][A-Za-z0-9_]*\+?=/,mn=/^[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/,gn=/(?:^|[;&|\n({])\s*[A-Za-z_][A-Za-z0-9_-]*\s*\(\s*\)/;function G(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Lt(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 Rt(t){let e=Lt(t);if(!e)return!0;for(let n=0;n<t.length;n++)if(e[n]&&t[n]===">")return!0;return!1}function ct(t){let e=Lt(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 jt(t){return t.trim().split(/\s+/)[0]??""}function b(t,e=process.platform){try{let n=Ht(Qe(import.meta.url)),r=e==="win32",o=t&&t!=="claude-code"&&t!=="codex"&&!r?`TOKMIZER_HOST=${t} `:"";if(r&&(!t||t==="claude-code")){let c=f(n,"..","bin","tkr-exec.exe");if(W(c))return nt(c,e)?`'${c.replace(/\\/g,"/").replace(/'/g,"'\\''")}'`:null}let s=f(n,"..","bin","tkr-exec");if(!r&&W(s))return nt(s,e)?`${o}'${s.replace(/'/g,"'\\''")}'`:null;if(z()){let c=r?process.execPath.replace(/\\/g,"/"):process.execPath;return`${o}'${c.replace(/'/g,"'\\''")}' exec`}let i=f(n,"..","bin","tkr-exec.js");return W(i)?`${o}node '${i.replace(/'/g,"'\\''")}'`:null}catch{return null}}function hn(t,e="tkr-exec",n=()=>!0,r){return Ft(t,e,0,n,r)}function Ft(t,e,n,r,o){if(t.includes("<<")||gn.test(t))return t;let s=ct(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=jt(l),d=s[c+1],k=d?.kind==="sep"&&(d.text==="|"||d.text==="|&"),g=d?.kind==="sep"&&d.text==="&",w=!k&&!g&&!Rt(u.text)&&!u.text.includes("<(")&&!u.text.includes(">(")?fn(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))||en.has(a)||nn.has(a)||(At.has(a)||At.has(G(a)))&&!sn(l)||it.test(a)||a.startsWith("(")||a.startsWith("#")||a.startsWith("<")||a.startsWith(">")||mn.test(l)||pn(l,a)||a.endsWith(")")||k||g||Rt(u.text)||u.text.includes("<(")||u.text.includes(">(")||a==="node"&&l.includes("tkr-exec.js")||!r(a)){i.push(u.text);continue}let A=u.text.match(/^\s*/)?.[0]??"",_=u.text.match(/\s*$/)?.[0]??"";o?.(l),i.push(`${A}${e} ${l}${_}`)}return i.join("")}var kn=new Set(["command","workdir","timeout_ms","yield_time_ms","max_output_tokens","shell","login","tty","description"]),_n=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"]),bn=new Set(["log","diff","show","status","blame","ls-files","rev-parse","describe","shortlog"]),wn={find:/^-(?:delete|exec|execdir|ok|okdir|fprint|fls)/,sort:/^(?:-[^-]*o|--output|--compress-program)/,rg:/^(?:--pre|-[^-]*z|--search-zip)/,yq:/^(?:-[^-]*[is]|--inplace|--split-exp)/,file:/^(?:-C|--compile)/,tree:/^(?:-o|--output|-R$|-H$)/,git:/^(?:--output|--ext-diff|--textconv|-c$|--exec-path|--git-dir|--work-tree)/,eslint:/^--fix/},B=["test","run test","run build","run lint","run typecheck"],Sn={npm:new Set(B),pnpm:new Set([...B,"build","lint","typecheck"]),yarn:new Set([...B,"build","lint","typecheck"]),bun:new Set(B),cargo:new Set(["test","build","check","clippy"]),go:new Set(["test","build","vet"]),mvn:new Set(["test","compile","verify"]),gradle:new Set(["test","build","check"]),dotnet:new Set(["test","build"])},yn=new Set(["pytest","tsc","vitest","jest","eslint","mypy"]);function Dt(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 ct(t)){if(r.kind==="sep")continue;if(r.unsafe)return!1;let o=n<Nt?It(r.text.trim()):null;if(o){if(!Dt(o.script,e,n+1))return!1;continue}let s=r.text.trim().split(/\s+/).filter(Boolean).map(l=>l.replace(/['"\\]/g,""));if(s.length===0)continue;if(s.some(l=>it.test(l)))return!1;let i=G(s[0]);if(i!==s[0])return!1;let c=wn[i];if(c&&s.slice(1).some(l=>c.test(l)))return!1;if((i==="git"?bn.has(s[1]??""):_n.has(i))||e&&yn.has(i))continue;let u=e?Sn[i]:void 0;if(!(u&&(u.has(s[1]??"")||s[1]==="run"&&u.has(`run ${s[2]??""}`))))return!1}return!0}function Mt(t,e,n=b(e),r=h,o=K(),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=>!kn.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=Zt(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 xn(t,e){if(!W(t))return"missing";try{let n=ot(t,"utf8");return JSON.parse(e?Ut(n):n)}catch{return"unreadable"}}function Ut(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 G(t){let e=[],n=We(t);for(;;){e.push(n);let r=At(n);if(r===n)return e;n=r}}function gn(){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 rt(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=mn(i,e);if(s!=="missing"&&(s==="unreadable"||!h(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 Z(){return{projectDir:process.env.CLAUDE_PROJECT_DIR,configDir:process.env.CLAUDE_CONFIG_DIR}}function hn(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=[[gn(),"managed"],[n(e.configDir||o),"loaded"],[e.configDir?n(o):[],"extra"],[e.projectDir?r(e.projectDir):[],"project"],[G(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 M of["deny","ask","allow"]){let at=L(g[M]);if(!at)return!1;for(let Wt of at){let P=/^\s*Bash\s*(?:\(([\s\S]*)\))?\s*$/.exec(Wt);P&&(M!=="allow"?y.push(O((P[1]??"*").replace(/:\*$/," *"))):P[1]===void 0||P[1].trim()==="*"?c[l]=!0:s.push(O(P[1].replace(/:\*$/," *"))))}}return!0},p=[];for(let[d,y]of i){l=y;let g=j(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 kn(t){let e=[f(A(),".cursor","cli-config.json"),...G(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(!h(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 _n(){return process.platform==="darwin"?"/Library/Application Support/GeminiCli":process.platform==="win32"?"C:\\ProgramData\\gemini-cli":"/etc/gemini-cli"}var jt=/^\s*(?:run_shell_command|ShellTool)\s*(?:\(([\s\S]*)\))?\s*$/;function bn(t,e){let n=t.tools;if(n!==void 0&&!h(n))return!1;let r=[L(t.excludeTools),L(h(n)?n.exclude:void 0)];for(let o of r){if(!o)return!1;for(let i of o){let s=jt.exec(i);s&&e.push(O(s[1]===void 0?"*":`${s[1]}*`))}}return!0}function vt(t){try{return JSON.parse(t)}catch{return null}}function Sn(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]??vt(`"${r[1]}"`);if(o===null)return null;n.push(o)}return n}if(e.startsWith('"')){let n=/^"((?:\\.|[^"\\])*)"/.exec(e);return n?vt(`"${n[1]}"`):null}if(e.startsWith("'")){let n=/^'([^']*)'/.exec(e);return n?n[1]:null}return e.replace(/\s*#.*$/,"")}function yn(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=Sn(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==="*"||jt.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}))||it(l,a))}}return!0}function Ot(t){try{return rt(t).filter(e=>e.endsWith(".toml")).map(e=>f(t,e))}catch{return[]}}function wn(t){let e=_n(),n=[f(e,"system-defaults.json"),f(e,"settings.json"),process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,process.env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH,f(A(),".gemini","settings.json"),...G(t).map(o=>f(o,".gemini","settings.json"))].filter(o=>!!o),r=j(n,!0,bn,!1);if(r==="unreadable")return r;for(let o of[...Ot(f(A(),".gemini","policies")),...Ot(f(e,"policies"))]){let i;try{i=nt(o,"utf8")}catch{return"unreadable"}if(!yn(i,r.matchers))return"unreadable"}return r}function et(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(O(o.replace(/\?/g,"*")))}}return!0}function Et(t,e){if(t.permissions!==void 0||!et(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||!et(o.permission,e)))return!1}}return!0}function xn(t){for(let e of t)for(let n of["agent","agents","mode","modes"]){let r;try{r=rt(f(e,n))}catch{continue}for(let o of r)try{if(o.endsWith(".md")&&/permission/i.test(nt(f(e,n,o),"utf8")))return!0}catch{return!0}}return!1}function $n(t){let e=f(process.env.XDG_CONFIG_HOME||f(A(),".config"),"opencode"),n=G(t),r=[e,...n.map(c=>f(c,".opencode"))];if(xn(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,Et,!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(Lt(c))}catch{return"unreadable"}if(!(c===process.env.OPENCODE_PERMISSION?et(u,s.matchers):h(u)&&Et(u,s.matchers)))return"unreadable"}return s}function vn(){return j([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=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=>it(u,l))}}return!0},!1)}function h(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function On(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function En(t){let e=t.trim().replace(/\s+/g," "),n=e.endsWith(" *")&&e.length>2,r=(n?e.slice(0,-2):e).split("*").map(On).join("[\\s\\S]*");return new RegExp(`^${r}${n?"(?: [\\s\\S]*)?":""}(?= |$)`)}var An=512;function Rn(t){let e=t.replace(/['"\\]/g,"").split(/[\s;&|(){}<>`$]+/).filter(Boolean);return[e,e.map(W)]}function it(t,e){if(t.test(e)||t.test(e.trim().replace(/\s+/g," ")))return!0;for(let n of Rn(e)){if(n.length>An)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=En(t);return n=>it(e,n)}var Tn={"claude-code":hn,cursor:kn,"gemini-cli":wn,opencode:$n,antigravity:vn},Cn=new Set(["codex"]),Hn=/(?:^|[\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 Pn(t,e,n){let r=Tn[t];return r?r(e??process.cwd(),n):{matchers:[],complete:!1}}function Nn(t,e,n){return t==="unreadable"||Hn.test(e.replace(/['"\\]/g,""))||t.matchers.some(r=>r(e))?!1:t.complete||Nt(e,!Cn.has(n))}var In=new Set(["default","acceptEdits","dontAsk"]);function Ln(t,e){return e.host!=="claude-code"||e.permissionMode==="bypassPermissions"?!0:t!=="unreadable"&&t.allowsEverything===!0&&In.has(e.permissionMode??"")}function jn(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??=kt(e.configDir),!E(o,t.cwd,n)&&!r.paths.some(i=>E(o,t.cwd,i))?!1:o.includes("/")||!_t(o,r))}function w(t,e,n,r){if(!n||/["\\$`;&|<>(){}]|'\\''/.test(n))return null;let o=e.claudeDirs??Z(),i=Pn(e.host,e.cwd,o),s=Nn(i,t,e.host)?cn(t,n,jn(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||!Ln(i,e)?null:s}function R(t,e,n="unknown",r=b(e),o=k){return t?w(t,{host:e,sessionId:n},S()?null:r,o):null}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 Fn(t){return m(t,"prompt_id")||m(t,"scratchpad_dir")?!0:F(t.effort)}function Dn(t){return m(t,"tool_use_id")?.startsWith("toolu_")===!0||/^claude/i.test(m(t,"model")??"")}var Mn=new Set(["BeforeTool","AfterTool","BeforeAgent","AfterAgent","BeforeModel","AfterModel","BeforeToolSelection"]),Un=new Set(["preToolUse","postToolUse","beforeShellExecution","afterShellExecution","beforeSubmitPrompt","sessionStart","sessionEnd","stop"]),zn=new Set(["pre_tool","post_tool"]),Jn=new Set(["before_tool_call","after_tool_call"]),Bn=new Set(["runTerminalCommand","run_in_terminal"]),Wn=[["codex",t=>m(t,"turn_id")!==null],["claude-code",Fn],["cursor",t=>m(t,"cursor_version")!==null||m(t,"generation_id")!==null||m(t,"conversation_id")!==null||Array.isArray(t.workspace_roots)||Un.has(m(t,"hook_event_name")??"")],["gemini-cli",t=>Mn.has(m(t,"hook_event_name")??"")],["qwen-code",t=>t.hook_event_name==="PreToolUse"&&t.tool_name==="run_shell_command"],["vibe",t=>zn.has(m(t,"hook_event_name")??"")],["antigravity",t=>F(t.toolCall)],["copilot",t=>m(t,"toolName")!==null&&"toolArgs"in t||Bn.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&&!Jn.has(m(t,"event"))]],Gn=new Set(["codex","antigravity"]);function Zn(t){return F(t)?Wn.filter(([,e])=>e(t)).map(([e])=>e):[]}function Ft(t,e){if(!F(t))return null;let n=Zn(t);return n.length>1?null:n.length===1?n[0]:Dn(t)&&Gn.has(e)?"claude-code":e==="codex"?null:e}var ct=JSON.stringify({permission:"allow"});function Dt(t,e=b("cursor"),n=k){if(t.tool_name!=="Shell")return ct;let r=t.tool_input??{},o=r.command;if(typeof o!="string"||!o)return ct;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}}):ct}var K="{}";function Mt(t,e=b("gemini-cli"),n=k){if(t.hook_event_name!=="BeforeTool"||t.tool_name!=="run_shell_command")return K;let r=t.tool_input??{};if(r.is_background)return K;let o=r.command;if(typeof o!="string"||!o)return K;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}}}):K}var x="{}",Kn=new Set(["runTerminalCommand","run_in_terminal","Bash","bash"]),qn=["run_in_background","is_background","isBackground"];function q(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(!q(e)||qn.some(s=>e[s]===!0))return null;let i=e.command;return typeof i!="string"||!i?null:w(i,{host:t,sessionId:Yn(n),cwd:Vn(n,e)},S()?null:r,o)}function C(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...t,command:e}}})}function Xn(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 Qn(t,e,n){if(typeof t.tool_name=="string"){if(!Kn.has(t.tool_name))return x;let i=t.tool_input,s=Y("copilot",i,t,e,n);return s?C(i,s):x}if(t.toolName!=="bash")return x;let r=Xn(t.toolArgs),o=Y("copilot",r,t,e,n);return o?JSON.stringify({modifiedArgs:{...r,command:o}}):x}function T(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 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 x;let o=t.toolInput??t.tool_input,i=Y("grok",o,t,e,n);return i?C(o,i):x}var nr={copilot:Qn,droid:T("droid","Execute",C),trae:T("trae","RunCommand",C),"qwen-code":T("qwen-code","run_shell_command",C),crush:T("crush","bash",(t,e)=>JSON.stringify({updated_input:{command:e}})),junie:T("junie","Bash",(t,e)=>JSON.stringify({updatedInput:{...t,command:e}})),zcode:T("zcode","Bash",C),grok:er};function Ut(t,e,n=b(t),r=k){return q(e)?nr[t](e,n,r):x}function H(t){return S()?null:b(t)}function rr(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"?"":It(e,t,H(t),r,n.claudeDirs??Z(),n.pathEnv??process.env.PATH)??"";case"cursor":return Dt(e,H(t),r);case"gemini-cli":return Mt(e,H(t),r);case"vibe":return ut(e,(o,i)=>R(o,"vibe",i,H(t),r));case"antigravity":return lt(e,(o,i)=>R(o,"antigravity",i,H(t),r));default:return Ut(t,e,H(t),r)}}function D(t,e,n={}){let r=Ft(t,e);return r?rr(r,t,n):n.fallback??""}var or=new Set(["bash","file_system.bash"]),V=JSON.stringify({decision:"allow"});function ut(t,e=(n,r)=>R(n,"vibe",r)){if(!v(t)||t.hook_event_name!=="pre_tool"||typeof t.tool_name!="string"||!or.has(t.tool_name))return"";let n=t.tool_input;if(!v(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 lt(t,e=(n,r)=>R(n,"antigravity",r)){if(!v(t)||!v(t.toolCall)||t.toolCall.name!=="run_command")return V;let n=t.toolCall.args;if(!v(n)||typeof n.CommandLine!="string"||!n.CommandLine)return V;let r=e(n.CommandLine,typeof t.conversationId=="string"?t.conversationId:"unknown");return r?JSON.stringify({decision:"allow",overwrite:{CommandLine:r}}):V}var zt={vibe:{build:t=>ut(t),fallback:""},antigravity:{build:t=>lt(t),fallback:V}};function Jt(t){return zt[t??""]?.fallback??""}function sr(t,e){let n=zt[t??""];if(!n)return"";let r;try{r=JSON.parse(e.replace(/^/,""))}catch{return n.fallback}return v(r)?D(r,t,{fallback:n.fallback}):n.build(r)}async function Bt(t){process.stdout.write(sr(t,await N()))}Bt(process.argv[2]).catch(t=>{process.stderr.write(`tkr-agent-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 Z(t){let e=[],n=tn(t);for(;;){e.push(n);let r=Ht(n);if(r===n)return e;n=r}}function $n(){let t=process.platform==="darwin"?"/Library/Application Support/ClaudeCode":process.platform==="win32"?"C:\\Program Files\\ClaudeCode":"/etc/claude-code",e=[f(t,"managed-settings.json")];try{for(let n of st(f(t,"managed-settings.d")))n.endsWith(".json")&&e.push(f(t,"managed-settings.d",n))}catch{return e}return e}function D(t,e,n,r){let o=[];for(let s of t){let i=xn(s,e);if(i!=="missing"&&(i==="unreadable"||!m(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 K(){return{projectDir:process.env.CLAUDE_PROJECT_DIR,configDir:process.env.CLAUDE_CONFIG_DIR}}function vn(t,e){let n=_=>[f(_,"settings.json"),f(_,"settings.local.json")],r=_=>n(f(_,".claude")),o=f(C(),".claude"),s=e.configDir||o,i=[[$n(),"managed"],[[f(s,"settings.json")],"loaded"],[[f(s,"settings.local.json")],"loadedLocal"],[e.configDir?n(o):[],"extra"],[e.projectDir?r(e.projectDir):[],"project"],[Z(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=(_,Q)=>{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 dt of["deny","ask","allow"]){let pt=F(x[dt]);if(!pt)return!1;for(let mt of pt){let R=/^\s*Bash\s*(?:\(([\s\S]*)\))?\s*$/.exec(mt);if(R)if(dt!=="allow")Q.push(O((R[1]??"*").replace(/:\*$/," *")));else if(R[1]===void 0||R[1].trim()==="*")l[d]=!0;else{c.push(O(R[1].replace(/:\*$/," *")));let gt=Fn(R[1]);gt&&u[d].push({rule:mt.trim(),matches:gt})}}}return!0},g=[];for(let[_,Q]of i){d=Q;let x=D(_,!1,k,!0);if(x==="unreadable")return"unreadable";g.push(...x.matchers)}let w=l.managed||(l.loaded||l.loadedLocal)&&!a,A=[...u.managed,...a?[]:u.loaded];return{matchers:[...g,...w?[]:c],complete:!0,allow:c,allowsEverything:w,guards:g,trustedAllow:A}}function An(t){let e=[f(C(),".cursor","cli-config.json"),...Z(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(!m(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 En(){return process.platform==="darwin"?"/Library/Application Support/GeminiCli":process.platform==="win32"?"C:\\ProgramData\\gemini-cli":"/etc/gemini-cli"}var zt=/^\s*(?:run_shell_command|ShellTool)\s*(?:\(([\s\S]*)\))?\s*$/;function On(t,e){let n=t.tools;if(n!==void 0&&!m(n))return!1;let r=[F(t.excludeTools),F(m(n)?n.exclude:void 0)];for(let o of r){if(!o)return!1;for(let s of o){let i=zt.exec(s);i&&e.push(O(i[1]===void 0?"*":`${i[1]}*`))}}return!0}function Tt(t){try{return JSON.parse(t)}catch{return null}}function Rn(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]??Tt(`"${r[1]}"`);if(o===null)return null;n.push(o)}return n}if(e.startsWith('"')){let n=/^"((?:\\.|[^"\\])*)"/.exec(e);return n?Tt(`"${n[1]}"`):null}if(e.startsWith("'")){let n=/^'([^']*)'/.exec(e);return n?n[1]:null}return e.replace(/\s*#.*$/,"")}function Tn(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=Rn(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==="*"||zt.test(u)))continue;let i=r.commandPrefix===void 0?[]:[r.commandPrefix].flat(),c=[r.commandRegex,r.argsPattern].flat().filter(u=>typeof u=="string");if(i.length===0&&c.length===0){e.push(()=>!0);continue}for(let u of i)e.push(O(`${u}*`));for(let u of c){let l;try{l=new RegExp(u)}catch{return!1}e.push(a=>l.test(JSON.stringify({command:a}))||ut(l,a))}}return!0}function Ct(t){try{return st(t).filter(e=>e.endsWith(".toml")).map(e=>f(t,e))}catch{return[]}}function Cn(t){let e=En(),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"),...Z(t).map(o=>f(o,".gemini","settings.json"))].filter(o=>!!o),r=D(n,!0,On,!1);if(r==="unreadable")return r;for(let o of[...Ct(f(C(),".gemini","policies")),...Ct(f(e,"policies"))]){let s;try{s=ot(o,"utf8")}catch{return"unreadable"}if(!Tn(s,r.matchers))return"unreadable"}return r}function rt(t,e){if(t===void 0)return!0;if(typeof t=="string")return t!=="allow"&&e.push(()=>!0),!0;if(!m(t))return!1;for(let n of["bash","shell","*"]){let r=t[n];if(r!==void 0){if(typeof r=="string"){r!=="allow"&&e.push(()=>!0);continue}if(!m(r))return!1;for(let[o,s]of Object.entries(r))s!=="allow"&&e.push(O(o.replace(/\?/g,"*")))}}return!0}function Pt(t,e){if(t.permissions!==void 0||!rt(t.permission,e))return!1;for(let n of["agent","agents","mode"]){let r=t[n];if(r!==void 0){if(!m(r))return!1;for(let o of Object.values(r))if(m(o)&&(o.permissions!==void 0||!rt(o.permission,e)))return!1}}return!0}function Pn(t){for(let e of t)for(let n of["agent","agents","mode","modes"]){let r;try{r=st(f(e,n))}catch{continue}for(let o of r)try{if(o.endsWith(".md")&&/permission/i.test(ot(f(e,n,o),"utf8")))return!0}catch{return!0}}return!1}function Hn(t){let e=f(process.env.XDG_CONFIG_HOME||f(C(),".config"),"opencode"),n=Z(t),r=[e,...n.map(c=>f(c,".opencode"))];if(Pn(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,Pt,!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(Ut(c))}catch{return"unreadable"}if(!(c===process.env.OPENCODE_PERMISSION?rt(u,i.matchers):m(u)&&Pt(u,i.matchers)))return"unreadable"}return i}function Nn(){return D([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=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=>ut(u,l))}}return!0},!1)}function m(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}function Jt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function In(t){let e=t.trim().replace(/\s+/g," "),n=e.endsWith(" *")&&e.length>2,r=(n?e.slice(0,-2):e).split("*").map(Jt).join("[\\s\\S]*");return new RegExp(`^${r}${n?"(?: [\\s\\S]*)?":""}(?= |$)`)}var Ln=512;function jn(t){let e=t.replace(/['"\\]/g,"").split(/[\s;&|(){}<>`$]+/).filter(Boolean);return[e,e.map(G)]}function ut(t,e){if(t.test(e)||t.test(e.trim().replace(/\s+/g," ")))return!0;for(let n of jn(e)){if(n.length>Ln)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=In(t);return n=>ut(e,n)}function Fn(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(`^${Jt(r)}${n?"(?: [\\s\\S]*)?":""}$`);return s=>o.test(s)}var Dn={"claude-code":vn,cursor:An,"gemini-cli":Cn,opencode:Hn,antigravity:Nn},Mn=new Set(["codex"]),Bt=/(?:^|[\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 Un(t,e,n){let r=Dn[t];return r?r(e??process.cwd(),n):{matchers:[],complete:!1}}function zn(t,e,n){return t==="unreadable"||Bt.test(e.replace(/['"\\]/g,""))||t.matchers.some(r=>r(e))?!1:t.complete||Dt(e,!Mn.has(n))}var Wt=new Set(["default","acceptEdits","dontAsk"]);function Gt(t,e){return e.host!=="claude-code"||e.permissionMode==="bypassPermissions"?!0:t!=="unreadable"&&t.allowsEverything===!0&&Wt.has(e.permissionMode??"")}function Jn(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??=yt(e.configDir),!T(o,t.cwd,n)&&!r.paths.some(s=>T(o,t.cwd,s))?!1:o.includes("/")||!xt(o,r))}var Bn=/^[^\s;&|<>()$`\\{}*?[\]~#!]+(?: [^\s;&|<>()$`\\{}*?[\]~#!]+)*$/;function Wn(t,e,n){return n.host!=="claude-code"||t==="unreadable"||Gt(t,n)||!Wt.has(n.permissionMode??"")||!Bn.test(e)||Bt.test(e.replace(/['"]/g,""))||(t.guards??[]).some(r=>r(e))?null:(t.trustedAllow??[]).find(r=>r.matches(e))?.rule??null}function Zt(t,e,n,r){if(!n||/["\\$`;&|<>(){}]|'\\''/.test(n))return null;let o=e.claudeDirs??K(),s=Un(e.host,e.cwd,o),i=Wn(s,t,e),c=i||zn(s,t,e.host)?hn(t,n,Jn(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}:Gt(s,e)?{command:c}:null}function v(t,e,n,r){return Zt(t,e,n,r)?.command??null}function P(t,e,n="unknown",r=b(e),o=h){return t?v(t,{host:e,sessionId:n},S()?null:r,o):null}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 Gn(t){return p(t,"prompt_id")||p(t,"scratchpad_dir")?!0:M(t.effort)}function Zn(t){return p(t,"tool_use_id")?.startsWith("toolu_")===!0||/^claude/i.test(p(t,"model")??"")}var Kn=new Set(["BeforeTool","AfterTool","BeforeAgent","AfterAgent","BeforeModel","AfterModel","BeforeToolSelection"]),qn=new Set(["preToolUse","postToolUse","beforeShellExecution","afterShellExecution","beforeSubmitPrompt","sessionStart","sessionEnd","stop"]),Yn=new Set(["pre_tool","post_tool"]),Vn=new Set(["before_tool_call","after_tool_call"]),Xn=new Set(["runTerminalCommand","run_in_terminal"]),Qn=[["codex",t=>p(t,"turn_id")!==null],["claude-code",Gn],["cursor",t=>p(t,"cursor_version")!==null||p(t,"generation_id")!==null||p(t,"conversation_id")!==null||Array.isArray(t.workspace_roots)||qn.has(p(t,"hook_event_name")??"")],["gemini-cli",t=>Kn.has(p(t,"hook_event_name")??"")],["qwen-code",t=>t.hook_event_name==="PreToolUse"&&t.tool_name==="run_shell_command"],["vibe",t=>Yn.has(p(t,"hook_event_name")??"")],["antigravity",t=>M(t.toolCall)],["copilot",t=>p(t,"toolName")!==null&&"toolArgs"in t||Xn.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&&!Vn.has(p(t,"event"))]],tr=new Set(["codex","antigravity"]);function er(t){return M(t)?Qn.filter(([,e])=>e(t)).map(([e])=>e):[]}function Kt(t,e){if(!M(t))return null;let n=er(t);return n.length>1?null:n.length===1?n[0]:Zn(t)&&tr.has(e)?"claude-code":e==="codex"?null:e}var lt=JSON.stringify({permission:"allow"});function qt(t,e=b("cursor"),n=h){if(t.tool_name!=="Shell")return lt;let r=t.tool_input??{},o=r.command;if(typeof o!="string"||!o)return lt;let s=typeof r.working_directory=="string"?r.working_directory:void 0,i=v(o,{host:"cursor",sessionId:t.conversation_id??"unknown",cwd:s},S()?null:e,n);return i?JSON.stringify({permission:"allow",updated_input:{...r,command:i}}):lt}var q="{}";function Yt(t,e=b("gemini-cli"),n=h){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 s=typeof t.cwd=="string"?t.cwd:void 0,i=v(o,{host:"gemini-cli",sessionId:t.session_id??"unknown",cwd:s},S()?null:e,n);return i?JSON.stringify({hookSpecificOutput:{tool_input:{command:i}}}):q}var y="{}",nr=new Set(["runTerminalCommand","run_in_terminal","Bash","bash"]),rr=["run_in_background","is_background","isBackground"];function Y(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(!Y(e)||rr.some(i=>e[i]===!0))return null;let s=e.command;return typeof s!="string"||!s?null:v(s,{host:t,sessionId:or(n),cwd:sr(n,e)},S()?null:r,o)}function N(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...t,command:e}}})}function ir(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 cr(t,e,n){if(typeof t.tool_name=="string"){if(!nr.has(t.tool_name))return y;let s=t.tool_input,i=V("copilot",s,t,e,n);return i?N(s,i):y}if(t.toolName!=="bash")return y;let r=ir(t.toolArgs),o=V("copilot",r,t,e,n);return o?JSON.stringify({modifiedArgs:{...r,command:o}}):y}function H(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 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 y;let o=t.toolInput??t.tool_input,s=V("grok",o,t,e,n);return s?N(o,s):y}var ar={copilot:cr,droid:H("droid","Execute",N),trae:H("trae","RunCommand",N),"qwen-code":H("qwen-code","run_shell_command",N),crush:H("crush","bash",(t,e)=>JSON.stringify({updated_input:{command:e}})),junie:H("junie","Bash",(t,e)=>JSON.stringify({updatedInput:{...t,command:e}})),zcode:H("zcode","Bash",N),grok:lr};function Vt(t,e,n=b(t),r=h){return Y(e)?ar[t](e,n,r):y}function I(t){return S()?null:b(t)}function fr(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"?"":Mt(e,t,I(t),r,n.claudeDirs??K(),n.pathEnv??process.env.PATH)??"";case"cursor":return qt(e,I(t),r);case"gemini-cli":return Yt(e,I(t),r);case"vibe":return at(e,(o,s)=>P(o,"vibe",s,I(t),r));case"antigravity":return ft(e,(o,s)=>P(o,"antigravity",s,I(t),r));default:return Vt(t,e,I(t),r)}}function U(t,e,n={}){let r=Kt(t,e);return r?fr(r,t,n):n.fallback??""}var dr=new Set(["bash","file_system.bash"]),X=JSON.stringify({decision:"allow"});function at(t,e=(n,r)=>P(n,"vibe",r)){if(!E(t)||t.hook_event_name!=="pre_tool"||typeof t.tool_name!="string"||!dr.has(t.tool_name))return"";let n=t.tool_input;if(!E(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 ft(t,e=(n,r)=>P(n,"antigravity",r)){if(!E(t)||!E(t.toolCall)||t.toolCall.name!=="run_command")return X;let n=t.toolCall.args;if(!E(n)||typeof n.CommandLine!="string"||!n.CommandLine)return X;let r=e(n.CommandLine,typeof t.conversationId=="string"?t.conversationId:"unknown");return r?JSON.stringify({decision:"allow",overwrite:{CommandLine:r}}):X}var Xt={vibe:{build:t=>at(t),fallback:""},antigravity:{build:t=>ft(t),fallback:X}};function Qt(t){return Xt[t??""]?.fallback??""}function pr(t,e){let n=Xt[t??""];if(!n)return"";let r;try{r=JSON.parse(e.replace(/^/,""))}catch{return n.fallback}return E(r)?U(r,t,{fallback:n.fallback}):n.build(r)}async function te(t){process.stdout.write(pr(t,await L()))}te(process.argv[2]).catch(t=>{process.stderr.write(`tkr-agent-hook: ${t.message}
|
|
13
|
+
`),process.stdout.write(Qt(process.argv[2])),process.exit(0)});
|