cc-safety-net 2.4.8 → 2.4.9
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/README.md +2 -0
- package/dist/amp/cc-safety-net/index.ts +2 -2
- package/dist/bin/hook.js +1 -1
- package/dist/chunks/{index-tfdjszbb.js → index-g2gqgqzy.js} +1 -1
- package/dist/cli.js +4 -4
- package/dist/index.js +1 -1
- package/dist/openclaw/cc-safety-net/index.js +2 -2
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -89,6 +89,8 @@ Keep the `@latest` qualifier. A bare `cc-safety-net` spec can run an older copy
|
|
|
89
89
|
|
|
90
90
|
OpenCode integration supports v1.18.29+ and v2.0.6+. Run `npx -y cc-safety-net@latest install --opencode`; the installer selects the host's plugin commands. See [OpenCode compatibility](docs/opencode-compatibility.md) for v2 shell configuration and host limitations.
|
|
91
91
|
|
|
92
|
+
OpenClaw integration requires OpenClaw 2026.8.1+. The installer accepts the plugin's declared capabilities for you, and older OpenClaw releases reject that option.
|
|
93
|
+
|
|
92
94
|
## Safety presets
|
|
93
95
|
|
|
94
96
|
To set a preset, run `npx cc-safety-net gui` and open Policy.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// cc-safety-net managed Amp plugin. Do not edit. Reinstall with: npx -y cc-safety-net install --amp
|
|
2
|
-
// version: 2.4.
|
|
2
|
+
// version: 2.4.9
|
|
3
3
|
// @bun
|
|
4
4
|
var Ci="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",He="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",wn="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var bi={errorCode:"path-canonicalization-limit",reason:"CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry."},_n={errorCode:"structural-shell-syntax-limit",reason:"Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry."},V=Object.freeze({realpathAttempts:{cap:16384,...bi},processedCandidateBytes:{cap:4194304,...bi},pathEnvironmentExpansion:{cap:64,...bi},recursionDepth:{cap:10,errorCode:"structural-shell-syntax-limit",reason:"Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry."},derivedTokens:{cap:16384,..._n},trackedHeredocFiles:{cap:64,..._n},controlFlowStates:{cap:64,..._n},wrapperPeelIterations:{cap:20,..._n},derivedCommandShape:_n});class D extends Error{kind;name="AnalysisLimit";constructor(e){super(V[e].reason);this.kind=e}}function be(){let e=new Map;return{counters:e,resolvedPaths:new Map,charge(t,n=1){let r=(e.get(t)??0)+n;if(e.set(t,r),r>V[t].cap)throw new D(t)}}}var Pp=[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bglpat-[A-Za-z0-9_-]{20,}\b/g,/\bxox[abeprs]-[A-Za-z0-9-]{20,}\b/g,/\bnpm_[A-Za-z0-9_]{20,}\b/g,/\bpypi-[A-Za-z0-9_-]{20,}\b/g,/\b[rs]k_(?:live|test)_[A-Za-z0-9_]{20,}\b/g,/\bsk-[A-Za-z0-9_-]{20,}\b/g,/\bsk_[A-Za-z0-9]{20,}\b/g,/\bgsk_[A-Za-z0-9]{52,}\b/g,/\bxai-[A-Za-z0-9_-]{80,}\b/g,/\bpplx-[A-Za-z0-9_-]{20,}\b/g,/\bbastn_[A-Za-z0-9]{16,}\b/g,/\btgp_v1_[A-Za-z0-9_-]{43,}\b/g,/\bflp_[A-Za-z0-9]{10,}\b/g,/\bwfr_[A-Za-z0-9]{20,}\b/g,/\bfwp?_[A-Za-z0-9_-]{20,}\b/g,/\btp-[A-Za-z0-9_-]{20,}\b/g,/\bpsk-[A-Za-z0-9_-]{8,}-[A-Za-z0-9_-]{8,}\b/g,/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/g];function lt(e){return Tp(e.replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_DSN|CONNECTION_STRING)=("[^"]*"|'[^']*'|[^\s]+(?:\s+[A-Z_][A-Z0-9_]*=[^\s]+)*)/gi,"$1=<redacted>").replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_(?:URL|URI|CONNECTION_STRING))=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIALS)[A-Z0-9_]*)=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>"))}function Tp(e){return Pp.reduce((t,n)=>t.replace(n,"<redacted>"),e.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,"<redacted>").replace(/((?:(['"])(?:authorization|cookie|x-api-key|api-key)\2|(?:authorization|cookie|x-api-key|api-key))\s*:\s*)(['"])(?:\\[^\r\n]|(?!\3)[^\\\r\n])*\3/gi,"$1$3<redacted>$3").replace(/(['"]?\s*(?:authorization|cookie|x-api-key|api-key)\s*:(?!\s*(?:"<redacted>"|'<redacted>'))\s*)([^'"\r\n]+)(['"]?)/gi,"$1<redacted>$3").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1<redacted>:<redacted>@").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)@/gi,"$1<redacted>@").replace(/(^|[\s?&;|])((?:x-amz-signature|x-goog-signature|sig|signature)=)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^&#\s'"`;|<>()]*)/gi,"$1$2<redacted>").replace(/(^|\s)((?:-u|--user)(?:\s+|=))([^\s:]+):([^\s]+)/g,"$1$2<redacted>:<redacted>")).replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"<redacted>").replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,"<redacted>")}var Ip={hard_stop:"Do not retry this operation or attempt any workaround (other tools, flags, or paths). Report the block to the user and continue with the rest of the task.",use_alternative:"Do not retry the blocked form. Continue the task using the safer alternative described above.",scope_down:"Retry with a narrower, explicit target as described above. Escalate to the user if the broad operation is truly required.",manual_only:"If this operation is truly needed, ask the user for explicit permission and have them run the command manually.",stop_and_explain:"Do not brute-force variants. Simplify or restructure the command so it can be analyzed, or report the block to the user."};function kp(e){let t=e.maxLen??200,n=e.redact??((o)=>o),r=(o)=>o.length>t?`${o.slice(0,t)}...`:o;return[e.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${n(e.reason)}`,e.ruleId?`Rule: ${e.ruleId}`:void 0,e.toolName?`Tool: ${e.toolName}`:void 0,e.command?`Command: ${r(n(e.command))}`:void 0,e.segment&&e.segment!==e.command?`Segment: ${r(n(e.segment))}`:void 0,e.configWarning?`Config warning: ${n(e.configWarning)}`:void 0,e.askUser?"Approve only if you expected this command.":Ip[e.intent??"manual_only"]].filter((o)=>o!==void 0).join(`
|
|
5
5
|
|
|
@@ -45,5 +45,5 @@ var Ci="CC Safety Net could not analyze the command because it exceeds safe anal
|
|
|
45
45
|
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function Q_(e,t,n,r,o,i){let s=at(e);if(s.length===0||Ue(s[0]??"").toLowerCase()!=="xargs")return!1;let a=$t(s),l=s.slice(a.childStart);if(l.length===0)return!1;if(a.replacementToken==="")return!1;let c=a.replacementToken,u=c===null?[...l,Xa]:l.map((m)=>m.split(c).join(Xa));return fi(u,t,n,r,o,i).some((m)=>m.target.includes(Xa))}function ew(e){let t=at(e);if(t.length===0)return null;let n=Ue(t[0]??"").toLowerCase();if(!nr(n))return null;return tw(n,t.slice(1))?n:null}function tw(e,t){let n=il(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(rp.has(o)||ap(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if(H_.get(n)?.has(o))r++;continue}return!1}return!0}function il(e){return/^python\d/.test(e)?"python":e}function nw(e){let t=[];for(let n of e){if(cp(n))continue;let r=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(n);if(r===null)break;if(r[1]!==void 0&&r[1]!=="")t.push(r[1])}return t}var Yf=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function rw(e,t){if(!t||!Yf.test(e))return e;return`~${e.replace(Yf,"").replace(/\\/g,"/")}`}function Ke(e,t){if(t==="--")return[];let n=[],r=t.indexOf("=");if(r>0&&r<t.length-1)n.push(t.slice(r+1));if(t.startsWith("-"))return n;if(e==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(t))return n;if(e==="zip"&&/\.zip$/i.test(t))return n;return n.push(t),n}function ow(e){let t=-1,n=!1;for(let r=0;r<e.length;r++){let o=e[r]??"";if(!n&&o==="--"){n=!0;continue}if(n||!/^-(?:[A-Za-z]|-)/.test(o)){if(t===-1)t=r;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(o)){r+=2;continue}if(o==="--indent"||o==="-L"){r++;continue}if(o.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(o)||/^--(?:slurp|raw-output0?|join-output|compact-output|color-output|monochrome-output|ascii-output|unbuffered|sort-keys|raw-input|null-input|binary|tab|seq|stream|stream-errors|exit-status|args|jsonargs|help|version|build-configuration)$/.test(o))continue;return e.flatMap((i)=>Ke("jq",i))}return e.flatMap((r,o)=>o===t?[]:Ke("jq",r))}function iw(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??"";if(r==="--"||!r.startsWith("-"))return[...t,...k_.has(r)?el("git",e.slice(n).map((i)=>/^-[aeinopqsv]+m$/.test(i)?"-m":i),O_):el("git",e.slice(n),M_)];if(t.push(...Ke("git",r)),!Se.has(r))continue;let o=e[n+1];if(o===void 0)break;t.push(...r==="-c"&&o.includes("=")?[o.slice(o.indexOf("=")+1)]:Ke("git",o)),n++}return t}function el(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o]??"";if(i==="--")return[...r,...t.slice(o).flatMap((s)=>Ke(e,s))];if(n.has(i)){o++;continue}if(i.includes("=")&&n.has(i.slice(0,i.indexOf("="))))continue;r.push(...Ke(e,i))}return r}function sw(e){return e.flatMap((t,n)=>{let r=lw(t);if(r!==null)return Zf(r.flag,r.value);let o=aw(e[n-1]);return o===null?[]:Zf(o,t)})}function Zf(e,t){if(e==="-F"||e==="--form"){let n=t.indexOf("="),r=n===-1?t:t.slice(n+1);if(!r.startsWith("@")&&!r.startsWith("<"))return[];return Ja(r.slice(1).split(";")[0]??"")}if(e==="--data-urlencode"){let n=t.indexOf("@"),r=t.indexOf("=");if(n===-1||r!==-1&&r<n)return[];return Ja(t.slice(n+1))}return t.startsWith("@")?Ja(t.slice(1)):[]}function aw(e){if(e===void 0)return null;if(np.has(e))return e;return/^-[A-Za-z]+[dF]$/.test(e)?`-${e.slice(-1)}`:null}function lw(e){let t=e.slice(0,2);if(e.length>2&&(t==="-d"||t==="-F"))return{flag:t,value:e.slice(2)};let n=e.indexOf("=");if(n===-1)return null;let r=e.slice(0,n);return np.has(r)?{flag:r,value:e.slice(n+1)}:null}function Ja(e){return e===""||e==="-"?[]:[e]}function cw(e,t,n,r,o,i){let s=e.findIndex((l)=>l.startsWith("-")||l==="("||l==="!"||l===";"),a=[...e.slice(0,s===-1?e.length:s),...e.flatMap((l,c)=>l==="-files0-from"&&e[c+1]!==void 0?[e[c+1]??""]:[])];for(let l=0;l<e.length;l++){if(!E_.has(e[l]??""))continue;let c=e.slice(l+1),u=c.findIndex((f)=>x_.has(f)),m=u===-1?c:c.slice(0,u),d=fi(m,t,n,r,o,i).map((f)=>f.target);if(a.push(...d.filter((f)=>f!=="{}")),!d.includes("{}"))continue;a.push(...e.slice(0,l).flatMap((f,p,g)=>{if(!__.has(f))return[];let h=g[p+1];return h===void 0?[]:[h,h.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return a}function uw(e,t,n,r,o,i,s){let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c===void 0)break;if(rp.has(c)||ap(e,c)){let m=t[l+1];if(m!==void 0)a.push(...di(e,m,n,r,o,i,s)),l++;continue}let u=/^--(?:eval|exec)=(.*)$/.exec(c);if(u!==null&&u[1]!==void 0){a.push(...di(e,u[1],n,r,o,i,s));continue}if(!c.startsWith("-"))a.push({target:c,cwd:i})}return a}function ap(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return P_.get(t[t.length-1]??"")?.has(il(e))??!1}function dw(e,t,n,r,o,i){if(!e.includes("system"))return[];return fa(e)?.commands.flatMap((s)=>Rn(t.getShellSyntax(s),t,n,r,o,i))??[]}function mw(e){return Array.from(e.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((t)=>t[1]).filter((t)=>t!==void 0&&t!=="")}function fw(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((n)=>n[2]).filter((n)=>n!==void 0&&n!=="");return[...t,...t.flatMap(sl),...e.match(Qa)??[]]}function di(e,t,n,r,o,i,s){let a=(g)=>({target:g,cwd:i}),l=gw(t,pw(e));if(l===null)return fw(t).map(a);let c=l.masked.match(jf)!==null||l.literals.some((g)=>Vf.test(l.masked.slice(0,g.start))),u=l.masked.match($_)!==null||l.literals.some((g)=>U_.test(l.masked.slice(0,g.start))),m=r.standard===!0&&!er.has(e),d=m&&!(Cw(l.masked)||c||u)?[]:l.literals,f=m?Array.from(l.masked.matchAll(jf),(g)=>{let h=g.index+g[0].length;return{start:h,end:Ks(l.masked,h)}}):[],p=!m||f.some((g)=>qs(l.masked,g.start))?l.literals:l.literals.filter((g)=>Vf.test(l.masked.slice(0,g.start))||f.some((h)=>g.start>=h.start&&g.start<h.end));return[...d.map((g)=>g.text).filter((g)=>g!=="").map(a),...d.flatMap((g)=>sl(g.text)).map(a),...m?[]:l.literals.flatMap((g)=>g.text.match(Qa)??[]).map(a),...c?p.flatMap((g)=>rl(g.text,n,r,o,i,s)??[a(g.text)]):[],...u?l.literals.flatMap((g)=>di(e,g.text.replace(/\\(.)/g,(h,y)=>y==="n"?`
|
|
46
46
|
`:y),n,r,o,i,s)):[],...(l.masked.match(Qa)??[]).map(a)]}function pw(e){let t=il(e);if(t==="python")return"python";if(t==="osascript")return"opaque";return t==="node"||t==="bun"||t==="deno"?"javascript":"simple"}function gw(e,t){if(t==="opaque")return null;let n=e.split(""),r=[];for(let o=0;o<e.length;o++){let i=e[o]??"";if(t==="simple"&&(i==="`"||i==="%"||i==="<")){if(z_.test(e.slice(o)))return null}let s=i==="'"||i==='"'||t==="javascript"&&i==="`"?i:null;if(s===null)continue;if(s==="`"&&bw(e,o))return null;let a=t==="python"?hw(e,o):"",l=t==="python"&&e.startsWith(s.repeat(3),o)?s.repeat(3):s,c=o+l.length,u=yw(e,c,l);if(u===null)return null;let m=e.slice(c,u);if(/[fF]/.test(a)&&m.includes("{"))return null;if(t==="simple"&&s==='"'&&B_.test(m))return null;r.push({start:c,text:m});for(let d=o;d<u+l.length;d++)n[d]=" ";o=u+l.length-1}return{masked:n.join(""),literals:r}}function hw(e,t){return G_.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function yw(e,t,n){let r=n==="`",o=r||n.length===3;for(let i=t;i<e.length;i++){let s=e[i];if(s==="\\"){i++;continue}if(r&&s==="$"&&e[i+1]==="{")return null;if(!o&&(s===`
|
|
47
47
|
`||s==="\r"))return null;if(e.startsWith(n,i))return i}return null}function bw(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function Cw(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(w_.has(n.toLowerCase()))return!0;let o=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((i)=>i.toLowerCase());if(!o.some((i)=>A_.has(i)))continue;if(o.length>1)return!0;if(Sw(e,r)===".")return!0;if(vw(e,r+n.length)==="(")return!0}return!1}function Sw(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function vw(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function Ew(e,t,n,r,o,i){return Aw(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...Rn(a,t,{...n,capturedOutput:!0},r,o,i),...xw(a,r)?Rw(a,r).map((l)=>({target:l,cwd:o})):[]]})}function xw(e,t){let n=_o(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||Ue(et(o.text,t)).toLowerCase()!=="base64")continue;for(let i=r+1;i<n.length;i++){let s=n[i];if(s?.kind==="operator")break;if(s?.kind!=="word")continue;let a=et(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function Rw(e,t){return _o(e).flatMap((n)=>n.kind==="word"?[et(n.text,t)]:n.kind==="redirection"&&n.target?[et(n.target,t)]:[]).flatMap(sl)}function sl(e){let t=ww(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||_w(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function _w(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function ww(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function Aw(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(Wn(o,n))continue;if(lp(e,r,n)){let i=Pw(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=Tw(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function Pw(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(Wn(i,n))continue;if(lp(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function Tw(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function lp(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function Iw(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let u=/^--([^=]+)(?:=(.*))?$/.exec(c);if(u!==null){let m=u[1]??"",d=u[2];if(m===D_)o=!0;if(L_.has(m))r=!0;if(d!==void 0){if(m===Hf)t.push(d);continue}if(F_.has(m)){let f=e[l+1];if(m===Hf&&f!==void 0)t.push(f);l++}continue}if(c.startsWith("-")&&c.length>1){let m=c.slice(1),d="",f="";for(let g=0;g<m.length;g++){let h=m[g]??"";if(N_.has(h))r=!0;if(W_.has(h)){d=h,f=m.slice(g+1);break}}if(d==="")continue;if(f.length>0){if(d===Uf)t.push(f);continue}let p=e[l+1];if(d===Uf&&p!==void 0)t.push(p);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function at(e){let t=e.findIndex((n)=>!cp(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function cp(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var kw=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),Ow=".env.",Mw=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),Dw=[".env.example.",".env.sample."];function Nw(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function Lw(e){return e.length>0&&!/\s/.test(e)}function tl(e,t,n,r){let o=up(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function up(e,t,n,r){try{return Er(e,t,n,r)}catch(o){if(o instanceof D)throw o;return""}}var Ww=new Set(["node_modules","__pycache__"]),Fw=[["vendor","bundle"],["vendor","cache"]];function Gw(e,t,n,r,o){if(Nw(e))return null;let i=Ve(e,t,r,o);if(!i)return null;let s=G(i.split("/").pop()??""),a=G(i),l=()=>Lw(s)||tl(e,t,r,o);if(Mw.has(s)||Dw.some((d)=>s.startsWith(d)))return null;let c=G(jw(e,t,r,o));for(let d of ls){let f=`~/${d.suffixParts.join("/")}`;if((Jf(a,f)||Jf(c,f))&&st(d.id,n))return d.id}let u=zw(i,t,n,r,o);if(u)return u;if(kw.has(s))return null;for(let d of as)if(s===d.basename&&st(d.id,n))return d.id;if(s.startsWith(Ow)&&st($r.id,n)&&l())return $r.id;for(let d of cs)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){let f=s.slice(d.prefix.length)[0];if((f==="-"||f==="_")&&st(d.id,n)&&l())return d.id}for(let d of us)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){if(s.slice(d.prefix.length)===d.suffix&&st(d.id,n))return d.id}if(Uw(a))return null;if(!s.includes(".")&&Fn.pattern.test(s)&&st(Fn.id,n))return Fn.id;let m=Hw(s,n);if(m)return m;return null}function zw(e,t,n,r,o){return Ur.find((i)=>{if(!st(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return W(e,B(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=G(e).split("/");return W(e,B(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||vr(e,"~/.claude.json",t,r,o)||s.at(-1)==="settings.local.json"&&s.at(-2)===".claude"||s.at(-1)===".mcp.json"}case"secret.cli.antigravity":return W(e,Ve("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=B(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return W(e,s,["auth.json",".credentials.json"])||Sr(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=B(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=G(e).split("/").at(-1)??"";return W(e,s,["config.toml"])||a.endsWith(".config.toml")&&W(e,s,[a])}case"secret.cli.gemini":return W(e,ce(B(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let s=G(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[ce(B(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return W(e,ce(B(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["settings.json","google_accounts.json"])||s.at(-1)==="settings.json"&&s.at(-2)===".gemini"||(a?.trim()?vr(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>W(e,Ve(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=B(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return W(e,s,["config.json"])||Sr(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return W(e,B(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=B(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=B(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return W(e,s,["server.token"])||Sr(e,s,["credentials"])||Sr(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=G(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||W(e,B(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||W(e,B(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=ce(B(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=G(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return W(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&W(e,s,[a])||c.some((u)=>vr(e,u,t,r,o))}case"secret.cli.opencode.config":{let s=r.env.get("OPENCODE_CONFIG_DIR")?B(r.env.get("OPENCODE_CONFIG_DIR"),"~/.config/opencode",t,r,o):ce(B(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[ce(B(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(G(e).split("/").at(-1)??"")||W(e,s,l)||(c?.trim()?vr(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((u)=>W(e,Ve(u,t,r,o),l))}case"secret.cli.pi":return W(e,B(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return W(e,B(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=Ve("~",t,r,o);return[ce(B(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),ce(s,".local","share","amp")].some((l)=>W(e,l,["secrets.json"]))||Sr(e,ce(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[ce(B(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),ce(Ve("~",t,r,o),".config","amp")],l=G(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((u)=>W(e,u,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?vr(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=ce(B(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=ce(B(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return W(e,Ve("~/.cursor",t,r,o),["auth.json"])||W(e,s,["auth.json"])||G(e).split("/").at(-1)==="mcp-auth.json"&&jt(G(e),G(a))}case"secret.cli.cursor.config":{let s=G(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return W(e,B(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=G(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||W(e,B(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||W(e,Ve("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var Xf=new WeakMap;function B(e,t,n,r,o){let i=Xf.get(o)??new Map;Xf.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=Ve(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function W(e,t,n){return n.some((r)=>dp(e,ce(t,r)))}function Sr(e,t,n){return n.some((r)=>jt(G(e),G(ce(t,r))))}function vr(e,t,n,r,o){return dp(e,Ve(t,n,r,o))}function dp(e,t){return G(e)===G(t)}function ce(e,...t){return $e([e,...t].filter(Boolean).join("/"))}function Bw(e,t,n,r,o,i){if(n.length===0)return!1;let s=G(Er(e,t,o,i));return n.some((a)=>jt(s,G(Er(a,r,o,i))))}function $w(e,t,n,r,o,i){if(n.length===0)return!1;let s=G(Er(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?$e(z(Ce(a),o.paths,i)):"",c=G(l),u=o.env.get("CC_SAFETY_NET_HOME"),m=G(u?$e(z(mi(Ce(u)),o.paths,i)):l&&$e(z(`${l}/.cc-safety-net`,o.paths,i)));if(m&&jt(s,m))return!1;return n.some((d)=>{let f=gs(d);if(f&&Qf.basename(s)!==G(f.name))return!1;let p=G(Er(f?.root??d,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return jt(s,p)&&!(f&&s===p)})}function Uw(e){let t=e.split("/");return t.some((n)=>Ww.has(n))||Fw.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function Hw(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of ds)if(r===o.extension&&st(o.id,t))return o.id;for(let o of ms)if(o.pattern.test(r)&&st(o.id,t))return o.id;return null}function G(e){return e.toLowerCase()}function st(e,t){return!t?.disabledRules?.includes(e)}function Ve(e,t,n,r){let{home:o,normalized:i}=al(e,n,r);if(!i)return"";if(!o)return i;let s=ll(i,o),a=ui(s)?s:$e(mi(t,s)),l=$e(z(a,n.paths,r));if(!jt(l,o)){if(ui(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function Jf(e,t){return e===t||e.startsWith(`${t}/`)}function jw(e,t,n,r){let{home:o,normalized:i}=al(e,n,r);if(!i||!o)return"";let s=ll(i,o),a=Qf.normalize(ui(s)?s:$e(mi(t,s))),l=$e(Ce(n.env.get("HOME")??n.home)),c=(d)=>process.platform==="win32"?d.toLowerCase():d,u=[o,l].find((d)=>d!==""&&jt(c(a),c(d)));if(u===void 0)return"";let m=a.slice(u.length);return m?`~${m}`:"~"}function Er(e,t,n,r){let{home:o,normalized:i}=al(e,n,r);if(!i)return"";let s=o?ll(i,o):i;return $e(z(ui(s)?s:mi(t,s),n.paths,r))}function al(e,t,n){let r=t.env.get("HOME")??t.home,o=r?$e(z(Ce(r),t.paths,n)):"",i=$e(Ce(Vw(et(e,t))));return{home:o,normalized:i}}function Vw(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return C_(e)}catch{return e}}function ll(e,t){if(e==="~")return t;if(e.startsWith("~/"))return ce(t,e.slice(2));return e}function Kw(e){if(process.platform==="win32")return!0;return b_.parse(e).root.length>1}function $e(e){let t=e.trim(),n=(t.includes("\\")&&Kw(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function jt(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function Ue(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class Vt extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var qw={findPolicyMutation:zf,findGitMetadataMutation:bd,resolveGitMetadata:Yw,loadPolicySnapshot:iu,findSensitiveTarget:op,analyzeCommand:kf,getModes:Li};function mp(e,t){let n={...qw,...t.dependencies},r=Jw(e),o=xr(e)?e.command:r,i=vt("policy-protection",o,()=>rr(e)),s=ge(i,"input-candidate"),a=ge(i,"declared-command");if(xr(e)&&e.command?.trim()&&a?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:He,intent:"stop_and_explain",evidence:{command:e.command,segment:e.command}}};if(s?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Wd,intent:"stop_and_explain"}};let l=be(),c=vt("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd],t.environment)),u=vt("policy-protection",o,()=>n.findPolicyMutation(i,t.environment,l));if(u){let E=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Gf,intent:"hard_stop",evidence:{command:E,segment:u.target}}}}let m=vt("policy-protection",o,()=>Nf(i,t.environment,l));if(m){let E=o??m.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Df,intent:"hard_stop",evidence:{command:E,segment:m.target}}}}let d=vt("policy-protection",o,()=>n.findGitMetadataMutation(i,c,t.environment,l));if(d){let E=o??d.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Te,intent:"hard_stop",evidence:{command:E,segment:d.target}}}}let f=vt("config-load",o,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),p=f.policy,g=n.getModes(p,t.environment.env),h={level:g.effectiveLevel,...Zw(f)},y=p.secretProtection.enabled===!1?null:vt("secret-protection",o,()=>n.findSensitiveTarget(i,p.secretProtection,t.environment,l,{strict:xr(e)||s?.program.dialect==="powershell"?g.strict:void 0}));if(y){let E=o??y.target;return{stage:"secret-protection",...h,decision:{kind:"deny",reason:ep,intent:"hard_stop",ruleId:y.ruleId,evidence:{command:E,segment:y.target}}}}if(!xr(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...cl("command-validation",o),...h};let S=vt("command-analysis",o,()=>Of(()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:f,environment:t.environment,protectedGitMetadata:c,effectiveCapabilities:g.capabilities,strict:g.strict,paranoidRm:g.paranoidRm,paranoidInterpreters:g.paranoidInterpreters,worktreeMode:g.worktreeMode,budget:l,...t.trace?{trace:t.trace}:{}},Xw(i),i.store),e.command,t.trace));if(S.decision){let E=!g.strict&&S.decision.kind==="deny"&&(S.decision.ruleId==="raw-text.dangerous-command"||S.decision.reason===ar&&!/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/.test(S.decision.evidence?.segment??"")&&Ae(e.command)===null);return{stage:"command-analysis",...h,..."errorCode"in S?{errorCode:S.errorCode}:{},decision:E?{...S.decision,ask:!0}:S.decision}}return{stage:"command-analysis",...h,decision:{kind:"allow"}}}function Yw(e,t){let n=[...new Set(e.filter((r)=>typeof r==="string"&&r!==""))].flatMap((r)=>t.gitMetadata(r)??[]);if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.flatMap((r)=>r.entries))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFiles))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function Zw(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function Xw(e){return ge(e,"declared-command")?.program}function Jw(e){try{return In(e.input)}catch(t){let n=xr(e)?e.command:void 0;throw new Vt("policy-protection",cl("policy-protection",t instanceof Ye?void 0:n,t),t)}}function vt(e,t,n){try{return n()}catch(r){throw new Vt(e,cl(e,r instanceof Ye?void 0:t,r),r)}}function cl(e,t,n){let r=n instanceof D||n instanceof Fe;return{stage:e,decision:{kind:"deny",reason:r?Ci:wn,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function xr(e){return e.route.kind==="command"}import{appendFileSync as dA,mkdirSync as mA}from"fs";import{isAbsolute as fA,join as ml}from"path";import{lstatSync as pp,readdirSync as Qw,readFileSync as eA,rmdirSync as tA,statSync as gp,unlinkSync as nA,utimesSync as rA,writeFileSync as oA}from"fs";import{join as Rr}from"path";function fp(e,t={}){return Jr(en(e,t),e.home).policy.audit.retention_days}var dl=86400000,iA=".last-prune",sA=/^\d{4}-\d{2}$/,aA=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,hp=(e)=>Math.floor(e/dl);function bp(e,t,n=()=>new Date){try{let r=n().getTime();if(!gp(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=Rr(t,iA),i=gp(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&hp(i)===hp(r))return;let s=r-fp(e)*dl,a=new Date(r).toISOString().slice(0,7);for(let l of ul(t)){if(l.isDirectory()){lA(Rr(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))cA(Rr(t,l.name),s)}oA(o,"",{mode:384}),rA(o,r/1000,r/1000)}catch{}}function lA(e,t,n){for(let r of ul(e)){if(!r.isDirectory()||!sA.test(r.name))continue;let o=Rr(e,r.name);for(let i of ul(o)){if(!i.isFile())continue;let s=aA.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+dl;if(!Number.isFinite(a)||a>=t)continue;Cp(Rr(o,i.name))}if(r.name!==n)yp(o)}yp(e)}function cA(e,t){try{let n=pp(e);if(n.mtimeMs>=t)return;let r=eA(e,"utf-8").split(`
|
|
48
|
-
`).filter((o)=>o.trim()).map(uA);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(pp(e).mtimeMs!==n.mtimeMs)return;Cp(e)}catch{}}function uA(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function ul(e){try{return Qw(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Cp(e){try{nA(e)}catch{}}function yp(e){try{tA(e)}catch{}}var pA="2.4.
|
|
48
|
+
`).filter((o)=>o.trim()).map(uA);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(pp(e).mtimeMs!==n.mtimeMs)return;Cp(e)}catch{}}function uA(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function ul(e){try{return Qw(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Cp(e){try{nA(e)}catch{}}function yp(e){try{tA(e)}catch{}}var pA="2.4.9",gA=1e4,hA=2000,yA=256,bA=32768;function CA(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function SA(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function fl(e,t,n,r,o,i,s={}){let a=CA(t);if(!a)return;let l=EA(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),u=pi(lt(n),s.failureStage?Number.POSITIVE_INFINITY:gA),m=pi(lt(r),hA),d=s.toolName?pi(lt(s.toolName),yA):void 0,f=i===null?void 0:pi(lt(i),bA),p=ml(l,SA(f?.value??null),c.slice(0,7));mA(p,{recursive:!0,mode:448});let g=ml(p,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??Fi)(),v:pA,sessionId:a,decision:s.decision??"deny",agent:s.agent,shape:s.shape,level:s.level,configFallback:s.configFallback,toolName:d?.value,command:u.value,segment:m.value,...u.truncated||m.truncated||d?.truncated||f?.truncated?{truncated:!0}:{},reason:o,ruleId:s.ruleId,intent:s.intent,failureStage:s.failureStage,errorCode:s.errorCode,cwd:f?.value??null};dA(g,`${JSON.stringify(h)}
|
|
49
49
|
`,{encoding:"utf-8",mode:384}),bp(e,l,s.now)}catch{}}function pi(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function vA(e){let t=e.env.get("CC_SAFETY_NET_AUDIT_HOME");if(e.env.get("NODE_ENV")==="test"&&!t)return null;let n=t||e.home;return n&&fA(n)?n:null}function EA(e){let t=vA(e);return t?ml(t,".cc-safety-net","logs"):null}function vp(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=Sp(e);return{decision:"allow",command:a,segment:a,reason:"allowed",cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{}}}let i=t.decision.evidence,s=i?.command??(r?Sp(e):"");return{decision:"deny",command:s,segment:i?.segment??s,reason:t.decision.reason,cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{},ruleId:t.decision.ruleId,intent:t.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function Sp(e){return"command"in e?e.command??"":""}function Ep(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;fl(e,o,t.command,t.segment,t.reason,t.cwd,{decision:t.decision,agent:r.agent,shape:r.shape,level:t.level,configFallback:t.configFallback,toolName:t.toolName,ruleId:t.ruleId,intent:t.intent,failureStage:t.failureStage,errorCode:t.errorCode})}function xp(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;fl(e,o,t.command??"",t.segment??t.command??"",t.reason,r.cwd??null,{decision:"deny",agent:r.agent,shape:r.shape,toolName:r.toolName??t.toolName,ruleId:t.ruleId,intent:t.intent})}function _p(e,t,n){try{let r=mp(t,{environment:e,...n.guard});return Rp(e,t,r,n),r}catch(r){if(!(r instanceof Vt))throw r;throw Rp(e,t,r.evaluation,n,!(r.cause instanceof Ye),{stage:r.stage,errorCode:xA(r.cause)}),r}}function Rp(e,t,n,r,o=!0,i){Ep(e,vp(t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function xA(e){if(e instanceof D)return V[e.kind].errorCode;if(e instanceof Ye)return"tool-input-limit";if(e instanceof Fe)return"structural-shell-syntax-limit";return"unexpected-error"}function Kt(e,t={}){return{malformed:!0,denial:An(t),cwd:e}}function wp(e,t={}){return(n,r)=>{try{return RA(n,r,e,t)}catch(o){return console.error("CC Safety Net error:",o),e.block(An())}}}function RA(e,t,n,r){let o=Zl();if(n.cancelled?.(t))return n.block(An());let i=n.extract(e,t,o.paths);if(!i)return n.allow;let s=()=>n.getSessionId(e,t);if("malformed"in i)return xp(o,i.denial,s,{agent:n.agent,toolName:i.denial.toolName,cwd:i.cwd}),n.block(i.denial);let a=(l,c)=>{let u=yl(l,{includeEvidence:c});return u?n.block(u):n.allow};try{let l=_p(o,i,{guard:{auditAllowed:Xl(o.env),policyOptions:r.policyOptions,dependencies:r.guardDependencies},audit:{agent:n.agent,getSessionId:s}});return a(l,!0)}catch(l){if(!(l instanceof Vt))throw l;if(xt(Q.debug,o.env))console.error(`CC Safety Net debug: ${n.debugLabel} analysis failed: ${Cl(l.cause)}`);return a(l.evaluation,n.includeEvidenceOnError(i))}}var _A={agent:"amp",debugLabel:"amp tool.call",extract:(e,t,n)=>AA(e,t,n),getSessionId:(e)=>IA(e),allow:{action:"allow"},block:(e)=>kA(e),includeEvidenceOnError:(e)=>e.route.kind==="command"},Ap=wA();function wA(e={}){return wp(_A,e)}function AA(e,t,n){if(!e||typeof e!=="object")return Kt(null);let r=e;if(typeof r.tool!=="string"||r.tool.trim()==="")return Kt(null);if(!r.input||typeof r.input!=="object")return Kt(null,{toolName:r.tool});let o=PA(t,n);if(!o)return Kt(null,{toolName:r.tool});let i=TA(t,e);if(!i.ok)return Kt(o,{toolName:r.tool});if(!i.command)return Yt(r.tool,r.input,{kind:xi(r.tool)},{configCwd:o,executionCwd:o},null);if(typeof i.command.command!=="string"||i.command.command.trim()==="")return Kt(o,{toolName:r.tool});let s=typeof i.command.dir==="string"?Ul(i.command.dir,o,n):o;if(!s)return{malformed:!0,denial:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative",command:i.command.command,segment:i.command.dir,toolName:r.tool},cwd:o};return Yt(r.tool,r.input,{kind:"command",shell:"posix"},{configCwd:o,executionCwd:s},i.command.command)}function PA(e,t){let n=e.system.workspaceRoot;if(!n)return;try{let r=e.helpers.filePathFromURI(n);if(typeof r!=="string"||r.trim()==="")return;return $l(".",[r],t)}catch{return}}function TA(e,t){try{return{ok:!0,command:e.helpers.shellCommandFromToolCall(t)}}catch{return{ok:!1}}}function IA(e){if(!e||typeof e!=="object")return;let t=e.thread?.id;return typeof t==="string"&&t.trim()!==""?t:void 0}function kA(e){return{action:"reject-and-continue",message:bl(e)}}function OA(e){e.on("tool.call",(t)=>Ap(t,e))}export{OA as default};
|
package/dist/bin/hook.js
CHANGED
|
@@ -43,5 +43,5 @@ var qp=["-h","--help"];function Kr(e,t){let n=Object.entries(e.booleans??{}),r=O
|
|
|
43
43
|
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function P_(e,t,n,r,o,i){let s=wt(e);if(s.length===0||ot(s[0]??"").toLowerCase()!=="xargs")return!1;let a=sn(s),l=s.slice(a.childStart);if(l.length===0)return!1;if(a.replacementToken==="")return!1;let c=a.replacementToken,u=c===null?[...l,cl]:l.map((m)=>m.split(c).join(cl));return Mi(u,t,n,r,o,i).some((m)=>m.target.includes(cl))}function T_(e){let t=wt(e);if(t.length===0)return null;let n=ot(t[0]??"").toLowerCase();if(!xr(n))return null;return I_(n,t.slice(1))?n:null}function I_(e,t){let n=yl(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(lp.has(o)||mp(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if(b_.get(n)?.has(o))r++;continue}return!1}return!0}function yl(e){return/^python\d/.test(e)?"python":e}function k_(e){let t=[];for(let n of e){if(pp(n))continue;let r=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(n);if(r===null)break;if(r[1]!==void 0&&r[1]!=="")t.push(r[1])}return t}var ep=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function O_(e,t){if(!t||!ep.test(e))return e;return`~${e.replace(ep,"").replace(/\\/g,"/")}`}function ct(e,t){if(t==="--")return[];let n=[],r=t.indexOf("=");if(r>0&&r<t.length-1)n.push(t.slice(r+1));if(t.startsWith("-"))return n;if(e==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(t))return n;if(e==="zip"&&/\.zip$/i.test(t))return n;return n.push(t),n}function M_(e){let t=-1,n=!1;for(let r=0;r<e.length;r++){let o=e[r]??"";if(!n&&o==="--"){n=!0;continue}if(n||!/^-(?:[A-Za-z]|-)/.test(o)){if(t===-1)t=r;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(o)){r+=2;continue}if(o==="--indent"||o==="-L"){r++;continue}if(o.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(o)||/^--(?:slurp|raw-output0?|join-output|compact-output|color-output|monochrome-output|ascii-output|unbuffered|sort-keys|raw-input|null-input|binary|tab|seq|stream|stream-errors|exit-status|args|jsonargs|help|version|build-configuration)$/.test(o))continue;return e.flatMap((i)=>ct("jq",i))}return e.flatMap((r,o)=>o===t?[]:ct("jq",r))}function D_(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??"";if(r==="--"||!r.startsWith("-"))return[...t,...s_.has(r)?ml("git",e.slice(n).map((i)=>/^-[aeinopqsv]+m$/.test(i)?"-m":i),a_):ml("git",e.slice(n),l_)];if(t.push(...ct("git",r)),!Me.has(r))continue;let o=e[n+1];if(o===void 0)break;t.push(...r==="-c"&&o.includes("=")?[o.slice(o.indexOf("=")+1)]:ct("git",o)),n++}return t}function ml(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o]??"";if(i==="--")return[...r,...t.slice(o).flatMap((s)=>ct(e,s))];if(n.has(i)){o++;continue}if(i.includes("=")&&n.has(i.slice(0,i.indexOf("="))))continue;r.push(...ct(e,i))}return r}function N_(e){return e.flatMap((t,n)=>{let r=W_(t);if(r!==null)return tp(r.flag,r.value);let o=L_(e[n-1]);return o===null?[]:tp(o,t)})}function tp(e,t){if(e==="-F"||e==="--form"){let n=t.indexOf("="),r=n===-1?t:t.slice(n+1);if(!r.startsWith("@")&&!r.startsWith("<"))return[];return ul(r.slice(1).split(";")[0]??"")}if(e==="--data-urlencode"){let n=t.indexOf("@"),r=t.indexOf("=");if(n===-1||r!==-1&&r<n)return[];return ul(t.slice(n+1))}return t.startsWith("@")?ul(t.slice(1)):[]}function L_(e){if(e===void 0)return null;if(ap.has(e))return e;return/^-[A-Za-z]+[dF]$/.test(e)?`-${e.slice(-1)}`:null}function W_(e){let t=e.slice(0,2);if(e.length>2&&(t==="-d"||t==="-F"))return{flag:t,value:e.slice(2)};let n=e.indexOf("=");if(n===-1)return null;let r=e.slice(0,n);return ap.has(r)?{flag:r,value:e.slice(n+1)}:null}function ul(e){return e===""||e==="-"?[]:[e]}function G_(e,t,n,r,o,i){let s=e.findIndex((l)=>l.startsWith("-")||l==="("||l==="!"||l===";"),a=[...e.slice(0,s===-1?e.length:s),...e.flatMap((l,c)=>l==="-files0-from"&&e[c+1]!==void 0?[e[c+1]??""]:[])];for(let l=0;l<e.length;l++){if(!XR.has(e[l]??""))continue;let c=e.slice(l+1),u=c.findIndex((f)=>JR.has(f)),m=u===-1?c:c.slice(0,u),d=Mi(m,t,n,r,o,i).map((f)=>f.target);if(a.push(...d.filter((f)=>f!=="{}")),!d.includes("{}"))continue;a.push(...e.slice(0,l).flatMap((f,p,g)=>{if(!e_.has(f))return[];let h=g[p+1];return h===void 0?[]:[h,h.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return a}function F_(e,t,n,r,o,i,s){let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c===void 0)break;if(lp.has(c)||mp(e,c)){let m=t[l+1];if(m!==void 0)a.push(...Oi(e,m,n,r,o,i,s)),l++;continue}let u=/^--(?:eval|exec)=(.*)$/.exec(c);if(u!==null&&u[1]!==void 0){a.push(...Oi(e,u[1],n,r,o,i,s));continue}if(!c.startsWith("-"))a.push({target:c,cwd:i})}return a}function mp(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return r_.get(t[t.length-1]??"")?.has(yl(e))??!1}function z_(e,t,n,r,o,i){if(!e.includes("system"))return[];return _a(e)?.commands.flatMap((s)=>Bn(t.getShellSyntax(s),t,n,r,o,i))??[]}function H_(e){return Array.from(e.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((t)=>t[1]).filter((t)=>t!==void 0&&t!=="")}function B_(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((n)=>n[2]).filter((n)=>n!==void 0&&n!=="");return[...t,...t.flatMap(Cl),...e.match(dl)??[]]}function Oi(e,t,n,r,o,i,s){let a=(g)=>({target:g,cwd:i}),l=$_(t,U_(e));if(l===null)return B_(t).map(a);let c=l.masked.match(Zf)!==null||l.literals.some((g)=>Xf.test(l.masked.slice(0,g.start))),u=l.masked.match(y_)!==null||l.literals.some((g)=>C_.test(l.masked.slice(0,g.start))),m=r.standard===!0&&!vr.has(e),d=m&&!(q_(l.masked)||c||u)?[]:l.literals,f=m?Array.from(l.masked.matchAll(Zf),(g)=>{let h=g.index+g[0].length;return{start:h,end:sa(l.masked,h)}}):[],p=!m||f.some((g)=>aa(l.masked,g.start))?l.literals:l.literals.filter((g)=>Xf.test(l.masked.slice(0,g.start))||f.some((h)=>g.start>=h.start&&g.start<h.end));return[...d.map((g)=>g.text).filter((g)=>g!=="").map(a),...d.flatMap((g)=>Cl(g.text)).map(a),...m?[]:l.literals.flatMap((g)=>g.text.match(dl)??[]).map(a),...c?p.flatMap((g)=>gl(g.text,n,r,o,i,s)??[a(g.text)]):[],...u?l.literals.flatMap((g)=>Oi(e,g.text.replace(/\\(.)/g,(h,y)=>y==="n"?`
|
|
44
44
|
`:y),n,r,o,i,s)):[],...(l.masked.match(dl)??[]).map(a)]}function U_(e){let t=yl(e);if(t==="python")return"python";if(t==="osascript")return"opaque";return t==="node"||t==="bun"||t==="deno"?"javascript":"simple"}function $_(e,t){if(t==="opaque")return null;let n=e.split(""),r=[];for(let o=0;o<e.length;o++){let i=e[o]??"";if(t==="simple"&&(i==="`"||i==="%"||i==="<")){if(g_.test(e.slice(o)))return null}let s=i==="'"||i==='"'||t==="javascript"&&i==="`"?i:null;if(s===null)continue;if(s==="`"&&K_(e,o))return null;let a=t==="python"?j_(e,o):"",l=t==="python"&&e.startsWith(s.repeat(3),o)?s.repeat(3):s,c=o+l.length,u=V_(e,c,l);if(u===null)return null;let m=e.slice(c,u);if(/[fF]/.test(a)&&m.includes("{"))return null;if(t==="simple"&&s==='"'&&h_.test(m))return null;r.push({start:c,text:m});for(let d=o;d<u+l.length;d++)n[d]=" ";o=u+l.length-1}return{masked:n.join(""),literals:r}}function j_(e,t){return p_.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function V_(e,t,n){let r=n==="`",o=r||n.length===3;for(let i=t;i<e.length;i++){let s=e[i];if(s==="\\"){i++;continue}if(r&&s==="$"&&e[i+1]==="{")return null;if(!o&&(s===`
|
|
45
45
|
`||s==="\r"))return null;if(e.startsWith(n,i))return i}return null}function K_(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function q_(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(t_.has(n.toLowerCase()))return!0;let o=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((i)=>i.toLowerCase());if(!o.some((i)=>n_.has(i)))continue;if(o.length>1)return!0;if(Y_(e,r)===".")return!0;if(Z_(e,r+n.length)==="(")return!0}return!1}function Y_(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function Z_(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function X_(e,t,n,r,o,i){return nw(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...Bn(a,t,{...n,capturedOutput:!0},r,o,i),...J_(a,r)?Q_(a,r).map((l)=>({target:l,cwd:o})):[]]})}function J_(e,t){let n=Yo(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||ot(Ct(o.text,t)).toLowerCase()!=="base64")continue;for(let i=r+1;i<n.length;i++){let s=n[i];if(s?.kind==="operator")break;if(s?.kind!=="word")continue;let a=Ct(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function Q_(e,t){return Yo(e).flatMap((n)=>n.kind==="word"?[Ct(n.text,t)]:n.kind==="redirection"&&n.target?[Ct(n.target,t)]:[]).flatMap(Cl)}function Cl(e){let t=tw(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||ew(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function ew(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function tw(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function nw(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(tr(o,n))continue;if(fp(e,r,n)){let i=rw(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=ow(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function rw(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(tr(i,n))continue;if(fp(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function ow(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function fp(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function iw(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let u=/^--([^=]+)(?:=(.*))?$/.exec(c);if(u!==null){let m=u[1]??"",d=u[2];if(m===c_)o=!0;if(d_.has(m))r=!0;if(d!==void 0){if(m===Yf)t.push(d);continue}if(f_.has(m)){let f=e[l+1];if(m===Yf&&f!==void 0)t.push(f);l++}continue}if(c.startsWith("-")&&c.length>1){let m=c.slice(1),d="",f="";for(let g=0;g<m.length;g++){let h=m[g]??"";if(u_.has(h))r=!0;if(m_.has(h)){d=h,f=m.slice(g+1);break}}if(d==="")continue;if(f.length>0){if(d===qf)t.push(f);continue}let p=e[l+1];if(d===qf&&p!==void 0)t.push(p);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function wt(e){let t=e.findIndex((n)=>!pp(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function pp(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var sw=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),aw=".env.",lw=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),cw=[".env.example.",".env.sample."];function uw(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function dw(e){return e.length>0&&!/\s/.test(e)}function fl(e,t,n,r){let o=gp(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function gp(e,t,n,r){try{return $r(e,t,n,r)}catch(o){if(o instanceof D)throw o;return""}}var mw=new Set(["node_modules","__pycache__"]),fw=[["vendor","bundle"],["vendor","cache"]];function pw(e,t,n,r,o){if(uw(e))return null;let i=lt(e,t,r,o);if(!i)return null;let s=U(i.split("/").pop()??""),a=U(i),l=()=>dw(s)||fl(e,t,r,o);if(lw.has(s)||cw.some((d)=>s.startsWith(d)))return null;let c=U(Sw(e,t,r,o));for(let d of Es){let f=`~/${d.suffixParts.join("/")}`;if((rp(a,f)||rp(c,f))&&_t(d.id,n))return d.id}let u=gw(i,t,n,r,o);if(u)return u;if(sw.has(s))return null;for(let d of vs)if(s===d.basename&&_t(d.id,n))return d.id;if(s.startsWith(aw)&&_t(fo.id,n)&&l())return fo.id;for(let d of xs)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){let f=s.slice(d.prefix.length)[0];if((f==="-"||f==="_")&&_t(d.id,n)&&l())return d.id}for(let d of Rs)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){if(s.slice(d.prefix.length)===d.suffix&&_t(d.id,n))return d.id}if(Cw(a))return null;if(!s.includes(".")&&rr.pattern.test(s)&&_t(rr.id,n))return rr.id;let m=bw(s,n);if(m)return m;return null}function gw(e,t,n,r,o){return po.find((i)=>{if(!_t(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return H(e,V(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=U(e).split("/");return H(e,V(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||Ur(e,"~/.claude.json",t,r,o)||s.at(-1)==="settings.local.json"&&s.at(-2)===".claude"||s.at(-1)===".mcp.json"}case"secret.cli.antigravity":return H(e,lt("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=V(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return H(e,s,["auth.json",".credentials.json"])||Br(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=V(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=U(e).split("/").at(-1)??"";return H(e,s,["config.toml"])||a.endsWith(".config.toml")&&H(e,s,[a])}case"secret.cli.gemini":return H(e,be(V(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let s=U(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[be(V(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return H(e,be(V(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["settings.json","google_accounts.json"])||s.at(-1)==="settings.json"&&s.at(-2)===".gemini"||(a?.trim()?Ur(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>H(e,lt(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=V(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return H(e,s,["config.json"])||Br(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return H(e,V(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=V(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=V(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return H(e,s,["server.token"])||Br(e,s,["credentials"])||Br(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=U(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||H(e,V(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||H(e,V(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=be(V(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=U(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return H(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&H(e,s,[a])||c.some((u)=>Ur(e,u,t,r,o))}case"secret.cli.opencode.config":{let s=r.env.get("OPENCODE_CONFIG_DIR")?V(r.env.get("OPENCODE_CONFIG_DIR"),"~/.config/opencode",t,r,o):be(V(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[be(V(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(U(e).split("/").at(-1)??"")||H(e,s,l)||(c?.trim()?Ur(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((u)=>H(e,lt(u,t,r,o),l))}case"secret.cli.pi":return H(e,V(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return H(e,V(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=lt("~",t,r,o);return[be(V(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),be(s,".local","share","amp")].some((l)=>H(e,l,["secrets.json"]))||Br(e,be(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[be(V(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),be(lt("~",t,r,o),".config","amp")],l=U(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((u)=>H(e,u,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?Ur(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=be(V(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=be(V(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return H(e,lt("~/.cursor",t,r,o),["auth.json"])||H(e,s,["auth.json"])||U(e).split("/").at(-1)==="mcp-auth.json"&&cn(U(e),U(a))}case"secret.cli.cursor.config":{let s=U(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return H(e,V(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=U(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||H(e,V(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||H(e,lt("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var np=new WeakMap;function V(e,t,n,r,o){let i=np.get(o)??new Map;np.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=lt(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function H(e,t,n){return n.some((r)=>hp(e,be(t,r)))}function Br(e,t,n){return n.some((r)=>cn(U(e),U(be(t,r))))}function Ur(e,t,n,r,o){return hp(e,lt(t,n,r,o))}function hp(e,t){return U(e)===U(t)}function be(e,...t){return rt([e,...t].filter(Boolean).join("/"))}function hw(e,t,n,r,o,i){if(n.length===0)return!1;let s=U($r(e,t,o,i));return n.some((a)=>cn(s,U($r(a,r,o,i))))}function yw(e,t,n,r,o,i){if(n.length===0)return!1;let s=U($r(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?rt(N(Oe(a),o.paths,i)):"",c=U(l),u=o.env.get("CC_SAFETY_NET_HOME"),m=U(u?rt(N(xe.resolve(Oe(u)),o.paths,i)):l&&rt(N(`${l}/.cc-safety-net`,o.paths,i)));if(m&&cn(s,m))return!1;return n.some((d)=>{let f=Ps(d);if(f&&xe.posix.basename(s)!==U(f.name))return!1;let p=U($r(f?.root??d,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return cn(s,p)&&!(f&&s===p)})}function Cw(e){let t=e.split("/");return t.some((n)=>mw.has(n))||fw.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function bw(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of _s)if(r===o.extension&&_t(o.id,t))return o.id;for(let o of ws)if(o.pattern.test(r)&&_t(o.id,t))return o.id;return null}function U(e){return e.toLowerCase()}function _t(e,t){return!t?.disabledRules?.includes(e)}function lt(e,t,n,r){let{home:o,normalized:i}=bl(e,n,r);if(!i)return"";if(!o)return i;let s=Sl(i,o),a=xe.isAbsolute(s)?s:rt(xe.resolve(t,s)),l=rt(N(a,n.paths,r));if(!cn(l,o)){if(xe.isAbsolute(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function rp(e,t){return e===t||e.startsWith(`${t}/`)}function Sw(e,t,n,r){let{home:o,normalized:i}=bl(e,n,r);if(!i||!o)return"";let s=Sl(i,o),a=xe.posix.normalize(xe.isAbsolute(s)?s:rt(xe.resolve(t,s))),l=rt(Oe(n.env.get("HOME")??n.home)),c=(d)=>process.platform==="win32"?d.toLowerCase():d,u=[o,l].find((d)=>d!==""&&cn(c(a),c(d)));if(u===void 0)return"";let m=a.slice(u.length);return m?`~${m}`:"~"}function $r(e,t,n,r){let{home:o,normalized:i}=bl(e,n,r);if(!i)return"";let s=o?Sl(i,o):i;return rt(N(xe.isAbsolute(s)?s:xe.resolve(t,s),n.paths,r))}function bl(e,t,n){let r=t.env.get("HOME")??t.home,o=r?rt(N(Oe(r),t.paths,n)):"",i=rt(Oe(vw(Ct(e,t))));return{home:o,normalized:i}}function vw(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return op.fileURLToPath(e)}catch{return e}}function Sl(e,t){if(e==="~")return t;if(e.startsWith("~/"))return be(t,e.slice(2));return e}function Ew(e){if(process.platform==="win32")return!0;return xe.win32.parse(e).root.length>1}function rt(e){let t=e.trim(),n=(t.includes("\\")&&Ew(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function cn(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function ot(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class un extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var xw={findPolicyMutation:jf,findGitMetadataMutation:_d,resolveGitMetadata:Rw,loadPolicySnapshot:hu,findSensitiveTarget:cp,analyzeCommand:Lf,getModes:rs};function yp(e,t){let n={...xw,...t.dependencies},r=Aw(e),o=jr(e)?e.command:r,i=Bt("policy-protection",o,()=>Rr(e)),s=Pe(i,"input-candidate"),a=Pe(i,"declared-command");if(jr(e)&&e.command?.trim()&&a?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:it,intent:"stop_and_explain",evidence:{command:e.command,segment:e.command}}};if(s?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:zd,intent:"stop_and_explain"}};let l=de(),c=Bt("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd],t.environment)),u=Bt("policy-protection",o,()=>n.findPolicyMutation(i,t.environment,l));if(u){let E=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:$f,intent:"hard_stop",evidence:{command:E,segment:u.target}}}}let m=Bt("policy-protection",o,()=>zf(i,t.environment,l));if(m){let E=o??m.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ff,intent:"hard_stop",evidence:{command:E,segment:m.target}}}}let d=Bt("policy-protection",o,()=>n.findGitMetadataMutation(i,c,t.environment,l));if(d){let E=o??d.target;return{stage:"policy-protection",decision:{kind:"deny",reason:$e,intent:"hard_stop",evidence:{command:E,segment:d.target}}}}let f=Bt("config-load",o,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),p=f.policy,g=n.getModes(p,t.environment.env),h={level:g.effectiveLevel,..._w(f)},y=p.secretProtection.enabled===!1?null:Bt("secret-protection",o,()=>n.findSensitiveTarget(i,p.secretProtection,t.environment,l,{strict:jr(e)||s?.program.dialect==="powershell"?g.strict:void 0}));if(y){let E=o??y.target;return{stage:"secret-protection",...h,decision:{kind:"deny",reason:ip,intent:"hard_stop",ruleId:y.ruleId,evidence:{command:E,segment:y.target}}}}if(!jr(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...vl("command-validation",o),...h};let b=Bt("command-analysis",o,()=>Wf(()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:f,environment:t.environment,protectedGitMetadata:c,effectiveCapabilities:g.capabilities,strict:g.strict,paranoidRm:g.paranoidRm,paranoidInterpreters:g.paranoidInterpreters,worktreeMode:g.worktreeMode,budget:l,...t.trace?{trace:t.trace}:{}},ww(i),i.store),e.command,t.trace));if(b.decision){let E=!g.strict&&b.decision.kind==="deny"&&(b.decision.ruleId==="raw-text.dangerous-command"||b.decision.reason===Pr&&!/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/.test(b.decision.evidence?.segment??"")&&Be(e.command)===null);return{stage:"command-analysis",...h,..."errorCode"in b?{errorCode:b.errorCode}:{},decision:E?{...b.decision,ask:!0}:b.decision}}return{stage:"command-analysis",...h,decision:{kind:"allow"}}}function Rw(e,t){let n=[...new Set(e.filter((r)=>typeof r==="string"&&r!==""))].flatMap((r)=>t.gitMetadata(r)??[]);if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.flatMap((r)=>r.entries))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFiles))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function _w(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function ww(e){return Pe(e,"declared-command")?.program}function Aw(e){try{return Pt(e.input)}catch(t){let n=jr(e)?e.command:void 0;throw new un("policy-protection",vl("policy-protection",t instanceof ve?void 0:n,t),t)}}function Bt(e,t,n){try{return n()}catch(r){throw new un(e,vl(e,r instanceof ve?void 0:t,r),r)}}function vl(e,t,n){let r=n instanceof D||n instanceof Qe;return{stage:e,decision:{kind:"deny",reason:r?Bi:qn,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function jr(e){return e.route.kind==="command"}var Ni=require("node:fs"),$n=require("node:path");var le=require("node:fs"),Un=require("node:path");function Cp(e,t={}){return xo(Cn(e,t),e.home).policy.audit.retention_days}var xl=86400000,Pw=".last-prune",Tw=/^\d{4}-\d{2}$/,Iw=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,bp=(e)=>Math.floor(e/xl);function vp(e,t,n=()=>new Date){try{let r=n().getTime();if(!le.statSync(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=Un.join(t,Pw),i=le.statSync(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&bp(i)===bp(r))return;let s=r-Cp(e)*xl,a=new Date(r).toISOString().slice(0,7);for(let l of El(t)){if(l.isDirectory()){kw(Un.join(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))Ow(Un.join(t,l.name),s)}le.writeFileSync(o,"",{mode:384}),le.utimesSync(o,r/1000,r/1000)}catch{}}function kw(e,t,n){for(let r of El(e)){if(!r.isDirectory()||!Tw.test(r.name))continue;let o=Un.join(e,r.name);for(let i of El(o)){if(!i.isFile())continue;let s=Iw.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+xl;if(!Number.isFinite(a)||a>=t)continue;Ep(Un.join(o,i.name))}if(r.name!==n)Sp(o)}Sp(e)}function Ow(e,t){try{let n=le.lstatSync(e);if(n.mtimeMs>=t)return;let r=le.readFileSync(e,"utf-8").split(`
|
|
46
|
-
`).filter((o)=>o.trim()).map(Mw);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(le.lstatSync(e).mtimeMs!==n.mtimeMs)return;Ep(e)}catch{}}function Mw(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function El(e){try{return le.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Ep(e){try{le.unlinkSync(e)}catch{}}function Sp(e){try{le.rmdirSync(e)}catch{}}var Dw="2.4.
|
|
46
|
+
`).filter((o)=>o.trim()).map(Mw);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(le.lstatSync(e).mtimeMs!==n.mtimeMs)return;Ep(e)}catch{}}function Mw(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function El(e){try{return le.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Ep(e){try{le.unlinkSync(e)}catch{}}function Sp(e){try{le.rmdirSync(e)}catch{}}var Dw="2.4.9",Nw=1e4,Lw=2000,Ww=256,Gw=32768;function Fw(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function zw(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function Rl(e,t,n,r,o,i,s={}){let a=Fw(t);if(!a)return;let l=Bw(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),u=Di(mt(n),s.failureStage?Number.POSITIVE_INFINITY:Nw),m=Di(mt(r),Lw),d=s.toolName?Di(mt(s.toolName),Ww):void 0,f=i===null?void 0:Di(mt(i),Gw),p=$n.join(l,zw(f?.value??null),c.slice(0,7));Ni.mkdirSync(p,{recursive:!0,mode:448});let g=$n.join(p,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??is)(),v:Dw,sessionId:a,decision:s.decision??"deny",agent:s.agent,shape:s.shape,level:s.level,configFallback:s.configFallback,toolName:d?.value,command:u.value,segment:m.value,...u.truncated||m.truncated||d?.truncated||f?.truncated?{truncated:!0}:{},reason:o,ruleId:s.ruleId,intent:s.intent,failureStage:s.failureStage,errorCode:s.errorCode,cwd:f?.value??null};Ni.appendFileSync(g,`${JSON.stringify(h)}
|
|
47
47
|
`,{encoding:"utf-8",mode:384}),vp(e,l,s.now)}catch{}}function Di(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function Hw(e){let t=e.env.get("CC_SAFETY_NET_AUDIT_HOME");if(e.env.get("NODE_ENV")==="test"&&!t)return null;let n=t||e.home;return n&&$n.isAbsolute(n)?n:null}function Bw(e){let t=Hw(e);return t?$n.join(t,".cc-safety-net","logs"):null}function Rp(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=xp(e);return{decision:"allow",command:a,segment:a,reason:"allowed",cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{}}}let i=t.decision.evidence,s=i?.command??(r?xp(e):"");return{decision:"deny",command:s,segment:i?.segment??s,reason:t.decision.reason,cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{},ruleId:t.decision.ruleId,intent:t.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function xp(e){return"command"in e?e.command??"":""}function _p(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Rl(e,o,t.command,t.segment,t.reason,t.cwd,{decision:t.decision,agent:r.agent,shape:r.shape,level:t.level,configFallback:t.configFallback,toolName:t.toolName,ruleId:t.ruleId,intent:t.intent,failureStage:t.failureStage,errorCode:t.errorCode})}function wp(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Rl(e,o,t.command??"",t.segment??t.command??"",t.reason,r.cwd??null,{decision:"deny",agent:r.agent,shape:r.shape,toolName:r.toolName??t.toolName,ruleId:t.ruleId,intent:t.intent})}function Pp(e,t,n){try{let r=yp(t,{environment:e,...n.guard});return Ap(e,t,r,n),r}catch(r){if(!(r instanceof un))throw r;throw Ap(e,t,r.evaluation,n,!(r.cause instanceof ve),{stage:r.stage,errorCode:Uw(r.cause)}),r}}function Ap(e,t,n,r,o=!0,i){_p(e,Rp(t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function Uw(e){if(e instanceof D)return X[e.kind].errorCode;if(e instanceof ve)return"tool-input-limit";if(e instanceof Qe)return"structural-shell-syntax-limit";return"unexpected-error"}var ut=(e,t,n,r,o)=>Ql(e.cwd,t,n,r,o.paths,process.cwd());function $w(e,t){console.log(JSON.stringify(e(Il(t))))}async function jw(e){let t;try{t=(await Jl(process.stdin)).trim()}catch{e({reason:"Failed to parse hook input JSON."});return}if(!t){e({reason:"Missing hook input JSON."});return}return Qr(t,e,"Failed to parse hook input JSON.")}async function Vw(e){let t=cc(),n=await jw(e.outputDeny);if(n===void 0)return;if(!n||typeof n!=="object"||Array.isArray(n)){ee(e.outputDeny);return}if(!e.isSupported(n))return;let r=e.getAgent?.(n,t)??e.agent,o=e.agent===r?void 0:e.agent,i=Zw(n),s=(p,g)=>{wp(t,p,()=>e.getSessionId(n),{agent:r,shape:o,toolName:g,cwd:i}),e.outputDeny(p)},a=e.getToolName(n);if(typeof a!=="string"||a.trim()===""){ee((p)=>s(p),Yw(n));return}let l=a,c=(p)=>s(p,l),u;try{u=e.getToolInput(n,l,c,t)}catch(p){if(!(p instanceof ve))throw p;ee(c,void 0,l);return}if(!u.ok)return;let m=e.getContext(n,u.input,l,c,t);if(!m)return;let d;try{d=Pt(u.input)}catch(p){if(!(p instanceof ve))throw p;ee(c,void 0,l);return}let f=Jn(l,u.input,u.route,m,d??null);try{let p=Pp(t,f,{guard:{auditAllowed:uc(t.env),dependencies:e.guardDependencies},audit:{agent:r,shape:o,getSessionId:()=>e.getSessionId(n)}}),g=Ui(p,{includeEvidence:!0,toolName:p.stage==="command-analysis"?void 0:l});if(g){if(g.ask&&e.outputAsk?.(n,g))return;e.outputDeny(g);return}e.outputAllow?.()}catch(p){if(!(p instanceof un))throw p;Kw(p,t.env);let g=Ui(p.evaluation,{includeEvidence:!0,toolName:p.evaluation.stage==="command-analysis"?void 0:l});if(g)e.outputDeny(g);return}}function Kw(e,t){if(!$t(ae.debug,t))return;console.error(`CC Safety Net debug: ${qw(e.stage)}: ${Ol(e.cause)}`)}function qw(e){if(e==="policy-protection")return"hook policy protection failed";if(e==="config-load")return"hook config loading failed";if(e==="secret-protection")return"hook secret protection failed";return"hook analysis failed"}function Yw(e){if(!e||typeof e!=="object"||Array.isArray(e))return;if(Object.hasOwn(e,"tool_input"))return e.tool_input;let t=e.toolCall;if(t&&typeof t==="object"&&!Array.isArray(t))return t.args;return}function Zw(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let t=e.cwd;if(typeof t==="string")return t;let n=e.toolCall;if(!n||typeof n!=="object"||Array.isArray(n))return null;let r=n.args;if(!r||typeof r!=="object"||Array.isArray(r))return null;let o=r.Cwd;return typeof o==="string"?o:null}async function ke(e){let t=(s)=>$w(e.createDenyOutput,s),n=e.createAskOutput,r=n?(s,a)=>{let l=n(s,kl(a));if(l===null)return!1;return console.log(JSON.stringify(l)),!0}:void 0,o=e.createAllowOutput,i=o?()=>console.log(JSON.stringify(o())):void 0;try{await Vw({...e,outputDeny:t,outputAsk:r,outputAllow:i})}catch(s){console.error("CC Safety Net error:",s),t(pn())}}var Xw=new Map([["run_command","auto"]]),Jw=new Set(["absolutepath","directorypath","file_path","filepath","path","searchdirectory","searchpath","target_file","targetfile"]);function Tp(e){return se(e,Xw)}async function Ip(){await ke({agent:"antigravity-cli",createDenyOutput:(e)=>({decision:"deny",reason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolCall?.name,getToolInput:(e,t)=>({ok:!0,input:rA(e.toolCall?.args,t),route:Tp(t)}),getContext:Qw,getSessionId:(e)=>e.conversationId})}function Qw(e,t,n,r,o){let s=nA(e,o.paths).flatMap((u)=>{let m=at([u],o.paths);return m?[m]:[]});if(!s[0])return dn(r,t,n),null;if(n!=="run_command"){let u;try{u=eA(t,n,s,o.paths)}catch(m){if(m instanceof ve)return dn(r,void 0,n),null;if(!(m instanceof D))throw m;return dn(r,t,n),null}if(!u)return dn(r,t,n),null;return{configCwd:u,executionCwd:u}}let a=e.toolCall?.args;if(!a||!Object.hasOwn(a,"Cwd"))return{configCwd:s[0],executionCwd:s[0]};let l=a.Cwd;if(typeof l!=="string"||l.trim()==="")return dn(r,t,n),null;let c=pt(l,s,o.paths);if(c){let u=kp(c,s);if(!u)return dn(r,t,n,l),null;return{configCwd:u,executionCwd:c}}return dn(r,t,n,l),null}function eA(e,t,n,r){let o=Tp(t),i=[...Xr(e,Jw),...o.kind==="patch"?Jr(e):[]].filter(jn.isAbsolute),s=de(),a=new Set(i.flatMap((l)=>{let c=kp(N(l,r,s),n);return c?[c]:[]}));if(a.size>1)return null;return[...a][0]??n[0]??null}function kp(e,t){return t.filter((n)=>tA(e,n)).reduce((n,r)=>r.length>n.length?r:n,"")||null}function tA(e,t){let n=jn.relative(t,e);return n===""||!n.startsWith("..")&&!jn.isAbsolute(n)}function dn(e,t,n,r){let o=t&&typeof t==="object"?t.command:void 0;e(pn({command:typeof o==="string"?o:void 0,segment:r,toolName:n}))}function nA(e,t){if(e.workspacePaths===void 0)return[process.cwd()];let n=Array.isArray(e.workspacePaths)?e.workspacePaths.filter((r)=>typeof r==="string"&&r.trim()!==""):[];return at(n,t)?n:[]}function rA(e,t){if(!e)return;if(t!=="run_command")return e;return{...e,command:typeof e.CommandLine==="string"&&e.CommandLine!==""?e.CommandLine:void 0}}var Li=[{id:"antigravity-cli",displayName:"Antigravity CLI",doctorOrder:3,runtime:{order:1,flags:["-ac","--agy-cli"],description:"Run as Antigravity CLI PreToolUse hook",legacyTopLevelFlags:[]},install:{order:2,flag:"--agy-cli",artifactKind:"hook config",probeCommand:["agy","--version"]}},{id:"claude-code",displayName:"Claude Code",doctorOrder:1,runtime:{order:2,displayName:"Coding CLI",flags:["-cc","--coding-cli"],legacyFlags:["--claude-code"],description:"Run as Coding CLI PreToolUse hook",legacyTopLevelFlags:["-cc","--claude-code"]},install:{order:3,flag:"--claude-code",artifactKind:"plugin",probeCommand:["claude","--version"]}},{id:"codex",displayName:"Codex",doctorOrder:4,runtime:{order:3,flags:["-cx","--codex"],description:"Run as a Codex PreToolUse hook",legacyTopLevelFlags:[]},install:{order:4,flag:"--codex",artifactKind:"plugin",probeCommand:["codex","--version"]}},{id:"copilot-cli",displayName:"GitHub Copilot CLI",doctorOrder:7,runtime:{order:6,flags:["-cp","--copilot-cli"],description:"Run as GitHub Copilot CLI PreToolUse hook",legacyTopLevelFlags:["-cp","--copilot-cli"]},install:{order:7,flag:"--copilot-cli",artifactKind:"plugin",probeCommand:["copilot","--binary-version"]}},{id:"gemini-cli",displayName:"Gemini CLI",doctorOrder:6,runtime:{order:5,flags:["-gc","--gemini-cli"],description:"Run as Gemini CLI BeforeTool hook",legacyTopLevelFlags:["-gc","--gemini-cli"]},install:{order:6,flag:"--gemini-cli",artifactKind:"extension",probeCommand:["gemini","--version"]}},{id:"grok-build",displayName:"Grok Build",doctorOrder:8,runtime:{order:7,flags:["-gb","--grok-build"],description:"Run as Grok Build PreToolUse hook",legacyTopLevelFlags:[]},install:{order:8,flag:"--grok-build",artifactKind:"hook config",probeCommand:["grok","--version"]}},{id:"hermes-agent",displayName:"Hermes Agent",doctorOrder:9,runtime:{order:8,flags:["-ha","--hermes-agent"],description:"Run as Hermes Agent pre_tool_call hook",legacyTopLevelFlags:[]},install:{order:9,flag:"--hermes-agent",artifactKind:"plugin",probeCommand:["hermes","--version"]}},{id:"kimi-code",displayName:"Kimi Code",doctorOrder:10,runtime:{order:9,flags:["-kc","--kimi-code"],description:"Run as Kimi Code PreToolUse hook",legacyTopLevelFlags:[]},install:{order:10,flag:"--kimi-code",artifactKind:"hook config",probeCommand:["kimi","--version"]}},{id:"openclaw",displayName:"OpenClaw",doctorOrder:11,install:{order:11,flag:"--openclaw",artifactKind:"plugin",probeCommand:["openclaw","--version"]}},{id:"opencode",displayName:"OpenCode",doctorOrder:12,install:{order:12,flag:"--opencode",artifactKind:"plugin",probeCommand:["opencode","--version"]}},{id:"pi",displayName:"Pi",doctorOrder:13,install:{order:13,flag:"--pi",artifactKind:"package",probeCommand:["pi","--version"]}},{id:"cursor",displayName:"Cursor",doctorOrder:5,runtime:{order:4,flags:["-cu","--cursor"],description:"Run as Cursor preToolUse hook",legacyTopLevelFlags:[]},install:{order:5,flag:"--cursor",artifactKind:"hook config",probeCommand:["cursor","--version"]}},{id:"amp",displayName:"Amp Code",doctorOrder:2,install:{order:1,flag:"--amp",artifactKind:"plugin",probeCommand:["amp","--version"]}}],nL=Li.slice().sort((e,t)=>e.doctorOrder-t.doctorOrder).map((e)=>e.id),Op=Li.filter((e)=>("runtime"in e)).slice().sort((e,t)=>e.runtime.order-t.runtime.order).map((e)=>({id:e.id,displayName:"displayName"in e.runtime?e.runtime.displayName:e.displayName,flags:e.runtime.flags,legacyFlags:"legacyFlags"in e.runtime?e.runtime.legacyFlags:[],description:e.runtime.description,legacyTopLevelFlags:e.runtime.legacyTopLevelFlags})),rL=Li.slice().sort((e,t)=>e.install.order-t.install.order).map((e)=>({id:e.id,...e.install})).map(({order:e,...t})=>t),oL=Object.fromEntries(Li.map((e)=>[e.id,e.displayName]));var mn=require("node:path");function Mp(e,t){if(e!==void 0&&e!==null&&typeof e!=="string")return"unknown";if(typeof e==="string"&&!mn.isAbsolute(e))return"unknown";try{let n=de(),r=typeof e==="string"&&e?N(e,t.paths,n):void 0,o=t.home,i=[["codex",t.env.get("CODEX_HOME")||mn.join(o,".codex")],["copilot-cli",t.env.get("COPILOT_HOME")||mn.join(o,".copilot")],["claude-code",t.env.get("CLAUDE_CONFIG_DIR")||mn.join(o,".claude")]],s=r?i.flatMap(([a,l])=>{if(!mn.isAbsolute(l))return[];return Ji(r,N(l,t.paths,n))?[a]:[]}):[];if(s.length===1)return s[0]??"unknown";if(s.length>1)return"unknown"}catch{return"unknown"}if(t.env.get("CLAUDECODE")==="1"||Boolean(t.env.get("CLAUDE_CODE_ENTRYPOINT")))return"claude-code";return"unknown"}var Wi="PreToolUse",Dp="BeforeTool",Np="pre_tool_call";async function Vn(e){await ke({agent:e.agent,...e.getAgent?{getAgent:e.getAgent}:{},createDenyOutput:(t)=>({hookSpecificOutput:{hookEventName:Wi,permissionDecision:"deny",permissionDecisionReason:t}}),...e.canAsk?{createAskOutput:(t,n)=>e.canAsk?.(t)?{hookSpecificOutput:{hookEventName:Wi,permissionDecision:"ask",permissionDecisionReason:n}}:null}:{},isSupported:(t)=>t.hook_event_name===Wi,getToolName:(t)=>t.tool_name,getToolInput:(t,n)=>({ok:!0,input:t.tool_input,route:e.getToolRoute(n)}),getContext:e.getContext??ut,getSessionId:(t)=>t.session_id})}var oA=new Map([["Bash","posix"],["PowerShell","powershell"]]);function iA(e){return se(e,oA)}async function Lp(){await Vn({agent:"claude-code",getAgent:(e,t)=>Mp(e.transcript_path,t),canAsk:(e)=>["default","acceptEdits","plan"].includes(e.permission_mode??""),getToolRoute:iA})}var sA=new Map([["Bash","auto"]]);async function Wp(){await Vn({agent:"codex",getToolRoute:(e)=>se(e,sA)})}var aA=new Map([["bash","auto"],["Bash","auto"],["powershell","powershell"],["PowerShell","powershell"]]);function lA(e){return se(e,aA)}async function Gp(){await ke({agent:"copilot-cli",createDenyOutput:(e)=>({permissionDecision:"deny",permissionDecisionReason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolName,getToolInput:(e,t,n)=>{if(typeof e.toolArgs!=="string")return n({reason:"Failed to parse toolArgs JSON."}),{ok:!1};let r=Qr(e.toolArgs,n,"Failed to parse toolArgs JSON.");if(r===void 0)return{ok:!1};return{ok:!0,input:r,route:lA(t)}},getContext:ut,getSessionId:(e)=>typeof e.sessionId==="string"&&e.sessionId.trim()?e.sessionId:void 0})}var cA=new Map([["Shell","auto"]]);function uA(e){return se(e,cA)}async function Fp(){await ke({agent:"cursor",createDenyOutput:(e)=>({permission:"deny",user_message:e,agent_message:e}),createAllowOutput:()=>({permission:"allow"}),isSupported:()=>!0,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:uA(t)}),getContext:dA,getSessionId:(e)=>e.conversation_id})}function dA(e,t,n,r,o){let i=mA(e,o.paths);if(!i[0])return ee(r,t,n),null;let s=pt(pA(e.cwd),i,o.paths);if(!s)return ee(r,t,n,typeof e.cwd==="string"?e.cwd:void 0),null;if(t===null||typeof t!=="object"||Array.isArray(t))return{configCwd:s,executionCwd:s};if(!Object.hasOwn(t,"working_directory"))return{configCwd:s,executionCwd:s};let a=t.working_directory;if(typeof a!=="string"||a.trim()==="")return ee(r,t,n),null;let l=pt(a,i,o.paths);if(!l)return ee(r,t,n,a),null;return{configCwd:s,executionCwd:l}}function mA(e,t){return fA(e).flatMap((n)=>{let r=at([n],t);return r?[r]:[]})}function fA(e){if(e.workspace_roots===void 0)return typeof e.cwd==="string"&&e.cwd.trim()!==""?[e.cwd]:[];if(!Array.isArray(e.workspace_roots))return[];return e.workspace_roots.filter((t)=>typeof t==="string"&&t.trim()!=="")}function pA(e){return typeof e==="string"&&e.trim()!==""?e:"."}var gA=new Map([["run_shell_command","auto"]]);function hA(e){return se(e,gA)}async function zp(){await ke({agent:"gemini-cli",createDenyOutput:(e)=>({decision:"deny",reason:e,systemMessage:e}),isSupported:(e)=>e.hook_event_name===Dp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:hA(t)}),getContext:ut,getSessionId:(e)=>e.session_id})}var yA=new Map([["run_terminal_command","auto"]]);function CA(e){return se(e,yA)}async function Hp(){await ke({agent:"grok-build",createDenyOutput:(e)=>({decision:"deny",reason:e}),createAllowOutput:()=>({decision:"allow"}),isSupported:()=>!0,getToolName:(e)=>e.toolName,getToolInput:(e,t,n)=>{if(e.toolInputTruncated===!0)return ee(n,e.toolInput,t),{ok:!1};return{ok:!0,input:e.toolInput,route:CA(t)}},getContext:bA,getSessionId:(e)=>e.sessionId})}function bA(e,t,n,r,o){let i=at(SA(e),o.paths);if(!i)return ee(r,t,n),null;let s=pt(vA(e.cwd),[i],o.paths);if(!s)return ee(r,t,n,typeof e.cwd==="string"?e.cwd:void 0),null;return{configCwd:s,executionCwd:s}}function SA(e){let t=e.workspaceRoot===void 0?e.cwd:e.workspaceRoot;return typeof t==="string"&&t.trim()!==""?[t]:[]}function vA(e){return typeof e==="string"&&e.trim()!==""?e:"."}var Bp=require("node:path");var EA=new Map([["terminal","posix"]]);async function Up(){await ke({agent:"hermes-agent",createDenyOutput:(e)=>({action:"block",message:e}),isSupported:(e)=>e.hook_event_name===Np,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:se(t,EA)}),getContext:xA,getSessionId:(e)=>e.session_id})}function xA(e,t,n,r,o){let i=ut(e,t,n,r,o);if(!i)return null;if(!t||typeof t!=="object"||Array.isArray(t))return i;if(!Object.hasOwn(t,"workdir"))return i;let s=t.workdir;if(typeof s!=="string"||s.trim()==="")return ee(r,t,n),null;let a=at([Bp.resolve(i.configCwd,s)],o.paths);if(!a)return ee(r,t,n,s),null;return{...i,executionCwd:a}}var $p=new Map([["Bash","posix"]]);function RA(e){return se(e,$p)}async function jp(){await Vn({agent:"kimi-code",getToolRoute:RA,getContext:(e,t,n,r,o)=>{let i=ut(e,t,n,r,o);if(!i)return null;let s=e.tool_input;if(!$p.has(n)||!s||!Object.hasOwn(s,"cwd"))return i;let a=s.cwd;if(typeof a!=="string"||a.trim()==="")return ee(r,t,n),null;let l=pt(a,[i.configCwd],o.paths);if(!l)return ee(r,t,n,a),null;return{configCwd:i.configCwd,executionCwd:l}}})}var _A={"antigravity-cli":Ip,"claude-code":Lp,codex:Wp,"copilot-cli":Gp,cursor:Fp,"gemini-cli":zp,"grok-build":Hp,"hermes-agent":Up,"kimi-code":jp},_l=Op.map((e)=>({...e,run:_A[e.id]}));function Vp(e){let t=Kr({label:"hook",booleans:Object.fromEntries(_l.map((r)=>[r.id,[...r.flags,...r.legacyFlags]]))},e);if(t.errors.length>0)return;let n=_l.filter((r)=>t.flags[r.id]);return n.length===1?n[0]:void 0}function Kp(e){return _l.find((t)=>t.legacyTopLevelFlags.some((n)=>n===e))}async function wA(){let e=process.argv.slice(2),t=e[0],n=Kr({label:"cc-safety-net",booleans:{version:["-V","--version"]},positionals:"list"},e);if(!n.help&&!n.flags.version){if(t?.toLowerCase()==="hook"){let i=Vp(e.slice(1));if(i){await i.run();return}}let o=Kp(t);if(o){await o.run();return}}let r=await import("../cli.js");await r.runCli(e)}wA().catch((e)=>{console.error("CC Safety Net error:",e),process.exit(1)});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{a,s,z,f,Re,u,Ie,y,p,W}from"./index-fvtsm6ez.js";import{appendFileSync as re,mkdirSync as oe}from"node:fs";import{isAbsolute as ie,join as I}from"node:path";import{lstatSync as C,readdirSync as j,readFileSync as U,rmdirSync as V,statSync as L,unlinkSync as K,utimesSync as X,writeFileSync as Y}from"node:fs";import{join as m}from"node:path";function ee(t,e={}){return Ie(u(t,e),t.home).policy.audit.retention_days}var S=86400000,Z=".last-prune",J=/^\d{4}-\d{2}$/,Q=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,G=(t)=>Math.floor(t/S);function B(t,e,r=()=>new Date){try{let n=r().getTime();if(!L(e,{throwIfNoEntry:!1})?.isDirectory())return;let o=m(e,Z),c=L(o,{throwIfNoEntry:!1})?.mtimeMs;if(c!==void 0&&G(c)===G(n))return;let i=n-ee(t)*S,d=new Date(n).toISOString().slice(0,7);for(let l of A(e)){if(l.isDirectory()){q(m(e,l.name),i,d);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))te(m(e,l.name),i)}Y(o,"",{mode:384}),X(o,n/1000,n/1000)}catch{}}function q(t,e,r){for(let n of A(t)){if(!n.isDirectory()||!J.test(n.name))continue;let o=m(t,n.name);for(let c of A(o)){if(!c.isFile())continue;let i=Q.exec(c.name);if(!i||i[2]!==n.name)continue;let d=Date.parse(`${i[1]}T00:00:00.000Z`)+S;if(!Number.isFinite(d)||d>=e)continue;b(m(o,c.name))}if(n.name!==r)T(o)}T(t)}function te(t,e){try{let r=C(t);if(r.mtimeMs>=e)return;let n=U(t,"utf-8").split(`
|
|
2
|
-
`).filter((o)=>o.trim()).map(ne);if(n.length===0)return;if(n.some((o)=>o===void 0||o>=e))return;if(C(t).mtimeMs!==r.mtimeMs)return;b(t)}catch{}}function ne(t){try{let e=JSON.parse(t).ts,r=typeof e==="string"?Date.parse(e):Number.NaN;return Number.isFinite(r)?r:void 0}catch{return}}function A(t){try{return j(t,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function b(t){try{K(t)}catch{}}function T(t){try{V(t)}catch{}}var ae="2.4.
|
|
2
|
+
`).filter((o)=>o.trim()).map(ne);if(n.length===0)return;if(n.some((o)=>o===void 0||o>=e))return;if(C(t).mtimeMs!==r.mtimeMs)return;b(t)}catch{}}function ne(t){try{let e=JSON.parse(t).ts,r=typeof e==="string"?Date.parse(e):Number.NaN;return Number.isFinite(r)?r:void 0}catch{return}}function A(t){try{return j(t,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function b(t){try{K(t)}catch{}}function T(t){try{V(t)}catch{}}var ae="2.4.9",ce=1e4,de=2000,ue=256,se=32768;function le(t){let e=t.trim();if(!e)return null;let r=e.replace(/[^A-Za-z0-9_.-]+/g,"_");if(r=r.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!r||r==="."||r==="..")return null;return r}function me(t){return(t??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function _(t,e,r,n,o,c,i={}){let d=le(e);if(!d)return;let l=O(t);if(!l)return;try{let E=(i.now??(()=>new Date))().toISOString(),N=g(z(r),i.failureStage?Number.POSITIVE_INFINITY:ce),h=g(z(n),de),w=i.toolName?g(z(i.toolName),ue):void 0,v=c===null?void 0:g(z(c),se),F=I(l,me(v?.value??null),E.slice(0,7));oe(F,{recursive:!0,mode:448});let H=I(F,`${E.slice(0,10)}-${d}.jsonl`),P={ts:E,id:(i.createId??Re)(),v:ae,sessionId:d,decision:i.decision??"deny",agent:i.agent,shape:i.shape,level:i.level,configFallback:i.configFallback,toolName:w?.value,command:N.value,segment:h.value,...N.truncated||h.truncated||w?.truncated||v?.truncated?{truncated:!0}:{},reason:o,ruleId:i.ruleId,intent:i.intent,failureStage:i.failureStage,errorCode:i.errorCode,cwd:v?.value??null};re(H,`${JSON.stringify(P)}
|
|
3
3
|
`,{encoding:"utf-8",mode:384}),B(t,l,i.now)}catch{}}function g(t,e){return{value:t.slice(0,e),truncated:t.length>e}}function je(t){let e=t.env.get("CC_SAFETY_NET_AUDIT_HOME");if(t.env.get("NODE_ENV")==="test"&&!e)return null;let r=e||t.home;return r&&ie(r)?r:null}function O(t){let e=je(t);return e?I(e,".cc-safety-net","logs"):null}function x(t,e,r,n=!0,o){if(e.decision.kind==="allow"){if(!r||t.route.kind!=="command")return;let d=k(t);return{decision:"allow",command:d,segment:d,reason:"allowed",cwd:t.context.executionCwd,toolName:t.toolName,level:e.level,...e.configFallback?{configFallback:!0}:{}}}let c=e.decision.evidence,i=c?.command??(n?k(t):"");return{decision:"deny",command:i,segment:c?.segment??i,reason:e.decision.reason,cwd:t.context.executionCwd,toolName:t.toolName,level:e.level,...e.configFallback?{configFallback:!0}:{},ruleId:e.decision.ruleId,intent:e.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function k(t){return"command"in t?t.command??"":""}function M(t,e,r,n){if(!e)return;let o;try{o=r()}catch{return}if(typeof o!=="string"||!o.trim())return;_(t,o,e.command,e.segment,e.reason,e.cwd,{decision:e.decision,agent:n.agent,shape:n.shape,level:e.level,configFallback:e.configFallback,toolName:e.toolName,ruleId:e.ruleId,intent:e.intent,failureStage:e.failureStage,errorCode:e.errorCode})}function he(t,e,r,n){let o;try{o=r()}catch{return}if(typeof o!=="string"||!o.trim())return;_(t,o,e.command??"",e.segment??e.command??"",e.reason,n.cwd??null,{decision:"deny",agent:n.agent,shape:n.shape,toolName:n.toolName??e.toolName,ruleId:e.ruleId,intent:e.intent})}function D(t,e,r){try{let n=W(e,{environment:t,...r.guard});return R(t,e,n,r),n}catch(n){if(!(n instanceof p))throw n;throw R(t,e,n.evaluation,r,!(n.cause instanceof f),{stage:n.stage,errorCode:fe(n.cause)}),n}}function R(t,e,r,n,o=!0,c){M(t,x(e,r,n.guard?.auditAllowed??!1,o,c),n.audit.getSessionId,{agent:n.audit.agent,shape:n.audit.shape})}function fe(t){if(t instanceof s)return a[t.kind].errorCode;if(t instanceof f)return"tool-input-limit";if(t instanceof y)return"structural-shell-syntax-limit";return"unexpected-error"}
|
|
4
4
|
export{ee,B,je,O,he,D};
|
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a,s,ke,Ue,k,Ze,Ge,c,o,He,R,L,ve,Qe,f,We,d,r,v,i,re,n,g,le,N,tt,nt,l,ue,de,rt,A,q,oe,S,ot,F,b,Se,M,u,K,Be,ze,I,w,T,pe,fe,Le,it,m,e,Te,we,Ve,qe,ie,Ce,se,_e,J,j,Pe,me,U,Ke,G,Y,Z,ae,Je,Ye,C,H,Ae,Oe,De,E,Ne,Ee,Fe,h,t,X,ge,y,x,_,st,Me,$e,p,W}from"./chunks/index-fvtsm6ez.js";import{ee,B,je,O,D}from"./chunks/index-
|
|
1
|
+
import{a,s,ke,Ue,k,Ze,Ge,c,o,He,R,L,ve,Qe,f,We,d,r,v,i,re,n,g,le,N,tt,nt,l,ue,de,rt,A,q,oe,S,ot,F,b,Se,M,u,K,Be,ze,I,w,T,pe,fe,Le,it,m,e,Te,we,Ve,qe,ie,Ce,se,_e,J,j,Pe,me,U,Ke,G,Y,Z,ae,Je,Ye,C,H,Ae,Oe,De,E,Ne,Ee,Fe,h,t,X,ge,y,x,_,st,Me,$e,p,W}from"./chunks/index-fvtsm6ez.js";import{ee,B,je,O,D}from"./chunks/index-g2gqgqzy.js";var Ud=["-h","--help"];function xt(P,V){let z=Object.entries(P.booleans??{}),Q=Object.entries(P.values??{}),te=Object.entries(P.lists??{}),ne=Object.fromEntries(z.map(([Xe])=>[Xe,!1])),ce={},he=Object.fromEntries(te.map(([Xe])=>[Xe,[]])),ye=[],be=[],xe=!1,Ie=-1;for(let[Xe,et]of V.entries()){if(Xe<=Ie)continue;if(et==="--"){ye.push(...V.slice(Xe+1));break}if(Ud.includes(et)){xe=!0;continue}let Re=z.find(([,lt])=>lt.includes(et));if(Re){ne[Re[0]]=!0;continue}let at=Q.find(([,lt])=>lt.includes(et));if(at){let lt=V[Xe+1];if(lt===void 0||lt.startsWith("-")){be.push(`${et} requires a value`);continue}ce[at[0]]=lt,Ie=Xe+1;continue}let ct=te.find(([,lt])=>lt.includes(et));if(ct){let lt=V.slice(Xe+1),pt=lt.findIndex((gt)=>gt.startsWith("-")),mt=lt.slice(0,pt===-1?lt.length:pt);if(mt.length===0){be.push(`${et} requires at least one value`);continue}he[ct[0]]=[...he[ct[0]]??[],...mt],Ie=Xe+mt.length;continue}if(et.startsWith("-")){be.push(`Unknown option for ${P.label}: ${et}`);continue}if(P.positionals==="tail"){ye.push(...V.slice(Xe));break}ye.push(et)}if(P.positionals!=="list"&&P.positionals!=="tail")be.push(...ye.map((Xe)=>`Unexpected argument for ${P.label}: ${Xe}`));return{flags:ne,values:ce,lists:he,positionals:ye,help:xe,errors:be}}function Ht(P){for(let V of P)console.error(V);return P.length>0}import{readdirSync as Wd,statSync as Ni,unlinkSync as Kd}from"node:fs";import{basename as Mi,dirname as Yd,isAbsolute as Zd,join as Xd,relative as Qd,resolve as eu,sep as tu}from"node:path";var Oi=(P)=>{let V=Date.now()-new Date(P).getTime();if(!Number.isFinite(V))return"";let z=Math.floor(V/60000),Q=Math.floor(z/60),te=Math.floor(Q/24);if(te>0)return`${te}d ago`;if(Q>0)return`${Q}h ago`;if(z>0)return`${z}m ago`;return"just now"},Qr=(P)=>{let V=(P??"").trim().split(/\s+/).filter((te)=>te&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(te)),z=V[0]?.split("/").pop();if(!z)return null;let Q=V[1];return Q&&/^[a-z][a-z0-9-]*$/.test(Q)?`${z} ${Q}`:z};function Fi(P){let V=(te)=>`${te.sessionId}
|
|
2
2
|
${Qr(te.segment||te.command)}`,z=P.filter((te)=>te.decision!=="allow"),Q=z.filter((te)=>te.sessionId).reduce((te,ne)=>te.set(V(ne),(te.get(V(ne))??0)+1),new Map);return new Set(z.filter((te)=>te.failureStage||(Q.get(V(te))??0)>=2))}import{existsSync as Gd,readdirSync as Bd,readFileSync as qd}from"node:fs";import{join as Vd}from"node:path";function Yt(P,V){try{return Bd(P,{withFileTypes:!0,encoding:"utf8"}).flatMap((z)=>{let Q=Vd(P,z.name);if(z.isDirectory())return Yt(Q,V);if(z.name.endsWith(".jsonl"))return[Q];return[]})}catch{if(V&&Gd(P))V.count++;return[]}}var zd=["segment","reason","sessionId","decision","agent","ruleId","failureStage"];function Jd(P){if(!P||typeof P!=="object"||Array.isArray(P))return!1;let V=P;if(typeof V.ts!=="string"||typeof V.command!=="string")return!1;return zd.every((z)=>V[z]===void 0||typeof V[z]==="string")}function pn(P,V){try{return qd(P,"utf-8").split(`
|
|
3
3
|
`).filter(Boolean).flatMap((z)=>{try{let Q=JSON.parse(z);if(!Jd(Q)){if(V)V.count++;return[]}return[Q]}catch{if(V)V.count++;return[]}})}catch{if(V)V.count++;return[]}}function Ct(P){return Array.from(P,(V)=>{let z=V.charCodeAt(0);if(z<=31||z>=127&&z<=159)return`\\x${z.toString(16).padStart(2,"0")}`;return V}).join("")}function nu(P,V){let z=ee(P),Q=xt({label:"logs",booleans:{all:["--all"],suspect:["--suspect"],json:["--json"],pruneLegacy:["--prune-legacy"],dryRun:["--dry-run"]},values:{id:["--id"],limit:["--limit"],since:["--since"],agent:["--agent"],rule:["--rule"],session:["--session"],project:["--project"]}},V);if(Ht(Q.errors))return null;if(Q.values.id!==void 0&&!/^[a-f0-9]{16}$/.test(Q.values.id))return console.error("--id must be 16 hexadecimal characters"),null;let te=Q.values.limit===void 0?20:ji(Q.values.limit);if(te===null)return console.error("--limit must be a positive number"),null;let ne=Q.values.since===void 0?Math.min(30,z):ji(Q.values.since);if(ne===null||ne>z)return console.error(`--since must be a positive number of days no greater than ${z}`),null;let ce={limit:te,limitExplicit:Q.values.limit!==void 0,since:ne,sinceExplicit:Q.values.since!==void 0,all:Q.flags.all,json:Q.flags.json,suspect:Q.flags.suspect,pruneLegacy:Q.flags.pruneLegacy,dryRun:Q.flags.dryRun,id:Q.values.id,agent:Q.values.agent,rule:Q.values.rule,session:Q.values.session,project:Q.values.project===void 0?void 0:eu(Q.values.project)};if(ce.id&&(ce.agent!==void 0||ce.rule!==void 0||ce.session!==void 0||ce.project!==void 0||ce.suspect||ce.sinceExplicit||ce.limitExplicit))return console.error("--id cannot be combined with --agent, --rule, --session, --project, --suspect, --since, or --limit"),null;if(ce.pruneLegacy&&(ce.id!==void 0||ce.agent!==void 0||ce.rule!==void 0||ce.session!==void 0||ce.project!==void 0||ce.suspect||ce.all||ce.sinceExplicit||ce.limitExplicit))return console.error("--prune-legacy cannot be combined with --id, --agent, --rule, --session, --project, --suspect, --all, --since, or --limit"),null;if(ce.dryRun&&!ce.pruneLegacy)return console.error("--dry-run requires --prune-legacy"),null;return ce}async function Hi(P,V,z={}){let Q=nu(P,V);if(!Q)return 1;let te=z.logsDir??O(P);if(Q.pruneLegacy)return ru(te,Q.json,Q.dryRun);if(!te)return console.log(Q.json?"[]":Q.id?`No retained audit log entry found for id ${Ct(Q.id)}.`:"No audit log entries found."),0;B(P,te);let ne={count:0},ce=Yt(te,ne).flatMap((Ie)=>pn(Ie,ne).map((Xe)=>({entry:Xe,file:Ie})));if(ne.count>0)console.error(`warning: ${ne.count} audit log ${ne.count===1?"source":"sources"} could not be read; these results are incomplete`);if(Q.id)return au(ce,Q,z.timeZone);let he=Date.now()-Q.since*24*60*60*1000,ye=ce.filter((Ie)=>lu(Ie,Q,te,he)),be=Q.suspect?Fi(ye.map((Ie)=>Ie.entry)):null,xe=(be?ye.filter((Ie)=>be.has(Ie.entry)):ye).sort((Ie,Xe)=>Date.parse(Xe.entry.ts)-Date.parse(Ie.entry.ts)).slice(0,Q.limit);if(Q.json)return console.log(JSON.stringify(xe.map((Ie)=>Ie.entry),null,2)),0;if(xe.length===0)return console.log("No audit log entries found."),0;for(let Ie of xe)console.log(uu(Ie.entry,z.timeZone));return 0}function ru(P,V,z){let Q=P?iu(P).map((he)=>Xd(P,he)):[];if(z)return ou(Q,V);let te=[],ne=0,ce=0;for(let he of Q){let ye=Ni(he,{throwIfNoEntry:!1})?.size??0,be=su(he);if(be){te.push(`${Mi(he)}: ${be}`);continue}ne++,ce+=ye}if(V)return console.log(JSON.stringify({removedFiles:ne,removedBytes:ce,failedFiles:te.length})),te.length===0?0:1;console.log(ne===0&&te.length===0?"No legacy audit log files found.":`Removed ${ne} legacy audit log ${ne===1?"file":"files"} (${Ui(ce)}).`);for(let he of te)console.error(`Could not remove ${Ct(he)}`);if(console.log("Nested v2 audit logs were not changed."),ne>0)console.log("This deletion cannot be undone.");return te.length===0?0:1}function ou(P,V){let z=P.reduce((Q,te)=>Q+(Ni(te,{throwIfNoEntry:!1})?.size??0),0);if(V)return console.log(JSON.stringify({dryRun:!0,files:P.length,bytes:z})),0;if(console.log(P.length===0?"No legacy audit log files found.":`Would remove ${P.length} legacy audit log ${P.length===1?"file":"files"} (${Ui(z)}).`),console.log("Nested v2 audit logs are not included."),P.length>0)console.log("Run the same command without --dry-run to delete them.");return 0}function iu(P){try{return Wd(P,{withFileTypes:!0}).filter((V)=>V.isFile()&&V.name.endsWith(".jsonl")).map((V)=>V.name)}catch{return[]}}function su(P){try{return Kd(P),null}catch(V){return V instanceof Error?V.message:String(V)}}function Ui(P){let V=["B","KiB","MiB","GiB"],z=Math.min(Math.floor(Math.log2(Math.max(P,1))/10),V.length-1);return`${Math.round(P/1024**z*10)/10} ${V[z]}`}function au(P,V,z){let Q=P.filter((ne)=>ne.entry.id===V.id);if(Q.length>1)return console.error(`Multiple audit log entries found for id ${Ct(V.id??"")}.`),1;if(V.json)return console.log(JSON.stringify(Q.map((ne)=>ne.entry),null,2)),0;let te=Q[0];if(!te)return console.log(`No retained audit log entry found for id ${Ct(V.id??"")}.`),0;return console.log(pu(te.entry,z)),0}function lu(P,V,z,Q){if(!V.all&&P.entry.decision==="allow")return!1;if(Date.parse(P.entry.ts)<Q)return!1;if(V.agent!==void 0&&P.entry.agent!==V.agent)return!1;if(V.rule!==void 0&&P.entry.ruleId!==V.rule)return!1;if(V.session!==void 0&&!cu(P,z,V.session))return!1;if(V.project!==void 0&&!du(P.entry.cwd,V.project))return!1;return!0}function cu(P,V,z){if(P.entry.sessionId===z)return!0;return Yd(P.file)===V&&Mi(P.file,".jsonl")===z}function du(P,V){if(!P)return!1;let z=Qd(V,P);return z!==".."&&!z.startsWith(`..${tu}`)&&!Zd(z)}function uu(P,V){let z=Ct(P.id??"-"),Q=Ct(P.decision??"deny"),te=P.cwd?` [${Ct(P.cwd)}]`:"",ne=P.segment||P.command,ce=ne===P.command?"":"↳ ",he=ne.length>50?`${ne.slice(0,50)}…`:ne;return`${z.padEnd(16)} ${Ct(Gi(P.ts,V))} ${Q.padEnd(5)} ${Ct(P.agent??"-").padEnd(15)} ${Ct(P.ruleId??"-").padEnd(20)} ${ce}${Ct(he)}${te}`}function pu(P,V){let z=(te)=>Ct(te===void 0||te===null||te===""?"-":te),Q=P.shape?`${P.agent??"-"} (shape: ${P.shape})`:P.agent??"-";return[`id: ${z(P.id)}`,`ts: ${z(Gi(P.ts,V))}`,`decision: ${z(P.decision)}`,`agent: ${z(Q)}`,`level: ${z(P.level)}`,`tool: ${z(P.toolName)}`,`rule: ${z(P.ruleId)}`,`intent: ${z(P.intent)}`,`stage: ${z(P.failureStage)}`,`error: ${z(P.errorCode)}`,`session: ${z(P.sessionId)}`,`cwd: ${z(P.cwd)}`,`version: ${z(P.v)}`,`truncated: ${z(P.truncated===!0?"yes":void 0)}`,`reason: ${z(P.reason)}`,`command: ${z(P.command)}`,`segment: ${z(P.segment)}`].join(`
|
|
4
4
|
`)}function Gi(P,V){let z=new Date(P);if(Number.isNaN(z.getTime()))return P;return new Intl.DateTimeFormat("sv-SE",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23",timeZone:V}).format(z)}function ji(P){let V=Number(P);return Number.isFinite(V)&&V>0?V:null}var Bi={name:"doctor",aliases:["--doctor"],description:"Run diagnostic checks to verify installation and configuration",usage:"doctor [options]",options:[{flags:"--json",description:"Output diagnostics as JSON"},{flags:"--skip-update-check",description:"Skip npm registry version check"},{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net doctor","cc-safety-net doctor --json","cc-safety-net doctor --skip-update-check"]};var qi={name:"explain",description:"Show step-by-step analysis trace of how a command would be analyzed",usage:"explain [options] <command>",argument:"<command>",options:[{flags:"--json",description:"Output analysis as JSON"},{flags:"--cwd",argument:"<path>",description:"Use custom working directory"},{flags:"-h, --help",description:"Show this help"}],examples:['cc-safety-net explain "git reset --hard"','cc-safety-net explain --json "rm -rf /"','cc-safety-net explain --cwd /tmp "git status"']};var Vi={name:"gui",description:"Open the local policy editor GUI",usage:"gui [options]",options:[{flags:"--no-open",description:"Print the URL without opening a browser"},{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net gui","cc-safety-net gui --no-open"]};var Yn=[{id:"antigravity-cli",displayName:"Antigravity CLI",doctorOrder:3,runtime:{order:1,flags:["-ac","--agy-cli"],description:"Run as Antigravity CLI PreToolUse hook",legacyTopLevelFlags:[]},install:{order:2,flag:"--agy-cli",artifactKind:"hook config",probeCommand:["agy","--version"]}},{id:"claude-code",displayName:"Claude Code",doctorOrder:1,runtime:{order:2,displayName:"Coding CLI",flags:["-cc","--coding-cli"],legacyFlags:["--claude-code"],description:"Run as Coding CLI PreToolUse hook",legacyTopLevelFlags:["-cc","--claude-code"]},install:{order:3,flag:"--claude-code",artifactKind:"plugin",probeCommand:["claude","--version"]}},{id:"codex",displayName:"Codex",doctorOrder:4,runtime:{order:3,flags:["-cx","--codex"],description:"Run as a Codex PreToolUse hook",legacyTopLevelFlags:[]},install:{order:4,flag:"--codex",artifactKind:"plugin",probeCommand:["codex","--version"]}},{id:"copilot-cli",displayName:"GitHub Copilot CLI",doctorOrder:7,runtime:{order:6,flags:["-cp","--copilot-cli"],description:"Run as GitHub Copilot CLI PreToolUse hook",legacyTopLevelFlags:["-cp","--copilot-cli"]},install:{order:7,flag:"--copilot-cli",artifactKind:"plugin",probeCommand:["copilot","--binary-version"]}},{id:"gemini-cli",displayName:"Gemini CLI",doctorOrder:6,runtime:{order:5,flags:["-gc","--gemini-cli"],description:"Run as Gemini CLI BeforeTool hook",legacyTopLevelFlags:["-gc","--gemini-cli"]},install:{order:6,flag:"--gemini-cli",artifactKind:"extension",probeCommand:["gemini","--version"]}},{id:"grok-build",displayName:"Grok Build",doctorOrder:8,runtime:{order:7,flags:["-gb","--grok-build"],description:"Run as Grok Build PreToolUse hook",legacyTopLevelFlags:[]},install:{order:8,flag:"--grok-build",artifactKind:"hook config",probeCommand:["grok","--version"]}},{id:"hermes-agent",displayName:"Hermes Agent",doctorOrder:9,runtime:{order:8,flags:["-ha","--hermes-agent"],description:"Run as Hermes Agent pre_tool_call hook",legacyTopLevelFlags:[]},install:{order:9,flag:"--hermes-agent",artifactKind:"plugin",probeCommand:["hermes","--version"]}},{id:"kimi-code",displayName:"Kimi Code",doctorOrder:10,runtime:{order:9,flags:["-kc","--kimi-code"],description:"Run as Kimi Code PreToolUse hook",legacyTopLevelFlags:[]},install:{order:10,flag:"--kimi-code",artifactKind:"hook config",probeCommand:["kimi","--version"]}},{id:"openclaw",displayName:"OpenClaw",doctorOrder:11,install:{order:11,flag:"--openclaw",artifactKind:"plugin",probeCommand:["openclaw","--version"]}},{id:"opencode",displayName:"OpenCode",doctorOrder:12,install:{order:12,flag:"--opencode",artifactKind:"plugin",probeCommand:["opencode","--version"]}},{id:"pi",displayName:"Pi",doctorOrder:13,install:{order:13,flag:"--pi",artifactKind:"package",probeCommand:["pi","--version"]}},{id:"cursor",displayName:"Cursor",doctorOrder:5,runtime:{order:4,flags:["-cu","--cursor"],description:"Run as Cursor preToolUse hook",legacyTopLevelFlags:[]},install:{order:5,flag:"--cursor",artifactKind:"hook config",probeCommand:["cursor","--version"]}},{id:"amp",displayName:"Amp Code",doctorOrder:2,install:{order:1,flag:"--amp",artifactKind:"plugin",probeCommand:["amp","--version"]}}],Zn=Yn.slice().sort((P,V)=>P.doctorOrder-V.doctorOrder).map((P)=>P.id),Sn=Yn.filter((P)=>("runtime"in P)).slice().sort((P,V)=>P.runtime.order-V.runtime.order).map((P)=>({id:P.id,displayName:"displayName"in P.runtime?P.runtime.displayName:P.displayName,flags:P.runtime.flags,legacyFlags:"legacyFlags"in P.runtime?P.runtime.legacyFlags:[],description:P.runtime.description,legacyTopLevelFlags:P.runtime.legacyTopLevelFlags})),$t=Yn.slice().sort((P,V)=>P.install.order-V.install.order).map((P)=>({id:P.id,...P.install})).map(({order:P,...V})=>V),fu=Object.fromEntries(Yn.map((P)=>[P.id,P.displayName]));function bt(P){return fu[P]}var mu=Sn.map((P)=>({flags:P.flags.join(", "),description:P.description})),gu=Sn.flatMap((P)=>P.flags.map((V)=>`cc-safety-net hook ${V}`)),zi={name:"hook",description:"Run as an agent CLI hook (reads JSON from stdin)",usage:"hook INTEGRATION_FLAG",options:[...mu,{flags:"-h, --help",description:"Show this help"}],examples:gu};var Ji={name:"install",description:"Install CC Safety Net into a coding agent CLI",usage:"install [TARGET_FLAG]",options:[...$t.map((P)=>({flags:P.flag,description:`Install ${bt(P.id)} ${P.artifactKind}`})),{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net install",...$t.map((P)=>`cc-safety-net install ${P.flag}`)]},Wi={name:"uninstall",description:"Uninstall CC Safety Net from a coding agent CLI",usage:"uninstall [TARGET_FLAG]",options:[...$t.map((P)=>({flags:P.flag,description:`Uninstall ${bt(P.id)} ${P.artifactKind}`})),{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net uninstall",...$t.map((P)=>`cc-safety-net uninstall ${P.flag}`)]},Ki={name:"update",description:"Update every installed CC Safety Net integration to the latest version",usage:"update",options:[{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net update"]};var Yi={name:"logs",description:"Browse audit log entries recorded by hooks",usage:"logs [options]",options:[{flags:"--id",argument:"<id>",description:"Show one entry from retained history by its 16-character id (not guaranteed once it is older than the configured retention)"},{flags:"--limit",argument:"<n>",description:"Maximum entries to print",default:"20"},{flags:"--since",argument:"<days>",description:"Only include entries newer than this many days (max: the configured audit retention, 1-365)",default:"30"},{flags:"--agent",argument:"<name>",description:"Filter by agent name"},{flags:"--rule",argument:"<ruleId>",description:"Filter by rule id"},{flags:"--session",argument:"<id>",description:"Filter by session id"},{flags:"--project",argument:"<path>",description:"Filter by project path"},{flags:"--suspect",description:"Only denials that look like false positives"},{flags:"--all",description:"Include allow entries"},{flags:"--prune-legacy",description:"Permanently delete all legacy root-level logs; nested logs are untouched"},{flags:"--dry-run",description:"With --prune-legacy, report what would be deleted and delete nothing"},{flags:"--json",description:"Output entries as JSON"},{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net logs --id 3fa9c2d1a70e8b42","cc-safety-net logs --agent claude-code","cc-safety-net logs --project . --since 7","cc-safety-net logs --suspect --since 7","cc-safety-net logs --json","cc-safety-net logs --prune-legacy --dry-run","cc-safety-net logs --prune-legacy"]};var Xn={name:"policy",description:"Check and apply project or user policy proposals",usage:"policy <subcommand>",subcommands:[{usage:"check <file>",description:"Validate a policy proposal and print its diff"},{usage:"apply <file>",description:"Apply a proposal after confirming in a terminal"}],options:[{flags:"-g, --global",description:"Use the user-scope policy instead of the project one"},{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net policy check proposal.json","cc-safety-net policy apply proposal.json","cc-safety-net policy apply proposal.json --global"]};var eo=[{flags:"--ref",argument:"<ref>",description:"Use a branch, tag, or commit"},{flags:"--only",argument:"<rulebook...>",description:"Add only these repository rulebooks"},{flags:"-g, --global",description:"Use user-scope rule config"},{flags:"-h, --help",description:"Show this help"}],to=["cc-safety-net rule add project-rules","cc-safety-net rule add acme/safety-rules","cc-safety-net rule add acme/safety-rules --only aws gcloud","cc-safety-net rule add acme/safety-rules --ref v2 --only aws","cc-safety-net rule add --only terraform aws"],fn={name:"rule",description:"Manage CC Safety Net rule config and rulebook sources",usage:"rule <subcommand>",subcommands:[{usage:"init [--example]",description:"Create inert rule config"},{usage:"add [source] [--ref <ref>] [--only <rulebook...>]",description:"Add rulebook sources and sync"},{usage:"remove <source>",description:"Remove a rulebook source and sync"},{usage:"update [source]",description:"Re-fetch and vendor remote rulebooks"},{usage:"sync",description:"Deprecated: migrate lock and cache leftovers"},{usage:"list",description:"List active rulebooks"},{usage:"wrapper add <command>",description:"Trust a transparent command wrapper"},{usage:"wrapper remove <command>",description:"Remove a transparent command wrapper"},{usage:"wrapper list",description:"List transparent command wrappers"},{usage:"migrate [--cleanup]",description:"Migrate legacy inline rules"},{usage:"doc",description:"Print the rulebook authoring guide"},{usage:"verify",description:"Validate rule config files"}],options:[{flags:"-g, --global",description:"Use user-scope rule config"},{flags:"--cleanup",description:"Delete legacy files after rule migrate verifies them"},{flags:"--delete-source",description:"Delete clean local source directory on remove"},{flags:"--example",description:"Create an inactive example rulebook with rule init"},...eo.slice(0,2),{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net rule init","cc-safety-net rule init --example","cc-safety-net rule wrapper add rtk",...to,"cc-safety-net rule update","cc-safety-net rule migrate --cleanup","cc-safety-net rule verify"]};var Zi={name:"status",description:"Show what the runtime is enforcing right now",usage:"status",options:[{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net status"]};var Xi={name:"statusline",description:"Print status line with mode indicators for shell integration",usage:"statusline --claude-code",options:[{flags:"-cc, --claude-code",description:"Print status line for Claude Code"},{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net statusline -cc","cc-safety-net statusline --claude-code"]};var Qn=[Zi,Bi,Yi,qi,fn,Xn,Ji,Ki,Wi,zi,Vi,Xi];function hu(P){return P.aliases??[]}function er(P){let V=P.toLowerCase();return Qn.find((z)=>z.name.toLowerCase()===V||hu(z).some((Q)=>Q.toLowerCase()===V))}import{basename as yu}from"node:path";function tr(P,V=7,z=O(P)){let Q=Date.now()-V*24*60*60*1000,te=[],ne=new Set,ce=0,he,ye,be,xe;if(z)B(P,z);let Ie={count:0},Xe=z?Yt(z,Ie):[];for(let Re of Xe)for(let at of pn(Re,Ie)){if(at.decision==="allow")continue;let ct=new Date(at.ts).getTime();if(ct>=Q){if(ce++,ne.add(at.sessionId??yu(Re,".jsonl")),ye===void 0||ct<=ye)he=at.ts,ye=ct;if(xe===void 0||ct>xe)be=at.ts,xe=ct;vu(te,at,ct)}}let et=te.map((Re)=>({timestamp:Re.ts,command:Re.command,reason:Re.reason,relativeTime:Oi(new Date(Re.ts))}));return{totalBlocked:ce,sessionCount:ne.size,recentEntries:et,oldestEntry:he,newestEntry:be,unreadable:Ie.count}}function vu(P,V,z){let Q=P.findIndex((te)=>z>new Date(te.ts).getTime());if(Q===-1){if(P.length<3)P.push(V);return}if(P.splice(Q,0,V),P.length>3)P.pop()}import{dirname as Au}from"node:path";import{dirname as bu,join as Lu,resolve as wu}from"node:path";var ku="config.json";function Rt(P,V,z,Q){g(xu(P),`${JSON.stringify(V,null,2)}
|
|
@@ -18,7 +18,7 @@ ${Qr(te.segment||te.command)}`,z=P.filter((te)=>te.decision!=="allow"),Q=z.filte
|
|
|
18
18
|
`)}function or(P){return Zt({rows:P})}function ys(P){let V=[];return V.push("System Info"),V.push(ep(P)),V.join(`
|
|
19
19
|
`)}function ep(P){let V=["Component","Version"],z=(ne)=>{if(ne===null)return dt.dim("not found");return ne},te=[{label:"cc-safety-net",value:P.version},...Zn.map((ne)=>({label:bt(ne),value:P.versions[ne]??null})),{label:"Node.js",value:P.nodeVersion},{label:"npm",value:P.npmVersion},{label:"Bun",value:P.bunVersion},{label:"Platform",value:P.platform}].map((ne)=>[ne.label,z(ne.value)]);return Zt({headers:V,rows:te})}function vs(P){if(P.findings.length===0)return dt.green(`
|
|
20
20
|
No findings from inspected doctor facts.`);let V={error:P.findings.filter((ne)=>ne.severity==="error").length,warning:P.findings.filter((ne)=>ne.severity==="warning").length,info:P.findings.filter((ne)=>ne.severity==="info").length},z=["error","warning","info"].filter((ne)=>V[ne]>0).map((ne)=>`${V[ne]} ${ne}`),Q=P.findings.length===1?"finding":"findings",te=`
|
|
21
|
-
${P.findings.length} ${Q}: ${z.join(", ")}.`;if(V.error>0)return dt.red(te);if(V.warning>0)return dt.yellow(te);return dt.blue(te)}import{lstatSync as tp}from"node:fs";import{dirname as so}from"node:path";function ao(P,V){try{let z=tp(V);if(z.isSymbolicLink())return{kind:P,path:V,status:"unsafe",issues:["symlink"]};if(!z.isDirectory())return{kind:P,path:V,status:"unsafe",issues:["not-directory"]};if(process.platform==="win32"||typeof process.getuid!=="function")return{kind:P,path:V,status:"unknown",issues:[]};let Q=[...z.uid!==process.getuid()?["ownership"]:[],...(z.mode&18)!==0?["permissions"]:[]];return{kind:P,path:V,status:Q.length>0?"unsafe":"safe",issues:Q}}catch(z){if(typeof z==="object"&&z!==null&&"code"in z&&z.code==="ENOENT")return{kind:P,path:V,status:"not-applicable",issues:[]};return{kind:P,path:V,status:"unknown",issues:[]}}}function bs(P,V){let z=O(P);return{directories:[ao("policy",so(so(V))),ao("config",so(V)),...z?[ao("audit",z)]:[{kind:"audit",status:"unknown",issues:[]}]]}}import{spawn as np}from"node:child_process";import{existsSync as Ls}from"node:fs";import{delimiter as rp,extname as op,join as ip}from"node:path";import{stripVTControlCharacters as ws}from"node:util";var xs="2.4.
|
|
21
|
+
${P.findings.length} ${Q}: ${z.join(", ")}.`;if(V.error>0)return dt.red(te);if(V.warning>0)return dt.yellow(te);return dt.blue(te)}import{lstatSync as tp}from"node:fs";import{dirname as so}from"node:path";function ao(P,V){try{let z=tp(V);if(z.isSymbolicLink())return{kind:P,path:V,status:"unsafe",issues:["symlink"]};if(!z.isDirectory())return{kind:P,path:V,status:"unsafe",issues:["not-directory"]};if(process.platform==="win32"||typeof process.getuid!=="function")return{kind:P,path:V,status:"unknown",issues:[]};let Q=[...z.uid!==process.getuid()?["ownership"]:[],...(z.mode&18)!==0?["permissions"]:[]];return{kind:P,path:V,status:Q.length>0?"unsafe":"safe",issues:Q}}catch(z){if(typeof z==="object"&&z!==null&&"code"in z&&z.code==="ENOENT")return{kind:P,path:V,status:"not-applicable",issues:[]};return{kind:P,path:V,status:"unknown",issues:[]}}}function bs(P,V){let z=O(P);return{directories:[ao("policy",so(so(V))),ao("config",so(V)),...z?[ao("audit",z)]:[{kind:"audit",status:"unknown",issues:[]}]]}}import{spawn as np}from"node:child_process";import{existsSync as Ls}from"node:fs";import{delimiter as rp,extname as op,join as ip}from"node:path";import{stripVTControlCharacters as ws}from"node:util";var xs="2.4.9",sp=5000,ap="_CC_SAFETY_NET_TEST_SPAWN_PLATFORM";function wt(){return xs}function lo(P,V){let z=P[V];if(z)return z;let Q=Object.keys(P).find((te)=>te.toLowerCase()===V.toLowerCase()&&!!P[te]);return Q?P[Q]:z}function lp(P){return(lo(P,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").filter((V)=>V.length>0)}function cp(P,V){let z=op(P)?[P]:[...lp(V).map((Q)=>`${P}${Q}`),P];if(P.includes("/")||P.includes("\\"))return z.find((Q)=>Ls(Q))??P;return(lo(V,"PATH")??"").split(rp).flatMap((Q)=>z.map((te)=>ip(Q,te))).find((Q)=>Ls(Q))??P}function ks(P){if(!/[\s"&|<>^]/.test(P))return P;return`"${P.replace(/"/g,'""')}"`}function Xt(P,V){let[z,...Q]=P,te=V[ap]==="win32"?"win32":process.platform;if(!z||te!=="win32")return{cmd:z??"",args:Q};let ne=cp(z,V);if(!/\.(?:bat|cmd)$/i.test(ne))return{cmd:ne,args:Q};return{cmd:lo(V,"COMSPEC")??"cmd.exe",args:["/d","/c",["call",ks(ne),...Q.map(ks)].join(" ")]}}var mn=async(P,V=sp)=>{let z=await dp(P,{timeoutMs:V});if(z.code!==0)return null;return ws(z.stdout).trim()||ws(z.stderr).trim()||null};function dp(P,V){let[z,...Q]=P;if(!z)return Promise.resolve({code:null,stdout:"",stderr:""});return new Promise((te)=>{try{let ne=Xt([z,...Q],process.env),ce=np(ne.cmd,ne.args,{stdio:["ignore","pipe","pipe"]}),he=!1,ye="",be="";ce.stdout.on("data",(Xe)=>{ye+=Xe.toString()}),ce.stderr.on("data",(Xe)=>{be+=Xe.toString()});let xe=(Xe)=>{if(he)return;he=!0,clearTimeout(Ie),te(Xe)},Ie=setTimeout(()=>{ce.kill(),xe({code:null,stdout:ye,stderr:be})},V.timeoutMs);ce.on("close",(Xe)=>{xe({code:Xe,stdout:ye,stderr:be})}),ce.on("error",()=>{xe({code:null,stdout:ye,stderr:be})})}catch{te({code:null,stdout:"",stderr:""})}})}function ir(P){if(!P)return null;let V=/Claude Code\s+(\d+\.\d+\.\d+)/i.exec(P);if(V)return V[1]??null;let z=/v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)/i.exec(P);if(z)return z[1]??null;return P.split(`
|
|
22
22
|
`)[0]?.trim()||null}async function sr(P=mn){let[V,z,Q,te,ne,ce]=await Promise.all([Promise.all($t.map(async(he)=>[he.id,ir(await P([...he.probeCommand]))])),P(["codex","plugin","list"],30000),P(["amp","plugins","list"],30000),P(["node","--version"]),P(["npm","--version"]),P(["bun","--version"])]);return{version:xs,versions:Object.fromEntries(V),codexPluginListOutput:z,ampPluginListOutput:Q,nodeVersion:ir(te),npmVersion:ir(ne),bunVersion:ir(ce),platform:`${process.platform} ${process.arch}`}}function co(P,V){if(V==="dev")return!1;let z=P.split(".").map(Number),Q=V.split(".").map(Number),[te=0,ne=0,ce=0]=z,[he=0,ye=0,be=0]=Q;if(te!==he)return te>he;if(ne!==ye)return ne>ye;return ce>be}async function Wt(){let P=wt(),V=new AbortController,z=setTimeout(()=>V.abort(),3000);try{let Q=await fetch("https://registry.npmjs.org/cc-safety-net/latest",{signal:V.signal});if(!Q.ok)return{currentVersion:P,latestVersion:null,updateAvailable:!1,error:`npm registry returned ${Q.status}`};let te=await Q.json(),ne=co(te.version,P);return{currentVersion:P,latestVersion:te.version,updateAvailable:ne}}catch(Q){return{currentVersion:P,latestVersion:null,updateAvailable:!1,error:Q instanceof Error?Q.message:"Network error"}}finally{clearTimeout(z)}}import*as _s from"node:readline";var Ps=(P)=>`\x1B[${P}B`,up=(P)=>`\x1B[${P}A`;var Cs=["░","▒","▓","╱","╲","┃","━","┏","┓","┗","┛","╋"];function pp(P){return new Promise((V)=>setTimeout(V,P))}function fp(P,V,z){if(!z)return V(P);if(z.aborted)return Promise.resolve();return new Promise((Q,te)=>{let ne=()=>z.removeEventListener("abort",ce),ce=()=>{ne(),Q()};z.addEventListener("abort",ce,{once:!0}),V(P).then(()=>{ne(),Q()},(he)=>{ne(),te(he)})})}function ar(P){return Math.max(0,Math.min(1,P))}function gn(P){return Math.max(0,Math.min(255,Math.round(P)))}function uo(P){return P<=0.0031308?12.92*P:1.055*P**0.4166666666666667-0.055}function mp(P,V,z){let Q=z*Math.PI/180,te=V*Math.cos(Q),ne=V*Math.sin(Q),ce=(P+0.3963377774*te+0.2158037573*ne)**3,he=(P-0.1055613458*te-0.0638541728*ne)**3,ye=(P-0.0894841775*te-1.291485548*ne)**3;return{blue:gn(uo(ar(-0.0041960863*ce-0.7034186147*he+1.707614701*ye))*255),green:gn(uo(ar(-1.2684380046*ce+2.6097574011*he-0.3413193965*ye))*255),red:gn(uo(ar(4.0767416621*ce-3.3077115913*he+0.2309699292*ye))*255)}}function po(P,V){let z=(V*P*180/Math.PI%360+360)%360;return mp(0.72,0.15,z)}function Es(P,V=0.1){let z=po(V,P);return`\x1B[38;2;${z.red};${z.green};${z.blue}m`}function gp(P,V){return{blue:gn(P.blue+(255-P.blue)*V),green:gn(P.green+(255-P.green)*V),red:gn(P.red+(255-P.red)*V)}}function Ds(P,V,z){let Q=Math.imul(P+2654435769,2246822507)^Math.imul(V+3266489909,668265263)^Math.imul(z+374761393,2654435761),te=Q^Q>>>15,ne=Math.imul(te,739982445),ce=ne^ne>>>12,he=Math.imul(ce,695872825);return((he^he>>>15)>>>0)/4294967296}function hp(P,V,z){let Q=Math.floor(Ds(P,V,z)*Cs.length);return Cs[Q]??"░"}function Ss(P){let V=ar(P);return V*V*V*(V*(V*6-15)+10)}function yp(P){if(P.length===0)return"";let V=[],z=!1,Q="";for(let te of P){let ne=`${te.red};${te.green};${te.blue}`;if(te.bold!==z)V.push(te.bold?"\x1B[1m":"\x1B[22m"),z=te.bold;if(ne!==Q)V.push(`\x1B[38;2;${ne}m`),Q=ne;V.push(te.character)}return`${V.join("")}\x1B[22m\x1B[39m`}function vp(P,V,z,Q,te){return P.map((ne,ce)=>({...po(z,Q+V+ce/te),bold:!1,character:ne}))}function bp(P,V,z,Q,te,ne,ce,he){let ye=Math.max(1,Q*0.75),be=Math.min(1,z/ye),xe=te*Ss(be),Ie=Math.max(0,(z-ye)/Math.max(1,Q-ye)),Xe=(1-Ss(z/Q))*he*2,et=0.35*Math.max(0,1-Ie*2),Re=be>=1,at=Math.min(P.length,Math.ceil(xe+2+1));return P.slice(0,at).map((ct,lt)=>{let pt=po(ne,ce+V+lt/he+Xe),mt=lt+Ds(V,lt,7919)*2-1;if(mt>xe+2)return{...pt,bold:!1,character:" "};let gt=xe-mt,ut=0.8*Math.exp(-(gt*gt)/12.5),vt=Math.min(0.9,ut+et),Dt=!Re&&mt>xe-4;return{...gp(pt,vt),bold:vt>0.3,character:Dt?hp(V,lt,z):ct}})}function Rs(P){return`\x1B[?2026h${P.map((V,z)=>`\x1B8${z>0?Ps(z):""}${yp(V)}`).join("")}\x1B[?2026l`}async function fo(P,V={}){if(!P)return;let z=V.output??process.stdout,Q=V.sleep??pp,te=V.seed??0,ne=P.split(`
|
|
23
23
|
`).map((xe)=>Array.from(xe)),ce=Math.max(...ne.map((xe)=>xe.length)),he=12000*ne.filter((xe)=>xe.length>0).length/40,ye=ce>0?Math.max(1,Math.ceil(he/16.666666666666668)):0,be=ye>0?he/ye:0;z.write(`\x1B[?25l${ne.length>1?`${`
|
|
24
24
|
`.repeat(ne.length-1)}${up(ne.length-1)}`:""}\x1B7`);try{for(let xe=1;xe<=ye;xe+=1){if(V.signal?.aborted)break;z.write(Rs(ne.map((Ie,Xe)=>bp(Ie,Xe,xe,ye,ce,0.1,te,3)))),await fp(be,Q,V.signal)}}finally{if(z.write(Rs(ne.map((xe,Ie)=>vp(xe,Ie,0.1,te,3)))),z.write("\x1B8"),ne.length>1)z.write(Ps(ne.length-1));z.write(`
|
|
@@ -207,11 +207,11 @@ def register(ctx):
|
|
|
207
207
|
`)}function Io(P){let V={stdout:"",stderr:""};return P.stdout.setEncoding("utf-8"),P.stderr.setEncoding("utf-8"),P.stdout.on("data",(z)=>{V.stdout+=z}),P.stderr.on("data",(z)=>{V.stderr+=z}),V}function _t(P,V){return new Promise((z,Q)=>{let te=Xt([...P],process.env),ne=z2(te.cmd,te.args,{stdio:["ignore","pipe","pipe"]}),ce=Io(ne),he=()=>[ce.stdout,ce.stderr].filter(Boolean).join(`
|
|
208
208
|
`),ye=V?.timeoutMs??120000,be=setTimeout(()=>{ne.kill(),Q(Error($o(P,null,`Timed out after ${ye}ms.
|
|
209
209
|
${he()}`.trim())))},ye);ne.on("error",(xe)=>{clearTimeout(be),Q(Error($o(P,null,`${xe.message}
|
|
210
|
-
${he()}`.trim())))}),ne.on("close",(xe)=>{if(clearTimeout(be),xe!==0){Q(Error($o(P,xe,he())));return}z(V?.stdoutOnly?ce.stdout:he())})})}async function Oo(P){for(let V of P)await _t(V)}async function Ua(P){for(let V of P)try{await _t(V)}catch(z){console.warn(z instanceof Error?z.message:String(z))}}var Fo=Gt("openclaw",yt),Q2=[It,yn,vn];function jo(P,V){if(P==="~")return V;if(P.startsWith("~/")||P.startsWith("~\\"))return Gt(V,P.slice(2));return P}function Ba(P){let V=P.env.get("OPENCLAW_STATE_DIR")?.trim();if(V)return jo(V,P.home);let z=P.env.get("OPENCLAW_CONFIG_PATH")?.trim();return z?Ga(jo(z,P.home)):Gt(P.home,".openclaw")}function qa(P){let V=P.env.get("OPENCLAW_CONFIG_PATH")?.trim();return V?jo(V,P.home):Gt(Ba(P),"openclaw.json")}function No(P){return Gt(Ba(P),"extensions",yt)}function ef(P){let V=Y2(P);if(V.length===0)return!0;if(V.some((te)=>!Q2.includes(te)))return!1;let z=Gt(P,It),Q=Lt(z);return Q!==void 0&&!Q.isSymbolicLink()&&Q.isFile()&&Z2(z,"utf-8").startsWith(Sr)}function Mo(P){let V=No(P),z=Lt(V);if(!z)return;if(!z.isSymbolicLink()&&z.isDirectory()&&ef(V))return;throw Error(`Refusing to modify ${V}: it does not hold a cc-safety-net managed OpenClaw plugin. Move or remove it, then run the command again.`)}function Va(){let P=Ga(X2(import.meta.url));return[Gt(P,Fo),Gt(P,"..",Fo),Gt(P,"..","..","..","dist",Fo)]}function Ho(P=Va()){return P.find((V)=>W2(V)&&K2(V).isDirectory())}function tf(P=Va()){let V=Ho(P);if(!V)throw Error("Packaged OpenClaw plugin directory not found. Reinstall cc-safety-net and try again.");return V}function za(P=tf()){return[["openclaw","plugins","install",P,"--force"],["openclaw","plugins","enable",yt]]}function nf(P){let V=(()=>{try{return JSON.parse(P)}catch{return}})(),z=ft(ft(V,"plugin"),"status");return typeof z==="string"?z:void 0}async function Ja(){let P=nf(await _t(["openclaw","plugins","inspect",yt,"--runtime","--json"],{stdoutOnly:!0}));if(P==="loaded")return;throw Error(`${P===void 0?`The ${yt} plugin's load state could not be verified: OpenClaw's runtime inspect report was unreadable.`:`OpenClaw reports the ${yt} plugin with status "${P}".`} Run \`openclaw plugins inspect ${yt} --runtime\` for details.`)}var Rr="openclaw",On=`run \`openclaw plugins enable ${yt}\``;function bn(P,V){let z=Fn(P,V),Q=Lt(z);if(!Q)return{error:`${V} is missing from ${z}; run install --openclaw`};if(Q.isSymbolicLink()||!Q.isFile())return{error:`${z} is a symlink or not a regular file; move or remove it`};try{return{content:Ka(z,"utf-8")}}catch(te){return{error:`Failed to read ${z}: ${te instanceof Error?te.message:String(te)}`}}}function Ya(P){try{return JSON.parse(At(P))}catch{return}}function rf(P){let V=bn(P,yn);if("error"in V)return V.error;if(ft(Ya(V.content),"id")===yt)return;return`${Fn(P,yn)} is not a valid ${yt} manifest; run install --openclaw`}function of(P){let V=bn(P,vn);if("error"in V)return V.error;let z=ft(ft(Ya(V.content),"openclaw"),"extensions");if(Array.isArray(z)&&z.includes(`./${It}`))return;return`${Fn(P,vn)} does not point OpenClaw at ${It}; run install --openclaw`}function Wa(P){return Array.isArray(P)?P.filter((V)=>typeof V==="string"):[]}function sf(P){let V=qa(P);if(!Lt(V))return`${yt} is not enabled; ${On}`;let z=(()=>{try{return JSON.parse(At(Ka(V,"utf-8")))}catch{return}})();if(z===void 0)return`Failed to read ${V}; fix it, then ${On}`;let Q=ft(z,"plugins");if(ft(Q,"enabled")===!1)return`plugins.enabled is false in ${V}; no OpenClaw plugin loads`;let te=ft(ft(ft(Q,"entries"),yt),"enabled");if(Wa(ft(Q,"deny")).includes(yt)||te===!1)return`${yt} is disabled in ${V}; ${On}`;let ne=Wa(ft(Q,"allow"));if(ne.length>0&&!ne.includes(yt))return`plugins.allow in ${V} does not list ${yt}; add it, then ${On}`;if(ne.includes(yt)||te===!0)return;return`${yt} is not enabled; ${On}`}function Za(P){return/^\/\/ version:\s*(.+)$/m.exec(P)?.[1]?.trim()}function af(P,V,z){if(z===void 0)return[];let Q=bn(z,It);if("error"in Q||Za(Q.content)!==V)return[];return[It,yn,vn].flatMap((te)=>{let ne=bn(P,te),ce=bn(z,te);if("error"in ne||"error"in ce||ne.content===ce.content)return[];return[`Modified ${te} occupies ${Fn(P,te)}; run install --openclaw to restore it`]})}function Xa(P){let V=No(P.environment),z=ur(Rr,V);if(z)return z;let Q=bn(V,It),ne=["error"in Q?Q.error:Q.content.startsWith(Sr)?void 0:`Unmanaged ${It} occupies ${Fn(V,It)}; move or remove it`,rf(V),of(V)].filter((xe)=>xe!==void 0),ce="content"in Q?Za(Q.content):void 0,he=ne.length>0?ne:af(V,ce,Ho());if(he.length>0)return{platform:Rr,status:"n/a",configPath:V,errors:he};let ye=ce===wt()?[]:["Installed OpenClaw plugin is outdated; run install --openclaw to update"],be=sf(P.environment);if(be)return{platform:Rr,status:"disabled",method:"plugin directory",configPath:V,errors:[be,...ye]};return{platform:Rr,status:"configured",method:"plugin directory",configPath:V,errors:ye.length>0?ye:void 0}}import{existsSync as mf,readFileSync as gf}from"node:fs";import{join as hf}from"node:path";import{existsSync as Pr,readFileSync as Uo,rmSync as lf}from"node:fs";import{join as Bt}from"node:path";import{pathToFileURL as cf}from"node:url";var Er="cc-safety-net",nn=`${Er}@latest`,el=["opencode.json","opencode.jsonc"],Qa="CCSafetyNetPlugin",df={stringError:"Unterminated string in OpenCode config",bracketError:"Unmatched plugin array in OpenCode config"};function Dr(P){return P.env.get("OPENCODE_CONFIG_DIR")??Bt(P.env.get("XDG_CONFIG_HOME")||Bt(P.home,".config"),"opencode")}function uf(P){return Bt(Dr(P),el[0])}function tl(P){return el.map((V)=>Bt(Dr(P),V))}function nl(P){return Bt(P.env.get("XDG_CACHE_HOME")||Bt(P.home,".cache"),"opencode","packages",nn)}function rl(P){lf(nl(P),{recursive:!0,force:!0})}async function ol(P){let V=(await _t(["opencode","--version"],{stdoutOnly:!0})).trim(),z=/^(?:opencode\s+)?v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(V),Q=Number(z?.[1]),te=Number(z?.[2]),ne=Number(z?.[3]);if(!z||Q!==1&&Q!==2||Q===1&&(te<18||te===18&&ne<29)||Q===2&&te===0&&ne<6)throw Error(`OpenCode 1.18.29+ or 2.0.6+ is required; found ${V||"an unknown version"}.`);if(Q===2){for(let ce of tl(P)){if(!Pr(ce))continue;let he=Go(Uo(ce,"utf-8"),ce);if(["plugin","plugins"].some((be)=>{let xe=ft(he,be);return Array.isArray(xe)&&xe.some((Ie)=>Bo(Ie)&&(typeof Ie==="string"?Ie:ft(Ie,"package"))!==nn)}))throw Error(`Change the cc-safety-net package spec in ${ce} to ${nn}, preserving its options, then retry. Adding another spec would create a duplicate plugin ID.`)}return{commands:[["opencode","plugin","add",nn],["opencode","plugin","update",nn]],afterInstall:async()=>{let ce=await _t(["opencode","plugin","list"],{stdoutOnly:!0});if(/^cc-safety-net\s+\S+\s+cc-safety-net@latest\s*$/m.test(ce))return;throw Error("OpenCode did not load cc-safety-net from cc-safety-net@latest. Run `opencode plugin list` for details.")}}}return rl(P),{commands:[["opencode","plugin","-g","-f",nn]],afterInstall:()=>pf(P)}}async function pf(P){let V=Bt(nl(P),"node_modules",Er),z=Bt(V,"package.json");if(!Pr(z))throw Error(`The OpenCode plugin cache at ${V} is missing its package, so OpenCode would load nothing and fail open. Run \`opencode plugin -g -f ${nn}\` for details.`);let Q=ft(JSON.parse(Uo(z,"utf-8")),"main");if(typeof Q!=="string")throw Error(`The cached OpenCode plugin at ${V} declares no "main" entry.`);let te=Bt(V,Q);if(typeof(await import(cf(te).href))[Qa]==="function")return;throw Error(`The cached OpenCode plugin at ${te} does not export a callable ${Qa}, so OpenCode would load nothing and fail open.`)}function Go(P,V){try{return JSON.parse(At(P))}catch(z){if(z instanceof SyntaxError)throw Error(`Failed to parse OpenCode config ${V}: ${z.message}`);throw z}}function Bo(P){let V=typeof P==="string"?P:ft(P,"package");return typeof V==="string"&&(V===Er||V.startsWith(`${Er}@`))}function qo(P){return["plugin","plugins"].some((V)=>{let z=ft(P,V);return Array.isArray(z)&&z.some(Bo)})}function ff(P,V){let Q=["plugin","plugins"].flatMap((te)=>{let ne=Xs(P,te,df);if(!ne)return[];let ce=[],he=0,ye=ne.start+1,be=P.slice(ne.start+1,ne.end).matchAll(/\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|[^"\s{}[\],/]+|[{}[\],]/g);for(let xe of be){if(xe[0].startsWith("//")||xe[0].startsWith("/*"))continue;let Ie=ne.start+1+xe.index;if(he===0)ye=Ie;if(xe[0]==="{"||xe[0]==="[")he++;if(xe[0]==="}"||xe[0]==="]")he--;if(he!==0||xe[0]===",")continue;let Xe=Ie+xe[0].length;if(Bo(JSON.parse(At(P.slice(ye,Xe)))))ce.push({start:ye,end:Xe})}return ce}).sort((te,ne)=>te.start-ne.start).reverse().reduce((te,ne)=>{let ce=/^(?:\s|\/\/[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*,/.exec(te.slice(ne.end));if(ce?.[0].includes("/")){let he=ne.end+ce[0].length-1;return te.slice(0,ne.start)+te.slice(ne.end,he)+te.slice(he+1)}return fr(te,ne)},P);return Go(Q,V),Q}function il(P){rl(P);let V=tl(P),z=V.find((ne)=>Pr(ne)),Q=[],te=[];for(let ne of V){if(!Pr(ne))continue;try{let ce=Uo(ne,"utf-8");if(!qo(Go(ce,ne)))continue;kt(ne,ff(ce,ne)),te.push(ne)}catch(ce){Q.push(ce instanceof Error?ce.message:String(ce))}}if(Q.length>0)throw Error(Q.join(`
|
|
210
|
+
${he()}`.trim())))}),ne.on("close",(xe)=>{if(clearTimeout(be),xe!==0){Q(Error($o(P,xe,he())));return}z(V?.stdoutOnly?ce.stdout:he())})})}async function Oo(P){for(let V of P)await _t(V)}async function Ua(P){for(let V of P)try{await _t(V)}catch(z){console.warn(z instanceof Error?z.message:String(z))}}var Fo=Gt("openclaw",yt),Q2=[It,yn,vn];function jo(P,V){if(P==="~")return V;if(P.startsWith("~/")||P.startsWith("~\\"))return Gt(V,P.slice(2));return P}function Ba(P){let V=P.env.get("OPENCLAW_STATE_DIR")?.trim();if(V)return jo(V,P.home);let z=P.env.get("OPENCLAW_CONFIG_PATH")?.trim();return z?Ga(jo(z,P.home)):Gt(P.home,".openclaw")}function qa(P){let V=P.env.get("OPENCLAW_CONFIG_PATH")?.trim();return V?jo(V,P.home):Gt(Ba(P),"openclaw.json")}function No(P){return Gt(Ba(P),"extensions",yt)}function ef(P){let V=Y2(P);if(V.length===0)return!0;if(V.some((te)=>!Q2.includes(te)))return!1;let z=Gt(P,It),Q=Lt(z);return Q!==void 0&&!Q.isSymbolicLink()&&Q.isFile()&&Z2(z,"utf-8").startsWith(Sr)}function Mo(P){let V=No(P),z=Lt(V);if(!z)return;if(!z.isSymbolicLink()&&z.isDirectory()&&ef(V))return;throw Error(`Refusing to modify ${V}: it does not hold a cc-safety-net managed OpenClaw plugin. Move or remove it, then run the command again.`)}function Va(){let P=Ga(X2(import.meta.url));return[Gt(P,Fo),Gt(P,"..",Fo),Gt(P,"..","..","..","dist",Fo)]}function Ho(P=Va()){return P.find((V)=>W2(V)&&K2(V).isDirectory())}function tf(P=Va()){let V=Ho(P);if(!V)throw Error("Packaged OpenClaw plugin directory not found. Reinstall cc-safety-net and try again.");return V}function za(P=tf()){return[["openclaw","plugins","install",P,"--force","--accept-capabilities"],["openclaw","plugins","enable",yt]]}function nf(P){let V=(()=>{try{return JSON.parse(P)}catch{return}})(),z=ft(ft(V,"plugin"),"status");return typeof z==="string"?z:void 0}async function Ja(){let P=nf(await _t(["openclaw","plugins","inspect",yt,"--runtime","--json"],{stdoutOnly:!0}));if(P==="loaded")return;throw Error(`${P===void 0?`The ${yt} plugin's load state could not be verified: OpenClaw's runtime inspect report was unreadable.`:`OpenClaw reports the ${yt} plugin with status "${P}".`} Run \`openclaw plugins inspect ${yt} --runtime\` for details.`)}var Rr="openclaw",On=`run \`openclaw plugins enable ${yt}\``;function bn(P,V){let z=Fn(P,V),Q=Lt(z);if(!Q)return{error:`${V} is missing from ${z}; run install --openclaw`};if(Q.isSymbolicLink()||!Q.isFile())return{error:`${z} is a symlink or not a regular file; move or remove it`};try{return{content:Ka(z,"utf-8")}}catch(te){return{error:`Failed to read ${z}: ${te instanceof Error?te.message:String(te)}`}}}function Ya(P){try{return JSON.parse(At(P))}catch{return}}function rf(P){let V=bn(P,yn);if("error"in V)return V.error;if(ft(Ya(V.content),"id")===yt)return;return`${Fn(P,yn)} is not a valid ${yt} manifest; run install --openclaw`}function of(P){let V=bn(P,vn);if("error"in V)return V.error;let z=ft(ft(Ya(V.content),"openclaw"),"extensions");if(Array.isArray(z)&&z.includes(`./${It}`))return;return`${Fn(P,vn)} does not point OpenClaw at ${It}; run install --openclaw`}function Wa(P){return Array.isArray(P)?P.filter((V)=>typeof V==="string"):[]}function sf(P){let V=qa(P);if(!Lt(V))return`${yt} is not enabled; ${On}`;let z=(()=>{try{return JSON.parse(At(Ka(V,"utf-8")))}catch{return}})();if(z===void 0)return`Failed to read ${V}; fix it, then ${On}`;let Q=ft(z,"plugins");if(ft(Q,"enabled")===!1)return`plugins.enabled is false in ${V}; no OpenClaw plugin loads`;let te=ft(ft(ft(Q,"entries"),yt),"enabled");if(Wa(ft(Q,"deny")).includes(yt)||te===!1)return`${yt} is disabled in ${V}; ${On}`;let ne=Wa(ft(Q,"allow"));if(ne.length>0&&!ne.includes(yt))return`plugins.allow in ${V} does not list ${yt}; add it, then ${On}`;if(ne.includes(yt)||te===!0)return;return`${yt} is not enabled; ${On}`}function Za(P){return/^\/\/ version:\s*(.+)$/m.exec(P)?.[1]?.trim()}function af(P,V,z){if(z===void 0)return[];let Q=bn(z,It);if("error"in Q||Za(Q.content)!==V)return[];return[It,yn,vn].flatMap((te)=>{let ne=bn(P,te),ce=bn(z,te);if("error"in ne||"error"in ce||ne.content===ce.content)return[];return[`Modified ${te} occupies ${Fn(P,te)}; run install --openclaw to restore it`]})}function Xa(P){let V=No(P.environment),z=ur(Rr,V);if(z)return z;let Q=bn(V,It),ne=["error"in Q?Q.error:Q.content.startsWith(Sr)?void 0:`Unmanaged ${It} occupies ${Fn(V,It)}; move or remove it`,rf(V),of(V)].filter((xe)=>xe!==void 0),ce="content"in Q?Za(Q.content):void 0,he=ne.length>0?ne:af(V,ce,Ho());if(he.length>0)return{platform:Rr,status:"n/a",configPath:V,errors:he};let ye=ce===wt()?[]:["Installed OpenClaw plugin is outdated; run install --openclaw to update"],be=sf(P.environment);if(be)return{platform:Rr,status:"disabled",method:"plugin directory",configPath:V,errors:[be,...ye]};return{platform:Rr,status:"configured",method:"plugin directory",configPath:V,errors:ye.length>0?ye:void 0}}import{existsSync as mf,readFileSync as gf}from"node:fs";import{join as hf}from"node:path";import{existsSync as Pr,readFileSync as Uo,rmSync as lf}from"node:fs";import{join as Bt}from"node:path";import{pathToFileURL as cf}from"node:url";var Er="cc-safety-net",nn=`${Er}@latest`,el=["opencode.json","opencode.jsonc"],Qa="CCSafetyNetPlugin",df={stringError:"Unterminated string in OpenCode config",bracketError:"Unmatched plugin array in OpenCode config"};function Dr(P){return P.env.get("OPENCODE_CONFIG_DIR")??Bt(P.env.get("XDG_CONFIG_HOME")||Bt(P.home,".config"),"opencode")}function uf(P){return Bt(Dr(P),el[0])}function tl(P){return el.map((V)=>Bt(Dr(P),V))}function nl(P){return Bt(P.env.get("XDG_CACHE_HOME")||Bt(P.home,".cache"),"opencode","packages",nn)}function rl(P){lf(nl(P),{recursive:!0,force:!0})}async function ol(P){let V=(await _t(["opencode","--version"],{stdoutOnly:!0})).trim(),z=/^(?:opencode\s+)?v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(V),Q=Number(z?.[1]),te=Number(z?.[2]),ne=Number(z?.[3]);if(!z||Q!==1&&Q!==2||Q===1&&(te<18||te===18&&ne<29)||Q===2&&te===0&&ne<6)throw Error(`OpenCode 1.18.29+ or 2.0.6+ is required; found ${V||"an unknown version"}.`);if(Q===2){for(let ce of tl(P)){if(!Pr(ce))continue;let he=Go(Uo(ce,"utf-8"),ce);if(["plugin","plugins"].some((be)=>{let xe=ft(he,be);return Array.isArray(xe)&&xe.some((Ie)=>Bo(Ie)&&(typeof Ie==="string"?Ie:ft(Ie,"package"))!==nn)}))throw Error(`Change the cc-safety-net package spec in ${ce} to ${nn}, preserving its options, then retry. Adding another spec would create a duplicate plugin ID.`)}return{commands:[["opencode","plugin","add",nn],["opencode","plugin","update",nn]],afterInstall:async()=>{let ce=await _t(["opencode","plugin","list"],{stdoutOnly:!0});if(/^cc-safety-net\s+\S+\s+cc-safety-net@latest\s*$/m.test(ce))return;throw Error("OpenCode did not load cc-safety-net from cc-safety-net@latest. Run `opencode plugin list` for details.")}}}return rl(P),{commands:[["opencode","plugin","-g","-f",nn]],afterInstall:()=>pf(P)}}async function pf(P){let V=Bt(nl(P),"node_modules",Er),z=Bt(V,"package.json");if(!Pr(z))throw Error(`The OpenCode plugin cache at ${V} is missing its package, so OpenCode would load nothing and fail open. Run \`opencode plugin -g -f ${nn}\` for details.`);let Q=ft(JSON.parse(Uo(z,"utf-8")),"main");if(typeof Q!=="string")throw Error(`The cached OpenCode plugin at ${V} declares no "main" entry.`);let te=Bt(V,Q);if(typeof(await import(cf(te).href))[Qa]==="function")return;throw Error(`The cached OpenCode plugin at ${te} does not export a callable ${Qa}, so OpenCode would load nothing and fail open.`)}function Go(P,V){try{return JSON.parse(At(P))}catch(z){if(z instanceof SyntaxError)throw Error(`Failed to parse OpenCode config ${V}: ${z.message}`);throw z}}function Bo(P){let V=typeof P==="string"?P:ft(P,"package");return typeof V==="string"&&(V===Er||V.startsWith(`${Er}@`))}function qo(P){return["plugin","plugins"].some((V)=>{let z=ft(P,V);return Array.isArray(z)&&z.some(Bo)})}function ff(P,V){let Q=["plugin","plugins"].flatMap((te)=>{let ne=Xs(P,te,df);if(!ne)return[];let ce=[],he=0,ye=ne.start+1,be=P.slice(ne.start+1,ne.end).matchAll(/\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|[^"\s{}[\],/]+|[{}[\],]/g);for(let xe of be){if(xe[0].startsWith("//")||xe[0].startsWith("/*"))continue;let Ie=ne.start+1+xe.index;if(he===0)ye=Ie;if(xe[0]==="{"||xe[0]==="[")he++;if(xe[0]==="}"||xe[0]==="]")he--;if(he!==0||xe[0]===",")continue;let Xe=Ie+xe[0].length;if(Bo(JSON.parse(At(P.slice(ye,Xe)))))ce.push({start:ye,end:Xe})}return ce}).sort((te,ne)=>te.start-ne.start).reverse().reduce((te,ne)=>{let ce=/^(?:\s|\/\/[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*,/.exec(te.slice(ne.end));if(ce?.[0].includes("/")){let he=ne.end+ce[0].length-1;return te.slice(0,ne.start)+te.slice(ne.end,he)+te.slice(he+1)}return fr(te,ne)},P);return Go(Q,V),Q}function il(P){rl(P);let V=tl(P),z=V.find((ne)=>Pr(ne)),Q=[],te=[];for(let ne of V){if(!Pr(ne))continue;try{let ce=Uo(ne,"utf-8");if(!qo(Go(ce,ne)))continue;kt(ne,ff(ce,ne)),te.push(ne)}catch(ce){Q.push(ce instanceof Error?ce.message:String(ce))}}if(Q.length>0)throw Error(Q.join(`
|
|
211
211
|
`));return{path:te[0]??z??uf(P),alreadyInstalled:te.length>0}}function sl(P){let V=[],z=Dr(P.environment),Q=["opencode.json","opencode.jsonc"];for(let te of Q){let ne=hf(z,te);if(mf(ne))try{let ce=gf(ne,"utf-8"),he=At(ce),ye=JSON.parse(he);if(qo(ye))return{platform:"opencode",status:"configured",method:"plugin array",configPath:ne,errors:V.length>0?V:void 0}}catch(ce){V.push(`Failed to parse ${te}: ${ce instanceof Error?ce.message:String(ce)}`)}}return{platform:"opencode",status:"n/a",errors:V.length>0?V:void 0}}import{join as yf}from"node:path";function Vo(P){return yf(P.home,".pi","agent","settings.json")}function zo(P){if(typeof P!=="string")return!1;return P==="npm:cc-safety-net"||P.startsWith("npm:cc-safety-net@")}function al(P){let V=Vo(P.environment),z=Ft(V);if(z.kind==="unreadable")return{platform:"pi",status:"not-inspected"};if(z.kind==="missing")return{platform:"pi",status:"n/a"};let Q=ft(z.value,"packages");if(!Array.isArray(Q))return{platform:"pi",status:"n/a"};let te=Q.find((he)=>zo(typeof he==="string"?he:ft(he,"source")));if(te===void 0)return{platform:"pi",status:"n/a"};let ne=ft(te,"extensions");if(Array.isArray(ne)&&ne.some((he)=>typeof he==="string"&&he.startsWith("-")))return{platform:"pi",status:"disabled",method:"package config",configPath:V,errors:["npm:cc-safety-net is installed but its extension is disabled in Pi settings"]};return{platform:"pi",status:"configured",method:"package config",configPath:V}}var vf={amp:Gs,"antigravity-cli":Bs,"claude-code":Js,codex:Ws,"copilot-cli":ca,cursor:ya,"gemini-cli":va,"grok-build":Ea,"hermes-agent":Ma,"kimi-code":In,openclaw:Xa,opencode:sl,pi:al};function Ln(P,V,z){let Q={...z,cwd:V,environment:P};return Zn.map((te)=>bf(vf[te](Q)))}function bf(P){if(P.status==="not-inspected")return{platform:P.platform,detected:!1,configured:!1,inspectionStatus:"not-inspected"};return{platform:P.platform,detected:P.status!=="n/a",configured:P.status==="configured",inspectionStatus:P.status!=="n/a"?"verified":P.errors&&P.errors.length>0?"failed":"not-applicable",method:P.method,configPath:P.configPath,configPaths:P.configPaths,errors:P.errors}}import{join as Lf}from"node:path";var wf=Object.freeze([{command:"git reset --hard",description:"git reset --hard",expectBlocked:!0},{command:"rm -rf /",description:"rm -rf /",expectBlocked:!0},{command:"rm -rf ./node_modules",description:"rm in cwd (safe)",expectBlocked:!1}]),kf=Object.freeze({state:"ready",diagnostics:Object.freeze([]),ruleMetadata:Object.freeze({}),policy:Object.freeze({rules:Object.freeze([]),transparentWrappers:Object.freeze([]),safety:Object.freeze({}),worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:Object.freeze({}),destructiveCommandAllowPaths:Object.freeze([]),secretProtection:Object.freeze({enabled:!0,disabledRules:Object.freeze([]),denyPaths:Object.freeze([]),allowPaths:Object.freeze([])})})}),xf={strict:!1,paranoidRm:!1,paranoidInterpreters:!1,worktreeMode:!1,effectiveLevel:"standard",capabilities:{fail_closed:{enabled:!1,source:"preset",sources:[]},paranoid_rm:{enabled:!1,source:"preset",sources:[]},paranoid_interpreters:{enabled:!1,source:"preset",sources:[]}}};function ll(P){let V=Lf(P.tmpdir,"cc-safety-net-self-test"),z=wf.map((Q)=>{let te=D(P,d("self-test",{command:Q.command},{kind:"command",shell:"auto"},{configCwd:V,executionCwd:V},Q.command),{guard:{dependencies:{loadPolicySnapshot:()=>kf,getModes:()=>xf,findPolicyMutation:()=>null}},audit:{agent:"self-test",getSessionId:()=>{return}}}),ne=Q.expectBlocked?"blocked":"allowed",ce=te.decision.kind==="deny"?"blocked":"allowed";return{command:Q.command,description:Q.description,expected:ne,actual:ce,passed:ne===ce,reason:te.decision.kind==="deny"?te.decision.reason:void 0,ruleId:te.decision.kind==="deny"?te.decision.ruleId:void 0}});return{passed:z.filter((Q)=>Q.passed).length,failed:z.filter((Q)=>!Q.passed).length,total:z.length,results:z}}function Jo(P){let V=xt({label:"doctor",booleans:{json:["--json"],skipUpdateCheck:["--skip-update-check"]}},P);if(Ht(V.errors))return null;return{json:V.flags.json,skipUpdateCheck:V.flags.skipUpdateCheck}}async function cl(P,V={}){let z=await Pn(!V.json,()=>{let Q=Cf(P,V);return{ready:Q,finish:()=>Q}},()=>Rn(),{loadingMessage:"Checking system status…"});if(V.json)console.log(JSON.stringify(z,null,2));else Sf(z);return z.engineSelfTest.failed>0||z.findings.some((Q)=>Q.severity==="error")?1:0}async function Cf(P,V){let z=V.cwd??process.cwd(),Q=await sr(),te=Ln(P,z,{ampPluginListOutput:Q.ampPluginListOutput,codexPluginListOutput:Q.codexPluginListOutput,copilotCliVersion:Q.versions["copilot-cli"]}),ne=os(P,z),ce=is(P),he=E(P,{cwd:z}),ye=he.policy,be=R(ye,P.env),xe=G(ye,be.capabilities),Ie=tr(P,7),Xe=js(P,z),et=V.skipUpdateCheck?{currentVersion:wt(),latestVersion:null,updateAvailable:!1}:await Wt(),Re={hooks:te,engineSelfTest:ll(P),userConfig:ne.userConfig,projectConfig:ne.projectConfig,configState:Ne(he),effectiveRules:ne.effectiveRules,environment:ce,effectiveSafety:{selectedPreset:ye.safety.level??"standard",level:be.effectiveLevel,capabilities:be.capabilities,ruleOverrides:ye.destructiveCommandRuleOverrides,weakenedRuleOverrides:Object.entries(xe).filter(([,at])=>at.source==="rule_override"&&at.override==="off"&&at.inheritedEnabled&&at.changesInherited).map(([at])=>at),ruleCounts:{stored:Object.keys(ye.destructiveCommandRuleOverrides).length,effective:Object.values(xe).filter((at)=>at.changesInherited).length},...he.policyScopes?{policyScopes:he.policyScopes}:{}},...Xe.length>0?{v2Leftovers:Xe}:{},posture:bs(P,ne.userConfig.path),activity:Ie,update:et,system:Q};return{...Re,findings:as(Re)}}function Sf(P){console.log(),console.log(cs(P.hooks)),console.log(),console.log(ds(P.engineSelfTest)),console.log(),console.log(us(P)),console.log(),console.log(ps(P.environment)),console.log(),console.log(fs(P)),console.log(),console.log(ms(P.findings)),console.log(),console.log(gs(P.activity)),console.log(),console.log(ys(P.system)),console.log(),console.log(hs(P.update)),console.log(vs(P))}import{existsSync as Rf}from"node:fs";var Pf=/^[A-Za-z0-9_@%+=:,./-]+$/,dl="Usage: cc-safety-net explain [--json] [--cwd <path>] <command>";function Wo(P){let V=xt({label:"explain",booleans:{json:["--json"]},values:{cwd:["--cwd"]},positionals:"tail"},P);if(Ht(V.errors))return console.error(dl),console.error("Pass -- before a command that starts with dashes."),null;if(V.values.cwd!==void 0&&!Rf(V.values.cwd))return console.error(`Error: --cwd path does not exist: ${V.values.cwd}`),null;let z=V.positionals.length===1?V.positionals[0]:V.positionals.map((Q)=>Pf.test(Q)?Q:`'${Q.replaceAll("'","'\\''")}'`).join(" ");if(!z)return console.error("Error: No command provided"),console.error(dl),null;return{json:V.flags.json,cwd:V.values.cwd,command:z}}function ul(P){if(P)return{dh:"=",dv:"|",dtl:"+",dtr:"+",dbl:"+",dbr:"+",h:"-",v:"|",tl:"+",tr:"+",bl:"+",br:"+",sh:"="};return{dh:"═",dv:"║",dtl:"╔",dtr:"╗",dbl:"╚",dbr:"╝",h:"─",v:"│",tl:"┌",tr:"┐",bl:"└",br:"┘",sh:"━"}}function pl(P,V){let Q=V-18;return[`${P.dtl}${P.dh.repeat(V)}${P.dtr}`,`${P.dv} Command Analysis${" ".repeat(Q)}${P.dv}`,`${P.dbl}${P.dh.repeat(V)}${P.dbr}`]}function Ko(P){return JSON.stringify(P)}function fl(P,V=0){return`[${P.map((Q,te)=>ls(Q,te,V)).join(",")}]`}function jn(P,V,z=70){let Q=P.split(" "),te=[],ne="";for(let ce of Q)if(ne&&ne.length+ce.length+1>z)te.push(ne),ne=ce;else ne=ne?`${ne} ${ce}`:ce;if(ne)te.push(ne);return te.map((ce,he)=>he===0?ce:`${V}${ce}`)}function ml(P,V,z){let Q=[];switch(P.type){case"parse":return null;case"env-strip":return Q.push(""),Q.push(`STEP ${V} ${z.h} Strip environment variables`),Q.push(` Removed: ${P.envVars.map((te)=>`${te}=<redacted>`).join(", ")}`),Q.push(` Tokens: ${Ko(P.output)}`),{lines:Q,incrementStep:!0};case"leading-tokens-stripped":return Q.push(""),Q.push(`STEP ${V} ${z.h} Strip wrappers`),Q.push(` Removed: ${P.removed.join(", ")}`),Q.push(` Tokens: ${Ko(P.output)}`),{lines:Q,incrementStep:!0};case"shell-wrapper":return Q.push(""),Q.push(`STEP ${V} ${z.h} Detect shell wrapper`),Q.push(` Wrapper: ${P.wrapper} -c`),Q.push(` Inner: ${P.innerCommand}`),{lines:Q,incrementStep:!0};case"interpreter":{if(Q.push(""),Q.push(`STEP ${V} ${z.h} Detect interpreter`),Q.push(` Interpreter: ${P.interpreter}`),Q.push(` Code: ${P.codeArg}`),P.paranoidBlocked)Q.push(" Result: ✗ BLOCKED (paranoid mode)");return{lines:Q,incrementStep:!0}}case"busybox":return Q.push(""),Q.push(`STEP ${V} ${z.h} Busybox wrapper`),Q.push(` Subcommand: ${P.subcommand}`),{lines:Q,incrementStep:!0};case"transparent-wrapper":return Q.push(""),Q.push(`STEP ${V} ${z.h} Transparent wrapper`),Q.push(` Wrapper: ${P.wrapper}`),Q.push(` Tokens: ${Ko(P.output)}`),{lines:Q,incrementStep:!0};case"recurse":return{lines:[],incrementStep:!1};case"rule-check":{if(Q.push(""),Q.push(`STEP ${V} ${z.h} Match rules`),Q.push(` Rule: ${P.rule}()`),P.matched)Q.push(" Result: MATCHED");else Q.push(" Result: No match");return{lines:Q,incrementStep:!0}}case"worktree-relaxation":return Q.push(""),Q.push(`STEP ${V} ${z.h} Worktree relaxation`),Q.push(` Mode: ${o.worktree.name}`),Q.push(` Git cwd: ${P.gitCwd}`),Q.push(" Result: Allowed local discard in linked worktree"),{lines:Q,incrementStep:!0};case"temp-root-relaxation":return Q.push(""),Q.push(`STEP ${V} ${z.h} Temp-root relaxation`),Q.push(` Git cwd: ${P.gitCwd}`),Q.push(" Result: Allowed git discard in a temp-root repository"),{lines:Q,incrementStep:!0};case"tmpdir-check":return null;case"fallback-scan":{if(P.embeddedCommandFound)return Q.push(""),Q.push(`STEP ${V} ${z.h} Fallback scan`),Q.push(` Found: ${P.embeddedCommandFound}`),{lines:Q,incrementStep:!0};return null}case"custom-rules-check":{if(P.rulesChecked){if(Q.push(""),Q.push(`STEP ${V} ${z.h} Custom rules`),P.matched)Q.push(" Result: MATCHED");else Q.push(" Result: No match");return{lines:Q,incrementStep:!0}}return null}case"cwd-change":return null;case"dangerous-text":{if(P.matched)return Q.push(""),Q.push(`STEP ${V} ${z.h} Dangerous text check`),Q.push(` Token: ${P.token}`),Q.push(" Result: MATCHED"),{lines:Q,incrementStep:!0};return null}case"strict-unparseable":return Q.push(""),Q.push(`STEP ${V} ${z.h} Strict mode check`),Q.push(` Command: ${P.rawCommand}`),Q.push(" Result: ✗ UNPARSEABLE"),{lines:Q,incrementStep:!0};case"segment-skipped":return null;case"error":return Q.push(""),Q.push(`ERROR: ${P.message}`),{lines:Q,incrementStep:!1};default:return P}}function Yo(P,V){let z=ul(V?.asciiOnly??!1),Q=58,te=[],ne=1;te.push(...pl(z,58)),te.push("");let ce=P.trace.steps.find((Re)=>Re.type==="error");if(ce&&ce.type==="error"){te.push("ERROR"),te.push(` ${ce.message}`),te.push(""),te.push("RESULT"),te.push(` Status: ${P.result==="blocked"?dt.red("BLOCKED"):dt.green("ALLOWED")}`),te.push(""),te.push("CONFIG");let Re=P.configSource??"none";return te.push(` Path: ${Re}`),te.join(`
|
|
212
212
|
`)}let he=P.trace.steps.find((Re)=>Re.type==="parse");if(he&&he.type==="parse"){te.push("INPUT"),te.push(` ${he.input}`),te.push(""),te.push(`STEP ${ne} ${z.h} Split shell commands`),ne++;for(let Re=0;Re<he.segments.length;Re++){let at=he.segments[Re];if(at){let ct=Math.random();te.push(` Segment ${Re+1}: ${fl(at,ct)}`)}}}let ye=P.trace.segments,be=ye.length>1;for(let Re of ye){if(be){te.push("");let pt="";if(he&&he.type==="parse"){let Xr=he.segments[Re.index];if(Xr)pt=Xr.join(" ")}let mt=54,gt=pt,ut=` Segment ${Re.index+1}: `,vt=" ";if(pt){if(ut.length+pt.length+vt.length>mt){let Hd=mt-ut.length-vt.length;gt=`${pt.substring(0,Hd-1)}…`}}let Dt=pt?`${ut}${gt}${vt}`:` Segment ${Re.index+1} `,Nd=pt?`${ut}${dt.cyan(gt)}${vt}`:Dt,$i=58-Dt.length,Ii=Math.floor($i/2),Md=$i-Ii;te.push(`${z.sh.repeat(Ii)}${Nd}${z.sh.repeat(Md)}`)}if(Re.steps.find((pt)=>pt.type==="segment-skipped")){te.push(""),te.push(" (skipped — prior segment blocked)");continue}let ct=!1,lt=!1;for(let pt of Re.steps){let mt=ml(pt,ne,z);if(mt){if(lt=!0,pt.type==="recurse"){te.push("");let gt=" RECURSING ",ut=58-gt.length-4;te.push(` ${z.tl}${z.h}${gt}${z.h.repeat(ut)}`),te.push(` ${z.v}`),ct=!0;continue}for(let gt of mt.lines)if(ct)te.push(` ${z.v} ${gt}`);else te.push(gt);if(mt.incrementStep)ne++}}if(ct)te.push(` ${z.v}`),te.push(` ${z.bl}${z.h.repeat(56)}`);if(!lt)te.push(""),te.push(` ${dt.green("✓")} Allowed (no matching rules)`)}if(te.push(""),te.push("RESULT"),P.result==="blocked"){if(te.push(` Status: ${dt.red("BLOCKED")}`),P.customRule){if(te.push(` Rule: ${P.customRule.id}`),P.customRule.rulebook)te.push(` Rulebook: ${P.customRule.rulebook.name} ${P.customRule.rulebook.version}`);if(P.customRule.source)te.push(` Source: ${P.customRule.source}`);if(P.customRule.override)te.push(` Override: reason ${P.customRule.override.reason}`)}if(P.reason){let Re=jn(P.reason," ");te.push(` Reason: ${Re[0]}`);for(let at=1;at<Re.length;at++)te.push(Re[at]??"")}}else te.push(` Status: ${dt.green("ALLOWED")}`);te.push(""),te.push("CONFIG");let xe=P.configSource??"none",Ie=P.configValid?"":" (invalid)";te.push(` Path: ${xe}${Ie}`);let Xe=P.safetyPresetScope;te.push(` Safety preset: ${P.selectedPreset??"standard"}${Xe?` (${rr(Xe)})`:""}`),te.push(` Effective capabilities: ${P.effectiveLevel}`);let et=Object.entries(P.destructiveCommandRuleOverrides??{});if(te.push(` Rule customizations: ${et.length}`),P.ruleActivation)te.push(` Rule activation: ${P.ruleActivation.id} — ${P.ruleActivation.enabled?"on":"off"} via ${P.ruleActivation.source}`);return te.join(`
|
|
213
213
|
`)}function Zo(P){return JSON.stringify(P,null,2)}import{resolve as Tf}from"node:path";var Ef=["AKIA","ASIA","ghp_","gho_","ghu_","ghs_","ghr_","github_pat_","glpat-","xox","npm_","pypi-","rk_","sk-","sk_","gsk_","xai-","pplx-","bastn_","tgp_v1_","flp_","wfr_","fw_","fwp_","tp-","psk-"];function gl(P){let V=0,z={allocateSegment(){return V++},getNextSegmentIndex(){return V},recordGlobal(Q){P.record({kind:"step",scope:"global",step:Q})},recordSegment(Q,te=z.currentSegmentIndex){if(te===void 0)return;P.record({kind:"step",scope:"segment",segmentIndex:te,step:Q})}};return z}function hl(P={}){let V=[],z=P.maxEvents??512,Q={maxTextLength:P.maxTextLength??2048,maxListLength:P.maxListLength??128,maxObjectProperties:P.maxObjectProperties??P.maxListLength??128,maxDepth:P.maxDepth??16},te,ne=new Set;return{record(ce){if(te)return;if(!ce||V.length>=z)return;try{V.push(ei(Df(ce,Q,ne)))}catch{}},finish(){if(te)return te;return te=ei({events:Object.freeze(V)}),te}}}function Df(P,V,z){if(P.kind!=="step")throw TypeError("invalid trace event");let{scope:Q,step:te}=P;Ar(te,z,V);let ne=Xo(te,V,z);if(Q==="global")return{kind:"step",scope:"global",step:ne};if(Q!=="segment")throw TypeError("invalid trace event scope");return{kind:"step",scope:"segment",segmentIndex:P.segmentIndex,step:ne}}function Ar(P,V,z,Q=0,te=new WeakSet){if(typeof P==="string"){let he=P.slice(0,z.maxTextLength);if(!Ge(he))return;for(let ye of Ze(he))for(let be of ye.match(/[^\s"'()$]+/g)??[])V.add(yl(be));return}if(!P||typeof P!=="object"||Q>=z.maxDepth||te.has(P))return;if(te.add(P),Array.isArray(P)){let he=Math.min(P.length,z.maxListLength);for(let ye=0;ye<he;ye++)Ar(P[ye],V,z,Q+1,te);return}let ne=0,ce=new Set;for(let he in P){if(!Object.hasOwn(P,he))continue;if(ne>=z.maxObjectProperties)break;ne++,Ar(he,V,z);let ye=Qo(he,z,V);if(ce.has(ye))continue;ce.add(ye),Ar(P[he],V,z,Q+1,te)}}function Xo(P,V,z,Q=0,te=new WeakSet){if(typeof P==="string")return Qo(P,V,z);if(!P||typeof P!=="object")return P;if(Q>=V.maxDepth)return;if(te.has(P))return;if(te.add(P),Array.isArray(P)){let he=[],ye=Math.min(P.length,V.maxListLength);for(let be=0;be<ye;be++)he.push(Xo(P[be],V,z,Q+1,te));return he}let ne={},ce=0;for(let he in P){if(!Object.hasOwn(P,he))continue;if(ce>=V.maxObjectProperties)break;ce++;let ye=Qo(he,V,z);if(Object.hasOwn(ne,ye))continue;Object.defineProperty(ne,ye,{value:Xo(P[he],V,z,Q+1,te),enumerable:!0,configurable:!0,writable:!0})}return ne}function Qo(P,V,z){let Q=P.slice(0,V.maxTextLength),te=Ge(Q)?Ue(Q):Q,ne=z.size>0?_f(te,z):te;return(Af(ne)?ke(ne):ne).slice(0,V.maxTextLength)}function Af(P){return P.includes("PRIVATE KEY")||P.includes("://")||P.includes("eyJ")||P.includes(":")&&/(?:authorization|cookie|x-api-key|api-key|(?:^|\s)(?:-u|--user)(?:\s|=))/i.test(P)||P.length>=14&&Ef.some((V)=>P.includes(V))||P.length>=49&&/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/.test(P)}function _f(P,V){return P.replace(/[^\s"'()$]+/g,(z)=>V.has(yl(z))?"<redacted>":z)}function yl(P){let V=2166136261,z=2166136261;for(let Q=0;Q<P.length;Q++)V=Math.imul(V^P.charCodeAt(Q),16777619),z=Math.imul(z^P.charCodeAt(P.length-Q-1),16777619);return`${V>>>0}:${z>>>0}:${P.length}`}function ei(P){if(P&&typeof P==="object"&&!Object.isFrozen(P)){for(let V of Object.values(P))ei(V);Object.freeze(P)}return P}function Nn(P,V={},z){let Q=Tf(V.cwd??process.cwd()),te=V.policySnapshot??E(z,{cwd:Q,userConfigDir:V.userConfigDir}),ne=R(te.policy,z.env),ce=Fe({policySnapshot:te,effectiveCapabilities:ne.capabilities,strict:ne.strict,paranoidRm:ne.paranoidRm,paranoidInterpreters:ne.paranoidInterpreters,worktreeMode:ne.worktreeMode}),he={effectiveLevel:ce.effectiveLevel,selectedPreset:te.policy.safety.level??"standard",...te.policyScopes?{safetyPresetScope:te.policyScopes.levelScope}:{},effectiveCapabilities:ce.effectiveCapabilities,destructiveCommandRuleOverrides:te.policy.destructiveCommandRuleOverrides},{configSource:ye,configValid:be}=If(z,{cwd:Q,userConfigDir:V.userConfigDir});if(!P||!P.trim())return{trace:{steps:[{type:"error",message:"No command provided"}],segments:[]},result:"allowed",configSource:ye,configValid:be,...he};let xe=h(P,"auto");if(xe.status==="limited")throw new y;let Ie=xe.dialect==="powershell"?h(P,"posix"):xe,Xe=st(Ie),et=hl(),Re=gl(et);Re.recordGlobal({type:"parse",input:P,segments:Xe.map((Dt)=>[...Dt])});let at=d("Bash",{command:P},{kind:"command",shell:"auto"},{configCwd:Q,executionCwd:Q},P),ct=W(at,{environment:z,trace:Re,dependencies:{loadPolicySnapshot:()=>te}}),lt=ct.decision.kind==="deny"?ct.decision:null;if(lt&&(ct.stage==="policy-protection"||ct.stage==="secret-protection")){let Dt=$f(lt);return{trace:{steps:[],segments:[{index:0,steps:[{type:"rule-check",rule:Dt.rule,matched:!0,reason:lt.reason}]}]},result:"blocked",reason:k(lt.reason),segment:k(vl(lt,P)),...Dt.ruleId?{ruleId:k(Dt.ruleId)}:{},configSource:ye,configValid:be,...he}}let pt=Re.getNextSegmentIndex();if(lt&&pt>0&&pt<Xe.length)Re.recordSegment({type:"segment-skipped",index:pt,reason:"prior-segment-blocked"},pt);let mt=et.finish(),gt=lt?.ruleId??Of(at,te,ne,z),ut=U.find((Dt)=>Dt.id===gt&&Dt.activationCapability),vt=ut?ce.policy.effectiveDestructiveCommandRules[ut.id]:void 0;return{trace:jf(mt),result:lt?"blocked":"allowed",reason:lt?k(lt.reason):void 0,segment:lt?k(vl(lt,P)):void 0,ruleId:lt?.ruleId?k(lt.ruleId):void 0,customRule:Ff(Nf(lt?.ruleId,te)),configSource:ye,configValid:be,...he,...ut&&vt?{ruleActivation:{id:ut.id,...vt}}:{}}}function vl(P,V){return P.evidence?.segment??V}function $f(P){if(P.reason===$e)return{ruleId:"policy-protection",rule:"policy-protection:findPolicyConfigMutationTargetInSemanticFacts"};if(P.reason===Me)return{ruleId:"policy-apply-protection",rule:"policy-apply-protection:findPolicyApplyInvocationInSemanticFacts"};if(P.reason===x)return{ruleId:"git-metadata-protection",rule:"git-metadata-protection:findGitMetadataMutationTargetInSemanticFacts"};return{ruleId:P.ruleId,rule:"secret-protection:findSensitiveTargetInSemanticFacts"}}function If(P,V){let z=F(V.cwd),Q=M(P,V),te=K(P,{cwd:V.cwd,userConfigDir:V.userConfigDir});try{if(n(te.projectConfigTarget)!==null){if(Jt(te.projectConfigTarget).errors.length===0)return{configSource:z,configValid:!0};return{configSource:z,configValid:!1}}}catch(ne){if(ne instanceof r)return{configSource:z,configValid:!1};throw ne}try{if(n(te.userConfigTarget)!==null){let ne=Jt(te.userConfigTarget);return{configSource:Q,configValid:ne.errors.length===0}}return{configSource:null,configValid:!0}}catch(ne){if(ne instanceof r)return{configSource:Q,configValid:!1};throw ne}}function Of(P,V,z,Q){let te=V.policy,ne=Ee({...te,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{...te.destructiveCommandRuleOverrides,...Object.fromEntries(U.flatMap((he)=>he.activationCapability?[[he.id,"on"]]:[]))}},V.state==="degraded"?{diagnostics:V.diagnostics,reason:V.reason}:void 0),ce=W(P,{environment:Q,dependencies:{loadPolicySnapshot:()=>ne,getModes:()=>({...z,strict:!0,paranoidRm:!0,paranoidInterpreters:!0}),findSensitiveTarget:()=>null}});return ce.decision.kind==="deny"?ce.decision.ruleId:void 0}function Ff(P){if(!P)return;return{id:k(P.id),...P.rulebook?{rulebook:{name:k(P.rulebook.name),version:k(P.rulebook.version)}}:{},...P.source?{source:k(P.source)}:{},...P.override?{override:{type:"reason",reason:k(P.override.reason)}}:{}}}function jf(P){let V=P.events.flatMap((Q)=>Q.kind==="step"&&Q.scope==="global"?[Q.step]:[]),z=new Map;for(let Q of P.events){if(Q.kind!=="step"||Q.scope!=="segment")continue;let te=z.get(Q.segmentIndex)??{index:Q.segmentIndex,steps:[]};te.steps.push(Q.step),z.set(Q.segmentIndex,te)}return{steps:V,segments:[...z.values()]}}function Nf(P,V){let z=P?.replace(/^custom\./,"");if(!z||!V.policy.rules.some((Q)=>Q.name===z))return;return V.ruleMetadata[z]??Object.freeze({id:z})}function bl(P){return new Promise((V)=>{process.stdout.write(`${P}
|
|
214
|
-
`,()=>V())})}async function Ll(P,V){let z=Wo(V);if(!z)return 1;try{let Q=Nn(z.command,{cwd:z.cwd},P),te=!!process.env.NO_COLOR||!process.stdout.isTTY;return await bl(z.json?Zo(Q):Yo(Q,{asciiOnly:te})),0}catch(Q){let te=Mf(Q instanceof p?Q.cause:Q);if(te===void 0)throw Q;if(z.json)return await bl(JSON.stringify({error:te})),1;return console.error(te),1}}function Mf(P){if(P instanceof y)return P.message;if(P instanceof f)return P.message;if(P instanceof s&&a[P.kind].errorCode==="path-canonicalization-limit")return"Path canonicalization work limit exceeded.";return}var wl="2.4.
|
|
214
|
+
`,()=>V())})}async function Ll(P,V){let z=Wo(V);if(!z)return 1;try{let Q=Nn(z.command,{cwd:z.cwd},P),te=!!process.env.NO_COLOR||!process.stdout.isTTY;return await bl(z.json?Zo(Q):Yo(Q,{asciiOnly:te})),0}catch(Q){let te=Mf(Q instanceof p?Q.cause:Q);if(te===void 0)throw Q;if(z.json)return await bl(JSON.stringify({error:te})),1;return console.error(te),1}}function Mf(P){if(P instanceof y)return P.message;if(P instanceof f)return P.message;if(P instanceof s&&a[P.kind].errorCode==="path-canonicalization-limit")return"Path canonicalization work limit exceeded.";return}var wl="2.4.9",Ot=" ",rn="cc-safety-net";function kl(P){return P.argument?`${P.flags} ${P.argument}`:P.flags}function Hf(P){return Math.max(...P.map((V)=>kl(V).length))}function Uf(P){return Math.max(...P.map((V)=>V.usage.length))}function Gf(P){return Math.max(...P.map((V)=>`${rn} ${V.usage}`.length))}function Bf(P,V){let z=`${rn} ${P.usage}`;return`${Ot}${z.padEnd(V+2)}${P.description}`}function qt(P,V){return`${Ot}${P.padEnd(Math.max(40,P.length+2))}${V}`}function wn(P,V=console.log){let z=[];if(z.push(`${rn} ${P.name}`),z.push(""),z.push(`${Ot}${P.description}`),z.push(""),z.push("USAGE:"),z.push(`${Ot}${rn} ${P.usage}`),z.push(""),P.subcommands&&P.subcommands.length>0){z.push("SUBCOMMANDS:");let Q=Uf(P.subcommands);for(let te of P.subcommands)z.push(`${Ot}${te.usage.padEnd(Q+2)}${te.description}`);z.push("")}if(P.options.length>0){z.push("OPTIONS:");let Q=Hf(P.options);for(let te of P.options){let ne=kl(te),ce=te.default?`${te.description} (default: ${te.default})`:te.description;z.push(`${Ot}${ne.padEnd(Q+2)}${ce}`)}z.push("")}if(P.examples&&P.examples.length>0){z.push("EXAMPLES:");for(let Q of P.examples)z.push(`${Ot}${Q}`)}V(z.join(`
|
|
215
215
|
`))}function ti(){let P=Gf(Qn),V=[];V.push(`${rn} v${wl}`),V.push(""),V.push("Blocks destructive commands and secret access."),V.push(""),V.push("COMMANDS:");for(let z of Qn)V.push(Bf(z,P));V.push(""),V.push("GLOBAL OPTIONS:"),V.push(`${Ot}-h, --help Show help (use with command for command-specific help)`),V.push(`${Ot}-V, --version Show version`),V.push(""),V.push("HELP:"),V.push(`${Ot}${rn} help <command> Show help for a specific command`),V.push(`${Ot}${rn} <command> --help Show help for a specific command`),V.push(""),V.push("ENVIRONMENT VARIABLES:"),V.push(qt(`${o.level.name}=standard|strict|paranoid`,"Set session safety level")),V.push(qt(`${o.worktree.name}=1`,"Allow local git discards in linked worktrees")),V.push(qt(`${o.debug.name}=1`,"Print diagnostic messages to stderr")),V.push(qt(`${o.auditScope.name}=all|blocked`,"Record all command decisions, or denials only")),V.push(qt("CC_SAFETY_NET_HOME","Override rule config home directory")),V.push(""),V.push("LEGACY ENVIRONMENT VARIABLES (STILL SUPPORTED):"),V.push(qt(`${o.strict.name}=1`,"Force safety.overrides.fail_closed on")),V.push(qt(`${o.paranoid.name}=1`,"Force paranoid_rm and paranoid_interpreters on")),V.push(qt(`${o.paranoidRm.name}=1`,"Force safety.overrides.paranoid_rm on")),V.push(qt(`${o.paranoidInterpreters.name}=1`,"Force safety.overrides.paranoid_interpreters on")),V.push(""),V.push("Documentation: https://ccsafetynet.com/docs"),console.log(V.join(`
|
|
216
216
|
`))}function xl(){console.log(wl)}function Mn(P,V=console.log){let z=er(P);if(!z)return!1;if(z.name.toLowerCase()!==P.toLowerCase())return!1;return wn(z,V),!0}import{existsSync as mi,readFileSync as bc}from"node:fs";import{join as pi}from"node:path";import*as Kt from"node:readline";function qf(P){return P==="install"?"Install":"Uninstall"}function Vf(P){return P==="install"?"Installing":"Uninstalling"}function zf(P){return P==="install"?"into":"from"}function Rl(P){return P?.available===!0}function Jf(P,V){let z=new Set(V);return P.filter((Q)=>z.has(Q.target)).map((Q)=>Q.target)}function Cl(P,V,z){if(P.every((Q)=>!Q.available))return V;return Array.from({length:P.length},(Q,te)=>te+1).map((Q)=>(V+Q*z+P.length)%P.length).find((Q)=>Rl(P[Q]))}function Wf(P,V,z){if(z.ctrl&&z.name==="c")return"interrupt";if(z.name==="escape"||V==="q")return"abort";if(P==="install"&&(V==="u"||V==="U"))return"update";if(z.name==="up"||V==="k")return"up";if(z.name==="down"||V==="j")return"down";if(z.name==="space"||V===" ")return"toggle";if(z.name==="return"||z.name==="enter")return"confirm";return null}function Kf(P){return{cursor:P.findIndex((V)=>V.available),selected:[]}}function Yf(P,V,z){if(z==="confirm"||z==="update"||z==="abort"||z==="interrupt")return{state:P,done:z};if(z==="up")return{state:{...P,cursor:Cl(V,P.cursor,-1)}};if(z==="down")return{state:{...P,cursor:Cl(V,P.cursor,1)}};let Q=V[P.cursor];if(!Rl(Q))return{state:P};let te=P.selected.includes(Q.target)?P.selected.filter((ne)=>ne!==Q.target):Jf(V,[...P.selected,Q.target]);return{state:{...P,selected:te}}}var Pl="◉",El="◯",Dl=">",Al=" ";function Zf(P,V,z,Q={}){let te=Q.color!==!1,ne=te?dt.dim:(ye)=>ye,ce=te?dt.green:(ye)=>ye,he=te?dt.bold:(ye)=>ye;return["",`${qf(P)} CC Safety Net ${zf(P)}:`,"",...V.map((ye,be)=>{let xe=z.selected.includes(ye.target),Ie=be===z.cursor,Xe=xe?Pl:El,et=Ie?Dl:Al,Re=ye.available?"":` (${ye.unavailableReason??"not installed"})`,at=`${Xe} ${ye.label}${Re}`,ct=!ye.available?ne(at):xe?ce(at):Ie?he(at):at;return`${et} ${ct}`}),"",P==="install"?"Space: select Enter: confirm u: update installed Up/Down: move q/Esc: cancel":V.some((ye)=>ye.available)?"Space: select Enter: confirm Up/Down: move q/Esc: cancel":`No selectable integrations found for ${P}. q/Esc: close`].join(`
|
|
217
217
|
`)}var Sl=["global-hook","plugin"];function Xf(P,V,z={}){let Q=z.color!==!1?dt.bold:(ne)=>ne;return["","Install the Kimi Code integration as:","",...[`Global hook — ${V?"already installed; selecting it reports the current state":"write the hook into ~/.kimi-code/config.toml now"}`,"Native Kimi plugin — print the steps to run inside Kimi Code"].map((ne,ce)=>{let he=ce===P,ye=`${he?Pl:El} ${ne}`;return`${he?Dl:Al} ${he?Q(ye):ye}`}),"","Enter: confirm Up/Down: move q/Esc: cancel"].join(`
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ye,P,be,c,xe,f,V,ne,ce,d,p}from"./chunks/index-fvtsm6ez.js";import{Q}from"./chunks/index-rr4ytenf.js";import{he,D}from"./chunks/index-tfdjszbb.js";import{resolve as Os}from"node:path";function Ir(){return{"cc-safety-net":{description:"Operate CC Safety Net: explain blocks, rules, integrations, diagnostics",template:Q.slice(Q.indexOf("# CC Safety Net"))}}}var $c=new Set(["powershell","pwsh"]),Bc=new Set(["bash","dash","ksh","sh","zsh"]);function ks(e={}){return async({directory:t,homeDir:r})=>{let n=Os(t),o;return{config:async(s)=>{o=s;let a=Ir(),u=s.command??{};s.command={...a,...u}},"tool.execute.before":async(s,a)=>{Rn({configCwd:n,homeDir:r,tool:s.tool,sessionID:s.sessionID,toolInput:a.args,route:jc(s.tool,_n(o?.shell)),guardDependencies:e})}}}}function Rn({configCwd:e,homeDir:t,tool:r,sessionID:n,toolInput:o,route:s,guardDependencies:a={}}){let u=t===void 0?c():{...c(),home:t},l=(h,g,I=e)=>{he(u,h,()=>n,{agent:"opencode",toolName:g,cwd:I}),Rs(h)};if(typeof r!=="string"||r.trim()==="")l(P());let i;try{i=ne(o)}catch(h){if(!(h instanceof f))throw h;l(P({toolName:r}),r)}let x=qc(e,o);if(!ce(e)||!x){l(P({command:i,toolName:r}),r);return}let S=d(r,o,s,{configCwd:e,executionCwd:x},i??null);try{let h=D(u,S,{guard:{auditAllowed:xe(u.env),dependencies:a},audit:{agent:"opencode",getSessionId:()=>n}});Cs(h)}catch(h){if(!(h instanceof p))throw h;if(h.stage==="policy-protection"||h.stage==="config-load"||h.stage==="secret-protection")throw h.cause;Cs(h.evaluation);return}}function _n(e,t=process.platform,r=process.env.SHELL){if(typeof e!=="string"&&t==="win32")return"powershell";let n=typeof e==="string"?e:r;if(typeof n!=="string")return"auto";let o=n.trim().split(/[\\/]/).at(-1)?.toLowerCase().replace(/\.exe$/,"");if(!o)return"auto";if($c.has(o))return"powershell";if(Bc.has(o))return"posix";return"auto"}function jc(e,t){if(e==="bash")return{kind:"command",shell:t};return{kind:V(e)}}function qc(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return e;if(!Object.hasOwn(t,"workdir"))return e;let r=t.workdir;if(typeof r!=="string"||r.trim()==="")return null;let n=process.platform==="win32"?Jc(r):r,o=Os(e,n);return ce(o)?o:null}function Jc(e){return e.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(r,n)=>`${n.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:[\\/]|$)/,(r,n)=>`${n.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:[\\/]|$)/,(r,n)=>`${n.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:[\\/]|$)/,(r,n)=>`${n.toUpperCase()}:/`)}function Cs(e){let t=ye(e,{includeEvidence:!0});if(t)Rs(t)}function Rs(e){throw Error(be(e))}var fe=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let r=e;for(let n=0,o=t.length;n<o;n++)r=t[n](r);return r}}},Gc={pipe(){return fe(this,arguments)}},Bt=function(){function e(){}return e.prototype=Gc,e}();var C=function(e,t){if(typeof e==="function")return function(){return e(arguments)?t.apply(this,arguments):(r)=>t(r,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(r,n){if(arguments.length>=2)return t(r,n);return function(o){return t(o,r)}};case 3:return function(r,n,o){if(arguments.length>=3)return t(r,n,o);return function(s){return t(s,r,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let r=arguments;return function(n){return t(n,...r)}}}};var ie=(e)=>e;var _s=(e)=>()=>e;var St=_s(void 0),As=St;function rt(e){let t=new WeakMap;return(r)=>{let n=t.get(r);if(n!==void 0)return n;let o=e(r);return t.set(r,o),o}}function yt(e){let t=new WeakMap;return(r)=>{let n=t.get(r);if(n!==void 0)return n;let o=e(r);return t.set(r,o),t.set(o,o),o}}var jt=(e)=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;if(e instanceof Error)t.delete("stack");let r=Object.getPrototypeOf(e),n=r;while(n!==null&&n!==Object.prototype){let o=Reflect.ownKeys(n);for(let s=0;s<o.length;s++)t.add(o[s]);n=Object.getPrototypeOf(n)}if(t.has("constructor")&&typeof e.constructor==="function"&&r===e.constructor.prototype)t.delete("constructor");return t},qt=new WeakSet;function Jt(e){return typeof e==="string"}function An(e){return typeof e==="number"}function Fs(e){return typeof e==="symbol"}function Cr(e){return Jt(e)||An(e)||Fs(e)}function Tt(e){return typeof e==="function"}function Fn(e){return e!==void 0}function Pn(e){return e!=null}function Ps(e){return!0}function Dn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Or(e){return typeof e==="object"&&e!==null||Tt(e)}var _=C(2,(e,t)=>Or(e)&&(t in e));function Ds(e){return e instanceof Error}var Y="~effect/interfaces/Hash",F=(e)=>{switch(typeof e){case"number":return Ar(e);case"bigint":return G(e.toString(10));case"boolean":return G(String(e));case"symbol":return G(String(e));case"string":return G(e);case"undefined":return G("undefined");case"function":case"object":if(e===null)return G("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return G("Invalid Date");return G(e.toISOString())}else if(e instanceof RegExp)return G(e.toString());else{if(qt.has(e))return kr(e);if(Nn.has(e))return Nn.get(e);let t=Wc(e,()=>{if(Kc(e))return e[Y]();else if(typeof e==="function")return kr(e);else if(e instanceof DataView)return Rr(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e)||ArrayBuffer.isView(e))return Rr(e);else if(e instanceof Map)return Vc(e);else if(e instanceof Set)return Hc(e);return zc(e)});return Nn.set(e,t),t}default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},kr=(e)=>{if(!Un.has(e))Un.set(e,Ar(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return Un.get(e)},ue=C(2,(e,t)=>e*53^t),_r=(e)=>e&3221225471|e>>>1&1073741824,Kc=(e)=>_(e,Y),Ar=(e)=>{if(e!==e)return G("NaN");if(e===1/0)return G("Infinity");if(e===-1/0)return G("-Infinity");let t=e|0;if(t!==e)t^=e*4294967295;while(e>4294967295)t^=e/=4294967295;return _r(t)},G=(e)=>{let t=5381,r=e.length;while(r)t=t*33^e.charCodeAt(--r);return _r(t)},Ln=(e,t)=>{let r=12289;for(let n of t)r^=ue(F(n),F(e[n]));return _r(r)},zc=(e)=>Ln(e,jt(e)),$n=(e,t)=>(r)=>{let n=e;for(let o of r)n^=t(o);return _r(n)},Rr=$n(6151,F),Vc=$n(G("Map"),([e,t])=>ue(F(e),F(t))),Hc=$n(G("Set"),F),Un=new WeakMap,Nn=new WeakMap,Mn=new WeakSet;function Wc(e,t){if(Mn.has(e))return G("[Circular]");Mn.add(e);let r=t();return Mn.delete(e),r}var X="~effect/interfaces/Equal";function H(){if(arguments.length===1)return(e)=>ot(e,arguments[0]);return ot(arguments[0],arguments[1])}function ot(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let r=typeof e;if(r!==typeof t)return!1;if(r==="number"&&e!==e&&t!==t)return!0;if(r!=="object"&&r!=="function")return!1;if(qt.has(e)||qt.has(t))return!1;return Xc(e,t,Yc)}function Zc(e,t,r){let n=Bn.has(e),o=jn.has(t);if(n&&o)return!0;if(n||o)return!1;Bn.add(e),jn.add(t);let s=r();return Bn.delete(e),jn.delete(t),s}var Bn=new WeakSet,jn=new WeakSet;function Yc(e,t){if(F(e)!==F(t))return!1;else if(e instanceof Date){if(!(t instanceof Date))return!1;let s=e.getTime(),a=t.getTime();return s===a||Number.isNaN(s)&&Number.isNaN(a)}else if(e instanceof RegExp){if(!(t instanceof RegExp))return!1;return e.toString()===t.toString()}let r=Ns(e),n=Ns(t);if(r!==n)return!1;let o=r&&n;if(typeof e==="function"&&!o)return!1;return Zc(e,t,()=>{if(o)return e[X](t);else if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;return Qc(e,t)}else if(ArrayBuffer.isView(e)){let s=e instanceof DataView;if(!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||s!==t instanceof DataView)return!1;if(s){let a=t;return Us(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}return Us(e,t)}else if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;return ru(e,t)}else if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;return ou(e,t)}return eu(e,t)})}function Xc(e,t,r){let n=Fr.get(e);if(!n)n=new WeakMap,Fr.set(e,n);else if(n.has(t))return n.get(t);let o=r(e,t);n.set(t,o);let s=Fr.get(t);if(!s)s=new WeakMap,Fr.set(t,s);return s.set(e,o),o}var Fr=new WeakMap;function Qc(e,t){for(let r=0;r<e.length;r++)if(!ot(e[r],t[r]))return!1;return!0}function Us(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function eu(e,t){let r=jt(e),n=jt(t);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o)||!ot(e[o],t[o]))return!1;return!0}function tu(e,t){return function(n,o){let s=Array.from(o);for(let[a,u]of n){let l=!1;for(let i=0;i<s.length;i++){let[x,T]=s[i];if(e(a,x)&&t(u,T)){s[i]=s[s.length-1],s.pop(),l=!0;break}}if(!l)return!1}return!0}}var ru=tu(ot,ot);function nu(e){return function(r,n){let o=Array.from(n);for(let s of r){let a=!1;for(let u=0;u<o.length;u++){let l=o[u];if(e(s,l)){o[u]=o[o.length-1],o.pop(),a=!0;break}}if(!a)return!1}return!0}}var ou=nu(ot),Ns=(e)=>_(e,X);var Gt=Symbol.for("~effect/Redactable"),su=(e)=>_(e,Gt);function wt(e){if(su(e))return qn(e);return e}function qn(e){return e[Gt](globalThis[It]?.context??au)}var It="~effect/Fiber/currentFiber",Ms=new Map,au={"~effect/Context":{},base:Ms,depth:0,mapUnsafe:Ms,pipe(){return fe(this,arguments)}};function N(e,t){let r=t?.space??0,n=new WeakSet,o=!r?"":typeof r==="number"?" ".repeat(r):r,s=(i)=>o.repeat(i),a=(i,x)=>{let T=i?.constructor;return T&&T!==Object.prototype.constructor&&T.name?`${T.name}(${x})`:x},u=(i)=>{try{return Reflect.ownKeys(i)}catch{return["[ownKeys threw]"]}};function l(i,x=0){if(typeof i==="string")return JSON.stringify(i);if(typeof i==="number"||i==null||typeof i==="boolean"||typeof i==="symbol")return String(i);if(typeof i==="bigint")return String(i)+"n";if(typeof i==="object"||typeof i==="function"){if(n.has(i))return iu;n.add(i);let T;if(Gt in i)T=l(qn(i),x);else if(Array.isArray(i))T=!o||i.length<=1?`[${i.map((S)=>l(S,x)).join(",")}]`:`[
|
|
1
|
+
import{ye,P,be,c,xe,f,V,ne,ce,d,p}from"./chunks/index-fvtsm6ez.js";import{Q}from"./chunks/index-rr4ytenf.js";import{he,D}from"./chunks/index-g2gqgqzy.js";import{resolve as Os}from"node:path";function Ir(){return{"cc-safety-net":{description:"Operate CC Safety Net: explain blocks, rules, integrations, diagnostics",template:Q.slice(Q.indexOf("# CC Safety Net"))}}}var $c=new Set(["powershell","pwsh"]),Bc=new Set(["bash","dash","ksh","sh","zsh"]);function ks(e={}){return async({directory:t,homeDir:r})=>{let n=Os(t),o;return{config:async(s)=>{o=s;let a=Ir(),u=s.command??{};s.command={...a,...u}},"tool.execute.before":async(s,a)=>{Rn({configCwd:n,homeDir:r,tool:s.tool,sessionID:s.sessionID,toolInput:a.args,route:jc(s.tool,_n(o?.shell)),guardDependencies:e})}}}}function Rn({configCwd:e,homeDir:t,tool:r,sessionID:n,toolInput:o,route:s,guardDependencies:a={}}){let u=t===void 0?c():{...c(),home:t},l=(h,g,I=e)=>{he(u,h,()=>n,{agent:"opencode",toolName:g,cwd:I}),Rs(h)};if(typeof r!=="string"||r.trim()==="")l(P());let i;try{i=ne(o)}catch(h){if(!(h instanceof f))throw h;l(P({toolName:r}),r)}let x=qc(e,o);if(!ce(e)||!x){l(P({command:i,toolName:r}),r);return}let S=d(r,o,s,{configCwd:e,executionCwd:x},i??null);try{let h=D(u,S,{guard:{auditAllowed:xe(u.env),dependencies:a},audit:{agent:"opencode",getSessionId:()=>n}});Cs(h)}catch(h){if(!(h instanceof p))throw h;if(h.stage==="policy-protection"||h.stage==="config-load"||h.stage==="secret-protection")throw h.cause;Cs(h.evaluation);return}}function _n(e,t=process.platform,r=process.env.SHELL){if(typeof e!=="string"&&t==="win32")return"powershell";let n=typeof e==="string"?e:r;if(typeof n!=="string")return"auto";let o=n.trim().split(/[\\/]/).at(-1)?.toLowerCase().replace(/\.exe$/,"");if(!o)return"auto";if($c.has(o))return"powershell";if(Bc.has(o))return"posix";return"auto"}function jc(e,t){if(e==="bash")return{kind:"command",shell:t};return{kind:V(e)}}function qc(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return e;if(!Object.hasOwn(t,"workdir"))return e;let r=t.workdir;if(typeof r!=="string"||r.trim()==="")return null;let n=process.platform==="win32"?Jc(r):r,o=Os(e,n);return ce(o)?o:null}function Jc(e){return e.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(r,n)=>`${n.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:[\\/]|$)/,(r,n)=>`${n.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:[\\/]|$)/,(r,n)=>`${n.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:[\\/]|$)/,(r,n)=>`${n.toUpperCase()}:/`)}function Cs(e){let t=ye(e,{includeEvidence:!0});if(t)Rs(t)}function Rs(e){throw Error(be(e))}var fe=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let r=e;for(let n=0,o=t.length;n<o;n++)r=t[n](r);return r}}},Gc={pipe(){return fe(this,arguments)}},Bt=function(){function e(){}return e.prototype=Gc,e}();var C=function(e,t){if(typeof e==="function")return function(){return e(arguments)?t.apply(this,arguments):(r)=>t(r,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(r,n){if(arguments.length>=2)return t(r,n);return function(o){return t(o,r)}};case 3:return function(r,n,o){if(arguments.length>=3)return t(r,n,o);return function(s){return t(s,r,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let r=arguments;return function(n){return t(n,...r)}}}};var ie=(e)=>e;var _s=(e)=>()=>e;var St=_s(void 0),As=St;function rt(e){let t=new WeakMap;return(r)=>{let n=t.get(r);if(n!==void 0)return n;let o=e(r);return t.set(r,o),o}}function yt(e){let t=new WeakMap;return(r)=>{let n=t.get(r);if(n!==void 0)return n;let o=e(r);return t.set(r,o),t.set(o,o),o}}var jt=(e)=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;if(e instanceof Error)t.delete("stack");let r=Object.getPrototypeOf(e),n=r;while(n!==null&&n!==Object.prototype){let o=Reflect.ownKeys(n);for(let s=0;s<o.length;s++)t.add(o[s]);n=Object.getPrototypeOf(n)}if(t.has("constructor")&&typeof e.constructor==="function"&&r===e.constructor.prototype)t.delete("constructor");return t},qt=new WeakSet;function Jt(e){return typeof e==="string"}function An(e){return typeof e==="number"}function Fs(e){return typeof e==="symbol"}function Cr(e){return Jt(e)||An(e)||Fs(e)}function Tt(e){return typeof e==="function"}function Fn(e){return e!==void 0}function Pn(e){return e!=null}function Ps(e){return!0}function Dn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Or(e){return typeof e==="object"&&e!==null||Tt(e)}var _=C(2,(e,t)=>Or(e)&&(t in e));function Ds(e){return e instanceof Error}var Y="~effect/interfaces/Hash",F=(e)=>{switch(typeof e){case"number":return Ar(e);case"bigint":return G(e.toString(10));case"boolean":return G(String(e));case"symbol":return G(String(e));case"string":return G(e);case"undefined":return G("undefined");case"function":case"object":if(e===null)return G("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return G("Invalid Date");return G(e.toISOString())}else if(e instanceof RegExp)return G(e.toString());else{if(qt.has(e))return kr(e);if(Nn.has(e))return Nn.get(e);let t=Wc(e,()=>{if(Kc(e))return e[Y]();else if(typeof e==="function")return kr(e);else if(e instanceof DataView)return Rr(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e)||ArrayBuffer.isView(e))return Rr(e);else if(e instanceof Map)return Vc(e);else if(e instanceof Set)return Hc(e);return zc(e)});return Nn.set(e,t),t}default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},kr=(e)=>{if(!Un.has(e))Un.set(e,Ar(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return Un.get(e)},ue=C(2,(e,t)=>e*53^t),_r=(e)=>e&3221225471|e>>>1&1073741824,Kc=(e)=>_(e,Y),Ar=(e)=>{if(e!==e)return G("NaN");if(e===1/0)return G("Infinity");if(e===-1/0)return G("-Infinity");let t=e|0;if(t!==e)t^=e*4294967295;while(e>4294967295)t^=e/=4294967295;return _r(t)},G=(e)=>{let t=5381,r=e.length;while(r)t=t*33^e.charCodeAt(--r);return _r(t)},Ln=(e,t)=>{let r=12289;for(let n of t)r^=ue(F(n),F(e[n]));return _r(r)},zc=(e)=>Ln(e,jt(e)),$n=(e,t)=>(r)=>{let n=e;for(let o of r)n^=t(o);return _r(n)},Rr=$n(6151,F),Vc=$n(G("Map"),([e,t])=>ue(F(e),F(t))),Hc=$n(G("Set"),F),Un=new WeakMap,Nn=new WeakMap,Mn=new WeakSet;function Wc(e,t){if(Mn.has(e))return G("[Circular]");Mn.add(e);let r=t();return Mn.delete(e),r}var X="~effect/interfaces/Equal";function H(){if(arguments.length===1)return(e)=>ot(e,arguments[0]);return ot(arguments[0],arguments[1])}function ot(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let r=typeof e;if(r!==typeof t)return!1;if(r==="number"&&e!==e&&t!==t)return!0;if(r!=="object"&&r!=="function")return!1;if(qt.has(e)||qt.has(t))return!1;return Xc(e,t,Yc)}function Zc(e,t,r){let n=Bn.has(e),o=jn.has(t);if(n&&o)return!0;if(n||o)return!1;Bn.add(e),jn.add(t);let s=r();return Bn.delete(e),jn.delete(t),s}var Bn=new WeakSet,jn=new WeakSet;function Yc(e,t){if(F(e)!==F(t))return!1;else if(e instanceof Date){if(!(t instanceof Date))return!1;let s=e.getTime(),a=t.getTime();return s===a||Number.isNaN(s)&&Number.isNaN(a)}else if(e instanceof RegExp){if(!(t instanceof RegExp))return!1;return e.toString()===t.toString()}let r=Ns(e),n=Ns(t);if(r!==n)return!1;let o=r&&n;if(typeof e==="function"&&!o)return!1;return Zc(e,t,()=>{if(o)return e[X](t);else if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;return Qc(e,t)}else if(ArrayBuffer.isView(e)){let s=e instanceof DataView;if(!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||s!==t instanceof DataView)return!1;if(s){let a=t;return Us(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}return Us(e,t)}else if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;return ru(e,t)}else if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;return ou(e,t)}return eu(e,t)})}function Xc(e,t,r){let n=Fr.get(e);if(!n)n=new WeakMap,Fr.set(e,n);else if(n.has(t))return n.get(t);let o=r(e,t);n.set(t,o);let s=Fr.get(t);if(!s)s=new WeakMap,Fr.set(t,s);return s.set(e,o),o}var Fr=new WeakMap;function Qc(e,t){for(let r=0;r<e.length;r++)if(!ot(e[r],t[r]))return!1;return!0}function Us(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function eu(e,t){let r=jt(e),n=jt(t);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o)||!ot(e[o],t[o]))return!1;return!0}function tu(e,t){return function(n,o){let s=Array.from(o);for(let[a,u]of n){let l=!1;for(let i=0;i<s.length;i++){let[x,T]=s[i];if(e(a,x)&&t(u,T)){s[i]=s[s.length-1],s.pop(),l=!0;break}}if(!l)return!1}return!0}}var ru=tu(ot,ot);function nu(e){return function(r,n){let o=Array.from(n);for(let s of r){let a=!1;for(let u=0;u<o.length;u++){let l=o[u];if(e(s,l)){o[u]=o[o.length-1],o.pop(),a=!0;break}}if(!a)return!1}return!0}}var ou=nu(ot),Ns=(e)=>_(e,X);var Gt=Symbol.for("~effect/Redactable"),su=(e)=>_(e,Gt);function wt(e){if(su(e))return qn(e);return e}function qn(e){return e[Gt](globalThis[It]?.context??au)}var It="~effect/Fiber/currentFiber",Ms=new Map,au={"~effect/Context":{},base:Ms,depth:0,mapUnsafe:Ms,pipe(){return fe(this,arguments)}};function N(e,t){let r=t?.space??0,n=new WeakSet,o=!r?"":typeof r==="number"?" ".repeat(r):r,s=(i)=>o.repeat(i),a=(i,x)=>{let T=i?.constructor;return T&&T!==Object.prototype.constructor&&T.name?`${T.name}(${x})`:x},u=(i)=>{try{return Reflect.ownKeys(i)}catch{return["[ownKeys threw]"]}};function l(i,x=0){if(typeof i==="string")return JSON.stringify(i);if(typeof i==="number"||i==null||typeof i==="boolean"||typeof i==="symbol")return String(i);if(typeof i==="bigint")return String(i)+"n";if(typeof i==="object"||typeof i==="function"){if(n.has(i))return iu;n.add(i);let T;if(Gt in i)T=l(qn(i),x);else if(Array.isArray(i))T=!o||i.length<=1?`[${i.map((S)=>l(S,x)).join(",")}]`:`[
|
|
2
2
|
${s(x+1)}${i.map((S)=>l(S,x+1)).join(`,
|
|
3
3
|
`+s(x+1))}
|
|
4
4
|
${s(x)}]`;else if(i instanceof Date)T=Ls(i);else if(!t?.ignoreToString&&_(i,"toString")&&typeof i.toString==="function"&&i.toString!==Object.prototype.toString&&i.toString!==Array.prototype.toString){let S=cu(i);T=i instanceof Error&&i.cause?`${S} (cause: ${l(i.cause,x)})`:S}else if(Symbol.iterator in i)T=`${i.constructor.name}(${l(Array.from(i),x)})`;else{let S=u(i);if(!o||S.length<=1){let h=`{${S.map((g)=>`${Kt(g)}:${l(i[g],x)}`).join(",")}}`;T=a(i,h)}else{let h=`{
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// cc-safety-net managed OpenClaw plugin. Do not edit. Reinstall with: npx -y cc-safety-net install --openclaw
|
|
2
|
-
// version: 2.4.
|
|
2
|
+
// version: 2.4.9
|
|
3
3
|
var gl={id:"cc-safety-net",name:"CC Safety Net",description:"Block destructive commands and secret-file access before OpenClaw runs a tool."};var bi="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",He="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",_n="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var Ci={errorCode:"path-canonicalization-limit",reason:"CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry."},Rn={errorCode:"structural-shell-syntax-limit",reason:"Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry."},V=Object.freeze({realpathAttempts:{cap:16384,...Ci},processedCandidateBytes:{cap:4194304,...Ci},pathEnvironmentExpansion:{cap:64,...Ci},recursionDepth:{cap:10,errorCode:"structural-shell-syntax-limit",reason:"Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry."},derivedTokens:{cap:16384,...Rn},trackedHeredocFiles:{cap:64,...Rn},controlFlowStates:{cap:64,...Rn},wrapperPeelIterations:{cap:20,...Rn},derivedCommandShape:Rn});class N extends Error{kind;name="AnalysisLimit";constructor(e){super(V[e].reason);this.kind=e}}function Ce(){let e=new Map;return{counters:e,resolvedPaths:new Map,charge(t,n=1){let r=(e.get(t)??0)+n;if(e.set(t,r),r>V[t].cap)throw new N(t)}}}var wp=[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bglpat-[A-Za-z0-9_-]{20,}\b/g,/\bxox[abeprs]-[A-Za-z0-9-]{20,}\b/g,/\bnpm_[A-Za-z0-9_]{20,}\b/g,/\bpypi-[A-Za-z0-9_-]{20,}\b/g,/\b[rs]k_(?:live|test)_[A-Za-z0-9_]{20,}\b/g,/\bsk-[A-Za-z0-9_-]{20,}\b/g,/\bsk_[A-Za-z0-9]{20,}\b/g,/\bgsk_[A-Za-z0-9]{52,}\b/g,/\bxai-[A-Za-z0-9_-]{80,}\b/g,/\bpplx-[A-Za-z0-9_-]{20,}\b/g,/\bbastn_[A-Za-z0-9]{16,}\b/g,/\btgp_v1_[A-Za-z0-9_-]{43,}\b/g,/\bflp_[A-Za-z0-9]{10,}\b/g,/\bwfr_[A-Za-z0-9]{20,}\b/g,/\bfwp?_[A-Za-z0-9_-]{20,}\b/g,/\btp-[A-Za-z0-9_-]{20,}\b/g,/\bpsk-[A-Za-z0-9_-]{8,}-[A-Za-z0-9_-]{8,}\b/g,/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/g];function at(e){return Ap(e.replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_DSN|CONNECTION_STRING)=("[^"]*"|'[^']*'|[^\s]+(?:\s+[A-Z_][A-Z0-9_]*=[^\s]+)*)/gi,"$1=<redacted>").replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_(?:URL|URI|CONNECTION_STRING))=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIALS)[A-Z0-9_]*)=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>"))}function Ap(e){return wp.reduce((t,n)=>t.replace(n,"<redacted>"),e.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,"<redacted>").replace(/((?:(['"])(?:authorization|cookie|x-api-key|api-key)\2|(?:authorization|cookie|x-api-key|api-key))\s*:\s*)(['"])(?:\\[^\r\n]|(?!\3)[^\\\r\n])*\3/gi,"$1$3<redacted>$3").replace(/(['"]?\s*(?:authorization|cookie|x-api-key|api-key)\s*:(?!\s*(?:"<redacted>"|'<redacted>'))\s*)([^'"\r\n]+)(['"]?)/gi,"$1<redacted>$3").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1<redacted>:<redacted>@").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)@/gi,"$1<redacted>@").replace(/(^|[\s?&;|])((?:x-amz-signature|x-goog-signature|sig|signature)=)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^&#\s'"`;|<>()]*)/gi,"$1$2<redacted>").replace(/(^|\s)((?:-u|--user)(?:\s+|=))([^\s:]+):([^\s]+)/g,"$1$2<redacted>:<redacted>")).replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"<redacted>").replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,"<redacted>")}var Pp={hard_stop:"Do not retry this operation or attempt any workaround (other tools, flags, or paths). Report the block to the user and continue with the rest of the task.",use_alternative:"Do not retry the blocked form. Continue the task using the safer alternative described above.",scope_down:"Retry with a narrower, explicit target as described above. Escalate to the user if the broad operation is truly required.",manual_only:"If this operation is truly needed, ask the user for explicit permission and have them run the command manually.",stop_and_explain:"Do not brute-force variants. Simplify or restructure the command so it can be analyzed, or report the block to the user."};function Tp(e){let t=e.maxLen??200,n=e.redact??((o)=>o),r=(o)=>o.length>t?`${o.slice(0,t)}...`:o;return[e.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${n(e.reason)}`,e.ruleId?`Rule: ${e.ruleId}`:void 0,e.toolName?`Tool: ${e.toolName}`:void 0,e.command?`Command: ${r(n(e.command))}`:void 0,e.segment&&e.segment!==e.command?`Segment: ${r(n(e.segment))}`:void 0,e.configWarning?`Config warning: ${n(e.configWarning)}`:void 0,e.askUser?"Approve only if you expected this command.":Pp[e.intent??"manual_only"]].filter((o)=>o!==void 0).join(`
|
|
4
4
|
|
|
5
5
|
`)}function hl(e,t){if(e.decision.kind!=="deny")return;let n=t.includeEvidence?e.decision.evidence:void 0;return{reason:e.decision.reason,ruleId:e.decision.ruleId,intent:e.decision.intent,command:n?.command,segment:n?.segment,toolName:t.toolName,...e.configFallback?{configWarning:e.configFallback.reason}:{},...e.decision.ask?{ask:!0}:{}}}function wn(e={}){return{reason:_n,intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}function yl(e){return Tp({...e,redact:at})}function Cl(e){return at(e instanceof Error?e.message:String(e))}import{isAbsolute as zl,relative as rg,resolve as og,sep as ig}from"node:path";import{basename as vl,dirname as Ip,isAbsolute as kp,join as Op,normalize as Mp,resolve as bl}from"node:path";var Np=256,wr=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_HOME","GROK_HOME","HOME","KIMI_CODE_HOME","KIMI_SHARE_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","ProgramData","TMPDIR","XDG_CONFIG_HOME","XDG_DATA_HOME"]);function be(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function lt(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function xi(e,t){return Si(e,0,t)}function Si(e,t,n){let r="",o=0;while(o<e.length){if(e[o]!=="$"){r+=e[o],o++;continue}if(e[o+1]==="{"){let s=vi(e,o+2),a=Dp(e,o,t);if(a===null){if(wr.has(s))throw new N("pathEnvironmentExpansion");r+=e.slice(o);break}let l=e.slice(o,a+1);r+=Lp(l,t,n),o=a+1;continue}let i=vi(e,o+1);if(!i){r+="$",o++;continue}r+=Ei(i,n)??`$${i}`,o+=i.length+1}return r}function Dp(e,t,n){let r=1;for(let o=t+2;o<e.length;o++){if(e[o]==="\\"){o++;continue}if(e[o]==="$"&&e[o+1]==="{"){if(r++,n+r>V.pathEnvironmentExpansion.cap)throw new N("pathEnvironmentExpansion");o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function Lp(e,t,n){let r=e.slice(2,-1),o=vi(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return Ei(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(wr.has(o))throw new N("pathEnvironmentExpansion");return e}if(!wr.has(o))return e;if(s.endsWith("="))throw new N("pathEnvironmentExpansion");let a=Ei(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new N("pathEnvironmentExpansion");if(s.endsWith("-")||s.endsWith("?"))return l?a??"":Si(i.slice(s.length),t+1,n);return l?Si(i.slice(s.length),t+1,n):""}function vi(e,t){if(!/[A-Za-z_]/.test(e[t]??""))return"";let n=t+1;while(/[A-Za-z0-9_]/.test(e[n]??""))n++;return e.slice(t,n)}function Ei(e,t){if(!wr.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}function z(e,t,n){if(!e)return e;let r=n.resolvedPaths.get(e);if(r!==void 0)return r;let o=[],i=e;while(!0){El(n,i);let s=t.realpath(i);if(s!==null)return Sl(n,e,s,o);let a=Ip(i);if(a===i||o.length>=Np)return Sl(n,e,i,o);o.push(vl(i)),i=a}}function Sl(e,t,n,r){let o=r.length===0?n:Op(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function Wp(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;El(n,e);let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function El(e,t){e.charge("realpathAttempts"),e.charge("processedCandidateBytes",Buffer.byteLength(t))}function se(e,t,n,r){let o=Rl(e,t,n);if(!o)return"";return z(o,n.paths,r).replace(/\\/g,"/")}function xl(e,t,n,r,o){let i=Rl(e,t,n);if(!i)return null;if(o(vl(i)))return z(i,n.paths,r).replace(/\\/g,"/");let s=Wp(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function Rl(e,t,n){let r=n.home,o=xi(e.trim(),n).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?bl(r,o.slice(2)):o,s=be(i);return Mp(kp(s)?s:bl(t,s))}import{types as Gp}from"node:util";var Fp=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),zp=new Set(["command","diff","input","patch","patchtext"]),_l=new TextEncoder,Bp=new TextDecoder,$p=/\s/,Up=64;class Ye extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var An=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Hp(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function Pr(e){return Fp.has(Hp(e))}function Tn(e){if(!e||typeof e!=="object")return;Ll(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)je();return}if(t.get||t.set)je();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function Il(e,t){return kl(e,t,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function kl(e,t,n,r){let o=Dl(e,n,r);if(!o)return[];let i=o.entries.flatMap(([s,a])=>{let l=kl(a,t,n,r+1);return typeof a==="string"&&t.has(Ol(s))?[a]:l});return n.ancestors.delete(o.object),i}function Ol(e){return e.replace(/-/g,"_").toLowerCase()}function Ml(e){return Nl(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Vp)}function Nl(e,t,n,r){let o=Dl(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>Nl(a,o.array?t:zp.has(Ol(s)),n,r+1));return n.ancestors.delete(o.object),i}function jp(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>An.maxDepth||t.nodes>An.maxNodes)je();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>An.maxStringBytes||t.stringBytes>An.maxAggregateStringBytes)je()}function Dl(e,t,n){if(jp(e,t,n),!e||typeof e!=="object")return null;let r=Ll(e);if(t.ancestors.has(e))je();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>An.maxKeys)je();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)je();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function Ll(e){if(Gp.isProxy(e))je();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)je();return t}function je(){throw new Ye}function Vp(e){let t=[],n=e.split(/\r?\n/),r=!1,o=!1,i=null,s=null,a=()=>{o=!1,i=null,s=null};for(let l=0;l<n.length;l++){let c=n[l]??"";if(c==="*** Begin Patch"){r=!0,a();continue}if(c==="*** End Patch"){r=!1,a();continue}if(c.startsWith("@@")){let u=Kp(c);if(o=!0,i=u?.oldLines??null,s=u?.newLines??null,i===0&&s===0)a();continue}if(o&&i!==null&&s!==null){let u=c.startsWith(" ")||c.startsWith("-")?1:0,f=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-u),s=Math.max(0,s-f),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...Ri(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...Ri(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...wi(Ar(c.slice(4),!0),Ar(u.slice(4),!0))),l++;continue}if(!r)t.push(...Ri(c))}return t}function Kp(e){let t=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(e);if(!t)return null;return{oldLines:Number(t[1]??1),newLines:Number(t[2]??1)}}function Ri(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Tl(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Tl(n[1]);if(e.startsWith("diff --git "))return qp(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Pl(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Pl(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return tg(i[1]);return[]}function qp(e){let t=Yp(e);if(t.length===2&&t[0]&&t[1])return wi(t[0],t[1]);let n=Zp(e);return n?wi(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function Yp(e){let t=[],n=0;while(n<e.length&&t.length<2){while(xt(e[n]))n++;if(n>=e.length)break;let r=e[n]==='"'||e[n]==="'"?e[n]:void 0;if(!r){let i=n;while(n<e.length&&!xt(e[n]))n++;t.push(e.slice(i,n));continue}let o=Wl(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(xt(e[n]))n++;return n===e.length?t:[]}function Zp(e){let t=0;while(t<e.length&&xt(e[t]))t++;let n=e.length;while(n>t&&xt(e[n-1]))n--;let r=0,o=t;while(o<n){if(!xt(e[o])){o++;continue}let i=o;while(o<n&&xt(e[o]))o++;if(i===t||o===n)continue;if(r++,r>Up)je();if(Xp(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function Xp(e,t,n,r,o){if(_i(e,t,n,r,o))return!0;let i=wl(e,"/",t,n),s=wl(e,"/",r,o);if(i<=t||s<=r)return!1;if(_i(e,t,i,r,s))return!1;return _i(e,i+1,n,s+1,o)}function _i(e,t,n,r,o){if(n-t!==o-r)return!1;for(let i=0;i<n-t;i++)if(e[t+i]!==e[r+i])return!1;return!0}function wl(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function xt(e){return e!==void 0&&$p.test(e)}function Wl(e,t,n){let r=[],o=t+1;while(o<e.length){let i=String.fromCodePoint(e.codePointAt(o)??0);if(i===n)return{value:Bp.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(..._l.encode(i)),o+=i.length;continue}let s=e.slice(o+1),a=/^[0-7]{1,3}/.exec(s)?.[0];if(a){r.push(Number.parseInt(a,8)),o+=a.length+1;continue}r.push(..._l.encode(Jp(s[0]??""))),o+=2}return null}function Jp(e){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
@@ -44,5 +44,5 @@ var gl={id:"cc-safety-net",name:"CC Safety Net",description:"Block destructive c
|
|
|
44
44
|
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function Y_(e,t,n,r,o,i){let s=st(e);if(s.length===0||Ue(s[0]??"").toLowerCase()!=="xargs")return!1;let a=Ut(s),l=s.slice(a.childStart);if(l.length===0)return!1;if(a.replacementToken==="")return!1;let c=a.replacementToken,u=c===null?[...l,Ya]:l.map((f)=>f.split(c).join(Ya));return mi(u,t,n,r,o,i).some((f)=>f.target.includes(Ya))}function Z_(e){let t=st(e);if(t.length===0)return null;let n=Ue(t[0]??"").toLowerCase();if(!nr(n))return null;return X_(n,t.slice(1))?n:null}function X_(e,t){let n=rl(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(ep.has(o)||op(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if(z_.get(n)?.has(o))r++;continue}return!1}return!0}function rl(e){return/^python\d/.test(e)?"python":e}function J_(e){let t=[];for(let n of e){if(sp(n))continue;let r=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(n);if(r===null)break;if(r[1]!==void 0&&r[1]!=="")t.push(r[1])}return t}var Vm=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function Q_(e,t){if(!t||!Vm.test(e))return e;return`~${e.replace(Vm,"").replace(/\\/g,"/")}`}function Ke(e,t){if(t==="--")return[];let n=[],r=t.indexOf("=");if(r>0&&r<t.length-1)n.push(t.slice(r+1));if(t.startsWith("-"))return n;if(e==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(t))return n;if(e==="zip"&&/\.zip$/i.test(t))return n;return n.push(t),n}function ew(e){let t=-1,n=!1;for(let r=0;r<e.length;r++){let o=e[r]??"";if(!n&&o==="--"){n=!0;continue}if(n||!/^-(?:[A-Za-z]|-)/.test(o)){if(t===-1)t=r;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(o)){r+=2;continue}if(o==="--indent"||o==="-L"){r++;continue}if(o.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(o)||/^--(?:slurp|raw-output0?|join-output|compact-output|color-output|monochrome-output|ascii-output|unbuffered|sort-keys|raw-input|null-input|binary|tab|seq|stream|stream-errors|exit-status|args|jsonargs|help|version|build-configuration)$/.test(o))continue;return e.flatMap((i)=>Ke("jq",i))}return e.flatMap((r,o)=>o===t?[]:Ke("jq",r))}function tw(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??"";if(r==="--"||!r.startsWith("-"))return[...t,...A_.has(r)?Ja("git",e.slice(n).map((i)=>/^-[aeinopqsv]+m$/.test(i)?"-m":i),P_):Ja("git",e.slice(n),T_)];if(t.push(...Ke("git",r)),!Se.has(r))continue;let o=e[n+1];if(o===void 0)break;t.push(...r==="-c"&&o.includes("=")?[o.slice(o.indexOf("=")+1)]:Ke("git",o)),n++}return t}function Ja(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o]??"";if(i==="--")return[...r,...t.slice(o).flatMap((s)=>Ke(e,s))];if(n.has(i)){o++;continue}if(i.includes("=")&&n.has(i.slice(0,i.indexOf("="))))continue;r.push(...Ke(e,i))}return r}function nw(e){return e.flatMap((t,n)=>{let r=ow(t);if(r!==null)return Km(r.flag,r.value);let o=rw(e[n-1]);return o===null?[]:Km(o,t)})}function Km(e,t){if(e==="-F"||e==="--form"){let n=t.indexOf("="),r=n===-1?t:t.slice(n+1);if(!r.startsWith("@")&&!r.startsWith("<"))return[];return Za(r.slice(1).split(";")[0]??"")}if(e==="--data-urlencode"){let n=t.indexOf("@"),r=t.indexOf("=");if(n===-1||r!==-1&&r<n)return[];return Za(t.slice(n+1))}return t.startsWith("@")?Za(t.slice(1)):[]}function rw(e){if(e===void 0)return null;if(Qm.has(e))return e;return/^-[A-Za-z]+[dF]$/.test(e)?`-${e.slice(-1)}`:null}function ow(e){let t=e.slice(0,2);if(e.length>2&&(t==="-d"||t==="-F"))return{flag:t,value:e.slice(2)};let n=e.indexOf("=");if(n===-1)return null;let r=e.slice(0,n);return Qm.has(r)?{flag:r,value:e.slice(n+1)}:null}function Za(e){return e===""||e==="-"?[]:[e]}function iw(e,t,n,r,o,i){let s=e.findIndex((l)=>l.startsWith("-")||l==="("||l==="!"||l===";"),a=[...e.slice(0,s===-1?e.length:s),...e.flatMap((l,c)=>l==="-files0-from"&&e[c+1]!==void 0?[e[c+1]??""]:[])];for(let l=0;l<e.length;l++){if(!C_.has(e[l]??""))continue;let c=e.slice(l+1),u=c.findIndex((m)=>b_.has(m)),f=u===-1?c:c.slice(0,u),d=mi(f,t,n,r,o,i).map((m)=>m.target);if(a.push(...d.filter((m)=>m!=="{}")),!d.includes("{}"))continue;a.push(...e.slice(0,l).flatMap((m,p,g)=>{if(!v_.has(m))return[];let h=g[p+1];return h===void 0?[]:[h,h.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return a}function sw(e,t,n,r,o,i,s){let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c===void 0)break;if(ep.has(c)||op(e,c)){let f=t[l+1];if(f!==void 0)a.push(...di(e,f,n,r,o,i,s)),l++;continue}let u=/^--(?:eval|exec)=(.*)$/.exec(c);if(u!==null&&u[1]!==void 0){a.push(...di(e,u[1],n,r,o,i,s));continue}if(!c.startsWith("-"))a.push({target:c,cwd:i})}return a}function op(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return R_.get(t[t.length-1]??"")?.has(rl(e))??!1}function aw(e,t,n,r,o,i){if(!e.includes("system"))return[];return da(e)?.commands.flatMap((s)=>xn(t.getShellSyntax(s),t,n,r,o,i))??[]}function lw(e){return Array.from(e.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((t)=>t[1]).filter((t)=>t!==void 0&&t!=="")}function cw(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((n)=>n[2]).filter((n)=>n!==void 0&&n!=="");return[...t,...t.flatMap(ol),...e.match(Xa)??[]]}function di(e,t,n,r,o,i,s){let a=(g)=>({target:g,cwd:i}),l=dw(t,uw(e));if(l===null)return cw(t).map(a);let c=l.masked.match($m)!==null||l.literals.some((g)=>Um.test(l.masked.slice(0,g.start))),u=l.masked.match(G_)!==null||l.literals.some((g)=>F_.test(l.masked.slice(0,g.start))),f=r.standard===!0&&!er.has(e),d=f&&!(gw(l.masked)||c||u)?[]:l.literals,m=f?Array.from(l.masked.matchAll($m),(g)=>{let h=g.index+g[0].length;return{start:h,end:js(l.masked,h)}}):[],p=!f||m.some((g)=>Vs(l.masked,g.start))?l.literals:l.literals.filter((g)=>Um.test(l.masked.slice(0,g.start))||m.some((h)=>g.start>=h.start&&g.start<h.end));return[...d.map((g)=>g.text).filter((g)=>g!=="").map(a),...d.flatMap((g)=>ol(g.text)).map(a),...f?[]:l.literals.flatMap((g)=>g.text.match(Xa)??[]).map(a),...c?p.flatMap((g)=>tl(g.text,n,r,o,i,s)??[a(g.text)]):[],...u?l.literals.flatMap((g)=>di(e,g.text.replace(/\\(.)/g,(h,y)=>y==="n"?`
|
|
45
45
|
`:y),n,r,o,i,s)):[],...(l.masked.match(Xa)??[]).map(a)]}function uw(e){let t=rl(e);if(t==="python")return"python";if(t==="osascript")return"opaque";return t==="node"||t==="bun"||t==="deno"?"javascript":"simple"}function dw(e,t){if(t==="opaque")return null;let n=e.split(""),r=[];for(let o=0;o<e.length;o++){let i=e[o]??"";if(t==="simple"&&(i==="`"||i==="%"||i==="<")){if(L_.test(e.slice(o)))return null}let s=i==="'"||i==='"'||t==="javascript"&&i==="`"?i:null;if(s===null)continue;if(s==="`"&&pw(e,o))return null;let a=t==="python"?fw(e,o):"",l=t==="python"&&e.startsWith(s.repeat(3),o)?s.repeat(3):s,c=o+l.length,u=mw(e,c,l);if(u===null)return null;let f=e.slice(c,u);if(/[fF]/.test(a)&&f.includes("{"))return null;if(t==="simple"&&s==='"'&&W_.test(f))return null;r.push({start:c,text:f});for(let d=o;d<u+l.length;d++)n[d]=" ";o=u+l.length-1}return{masked:n.join(""),literals:r}}function fw(e,t){return D_.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function mw(e,t,n){let r=n==="`",o=r||n.length===3;for(let i=t;i<e.length;i++){let s=e[i];if(s==="\\"){i++;continue}if(r&&s==="$"&&e[i+1]==="{")return null;if(!o&&(s===`
|
|
46
46
|
`||s==="\r"))return null;if(e.startsWith(n,i))return i}return null}function pw(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function gw(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(E_.has(n.toLowerCase()))return!0;let o=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((i)=>i.toLowerCase());if(!o.some((i)=>x_.has(i)))continue;if(o.length>1)return!0;if(hw(e,r)===".")return!0;if(yw(e,r+n.length)==="(")return!0}return!1}function hw(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function yw(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function Cw(e,t,n,r,o,i){return xw(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...xn(a,t,{...n,capturedOutput:!0},r,o,i),...bw(a,r)?Sw(a,r).map((l)=>({target:l,cwd:o})):[]]})}function bw(e,t){let n=_o(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||Ue(Qe(o.text,t)).toLowerCase()!=="base64")continue;for(let i=r+1;i<n.length;i++){let s=n[i];if(s?.kind==="operator")break;if(s?.kind!=="word")continue;let a=Qe(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function Sw(e,t){return _o(e).flatMap((n)=>n.kind==="word"?[Qe(n.text,t)]:n.kind==="redirection"&&n.target?[Qe(n.target,t)]:[]).flatMap(ol)}function ol(e){let t=Ew(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||vw(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function vw(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function Ew(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function xw(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(Wn(o,n))continue;if(ip(e,r,n)){let i=Rw(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=_w(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function Rw(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(Wn(i,n))continue;if(ip(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function _w(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function ip(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function ww(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let u=/^--([^=]+)(?:=(.*))?$/.exec(c);if(u!==null){let f=u[1]??"",d=u[2];if(f===I_)o=!0;if(O_.has(f))r=!0;if(d!==void 0){if(f===Bm)t.push(d);continue}if(N_.has(f)){let m=e[l+1];if(f===Bm&&m!==void 0)t.push(m);l++}continue}if(c.startsWith("-")&&c.length>1){let f=c.slice(1),d="",m="";for(let g=0;g<f.length;g++){let h=f[g]??"";if(k_.has(h))r=!0;if(M_.has(h)){d=h,m=f.slice(g+1);break}}if(d==="")continue;if(m.length>0){if(d===zm)t.push(m);continue}let p=e[l+1];if(d===zm&&p!==void 0)t.push(p);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function st(e){let t=e.findIndex((n)=>!sp(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function sp(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var Aw=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),Pw=".env.",Tw=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),Iw=[".env.example.",".env.sample."];function kw(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function Ow(e){return e.length>0&&!/\s/.test(e)}function Qa(e,t,n,r){let o=ap(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function ap(e,t,n,r){try{return Er(e,t,n,r)}catch(o){if(o instanceof N)throw o;return""}}var Mw=new Set(["node_modules","__pycache__"]),Nw=[["vendor","bundle"],["vendor","cache"]];function Dw(e,t,n,r,o){if(kw(e))return null;let i=Ve(e,t,r,o);if(!i)return null;let s=F(i.split("/").pop()??""),a=F(i),l=()=>Ow(s)||Qa(e,t,r,o);if(Tw.has(s)||Iw.some((d)=>s.startsWith(d)))return null;let c=F(Bw(e,t,r,o));for(let d of ss){let m=`~/${d.suffixParts.join("/")}`;if((Ym(a,m)||Ym(c,m))&&it(d.id,n))return d.id}let u=Lw(i,t,n,r,o);if(u)return u;if(Aw.has(s))return null;for(let d of is)if(s===d.basename&&it(d.id,n))return d.id;if(s.startsWith(Pw)&&it($r.id,n)&&l())return $r.id;for(let d of as)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){let m=s.slice(d.prefix.length)[0];if((m==="-"||m==="_")&&it(d.id,n)&&l())return d.id}for(let d of ls)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){if(s.slice(d.prefix.length)===d.suffix&&it(d.id,n))return d.id}if(Fw(a))return null;if(!s.includes(".")&&Gn.pattern.test(s)&&it(Gn.id,n))return Gn.id;let f=zw(s,n);if(f)return f;return null}function Lw(e,t,n,r,o){return Ur.find((i)=>{if(!it(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return W(e,B(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=F(e).split("/");return W(e,B(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||vr(e,"~/.claude.json",t,r,o)||s.at(-1)==="settings.local.json"&&s.at(-2)===".claude"||s.at(-1)===".mcp.json"}case"secret.cli.antigravity":return W(e,Ve("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=B(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return W(e,s,["auth.json",".credentials.json"])||Sr(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=B(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=F(e).split("/").at(-1)??"";return W(e,s,["config.toml"])||a.endsWith(".config.toml")&&W(e,s,[a])}case"secret.cli.gemini":return W(e,ce(B(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let s=F(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[ce(B(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return W(e,ce(B(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["settings.json","google_accounts.json"])||s.at(-1)==="settings.json"&&s.at(-2)===".gemini"||(a?.trim()?vr(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>W(e,Ve(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=B(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return W(e,s,["config.json"])||Sr(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return W(e,B(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=B(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=B(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return W(e,s,["server.token"])||Sr(e,s,["credentials"])||Sr(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=F(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||W(e,B(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||W(e,B(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=ce(B(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=F(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return W(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&W(e,s,[a])||c.some((u)=>vr(e,u,t,r,o))}case"secret.cli.opencode.config":{let s=r.env.get("OPENCODE_CONFIG_DIR")?B(r.env.get("OPENCODE_CONFIG_DIR"),"~/.config/opencode",t,r,o):ce(B(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[ce(B(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(F(e).split("/").at(-1)??"")||W(e,s,l)||(c?.trim()?vr(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((u)=>W(e,Ve(u,t,r,o),l))}case"secret.cli.pi":return W(e,B(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return W(e,B(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=Ve("~",t,r,o);return[ce(B(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),ce(s,".local","share","amp")].some((l)=>W(e,l,["secrets.json"]))||Sr(e,ce(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[ce(B(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),ce(Ve("~",t,r,o),".config","amp")],l=F(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((u)=>W(e,u,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?vr(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=ce(B(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=ce(B(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return W(e,Ve("~/.cursor",t,r,o),["auth.json"])||W(e,s,["auth.json"])||F(e).split("/").at(-1)==="mcp-auth.json"&&Vt(F(e),F(a))}case"secret.cli.cursor.config":{let s=F(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return W(e,B(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=F(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||W(e,B(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||W(e,Ve("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var qm=new WeakMap;function B(e,t,n,r,o){let i=qm.get(o)??new Map;qm.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=Ve(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function W(e,t,n){return n.some((r)=>lp(e,ce(t,r)))}function Sr(e,t,n){return n.some((r)=>Vt(F(e),F(ce(t,r))))}function vr(e,t,n,r,o){return lp(e,Ve(t,n,r,o))}function lp(e,t){return F(e)===F(t)}function ce(e,...t){return $e([e,...t].filter(Boolean).join("/"))}function Ww(e,t,n,r,o,i){if(n.length===0)return!1;let s=F(Er(e,t,o,i));return n.some((a)=>Vt(s,F(Er(a,r,o,i))))}function Gw(e,t,n,r,o,i){if(n.length===0)return!1;let s=F(Er(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?$e(z(be(a),o.paths,i)):"",c=F(l),u=o.env.get("CC_SAFETY_NET_HOME"),f=F(u?$e(z(fi(be(u)),o.paths,i)):l&&$e(z(`${l}/.cc-safety-net`,o.paths,i)));if(f&&Vt(s,f))return!1;return n.some((d)=>{let m=ms(d);if(m&&Zm.basename(s)!==F(m.name))return!1;let p=F(Er(m?.root??d,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return Vt(s,p)&&!(m&&s===p)})}function Fw(e){let t=e.split("/");return t.some((n)=>Mw.has(n))||Nw.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function zw(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of cs)if(r===o.extension&&it(o.id,t))return o.id;for(let o of us)if(o.pattern.test(r)&&it(o.id,t))return o.id;return null}function F(e){return e.toLowerCase()}function it(e,t){return!t?.disabledRules?.includes(e)}function Ve(e,t,n,r){let{home:o,normalized:i}=il(e,n,r);if(!i)return"";if(!o)return i;let s=sl(i,o),a=ui(s)?s:$e(fi(t,s)),l=$e(z(a,n.paths,r));if(!Vt(l,o)){if(ui(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function Ym(e,t){return e===t||e.startsWith(`${t}/`)}function Bw(e,t,n,r){let{home:o,normalized:i}=il(e,n,r);if(!i||!o)return"";let s=sl(i,o),a=Zm.normalize(ui(s)?s:$e(fi(t,s))),l=$e(be(n.env.get("HOME")??n.home)),c=(d)=>process.platform==="win32"?d.toLowerCase():d,u=[o,l].find((d)=>d!==""&&Vt(c(a),c(d)));if(u===void 0)return"";let f=a.slice(u.length);return f?`~${f}`:"~"}function Er(e,t,n,r){let{home:o,normalized:i}=il(e,n,r);if(!i)return"";let s=o?sl(i,o):i;return $e(z(ui(s)?s:fi(t,s),n.paths,r))}function il(e,t,n){let r=t.env.get("HOME")??t.home,o=r?$e(z(be(r),t.paths,n)):"",i=$e(be($w(Qe(e,t))));return{home:o,normalized:i}}function $w(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return g_(e)}catch{return e}}function sl(e,t){if(e==="~")return t;if(e.startsWith("~/"))return ce(t,e.slice(2));return e}function Uw(e){if(process.platform==="win32")return!0;return p_.parse(e).root.length>1}function $e(e){let t=e.trim(),n=(t.includes("\\")&&Uw(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Vt(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function Ue(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class Kt extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var Hw={findPolicyMutation:Wm,findGitMetadataMutation:gd,resolveGitMetadata:jw,loadPolicySnapshot:nu,findSensitiveTarget:tp,analyzeCommand:Pm,getModes:Ni};function cp(e,t){let n={...Hw,...t.dependencies},r=qw(e),o=xr(e)?e.command:r,i=vt("policy-protection",o,()=>rr(e)),s=ge(i,"input-candidate"),a=ge(i,"declared-command");if(xr(e)&&e.command?.trim()&&a?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:He,intent:"stop_and_explain",evidence:{command:e.command,segment:e.command}}};if(s?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Nd,intent:"stop_and_explain"}};let l=Ce(),c=vt("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd],t.environment)),u=vt("policy-protection",o,()=>n.findPolicyMutation(i,t.environment,l));if(u){let E=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Lm,intent:"hard_stop",evidence:{command:E,segment:u.target}}}}let f=vt("policy-protection",o,()=>Om(i,t.environment,l));if(f){let E=o??f.target;return{stage:"policy-protection",decision:{kind:"deny",reason:km,intent:"hard_stop",evidence:{command:E,segment:f.target}}}}let d=vt("policy-protection",o,()=>n.findGitMetadataMutation(i,c,t.environment,l));if(d){let E=o??d.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Te,intent:"hard_stop",evidence:{command:E,segment:d.target}}}}let m=vt("config-load",o,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),p=m.policy,g=n.getModes(p,t.environment.env),h={level:g.effectiveLevel,...Vw(m)},y=p.secretProtection.enabled===!1?null:vt("secret-protection",o,()=>n.findSensitiveTarget(i,p.secretProtection,t.environment,l,{strict:xr(e)||s?.program.dialect==="powershell"?g.strict:void 0}));if(y){let E=o??y.target;return{stage:"secret-protection",...h,decision:{kind:"deny",reason:Xm,intent:"hard_stop",ruleId:y.ruleId,evidence:{command:E,segment:y.target}}}}if(!xr(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...al("command-validation",o),...h};let S=vt("command-analysis",o,()=>Tm(()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:m,environment:t.environment,protectedGitMetadata:c,effectiveCapabilities:g.capabilities,strict:g.strict,paranoidRm:g.paranoidRm,paranoidInterpreters:g.paranoidInterpreters,worktreeMode:g.worktreeMode,budget:l,...t.trace?{trace:t.trace}:{}},Kw(i),i.store),e.command,t.trace));if(S.decision){let E=!g.strict&&S.decision.kind==="deny"&&(S.decision.ruleId==="raw-text.dangerous-command"||S.decision.reason===ar&&!/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/.test(S.decision.evidence?.segment??"")&&Ae(e.command)===null);return{stage:"command-analysis",...h,..."errorCode"in S?{errorCode:S.errorCode}:{},decision:E?{...S.decision,ask:!0}:S.decision}}return{stage:"command-analysis",...h,decision:{kind:"allow"}}}function jw(e,t){let n=[...new Set(e.filter((r)=>typeof r==="string"&&r!==""))].flatMap((r)=>t.gitMetadata(r)??[]);if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.flatMap((r)=>r.entries))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFiles))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function Vw(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function Kw(e){return ge(e,"declared-command")?.program}function qw(e){try{return Tn(e.input)}catch(t){let n=xr(e)?e.command:void 0;throw new Kt("policy-protection",al("policy-protection",t instanceof Ye?void 0:n,t),t)}}function vt(e,t,n){try{return n()}catch(r){throw new Kt(e,al(e,r instanceof Ye?void 0:t,r),r)}}function al(e,t,n){let r=n instanceof N||n instanceof Ge;return{stage:e,decision:{kind:"deny",reason:r?bi:_n,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function xr(e){return e.route.kind==="command"}import{appendFileSync as aA,mkdirSync as lA}from"node:fs";import{isAbsolute as cA,join as ul}from"node:path";import{lstatSync as dp,readdirSync as Yw,readFileSync as Zw,rmdirSync as Xw,statSync as fp,unlinkSync as Jw,utimesSync as Qw,writeFileSync as eA}from"node:fs";import{join as Rr}from"node:path";function up(e,t={}){return Jr(Qt(e,t),e.home).policy.audit.retention_days}var cl=86400000,tA=".last-prune",nA=/^\d{4}-\d{2}$/,rA=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,mp=(e)=>Math.floor(e/cl);function gp(e,t,n=()=>new Date){try{let r=n().getTime();if(!fp(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=Rr(t,tA),i=fp(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&mp(i)===mp(r))return;let s=r-up(e)*cl,a=new Date(r).toISOString().slice(0,7);for(let l of ll(t)){if(l.isDirectory()){oA(Rr(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))iA(Rr(t,l.name),s)}eA(o,"",{mode:384}),Qw(o,r/1000,r/1000)}catch{}}function oA(e,t,n){for(let r of ll(e)){if(!r.isDirectory()||!nA.test(r.name))continue;let o=Rr(e,r.name);for(let i of ll(o)){if(!i.isFile())continue;let s=rA.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+cl;if(!Number.isFinite(a)||a>=t)continue;hp(Rr(o,i.name))}if(r.name!==n)pp(o)}pp(e)}function iA(e,t){try{let n=dp(e);if(n.mtimeMs>=t)return;let r=Zw(e,"utf-8").split(`
|
|
47
|
-
`).filter((o)=>o.trim()).map(sA);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(dp(e).mtimeMs!==n.mtimeMs)return;hp(e)}catch{}}function sA(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function ll(e){try{return Yw(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function hp(e){try{Jw(e)}catch{}}function pp(e){try{Xw(e)}catch{}}var uA="2.4.
|
|
47
|
+
`).filter((o)=>o.trim()).map(sA);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(dp(e).mtimeMs!==n.mtimeMs)return;hp(e)}catch{}}function sA(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function ll(e){try{return Yw(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function hp(e){try{Jw(e)}catch{}}function pp(e){try{Xw(e)}catch{}}var uA="2.4.9",dA=1e4,fA=2000,mA=256,pA=32768;function gA(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function hA(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function dl(e,t,n,r,o,i,s={}){let a=gA(t);if(!a)return;let l=CA(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),u=pi(at(n),s.failureStage?Number.POSITIVE_INFINITY:dA),f=pi(at(r),fA),d=s.toolName?pi(at(s.toolName),mA):void 0,m=i===null?void 0:pi(at(i),pA),p=ul(l,hA(m?.value??null),c.slice(0,7));lA(p,{recursive:!0,mode:448});let g=ul(p,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??Li)(),v:uA,sessionId:a,decision:s.decision??"deny",agent:s.agent,shape:s.shape,level:s.level,configFallback:s.configFallback,toolName:d?.value,command:u.value,segment:f.value,...u.truncated||f.truncated||d?.truncated||m?.truncated?{truncated:!0}:{},reason:o,ruleId:s.ruleId,intent:s.intent,failureStage:s.failureStage,errorCode:s.errorCode,cwd:m?.value??null};aA(g,`${JSON.stringify(h)}
|
|
48
48
|
`,{encoding:"utf-8",mode:384}),gp(e,l,s.now)}catch{}}function pi(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function yA(e){let t=e.env.get("CC_SAFETY_NET_AUDIT_HOME");if(e.env.get("NODE_ENV")==="test"&&!t)return null;let n=t||e.home;return n&&cA(n)?n:null}function CA(e){let t=yA(e);return t?ul(t,".cc-safety-net","logs"):null}function Cp(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=yp(e);return{decision:"allow",command:a,segment:a,reason:"allowed",cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{}}}let i=t.decision.evidence,s=i?.command??(r?yp(e):"");return{decision:"deny",command:s,segment:i?.segment??s,reason:t.decision.reason,cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{},ruleId:t.decision.ruleId,intent:t.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function yp(e){return"command"in e?e.command??"":""}function bp(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;dl(e,o,t.command,t.segment,t.reason,t.cwd,{decision:t.decision,agent:r.agent,shape:r.shape,level:t.level,configFallback:t.configFallback,toolName:t.toolName,ruleId:t.ruleId,intent:t.intent,failureStage:t.failureStage,errorCode:t.errorCode})}function Sp(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;dl(e,o,t.command??"",t.segment??t.command??"",t.reason,r.cwd??null,{decision:"deny",agent:r.agent,shape:r.shape,toolName:r.toolName??t.toolName,ruleId:t.ruleId,intent:t.intent})}function Ep(e,t,n){try{let r=cp(t,{environment:e,...n.guard});return vp(e,t,r,n),r}catch(r){if(!(r instanceof Kt))throw r;throw vp(e,t,r.evaluation,n,!(r.cause instanceof Ye),{stage:r.stage,errorCode:bA(r.cause)}),r}}function vp(e,t,n,r,o=!0,i){bp(e,Cp(t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function bA(e){if(e instanceof N)return V[e.kind].errorCode;if(e instanceof Ye)return"tool-input-limit";if(e instanceof Ge)return"structural-shell-syntax-limit";return"unexpected-error"}function Et(e,t={}){return{malformed:!0,denial:wn(t),cwd:e}}function xp(e,t={}){return(n,r)=>{try{return SA(n,r,e,t)}catch(o){return console.error("CC Safety Net error:",o),e.block(wn())}}}function SA(e,t,n,r){let o=Kl();if(n.cancelled?.(t))return n.block(wn());let i=n.extract(e,t,o.paths);if(!i)return n.allow;let s=()=>n.getSessionId(e,t);if("malformed"in i)return Sp(o,i.denial,s,{agent:n.agent,toolName:i.denial.toolName,cwd:i.cwd}),n.block(i.denial);let a=(l,c)=>{let u=hl(l,{includeEvidence:c});return u?n.block(u):n.allow};try{let l=Ep(o,i,{guard:{auditAllowed:ql(o.env),policyOptions:r.policyOptions,dependencies:r.guardDependencies},audit:{agent:n.agent,getSessionId:s}});return a(l,!0)}catch(l){if(!(l instanceof Kt))throw l;if(Rt(Q.debug,o.env))console.error(`CC Safety Net debug: ${n.debugLabel} analysis failed: ${Cl(l.cause)}`);return a(l.evaluation,n.includeEvidenceOnError(i))}}var Rp="exec",vA=new Set(["auto","gateway"]);function _p(e){e.on("before_tool_call",EA(e),{matcher:[Rp],priority:50})}function EA(e,t={}){return xp({agent:"openclaw",debugLabel:"openclaw before_tool_call",extract:(r,o,i)=>xA(r,o,e,i),getSessionId:(r,o)=>o.sessionId??o.sessionKey,allow:void 0,block:(r)=>wA(r),includeEvidenceOnError:()=>!0,cancelled:(r)=>r.abortSignal?.aborted===!0},t)}function xA(e,t,n,r){if(!e||typeof e!=="object")return Et(null);let o=e.toolName;if(typeof o!=="string"||o.trim()==="")return Et(null);if(o!==Rp)return;if(e.toolKind!==void 0)return;let i=e.params;if(!i||typeof i!=="object"||Array.isArray(i))return Et(null,{toolName:o});let s=i,a=s.command;if(typeof a!=="string"||a.trim()==="")return Et(null,{toolName:o});if(s.host!==void 0&&!vA.has(s.host))return Et(null,{command:a,toolName:o});let l=RA(n,t.agentId,r);if(!l)return Et(null,{command:a,toolName:o});let c=_A(l,s,r);if(!c)return Et(l,{command:a,segment:typeof s.workdir==="string"?s.workdir:void 0,toolName:o});return In(o,s,{kind:"command",shell:"auto"},{configCwd:l,executionCwd:c},a)}function RA(e,t,n){if(typeof t!=="string"||t.trim()==="")return;try{let r=e.runtime.agent.resolveAgentWorkspaceDir(e.config,t);if(typeof r!=="string"||r.trim()==="")return;return Ai(".",[r],n)}catch{return}}function _A(e,t,n){if(!Object.hasOwn(t,"workdir")||t.workdir===void 0)return e;let r=t.workdir;if(typeof r!=="string"||r.trim()==="")return;return Ai(r,[e],n)}function wA(e){return{block:!0,blockReason:yl(e)}}var zL={...gl,register:_p};export{zL as default};
|
package/dist/pi/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ye,P,be,Xe,c,o,xe,L,V,et,d,p}from"../chunks/index-fvtsm6ez.js";import{Q}from"../chunks/index-rr4ytenf.js";import{he,D}from"../chunks/index-
|
|
1
|
+
import{ye,P,be,Xe,c,o,xe,L,V,et,d,p}from"../chunks/index-fvtsm6ez.js";import{Q}from"../chunks/index-rr4ytenf.js";import{he,D}from"../chunks/index-g2gqgqzy.js";var E="cc-safety-net",x="Operate CC Safety Net: explain blocks, rules, integrations, diagnostics",w="Help me with CC Safety Net.";function f(e){e.registerCommand(E,{description:x,handler:async(n,l)=>{e.sendUserMessage(N(n),l.isIdle()?void 0:{deliverAs:"followUp"})}})}function N(e){return`${Q.slice(Q.indexOf("# CC Safety Net")).trimEnd()}
|
|
2
2
|
|
|
3
3
|
## User request
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cc-safety-net",
|
|
3
|
-
"version": "2.4.
|
|
3
|
+
"version": "2.4.9",
|
|
4
4
|
"description": "A coding agent CLI hook - block destructive commands and secret file access",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"amp",
|
|
@@ -121,5 +121,5 @@
|
|
|
121
121
|
"./dist/pi/index.js"
|
|
122
122
|
]
|
|
123
123
|
},
|
|
124
|
-
"gitHead": "
|
|
124
|
+
"gitHead": "784064977b8ab01bf8b2a3f057c4ad574c0c7c1f"
|
|
125
125
|
}
|