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